hono-crud 0.13.14 → 0.13.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,49 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.16
4
+
5
+ ### Patch Changes
6
+
7
+ - fa184db: OpenAPI: document `?include=` relations in List/Read responses.
8
+
9
+ When a List/Read endpoint has `allowedIncludes` and an included relation declares
10
+ a `schema` (the related model's shape), that relation is now added to the response
11
+ **item** schema as an OPTIONAL field — `hasMany` → array, `belongsTo`/`hasOne` →
12
+ nullable object. Previously a relation's `schema` was used only for internal
13
+ response typing and never reached the generated OpenAPI document, so consumers of
14
+ generated typed clients had to hand-type the embedded relation.
15
+
16
+ Backward-compatible and opt-in: relations without a `schema` (or endpoints without
17
+ `allowedIncludes`) are unchanged. Adds the internal helper `withIncludableRelations`.
18
+
19
+ ## 0.13.15
20
+
21
+ ### Patch Changes
22
+
23
+ - 4ba4a85: Owner-scope relation includes (`?include=`) — security fix for cross-tenant exposure.
24
+
25
+ Previously, loading a relation via `?include=` fetched the related rows by foreign key alone, ignoring the **related** model's access scope. A caller who could read a parent row could therefore read a related row in another tenant (or a soft-deleted one) through the include — a cross-tenant data leak.
26
+
27
+ Relations can now declare a `scope` naming the related table's owner and soft-delete columns:
28
+
29
+ ```ts
30
+ relations: {
31
+ post: {
32
+ type: 'belongsTo', model: 'posts', table: posts,
33
+ foreignKey: 'postId', localKey: 'id',
34
+ scope: { tenantField: 'authorId', softDeleteField: 'deletedAt' },
35
+ },
36
+ }
37
+ ```
38
+
39
+ When set, included related rows are filtered to the request's resolved tenant id and exclude soft-deleted rows (unless `?withDeleted=true`), so a foreign key pointing at another tenant's row resolves to `null` (belongsTo/hasOne) or is omitted (hasMany). The filtering lives in the core orchestrator (`batchLoadRelations` / `loadRelationsForItem`), so it applies identically across the drizzle, memory, and prisma adapters; the endpoint threads the parent request's tenant id + `withDeleted` into `IncludeOptions.scope` (Read via core; List via each adapter).
40
+
41
+ New public types: `RelationScopeConfig`, `RelationRequestScope`; new fields `RelationConfig.scope` and `IncludeOptions.scope`; new protected `getRelationScope()` on the endpoint base class.
42
+
43
+ Backward-compatible and opt-in: relations without `scope` (or requests that resolve no tenant) behave exactly as before. Declare `scope` on any relation whose related model is access-scoped to close the leak.
44
+
45
+ Note: scoping is applied as a post-fetch filter in the orchestrator (related rows are fetched, then filtered before being mapped back onto the parent — they never reach the response), not yet pushed down to the adapter `WHERE`/`where`. Correct and leak-free; pushing the predicate into the query is a performance follow-up.
46
+
3
47
  ## 0.13.14
4
48
 
5
49
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  import { S as StorageRegistry } from '../registry-DYXgzGt0.js';
2
2
  import { Context, Env } from 'hono';
3
- import { m as AuditFieldChange, l as AuditConfig, Z as NormalizedAuditConfig, n as AuditLogEntry, k as AuditAction } from '../types-C2iJttg9.js';
3
+ import { m as AuditFieldChange, l as AuditConfig, Z as NormalizedAuditConfig, n as AuditLogEntry, k as AuditAction } from '../types-D72szrPV.js';
4
4
  import 'zod';
5
5
  import '../path-match-DGLu6wld.js';
6
6
  import '../types-B5wq2iKZ.js';
@@ -1,10 +1,10 @@
1
- import { d as AuthEnv, aC as APIKeyConfig, aD as APIKeyEntry, aE as AuthConfig, aF as Guard, aG as ApprovalConfig, aH as AuthorizationCheck, aI as OwnershipExtractor, N as ModelPolicies, aJ as ApprovalStorage, aK as PendingAction, aL as AuthUser, M as MetaInput, O as OpenAPIRouteSchema, aA as AbstractConstructor, aM as EndpointAuthConfig, aN as JWTClaims } from '../types-C2iJttg9.js';
2
- export { aO as APIKeyLookupResult, aP as ActionSource, aQ as AuthType, aR as JWTAlgorithm, aS as JWTClaimsSchema, aT as JWTConfig, aU as JWT_ALGORITHMS, aV as PendingActionSchema, aW as PendingActionStatus, aX as ValidatedJWTClaims, aY as parseJWTClaims, aZ as safeParseJWTClaims } from '../types-C2iJttg9.js';
3
- export { c as createJWTMiddleware, a as decodeJWT, v as verifyJWT } from '../jwt--gbnOqR-.js';
1
+ import { d as AuthEnv, aD as APIKeyConfig, aE as APIKeyEntry, aF as AuthConfig, aG as Guard, aH as ApprovalConfig, aI as AuthorizationCheck, aJ as OwnershipExtractor, N as ModelPolicies, aK as ApprovalStorage, aL as PendingAction, aM as AuthUser, M as MetaInput, O as OpenAPIRouteSchema, aB as AbstractConstructor, aN as EndpointAuthConfig, aO as JWTClaims } from '../types-D72szrPV.js';
2
+ export { aP as APIKeyLookupResult, aQ as ActionSource, aR as AuthType, aS as JWTAlgorithm, aT as JWTClaimsSchema, aU as JWTConfig, aV as JWT_ALGORITHMS, aW as PendingActionSchema, aX as PendingActionStatus, aY as ValidatedJWTClaims, aZ as parseJWTClaims, a_ as safeParseJWTClaims } from '../types-D72szrPV.js';
3
+ export { c as createJWTMiddleware, a as decodeJWT, v as verifyJWT } from '../jwt-DhJ3yOR6.js';
4
4
  import { Env, Context, MiddlewareHandler } from 'hono';
5
5
  import { S as StorageRegistry } from '../registry-DYXgzGt0.js';
6
- import { O as OpenAPIRoute } from '../route-CrJCBJMO.js';
7
- export { M as MemoryAPIKeyStorage, a as apiKeyStorageRegistry, g as generateAPIKey, b as getAPIKeyStorage, c as getAPIKeyStorageRequired, i as isValidAPIKeyFormat, r as resolveAPIKeyStorage, s as setAPIKeyStorage } from '../memory-B50rK9-O.js';
6
+ import { O as OpenAPIRoute } from '../route-CVsl4dg3.js';
7
+ export { M as MemoryAPIKeyStorage, a as apiKeyStorageRegistry, g as generateAPIKey, b as getAPIKeyStorage, c as getAPIKeyStorageRequired, i as isValidAPIKeyFormat, r as resolveAPIKeyStorage, s as setAPIKeyStorage } from '../memory-DfSspNoL.js';
8
8
  export { P as PathPattern } from '../path-match-DGLu6wld.js';
9
9
  export { a as getUserId } from '../request-info-OQ40JnWp.js';
10
10
  import 'zod';
@@ -1 +1 @@
1
- import {a,i}from'../chunk-57MTTJMU.js';export{b as MemoryAPIKeyStorage,e as apiKeyStorageRegistry,c as generateAPIKey,f as getAPIKeyStorage,g as getAPIKeyStorageRequired,a as hashAPIKey,d as isValidAPIKeyFormat,i as resolveAPIKeyStorage,h as setAPIKeyStorage}from'../chunk-57MTTJMU.js';import {q}from'../chunk-CTOFQ5RC.js';export{k as JWTClaimsSchema,j as JWT_ALGORITHMS,n as PendingActionSchema,q as createJWTMiddleware,s as decodeJWT,d as getAuthType,a as getUser,c as getUserPermissions,b as getUserRoles,i as hasAllPermissions,g as hasAllRoles,h as hasAnyRole,f as hasPermission,e as hasRole,l as parseJWTClaims,m as safeParseJWTClaims,o as validateJWTClaims,r as verifyJWT}from'../chunk-CTOFQ5RC.js';import {p,P}from'../chunk-JBKQLYEU.js';export{r as MemoryApprovalStorage,y as POLICIES_CONTEXT_KEY,G as allOf,J as allowAll,H as anyOf,s as approvalStorageRegistry,I as denyAll,u as getApprovalStorage,v as getApprovalStorageRequired,x as parseIso8601Duration,A as requireAllRoles,C as requireAnyPermission,M as requireApproval,D as requireAuth,K as requireAuthenticated,E as requireOwnership,F as requireOwnershipOrRole,B as requirePermissions,L as requirePolicy,z as requireRoles,w as resolveApprovalStorage,t as setApprovalStorage}from'../chunk-JBKQLYEU.js';import {d}from'../chunk-V7ABUFW5.js';export{b as getUserId}from'../chunk-V7ABUFW5.js';import'../chunk-DMGP7QDL.js';import'../chunk-5P4RVSHT.js';import'../chunk-TLI3TRUA.js';import {f,j,a as a$1,g}from'../chunk-XR6JRDGX.js';import {a as a$2}from'../chunk-NWOJZP4P.js';function w(e){if(!e)throw new f("Invalid API key");if(!e.active)throw new f("API key has been revoked");if(e.expiresAt&&new Date>e.expiresAt)throw new f("API key has expired");return e}var I=a;function Ie(e){return {id:e.userId,roles:e.roles,permissions:e.permissions,metadata:{...e.metadata,apiKeyId:e.id,apiKeyName:e.name}}}function Ue(e,s){return e.req.header(s)||null}function xe(e,s){return e.req.query(s)||null}function U(e){let s=e.headerName||"X-API-Key",i$1=e.queryParam??null,r=e.hashKey||I,t=e.extractUser||Ie;return async(o,u)=>{let n=Ue(o,s);if(!n&&i$1&&(n=xe(o,i$1)),!n)throw new f("Missing API key");let l=await r(n),g,A=e.lookupKey?null:i(o,e.storage);if(e.lookupKey)g=await e.lookupKey(l);else if(A)g=await A.lookup(l);else throw new j("API key auth requires lookupKey, storage, or a configured apiKeyStorage");let c=w(g),m=t(c);o.set(a$1.userId,m.id),o.set(a$1.user,m),o.set(a$1.roles,m.roles||[]),o.set(a$1.permissions,m.permissions||[]),o.set(a$1.authType,"api-key");let h=a$2(o);if(e.updateLastUsed){let y=Promise.resolve(e.updateLastUsed(c.id)).catch(()=>{});h?.(y);}else if(A){let y=Promise.resolve(A.updateLastUsed(c.id)).catch(()=>{});h?.(y);}await u();}}async function Ke(e,s){let r=await(s.hashKey||I)(e),t;if(s.lookupKey)t=await s.lookupKey(r);else {let o=i(void 0,s.storage);if(o)t=await o.lookup(r);else throw new j("API key auth requires lookupKey, storage, or a configured apiKeyStorage")}return w(t)}function x(e){let s=e.requireAuth??true,i=e.excludePaths||[],r=e.errorMessage||"Unauthorized",t=e.authOrder||["jwt","api-key"],o=e.jwt?q(e.jwt):null,u=e.apiKey?U(e.apiKey):null;return async(n,l)=>{let g=n.req.path;if(d(g,i))return n.set(a$1.authType,"none"),l();let A=false,c=null;for(let m of t)try{if(m==="jwt"&&o&&n.req.header("Authorization")?.toLowerCase().startsWith("bearer ")){await o(n,async()=>{}),A=!0;break}if(m==="api-key"&&u){let h=e.apiKey?.headerName||"X-API-Key",y=e.apiKey?.queryParam;if(n.req.header(h)||y&&n.req.query(y)){await u(n,async()=>{}),A=!0;break}}}catch(h){c=h instanceof Error?h:new Error(String(h));}if(!A){if(s)throw c instanceof f?c:new f(r);n.set(a$1.authType,"none");}await l();}}function ve(e){return x({...e,requireAuth:false})}function Ce(e){return x({...e,requireAuth:true})}var K=class extends p{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(s,i){return true}getUser(){let i=this.getContext().var.user;if(!i)throw new f("Authentication required");return i}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(s){return this.getUserRoles().includes(s)}hasAnyRole(...s){let i=this.getUserRoles();return s.some(r=>i.includes(r))}hasAllRoles(...s){let i=this.getUserRoles();return s.every(r=>i.includes(r))}hasPermission(s){return this.getUserPermissions().includes(s)}hasAllPermissions(...s){let i=this.getUserPermissions();return s.every(r=>i.includes(r))}hasAnyPermission(...s){let i=this.getUserPermissions();return s.some(r=>i.includes(r))}async enforceAuth(){let s=this.getContext();if(this.requiresAuth&&!s.var.user)throw new f("Authentication required");let i=s.var.user;if(!i)return;if(this.requiredRoles&&this.requiredRoles.length>0){let t=i.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(u=>t.includes(u)))throw new g(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(u=>t.includes(u)))throw new g(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let t=i.permissions||[];if(!this.requiredPermissions.every(u=>t.includes(u)))throw new g(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(i,s))throw new g("Access denied")}getSchema(){let s=super.getSchema(),i=this.requiresAuth?[{bearerAuth:[]}]:void 0,r={401:P("Unauthorized - Authentication required"),403:P("Forbidden - Insufficient permissions")};return {...s,security:i,responses:{...s.responses,...this.requiresAuth?r:{}}}}};function be(e){class s extends e{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(r,t){return true}getUser(){let t=this.getContext().var.user;if(!t)throw new f("Authentication required");return t}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 t=this.getUserOrNull();return t?(t.roles||[]).includes(r):false}hasAnyRole(...r){let t=this.getUserOrNull()?.roles||[];return r.some(o=>t.includes(o))}hasAllRoles(...r){let t=this.getUserOrNull()?.roles||[];return r.every(o=>t.includes(o))}hasPermission(r){let t=this.getUserOrNull();return t?(t.permissions||[]).includes(r):false}hasAllPermissions(...r){let t=this.getUserOrNull()?.permissions||[];return r.every(o=>t.includes(o))}hasAnyPermission(...r){let t=this.getUserOrNull()?.permissions||[];return r.some(o=>t.includes(o))}async enforceAuth(){let r=this.getContext();if(this.requiresAuth&&!r.var.user)throw new f("Authentication required");let t=r.var.user;if(!t)return;if(this.requiredRoles&&this.requiredRoles.length>0){let u=t.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(l=>u.includes(l)))throw new g(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(l=>u.includes(l)))throw new g(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let u=t.permissions||[];if(!this.requiredPermissions.every(l=>u.includes(l)))throw new g(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(t,r))throw new g("Access denied")}getSchema(){let r=super.getSchema(),t=this.requiresAuth?[{bearerAuth:[]}]:void 0,o={401:P("Unauthorized - Authentication required"),403:P("Forbidden - Insufficient permissions")};return {...r,security:t,responses:{...r.responses,...this.requiresAuth?o:{}}}}}return s}export{K as AuthenticatedEndpoint,U as createAPIKeyMiddleware,x as createAuthMiddleware,I as defaultHashAPIKey,ve as optionalAuth,Ce as requireAuthentication,Ke as validateAPIKey,w as validateAPIKeyEntry,be as withAuth};
1
+ import {a,i}from'../chunk-57MTTJMU.js';export{b as MemoryAPIKeyStorage,e as apiKeyStorageRegistry,c as generateAPIKey,f as getAPIKeyStorage,g as getAPIKeyStorageRequired,a as hashAPIKey,d as isValidAPIKeyFormat,i as resolveAPIKeyStorage,h as setAPIKeyStorage}from'../chunk-57MTTJMU.js';import {q}from'../chunk-CTOFQ5RC.js';export{k as JWTClaimsSchema,j as JWT_ALGORITHMS,n as PendingActionSchema,q as createJWTMiddleware,s as decodeJWT,d as getAuthType,a as getUser,c as getUserPermissions,b as getUserRoles,i as hasAllPermissions,g as hasAllRoles,h as hasAnyRole,f as hasPermission,e as hasRole,l as parseJWTClaims,m as safeParseJWTClaims,o as validateJWTClaims,r as verifyJWT}from'../chunk-CTOFQ5RC.js';import {p,P}from'../chunk-A27HDYSF.js';export{r as MemoryApprovalStorage,y as POLICIES_CONTEXT_KEY,G as allOf,J as allowAll,H as anyOf,s as approvalStorageRegistry,I as denyAll,u as getApprovalStorage,v as getApprovalStorageRequired,x as parseIso8601Duration,A as requireAllRoles,C as requireAnyPermission,M as requireApproval,D as requireAuth,K as requireAuthenticated,E as requireOwnership,F as requireOwnershipOrRole,B as requirePermissions,L as requirePolicy,z as requireRoles,w as resolveApprovalStorage,t as setApprovalStorage}from'../chunk-A27HDYSF.js';import {d}from'../chunk-V7ABUFW5.js';export{b as getUserId}from'../chunk-V7ABUFW5.js';import'../chunk-DMGP7QDL.js';import'../chunk-5P4RVSHT.js';import'../chunk-TLI3TRUA.js';import {f,j,a as a$1,g}from'../chunk-XR6JRDGX.js';import {a as a$2}from'../chunk-NWOJZP4P.js';function w(e){if(!e)throw new f("Invalid API key");if(!e.active)throw new f("API key has been revoked");if(e.expiresAt&&new Date>e.expiresAt)throw new f("API key has expired");return e}var I=a;function Ie(e){return {id:e.userId,roles:e.roles,permissions:e.permissions,metadata:{...e.metadata,apiKeyId:e.id,apiKeyName:e.name}}}function Ue(e,s){return e.req.header(s)||null}function xe(e,s){return e.req.query(s)||null}function U(e){let s=e.headerName||"X-API-Key",i$1=e.queryParam??null,r=e.hashKey||I,t=e.extractUser||Ie;return async(o,u)=>{let n=Ue(o,s);if(!n&&i$1&&(n=xe(o,i$1)),!n)throw new f("Missing API key");let l=await r(n),g,A=e.lookupKey?null:i(o,e.storage);if(e.lookupKey)g=await e.lookupKey(l);else if(A)g=await A.lookup(l);else throw new j("API key auth requires lookupKey, storage, or a configured apiKeyStorage");let c=w(g),m=t(c);o.set(a$1.userId,m.id),o.set(a$1.user,m),o.set(a$1.roles,m.roles||[]),o.set(a$1.permissions,m.permissions||[]),o.set(a$1.authType,"api-key");let h=a$2(o);if(e.updateLastUsed){let y=Promise.resolve(e.updateLastUsed(c.id)).catch(()=>{});h?.(y);}else if(A){let y=Promise.resolve(A.updateLastUsed(c.id)).catch(()=>{});h?.(y);}await u();}}async function Ke(e,s){let r=await(s.hashKey||I)(e),t;if(s.lookupKey)t=await s.lookupKey(r);else {let o=i(void 0,s.storage);if(o)t=await o.lookup(r);else throw new j("API key auth requires lookupKey, storage, or a configured apiKeyStorage")}return w(t)}function x(e){let s=e.requireAuth??true,i=e.excludePaths||[],r=e.errorMessage||"Unauthorized",t=e.authOrder||["jwt","api-key"],o=e.jwt?q(e.jwt):null,u=e.apiKey?U(e.apiKey):null;return async(n,l)=>{let g=n.req.path;if(d(g,i))return n.set(a$1.authType,"none"),l();let A=false,c=null;for(let m of t)try{if(m==="jwt"&&o&&n.req.header("Authorization")?.toLowerCase().startsWith("bearer ")){await o(n,async()=>{}),A=!0;break}if(m==="api-key"&&u){let h=e.apiKey?.headerName||"X-API-Key",y=e.apiKey?.queryParam;if(n.req.header(h)||y&&n.req.query(y)){await u(n,async()=>{}),A=!0;break}}}catch(h){c=h instanceof Error?h:new Error(String(h));}if(!A){if(s)throw c instanceof f?c:new f(r);n.set(a$1.authType,"none");}await l();}}function ve(e){return x({...e,requireAuth:false})}function Ce(e){return x({...e,requireAuth:true})}var K=class extends p{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(s,i){return true}getUser(){let i=this.getContext().var.user;if(!i)throw new f("Authentication required");return i}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(s){return this.getUserRoles().includes(s)}hasAnyRole(...s){let i=this.getUserRoles();return s.some(r=>i.includes(r))}hasAllRoles(...s){let i=this.getUserRoles();return s.every(r=>i.includes(r))}hasPermission(s){return this.getUserPermissions().includes(s)}hasAllPermissions(...s){let i=this.getUserPermissions();return s.every(r=>i.includes(r))}hasAnyPermission(...s){let i=this.getUserPermissions();return s.some(r=>i.includes(r))}async enforceAuth(){let s=this.getContext();if(this.requiresAuth&&!s.var.user)throw new f("Authentication required");let i=s.var.user;if(!i)return;if(this.requiredRoles&&this.requiredRoles.length>0){let t=i.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(u=>t.includes(u)))throw new g(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(u=>t.includes(u)))throw new g(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let t=i.permissions||[];if(!this.requiredPermissions.every(u=>t.includes(u)))throw new g(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(i,s))throw new g("Access denied")}getSchema(){let s=super.getSchema(),i=this.requiresAuth?[{bearerAuth:[]}]:void 0,r={401:P("Unauthorized - Authentication required"),403:P("Forbidden - Insufficient permissions")};return {...s,security:i,responses:{...s.responses,...this.requiresAuth?r:{}}}}};function be(e){class s extends e{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(r,t){return true}getUser(){let t=this.getContext().var.user;if(!t)throw new f("Authentication required");return t}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 t=this.getUserOrNull();return t?(t.roles||[]).includes(r):false}hasAnyRole(...r){let t=this.getUserOrNull()?.roles||[];return r.some(o=>t.includes(o))}hasAllRoles(...r){let t=this.getUserOrNull()?.roles||[];return r.every(o=>t.includes(o))}hasPermission(r){let t=this.getUserOrNull();return t?(t.permissions||[]).includes(r):false}hasAllPermissions(...r){let t=this.getUserOrNull()?.permissions||[];return r.every(o=>t.includes(o))}hasAnyPermission(...r){let t=this.getUserOrNull()?.permissions||[];return r.some(o=>t.includes(o))}async enforceAuth(){let r=this.getContext();if(this.requiresAuth&&!r.var.user)throw new f("Authentication required");let t=r.var.user;if(!t)return;if(this.requiredRoles&&this.requiredRoles.length>0){let u=t.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(l=>u.includes(l)))throw new g(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(l=>u.includes(l)))throw new g(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let u=t.permissions||[];if(!this.requiredPermissions.every(l=>u.includes(l)))throw new g(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(t,r))throw new g("Access denied")}getSchema(){let r=super.getSchema(),t=this.requiresAuth?[{bearerAuth:[]}]:void 0,o={401:P("Unauthorized - Authentication required"),403:P("Forbidden - Insufficient permissions")};return {...r,security:t,responses:{...r.responses,...this.requiresAuth?o:{}}}}}return s}export{K as AuthenticatedEndpoint,U as createAPIKeyMiddleware,x as createAuthMiddleware,I as defaultHashAPIKey,ve as optionalAuth,Ce as requireAuthentication,Ke as validateAPIKey,w as validateAPIKeyEntry,be as withAuth};
@@ -1,7 +1,7 @@
1
1
  import { Env, MiddlewareHandler } from 'hono';
2
2
  import { ZodObject, ZodRawShape } from 'zod';
3
- import { M as MetaInput, O as OpenAPIRouteSchema, w as HookContext, y as HookMode, t as FilterConfig, aj as SortDirection, g as AfterUpdateHook, f as AfterDeleteHook } from '../types-C2iJttg9.js';
4
- import { M as ModelObject } from '../types-C9boymY0.js';
3
+ import { M as MetaInput, O as OpenAPIRouteSchema, w as HookContext, y as HookMode, t as FilterConfig, aj as SortDirection, g as AfterUpdateHook, f as AfterDeleteHook } from '../types-D72szrPV.js';
4
+ import { M as ModelObject } from '../types-BTRpRT28.js';
5
5
  import '../path-match-DGLu6wld.js';
6
6
  import '../types-B5wq2iKZ.js';
7
7
  import '../types-lAPVBoYa.js';
@@ -1 +1 @@
1
- import {b as b$2}from'./chunk-DMGP7QDL.js';import {b as b$1}from'./chunk-5P4RVSHT.js';import {b as b$3,a as a$2}from'./chunk-TLI3TRUA.js';import {a,f,g}from'./chunk-XR6JRDGX.js';import {a as a$1}from'./chunk-NWOJZP4P.js';import {z as z$1}from'zod';var z=["eq","ne","gt","gte","lt","lte","in","nin","like","ilike","null","between"];function J(t){return z.includes(t)}function Q(t){throw new Error(`Unhandled discriminated union member: ${String(t)}`)}var ee=["asc","desc"],te=["any","all","phrase"],ne=["count","sum","avg","min","max","countDistinct"];function re(t){return t}function oe(t){return t}var se=z$1.object({path:z$1.string(),message:z$1.string(),code:z$1.string()}),H=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(),ie=z$1.object({success:z$1.literal(false),error:H});function ae(t){return z$1.object({success:z$1.literal(true),result:t})}var U=a.responseEnvelope;function k(t){return t?.var?.[U]}function R(t,e){try{return t.req.valid(e)}catch{return}}function y(t,e,n){return t.json(e,n)}var O=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 e=this.context,n=this.getSchema(),r={};if(n.request?.body){let o=R(e,"json");if(o===void 0)try{o=await e.req.json();}catch{}o!==void 0&&(r.body=o);}if(n.request?.query){let o=R(e,"query");o===void 0&&(o=e.req.query()),o!==void 0&&(r.query=o);}if(n.request?.params){let o=R(e,"param");o===void 0&&(o=e.req.param()),o!==void 0&&(r.params=o);}return r}setContext(e){this.context=e;}getContext(){if(!this.context)throw new Error("Context not set");return this.context}json(e,n=200){return y(this.getContext(),e,n)}getResponseEnvelope(){return k(this.context)}success(e,n=200){let r=this.getResponseEnvelope(),o=r?r.success(e):{success:true,result:e};return y(this.getContext(),o,n)}successPaginated(e,n,r=200){let o=this.getResponseEnvelope(),s=o?o.success(e,n):{success:true,result:e,result_info:n};return y(this.getContext(),s,r)}runAfterResponse(e){let n=a$1(this.getContext());n?n(e):e.catch(r=>{b$2().error("Background task failed",{error:r instanceof Error?r.message:String(r)});});}error(e,n="ERROR",r=400,o){let s={code:n,message:e};o!==void 0&&(s.details=o);let a=this.getResponseEnvelope(),f=a?a.error(s):{success:false,error:s};return y(this.getContext(),f,r)}};function le(t){return typeof t=="function"&&"isRoute"in t&&t.isRoute===true}var b=class{store=new Map;async create(e){this.store.set(e.id,{...e});}async get(e){let n=this.store.get(e);if(!n)return null;if(n.status==="pending"&&Date.parse(n.expiresAt)<=Date.now()){let r={...n,status:"expired"};return this.store.set(e,r),r}return {...n}}async approve(e,n){let r=await this.get(e);if(!r)throw new Error(`Pending action ${e} not found`);if(r.status!=="pending")throw new Error(`Pending action ${e} cannot be approved from status '${r.status}'`);this.store.set(e,{...r,status:"approved",approvedBy:n,approvedAt:new Date().toISOString()});}async reject(e,n,r){let o=await this.get(e);if(!o)throw new Error(`Pending action ${e} not found`);if(o.status!=="pending")throw new Error(`Pending action ${e} cannot be rejected from status '${o.status}'`);this.store.set(e,{...o,status:"rejected",rejectedBy:n,rejectedReason:r});}clear(){this.store.clear();}},h=b$1({contextKey:a.approvalStorage,defaultFactory:()=>(b$2().warn("requireApproval: no approval storage 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 storage (config.storage) or inject approvalStorage with createStorageMiddleware() for production."),new b)}),xe=h.registry,we=h.set,ye=h.get,I=h.getRequired;function P(t,e){return h.resolve(t,e)}var V=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;function q(t){let e=V.exec(t);if(!e)throw new Error(`Invalid ISO 8601 duration: ${t}. Use P[nD][T[nH][nM][nS]] (years and months unsupported).`);let[,n,r,o,s]=e,a=(n?Number(n)*864e5:0)+(r?Number(r)*36e5:0)+(o?Number(o)*6e4:0)+(s?Number(s)*1e3:0);if(a===0&&t!=="PT0S"&&t!=="P0D")throw new Error(`ISO 8601 duration ${t} parsed to zero milliseconds \u2014 verify the format.`);return a}function K(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var B=a.policies;function ke(...t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");let o=r.roles||[];if(!t.some(a=>o.includes(a)))throw new g("Insufficient permissions");await n();}}function Oe(...t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");let o=r.roles||[];if(!t.every(a=>o.includes(a)))throw new g("Insufficient permissions");await n();}}function Ie(...t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");let o=r.permissions||[];if(!t.every(a=>o.includes(a)))throw new g("Insufficient permissions");await n();}}function Pe(...t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");let o=r.permissions||[];if(!t.some(a=>o.includes(a)))throw new g("Insufficient permissions");await n();}}function qe(t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");if(!await t(r,e))throw new g("Access denied");await n();}}function Me(t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");let o=await t(e);if(r.id!==o)throw new g("Access denied: not resource owner");await n();}}function je(t,...e){return async(n,r)=>{let o=n.var.user;if(!o)throw new f("Authentication required");let s=o.roles||[];if(e.some(m=>s.includes(m))){await r();return}let f$1=await t(n);if(o.id===f$1){await r();return}throw new g("Access denied")}}function Ze(...t){return async(e,n)=>{for(let r of t)await r(e,async()=>{});await n();}}function Fe(...t){return async(e,n)=>{let r=null;for(let o of t)try{await o(e,async()=>{}),await n();return}catch(s){r=s instanceof Error?s:new Error(String(s));}throw r||new g("Access denied")}}function _e(t="Access denied"){return async()=>{throw new g(t)}}function De(){return async(t,e)=>{await e();}}function Ne(){return async(t,e)=>{if(!t.var.user)throw new f("Authentication required");await e();}}function ze(t){return async(e,n)=>{b$3(e,B,t),await n();}}function He(t){let e=t.resumeMarker??"_resume_",n=q(t.expiresAfter??"P1D"),r=z$1.object({[e]:z$1.string()}).loose();return async(o,s)=>{let a$1=P(o,t.storage)??I(),f={};try{let g=await o.req.json();K(g)&&(f=g);}catch{}let m=r.safeParse(f).data?.[e];if(m){let g$1=await a$1.get(m);if(!g$1)throw new g(`Pending action ${m} not found`);if(g$1.status==="expired")throw new g(`Pending action ${m} has expired`);if(g$1.status!=="approved")throw new g(`Pending action ${m} is ${g$1.status}, cannot resume`);$(o,g$1.input),await s();return}let T=a$2(o,a.userId),E=a$2(o,a.agentId),j=a$2(o,a.agentRunId),Z=a$2(o,a.onBehalfOfUserId),F=a$2(o,a.toolCallId),_=a$2(o,a.tenantId),D=a$2(o,a.organizationId),N=a$2(o,a.actionSource)??(E?"agent-mcp":"http"),A=Date.now(),x={id:crypto.randomUUID(),tenantId:_,organizationId:D,userId:T,actorUserId:T,onBehalfOfUserId:Z,agentId:E,agentRunId:j,toolCallId:F,source:N,toolName:t.toolName??`${o.req.method} ${o.req.path}`,input:f,status:"pending",createdAt:new Date(A).toISOString(),expiresAt:new Date(A+n).toISOString(),reason:t.reason};return await a$1.create(x),o.json({status:"pending",actionId:x.id,expiresAt:x.expiresAt,reason:x.reason},202)}}function $(t,e){let n=t.req,r=Promise.resolve(JSON.stringify(e));n.bodyCache?(n.bodyCache.text=r,delete n.bodyCache.parsedBody,delete n.bodyCache.json):n.bodyCache={text:r};}function Ke(t,e){let n=e??{},r={...t,...n};return (t.request||n.request)&&(r.request={...t.request,...n.request}),(t.responses||n.responses)&&(r.responses={...t.responses,...n.responses}),r}function L(){return z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.string(),message:z$1.string(),details:z$1.unknown().optional()})})}function G(t){return {description:t??"Error",content:{"application/json":{schema:L()}}}}function Be(t){let e={};for(let[n,r]of Object.entries(t))e[Number(n)]=G(r);return e}function $e(t){return z$1.object({ids:z$1.array(z$1.string()).min(1).max(t)})}function Le(t,e,n){let r=o=>z$1.object({success:z$1.literal(true),result:z$1.object({[t]:z$1.array(e),count:z$1.number(),notFound:z$1.array(z$1.string()).optional(),...o?{errors:z$1.array(z$1.object({id:z$1.string(),error:z$1.string()})).optional()}:{}})});return {200:{description:n,content:{"application/json":{schema:r(false)}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:r(true)}}}}}export{Oe as A,Ie as B,Pe as C,qe as D,Me as E,je as F,Ze as G,Fe as H,_e as I,De as J,Ne as K,ze as L,He as M,Ke as N,L as O,G as P,Be as Q,$e as R,Le as S,z as a,J as b,Q as c,ee as d,te as e,ne as f,re as g,oe as h,se as i,H as j,ie as k,ae as l,U as m,k as n,y as o,O as p,le as q,b as r,xe as s,we as t,ye as u,I as v,P as w,q as x,B as y,ke as z};
1
+ import {b as b$2}from'./chunk-DMGP7QDL.js';import {b as b$1}from'./chunk-5P4RVSHT.js';import {b as b$3,a as a$2}from'./chunk-TLI3TRUA.js';import {a,f,g}from'./chunk-XR6JRDGX.js';import {a as a$1}from'./chunk-NWOJZP4P.js';import {z as z$1}from'zod';var z=["eq","ne","gt","gte","lt","lte","in","nin","like","ilike","null","between"];function J(t){return z.includes(t)}function Q(t){throw new Error(`Unhandled discriminated union member: ${String(t)}`)}var ee=["asc","desc"],te=["any","all","phrase"],ne=["count","sum","avg","min","max","countDistinct"];function re(t){return t}function oe(t){return t}var se=z$1.object({path:z$1.string(),message:z$1.string(),code:z$1.string()}),H=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(),ie=z$1.object({success:z$1.literal(false),error:H});function ae(t){return z$1.object({success:z$1.literal(true),result:t})}var U=a.responseEnvelope;function k(t){return t?.var?.[U]}function R(t,e){try{return t.req.valid(e)}catch{return}}function y(t,e,n){return t.json(e,n)}var O=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 e=this.context,n=this.getSchema(),r={};if(n.request?.body){let o=R(e,"json");if(o===void 0)try{o=await e.req.json();}catch{}o!==void 0&&(r.body=o);}if(n.request?.query){let o=R(e,"query");o===void 0&&(o=e.req.query()),o!==void 0&&(r.query=o);}if(n.request?.params){let o=R(e,"param");o===void 0&&(o=e.req.param()),o!==void 0&&(r.params=o);}return r}setContext(e){this.context=e;}getContext(){if(!this.context)throw new Error("Context not set");return this.context}json(e,n=200){return y(this.getContext(),e,n)}getResponseEnvelope(){return k(this.context)}success(e,n=200){let r=this.getResponseEnvelope(),o=r?r.success(e):{success:true,result:e};return y(this.getContext(),o,n)}successPaginated(e,n,r=200){let o=this.getResponseEnvelope(),s=o?o.success(e,n):{success:true,result:e,result_info:n};return y(this.getContext(),s,r)}runAfterResponse(e){let n=a$1(this.getContext());n?n(e):e.catch(r=>{b$2().error("Background task failed",{error:r instanceof Error?r.message:String(r)});});}error(e,n="ERROR",r=400,o){let s={code:n,message:e};o!==void 0&&(s.details=o);let a=this.getResponseEnvelope(),f=a?a.error(s):{success:false,error:s};return y(this.getContext(),f,r)}};function le(t){return typeof t=="function"&&"isRoute"in t&&t.isRoute===true}var b=class{store=new Map;async create(e){this.store.set(e.id,{...e});}async get(e){let n=this.store.get(e);if(!n)return null;if(n.status==="pending"&&Date.parse(n.expiresAt)<=Date.now()){let r={...n,status:"expired"};return this.store.set(e,r),r}return {...n}}async approve(e,n){let r=await this.get(e);if(!r)throw new Error(`Pending action ${e} not found`);if(r.status!=="pending")throw new Error(`Pending action ${e} cannot be approved from status '${r.status}'`);this.store.set(e,{...r,status:"approved",approvedBy:n,approvedAt:new Date().toISOString()});}async reject(e,n,r){let o=await this.get(e);if(!o)throw new Error(`Pending action ${e} not found`);if(o.status!=="pending")throw new Error(`Pending action ${e} cannot be rejected from status '${o.status}'`);this.store.set(e,{...o,status:"rejected",rejectedBy:n,rejectedReason:r});}clear(){this.store.clear();}},h=b$1({contextKey:a.approvalStorage,defaultFactory:()=>(b$2().warn("requireApproval: no approval storage 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 storage (config.storage) or inject approvalStorage with createStorageMiddleware() for production."),new b)}),xe=h.registry,we=h.set,ye=h.get,I=h.getRequired;function P(t,e){return h.resolve(t,e)}var V=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;function q(t){let e=V.exec(t);if(!e)throw new Error(`Invalid ISO 8601 duration: ${t}. Use P[nD][T[nH][nM][nS]] (years and months unsupported).`);let[,n,r,o,s]=e,a=(n?Number(n)*864e5:0)+(r?Number(r)*36e5:0)+(o?Number(o)*6e4:0)+(s?Number(s)*1e3:0);if(a===0&&t!=="PT0S"&&t!=="P0D")throw new Error(`ISO 8601 duration ${t} parsed to zero milliseconds \u2014 verify the format.`);return a}function K(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var B=a.policies;function ke(...t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");let o=r.roles||[];if(!t.some(a=>o.includes(a)))throw new g("Insufficient permissions");await n();}}function Oe(...t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");let o=r.roles||[];if(!t.every(a=>o.includes(a)))throw new g("Insufficient permissions");await n();}}function Ie(...t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");let o=r.permissions||[];if(!t.every(a=>o.includes(a)))throw new g("Insufficient permissions");await n();}}function Pe(...t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");let o=r.permissions||[];if(!t.some(a=>o.includes(a)))throw new g("Insufficient permissions");await n();}}function qe(t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");if(!await t(r,e))throw new g("Access denied");await n();}}function Me(t){return async(e,n)=>{let r=e.var.user;if(!r)throw new f("Authentication required");let o=await t(e);if(r.id!==o)throw new g("Access denied: not resource owner");await n();}}function je(t,...e){return async(n,r)=>{let o=n.var.user;if(!o)throw new f("Authentication required");let s=o.roles||[];if(e.some(m=>s.includes(m))){await r();return}let f$1=await t(n);if(o.id===f$1){await r();return}throw new g("Access denied")}}function Fe(...t){return async(e,n)=>{for(let r of t)await r(e,async()=>{});await n();}}function Ze(...t){return async(e,n)=>{let r=null;for(let o of t)try{await o(e,async()=>{}),await n();return}catch(s){r=s instanceof Error?s:new Error(String(s));}throw r||new g("Access denied")}}function De(t="Access denied"){return async()=>{throw new g(t)}}function _e(){return async(t,e)=>{await e();}}function Ne(){return async(t,e)=>{if(!t.var.user)throw new f("Authentication required");await e();}}function ze(t){return async(e,n)=>{b$3(e,B,t),await n();}}function He(t){let e=t.resumeMarker??"_resume_",n=q(t.expiresAfter??"P1D"),r=z$1.object({[e]:z$1.string()}).loose();return async(o,s)=>{let a$1=P(o,t.storage)??I(),f={};try{let g=await o.req.json();K(g)&&(f=g);}catch{}let m=r.safeParse(f).data?.[e];if(m){let g$1=await a$1.get(m);if(!g$1)throw new g(`Pending action ${m} not found`);if(g$1.status==="expired")throw new g(`Pending action ${m} has expired`);if(g$1.status!=="approved")throw new g(`Pending action ${m} is ${g$1.status}, cannot resume`);$(o,g$1.input),await s();return}let T=a$2(o,a.userId),E=a$2(o,a.agentId),j=a$2(o,a.agentRunId),F=a$2(o,a.onBehalfOfUserId),Z=a$2(o,a.toolCallId),D=a$2(o,a.tenantId),_=a$2(o,a.organizationId),N=a$2(o,a.actionSource)??(E?"agent-mcp":"http"),A=Date.now(),x={id:crypto.randomUUID(),tenantId:D,organizationId:_,userId:T,actorUserId:T,onBehalfOfUserId:F,agentId:E,agentRunId:j,toolCallId:Z,source:N,toolName:t.toolName??`${o.req.method} ${o.req.path}`,input:f,status:"pending",createdAt:new Date(A).toISOString(),expiresAt:new Date(A+n).toISOString(),reason:t.reason};return await a$1.create(x),o.json({status:"pending",actionId:x.id,expiresAt:x.expiresAt,reason:x.reason},202)}}function $(t,e){let n=t.req,r=Promise.resolve(JSON.stringify(e));n.bodyCache?(n.bodyCache.text=r,delete n.bodyCache.parsedBody,delete n.bodyCache.json):n.bodyCache={text:r};}function Ke(t,e){let n=e??{},r={...t,...n};return (t.request||n.request)&&(r.request={...t.request,...n.request}),(t.responses||n.responses)&&(r.responses={...t.responses,...n.responses}),r}function L(){return z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.string(),message:z$1.string(),details:z$1.unknown().optional()})})}function G(t){return {description:t??"Error",content:{"application/json":{schema:L()}}}}function Be(t){let e={};for(let[n,r]of Object.entries(t))e[Number(n)]=G(r);return e}function $e(t){return z$1.object({ids:z$1.array(z$1.string()).min(1).max(t)})}function Le(t,e,n){let r=o=>z$1.object({success:z$1.literal(true),result:z$1.object({[t]:z$1.array(e),count:z$1.number(),notFound:z$1.array(z$1.string()).optional(),...o?{errors:z$1.array(z$1.object({id:z$1.string(),error:z$1.string()})).optional()}:{}})});return {200:{description:n,content:{"application/json":{schema:r(false)}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:r(true)}}}}}export{Oe as A,Ie as B,Pe as C,qe as D,Me as E,je as F,Fe as G,Ze as H,De as I,_e as J,Ne as K,ze as L,He as M,Ke as N,L as O,G as P,Be as Q,$e as R,Le as S,z as a,J as b,Q as c,ee as d,te as e,ne as f,re as g,oe as h,se as i,H as j,ie as k,ae as l,U as m,k as n,y as o,O as p,le as q,b as r,xe as s,we as t,ye as u,I as v,P as w,q as x,B as y,ke as z};
@@ -0,0 +1,11 @@
1
+ import {e as e$3,f as f$1}from'./chunk-P7HU2KIE.js';import {e as e$2}from'./chunk-H3VBYIDA.js';import {a as a$4,b as b$3}from'./chunk-CWQSQUV4.js';import {a as a$5,b as b$4}from'./chunk-SDNXN7M5.js';import {i,a as a$3}from'./chunk-HYXDMJ4K.js';import {h as h$1}from'./chunk-WBHWKOTP.js';import {a}from'./chunk-L5CVVJQH.js';import {f,b,N,P,d as d$1,S,R,c,e as e$1,p,y}from'./chunk-A27HDYSF.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {a as a$1,b as b$5}from'./chunk-TLI3TRUA.js';import {j,e,d,b as b$2,h,c as c$1,a as a$2,g}from'./chunk-XR6JRDGX.js';import {z}from'zod';import {stream}from'hono/streaming';var no=[["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"],["bulkPatch","patch","/bulk"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"],["versionHistory","get","/:id/versions"],["versionCompare","get","/:id/versions/compare"],["versionRead","get","/:id/versions/:version"],["versionRollback","post","/:id/versions/:version/rollback"]];var Se="createdAt",Oe="updatedAt";function ie(n){return n?n===true?{enabled:true,createdAt:Se,updatedAt:Oe}:{enabled:true,createdAt:n.createdAt??Se,updatedAt:n.updatedAt??Oe}:{enabled:false,createdAt:Se,updatedAt:Oe}}function v(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 Lt(n){return n!=null&&n!==""}function Qe(n,e,t,o){let r={...n},s=e.primaryKeys[0];if(!Lt(r[s])){let l=e.id;if(typeof l=="function")r[s]=l();else if(l==="database"){if(t==="memory")throw new j("MemoryAdapter does not support id:'database' (no database to generate the key)");delete r[s];}else r[s]=o?o():crypto.randomUUID();}let i=ie(e.timestamps);if(i.enabled){let l=Date.now();i.createdAt in n||(r[i.createdAt]=l),i.updatedAt in n||(r[i.updatedAt]=l);}return r}function We(n,e){let t=ie(e.timestamps);return t.enabled?{...n,[t.updatedAt]:Date.now()}:{...n}}function Ge(n,e){if(e==="memory"&&n.id==="database")throw new j("MemoryAdapter does not support id:'database' (no database to generate the key)")}function Ye(n,e){let t={...n};for(let o of v(e))delete t[o];return t}var Ut=new Set(["P2002","SQLITE_CONSTRAINT_UNIQUE","SQLITE_CONSTRAINT","23505","ER_DUP_ENTRY",1062,"1062"]),zt=/UNIQUE constraint failed|duplicate key value violates unique constraint|Duplicate entry/i;function Bt(n){if(!n||typeof n!="object")return false;let{code:e,message:t}=n;return (typeof e=="string"||typeof e=="number")&&Ut.has(e)?true:typeof t=="string"&&zt.test(t)}function*qt(n,e=8){for(let t=n,o=0;o<e&&t!=null&&typeof t=="object";o++)yield t,t=t.cause;}function ke(n){for(let e$1 of qt(n))if(Bt(e$1))return new e("Unique constraint violation");return null}function H(n){throw ke(n)??n}function Ht(n){return btoa(String(n))}function lo(n){try{return atob(n)}catch{return null}}function co(n){let{rows:e,limit:t,totalCount:o,cursorField:r,cursorApplied:s}=n,i=e.length>t,l=i?e.slice(0,t):e,d=l[l.length-1];return {items:l,result_info:{page:0,per_page:t,total_count:o,has_next_page:i,has_prev_page:s,next_cursor:i&&d!==void 0?Ht(d[r]):void 0}}}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 Je(n,e){return !e||Object.keys(e).length===0?n:Promise.all(n.map(t=>ae(t,e)))}function oe(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 pe(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 fo(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 Xe(n){let e=[],t={};for(let a of f){let p=n[a];if(p){let u=Array.isArray(p)?p:[p];for(let m of u)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(p=>p.trim()):Array.isArray(a)&&(o=a.filter(p=>typeof p=="string"));}let r;for(let[a,p]of Object.entries(n)){let u=a.match(/^having\[(\w+)\]\[(\w+)\]$/);if(u){let[,m,f]=u;r||(r={}),r[m]||(r[m]={}),r[m][f]=p;}}let s=typeof n.orderBy=="string"?n.orderBy:void 0,i=n.orderDirection==="desc"?"desc":"asc",l=typeof n.limit=="string"?Number.parseInt(n.limit,10):void 0,d=typeof n.offset=="string"?Number.parseInt(n.offset,10):void 0,c=[...f,"groupBy","orderBy","orderDirection","limit","offset"];for(let[a,p]of Object.entries(n))!c.includes(a)&&!a.startsWith("having[")&&(t[a]=p);return {aggregations:e,groupBy:o,filters:Object.keys(t).length>0?t:void 0,having:r,orderBy:s,orderDirection:i,limit:l,offset:d}}function et(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 re(n,e,t){return t.enabled&&e[t.field]!=null?{...n,[t.field]:null}:n}var $t=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 ot(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=>!$t.has(o)&&o.length>1):t}function rt(n,e){return e==="phrase"?[n.toLowerCase().trim()]:ot(n)}function Kt(n,e){return e.length===0?0:e.filter(o=>o===n||o.includes(n)).length/e.length}function nt(n,e,t,o){if(e.length===0)return {score:0,matchedFields:[]};let r=0,s=0,i=[];for(let[d,c]of Object.entries(t)){let a=n[d];if(a==null)continue;let p=c.weight??1;s+=p;let u;c.type==="array"&&Array.isArray(a)?u=a.join(" "):u=String(a);let m=ot(u,false),f=u.toLowerCase(),h=0,S=0;if(o==="phrase"){let g=e[0];f.includes(g)&&(h=1,S=1);}else {for(let g of e){let R=Kt(g,m);R>0?(S++,h+=R):f.includes(g)&&(S++,h+=.5/e.length);}e.length>0&&(h=h/e.length);}o==="all"&&S<e.length&&(h=0),h>0&&(i.push(d),r+=h*p);}return {score:s>0?Math.min(1,r/s):0,matchedFields:i}}function st(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=[],l=s.toLowerCase();if(t==="phrase"){let d=e[0],c=l.indexOf(d);if(c!==-1){let a=tt(s,c,d.length,r,o);a&&i.push(a);}}else {let d=[];for(let a of e){let p=0;for(;p<l.length;){let u=l.indexOf(a,p);if(u===-1)break;d.push({start:u,length:a.length}),p=u+1;}}d.sort((a,p)=>a.start-p.start);let c=new Set;for(let a of d){if(Array.from(c).some(m=>Math.abs(m-a.start)<r))continue;let u=tt(s,a.start,a.length,r,o);if(u&&(i.push(u),c.add(a.start)),i.length>=3)break}}return i}function tt(n,e,t,o,r){let s=Math.floor(o/2),i=Math.max(0,e-s),l=Math.min(n.length,e+t+s);if(i>0){let a=n.indexOf(" ",i);a!==-1&&a<e&&(i=a+1);}if(l<n.length){let a=n.lastIndexOf(" ",l);a!==-1&&a>e+t&&(l=a);}let d=n.slice(i,l);return i>0&&(d="..."+d),l<n.length&&(d=d+"..."),Qt(d,[n.slice(e,e+t)],r)}function Qt(n,e,t){let o=n,r=n.toLowerCase(),s=[...e].sort((i,l)=>l.length-i.length);for(let i of s){let l=i.toLowerCase(),d=0,c="",a=0;for(;a<r.length;){let p=r.indexOf(l,a);if(p===-1)break;c+=o.slice(d,p),c+=`<${t}>${o.slice(p,p+i.length)}</${t}>`,d=p+i.length,a=d;}c&&(c+=o.slice(d),o=c);}return o}function it(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 at(n,e){let t={};for(let o of n)t[o]={weight:e?.[o]??1};return t}function dt(n){return n==="all"||n==="phrase"?n:"any"}function xe(n){if(n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(xe);let e={};for(let t of Object.keys(n).sort())e[t]=xe(n[t]);return e}async function de(n){let e=JSON.stringify(xe(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 lt(n,e){return n?n==="*"?true:n.split(",").map(t=>t.trim()).includes(e):false}function ct(n,e){return !n||n==="*"?true:n.split(",").map(t=>t.trim()).includes(e)}function ut(n,e){return n==="in"||n==="nin"||n==="between"?e.split(",").map(t=>t.trim()):n==="null"?e.toLowerCase()==="true":e}function Ro(n){let e=n.match(/^\[([a-z]+)\](.*)$/);if(e&&b(e[1])){let t=e[1];return {operator:t,value:ut(t,e[2])}}return {operator:"eq",value:n}}function ne(n,e){let t=[],o={},{filterFields:r=[],filterConfig:s={},searchFields:i=[],searchParamName:l="search",sortFields:d=[],defaultSort:c,defaultPerPage:a=20,maxPerPage:p=100,cursorPaginationEnabled:u=false,cursorField:m,softDeleteQueryParam:f="withDeleted",allowedIncludes:h=[],fieldSelectionEnabled:S=false,allowedSelectFields:g=[],blockedSelectFields:R=[],alwaysIncludeFields:j=[],defaultSelectFields:N=[]}=e,J={};for(let C of r)J[C]=["eq"];Object.assign(J,s);for(let[C,Me]of Object.entries(n)){if(Me==null)continue;let D=String(Me);if(u&&C==="cursor"){o.cursor=D;continue}if(u&&C==="limit"){o.limit=Math.min(p,Math.max(1,Number.parseInt(D,10)||a));continue}if(C==="page"){o.page=Math.max(1,Number.parseInt(D,10)||1);continue}if(C==="per_page"){o.per_page=Math.min(p,Math.max(1,Number.parseInt(D,10)||a));continue}if(C==="sort"){(d.length===0||d.includes(D))&&(o.order_by=D);continue}if(C==="order"){(D==="asc"||D==="desc")&&(o.order_by_direction=D);continue}if(C===l&&i.length>0){o.search=D;continue}if(C===f){o.withDeleted=D.toLowerCase()==="true";continue}if(C==="onlyDeleted"){o.onlyDeleted=D.toLowerCase()==="true";continue}if(C==="include"){let X=D.split(",").map(U=>U.trim()).filter(Boolean);h&&h.length>0?o.include=X.filter(U=>h.includes(U)):o.include=X;continue}if(C==="fields"&&S){let U=D.split(",").map(se=>se.trim()).filter(Boolean);g.length>0&&(U=U.filter(se=>g.includes(se))),R.length>0&&(U=U.filter(se=>!R.includes(se))),j.length>0&&(U=[...new Set([...j,...U])]),o.fields=U;continue}let Re=C.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(Re){let X=Re[1],U=Re[2];J[X]?.includes(U)&&t.push({field:X,operator:U,value:ut(U,D)});continue}J[C]&&t.push({field:C,operator:"eq",value:D});}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"),u&&(o.cursor!==void 0||o.limit!==void 0)&&(o.order_by=m??"id",o.order_by_direction="asc"),S&&!o.fields&&N.length>0){let C=[...N];j.length>0&&(C=[...new Set([...j,...C])]),o.fields=C;}return {filters:t,options:o}}function _(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 So(n,e={},t=[],o=[],r=[]){let{allowedFields:s=[],blockedFields:i=[],alwaysIncludeFields:l=[],defaultFields:d=[],allowComputedFields:c=true,allowRelationFields:a=true}=e;if(!n||typeof n!="string"||n.trim()==="")return d.length>0?{fields:[...new Set([...l,...d])],isActive:false}:{fields:[],isActive:false};let p=n.split(",").map(h=>h.trim()).filter(Boolean),u=new Set;for(let h of t)(s.length===0||s.includes(h))&&(i.includes(h)||u.add(h));if(c)for(let h of o)(s.length===0||s.includes(h))&&(i.includes(h)||u.add(h));if(a)for(let h of r)(s.length===0||s.includes(h))&&(i.includes(h)||u.add(h));let m=p.filter(h=>u.has(h));return {fields:[...new Set([...l,...m])],isActive:true}}function je(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 pt(n,e){return !e.isActive||e.fields.length===0?n:n.map(t=>je(t,e))}var mt="__honoCrudResolvedSchema:";function Wt(n){return typeof n.getBodySchema=="function"}var k=class extends p{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=h$1(this._meta.model.audit,void 0,this.context??void 0)),this._auditLogger}getAuditConfig(){return a(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$2.userId):void 0}getVersionManager(){return this._versionManager||(this._versionManager=i(this._meta.model.versioning,this._meta.model.tableName,void 0,this.context??void 0)),this._versionManager}getVersioningConfig(){return a$3(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$2.userId):void 0}getSoftDeleteConfig(){return et(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return a$4(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,t,o){return Qe(e,this._meta.model,t,o)}applyManagedUpdateFields(e){return We(e,this._meta.model)}assertIdStrategySupported(e){Ge(this._meta.model,e);}getTimestampsConfig(){return ie(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return b$3(this.context,e)}getRelationScope(e=false){return {tenantId:this.getTenantId(),includeDeleted:e}}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();if(!t&&e.required)throw new b$2(e.errorMessage,400,"TENANT_REQUIRED");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=e$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$2.organizationId):void 0,timestamp:new Date().toISOString(),metadata:t.metadata});}async encryptOnWrite(e){let t=this._meta.model.fieldEncryption;return t?await e$3(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$5(e,t):e}applyProfileToArray(e){let t=this._meta.model.serializationProfile;return t?b$4(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),l=this.transform(i);return t?.isActive&&t.fields.length>0?je(l,t):l}async finalizeArray(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await Je(r,o.computedFields));let s=o.serializer?r.map(d=>o.serializer(d)):r,l=this.applyProfileToArray(s).map(d=>this.transform(d));return t?.isActive&&t.fields.length>0?pt(l,t):l}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,y);if(e)return e}return this._meta.model.policies}buildPolicyContext(){let e=this.context;return {user:e?a$1(e,a$2.user):void 0,userId:e?a$1(e,a$2.userId):void 0,tenantId:e?a$1(e,a$2.tenantId):void 0,organizationId:e?a$1(e,a$2.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 g("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$2.organizationId):void 0,userId:e?a$1(e,a$2.userId):void 0,agentId:e?a$1(e,a$2.agentId):void 0,agentRunId:e?a$1(e,a$2.agentRunId):void 0}}getModelSchema(){if(this.context&&this._meta.model.resolveSchema){let e=a$1(this.context,mt+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=mt+this._meta.model.tableName,o=a$1(this.context,t);if(o)return o;let r={tenantId:a$1(this.context,a$2.tenantId),organizationId:a$1(this.context,a$2.organizationId),request:this.context.req?.raw,env:this.context.env},s;try{s=await e(r);}catch(i){throw new b$2(i instanceof Error?i.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",i instanceof Error?{cause:i.message}:void 0)}return b$5(this.context,t,s),s}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&Wt(this)){let t=e.body;try{t=await this.context.req.json();}catch{}let r=this.getBodySchema().safeParse(t);if(!r.success)throw c$1.fromZodError(r.error);e.body=r.data;}return e}};var ht=class extends k{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,t=v(this._meta.model),o=this.getMultiTenantConfig();o.enabled&&t.push(o.field),this._meta.fields?e=this._meta.fields:e=_(this.getModelSchema(),t);let r=this.getNestedWritableRelations();if(r.length===0)return e;let s={...e.shape};for(let i of r){let l=this._meta.model.relations?.[i];if(!l?.schema)continue;let d=["id",l.foreignKey],c=_(l.schema,d);l.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 oe(e,t)}getSchema(){let e=this.getBodySchema();return N({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:P("Validation error")}},this.schema)}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(H),r=await this.decryptOnRead(r);let i=this.getParentId(r),l={};if(Object.keys(o).length>0&&i!==null)for(let[c,a]of Object.entries(o)){if(a==null)continue;let p=this._meta.model.relations?.[c];if(!p)continue;let u=await this.createNested(i,c,p,a);l[c]=u;}if(Object.keys(l).length>0){let c={};for(let[a,p]of Object.entries(l)){let u=this._meta.model.relations?.[a];u&&(u.type==="hasMany"?c[a]=p:c[a]=p[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 d=await this.finalizeRecord(r);return this.success(d,201)}};function he(n,e,t){let o=e.model.relations;if(!o||t.length===0)return n;let r={};for(let s of t){let i=o[s],l=i?.schema;l&&(r[s]=i.type==="hasMany"?z.array(l).optional():l.nullable().optional());}return Object.keys(r).length>0?n.extend(r):n}var ft=class extends k{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 N({request:{params:this.getParamsSchema(),...e&&{query:e}},responses:{200:{description:"Resource retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:he(this.getModelSchema(),this._meta,this.allowedIncludes)})}}},404:P("Resource not found")}},this.schema)}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();r&&(r.scope=this.getRelationScope());let 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 d(this._meta.model.tableName,t);i=await this.decryptOnRead(i);let l=await this.applyReadPolicy(i);if(l===null)throw new d(this._meta.model.tableName,t);i=l,i=await this.after(i);let d$1=await this.finalizeRecord(i,s);if(this.etagEnabled){let c=await de(d$1),a=this.getContext(),p=a.req.header("If-None-Match");if(lt(p,c))return new Response(null,{status:304,headers:{ETag:c}});a.header("ETag",c);}return this.success(d$1)}};var gt=class extends k{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=v(this._meta.model);this.blockedUpdateFields&&(r=[...r,...this.blockedUpdateFields]);let s=_(this.getModelSchema(),r);if(this.allowedUpdateFields){let i={};for(let l of this.allowedUpdateFields)i[l]=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,l=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]=l;}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 oe(e,t)}getSchema(){return N({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:P("Validation error"),404:P("Resource not found")}},this.schema)}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 g=this.getMultiTenantConfig();o[g.field]=e;}let r=await this.getObject(),{mainData:s,nestedData:i}=this.extractNestedData(r),l=this.getPolicies(),d$1=await this.findExisting(t,o,this._tx);if(d$1&&l?.write&&await this.applyWritePolicy(d$1),this.etagEnabled&&d$1){let g=this.getContext().req.header("If-Match");if(g){let R=await de(d$1);if(!ct(g,R))return this.error("Resource has been modified by another request","CONFLICT",409)}}let c;if(this.isVersioningEnabled()&&d$1){let g=this.getVersionManager(),R=this.getParentId(d$1);R!==null&&(c=await g.saveVersion(R,d$1,void 0,this.getVersioningUserId()));}let a=s;if(this.isVersioningEnabled()&&c!==void 0){let g=this.getVersioningConfig().field;a[g]=c;}let p=this.buildHookContext();a=await this.before(a,p),a=await this.encryptOnWrite(a);let u=await this.update(t,a,o,p.db.tx);if(!u)throw new d(this._meta.model.tableName,t);u=await this.decryptOnRead(u);let m=this.getParentId(u),f={};if(Object.keys(i).length>0&&m!==null)for(let[g,R]of Object.entries(i)){if(R==null)continue;let j=this._meta.model.relations?.[g];if(!j)continue;let N;pe(R)?N={create:R}:N=R;let J=await this.processNestedWrites(m,g,j,N);f[g]=J;}if(Object.keys(f).length>0)for(let[g,R]of Object.entries(f)){let j=this._meta.model.relations?.[g];j&&(j.type==="hasMany"?u[g]=[...R.created,...R.updated]:u[g]=R.created[0]||R.updated[0]||null);}let h=d$1??u;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(h,u,p)));else {let g=await this.after(h,u,p);g!=null&&(u=g);}if(this.isAuditEnabled()&&m!==null&&d$1){let g=this.getAuditLogger();this.runAfterResponse(g.logUpdate(this._meta.model.tableName,m,d$1,u,this.getAuditUserId()));}m!==null&&this.runAfterResponse(this.emitEvent("updated",{recordId:m,data:u,previousData:d$1??void 0}));let S=await this.finalizeRecord(u);if(this.etagEnabled){let g=await de(S);this.getContext().header("ETag",g);}return this.success(S)}};var bt=class extends k{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 N({request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:P("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()})})}}}}},this.schema)}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:l,config:d,action:c}of s)if(c==="cascade"){let a=await this.deleteRelated(e,l,d,o);a>0&&(i.deleted[l]=a);}else if(c==="setNull"){let a=await this.nullifyRelated(e,l,d,o);a>0&&(i.nullified[l]=a);}return i}async checkRestrictConstraints(e$1,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r);for(let{name:i,config:l,action:d}of s)if(d==="restrict"){let c=await this.countRelated(e$1,i,l,o);if(c>0)throw new e(`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 p=this.getMultiTenantConfig();o[p.field]=e;}let r=this.isSoftDeleteEnabled(),s=await this.findForDelete(t,o,this._tx);if(!s)throw new d(this._meta.model.tableName,t);let i=this.getParentId(s);i!==null&&await this.checkRestrictConstraints(i,r),await this.applyWritePolicy(s);let l=this.buildHookContext();if(await this.before(t,l),!await this.delete(t,o,l.db.tx))throw new d(this._meta.model.tableName,t);let c;if(i!==null&&(c=await this.processCascade(i,r)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(s,l))):await this.after(s,l),this.isAuditEnabled()&&i!==null){let p=this.getAuditLogger();this.runAfterResponse(p.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){let p=Object.keys(c.deleted).length>0,u=Object.keys(c.nullified).length>0;(p||u)&&(a.cascade=c);}return this.success(a)}};var fe=class extends k{filterFields=[];filterConfig;searchFields=[];searchParamName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;supportsCursorPagination=false;cursorField;isCursorPaginationActive(){return this.cursorPaginationEnabled&&this.supportsCursorPagination}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.searchParamName]=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.isCursorPaginationActive()&&(e.cursor=z.string().optional().meta({description:"Opaque cursor for fetching the next page. During a cursor walk, results are ordered by the cursor field ascending and sort/order are ignored."}),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(){let e={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()};return this.isCursorPaginationActive()&&(e.next_cursor=z.string().optional()),N({request:{query:this.getQuerySchema()},responses:{200:{description:"List of resources",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(he(this.getModelSchema(),this._meta,this.allowedIncludes)),result_info:z.object(e)})}}},400:P("Validation error")}},this.schema)}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:this.searchFields,searchParamName:this.searchParamName,sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,cursorPaginationEnabled:this.isCursorPaginationActive(),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 ne(e||{},o)}async after(e){return e}transform(e){return e}async handle(){if(this.cursorPaginationEnabled&&!this.supportsCursorPagination)throw new j("cursorPaginationEnabled is true but this adapter's List endpoint does not implement cursor pagination (supportsCursorPagination is false). Use an adapter List endpoint that supports it, or disable cursorPaginationEnabled.");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),l=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?{fields:t.options.fields,isActive:true}:void 0,d=await this.finalizeArray(i,l);return this.successPaginated(d,o.result_info)}};var yt=class extends k{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...v(this._meta.model),...this.excludeFromClone];return _(this.getModelSchema(),e).partial()}getSchema(){return N({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:P("Source resource not found"),409:P("Unique-constraint violation (e.g. natural-key collision)")}},this.schema)}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 d(this._meta.model.tableName,t);let i=Ye(s,this._meta.model);for(let a of this.excludeFromClone)delete i[a];Object.assign(i,o);let l=await this.before(i),d$1=await this.createClone(l).catch(H);d$1=await this.after(d$1);let c=await this.finalizeRecord(d$1);return this.success(c,201)}};var wt=class extends k{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:P("Soft delete not enabled or record not deleted"),404:P("Resource not found")}},this.schema)}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 b$2("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 d(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 Mt=class extends k{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=v(this._meta.model,{includePrimaryKeys:false});for(let d of this._meta.model.primaryKeys)r.includes(d)||s.push(d);let i=_(this.getModelSchema(),s),l={};for(let[d,c]of Object.entries(i.shape))r.includes(d)?l[d]=c:l[d]=c.optional();e=z.object(l);}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,l=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]=l;}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 oe(e,t)}getSchema(){return N({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:P("Validation error")}},this.schema)}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),r=re(r,o,this.getSoftDeleteConfig()),{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 l=await this.upsert(r).catch(H),d=l.data,c=this.getParentId(d),a={};if(Object.keys(o).length>0&&c!==null)for(let[u,m]of Object.entries(o)){if(m==null)continue;let f=this._meta.model.relations?.[u];if(!f)continue;let h;pe(m)?h={create:m}:h=m;let S=await this.processNestedWrites(c,u,f,h);a[u]=S;}if(Object.keys(a).length>0)for(let[u,m]of Object.entries(a)){let f=this._meta.model.relations?.[u];f&&(f.type==="hasMany"?d[u]=[...m.created,...m.updated]:d[u]=m.created[0]||m.updated[0]||null);}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(d,l.created))):d=await this.after(d,l.created),this.isAuditEnabled()&&c!==null){let u=this.getAuditLogger();this.runAfterResponse(u.logUpsert(this._meta.model.tableName,c,d,s,l.created,this.getAuditUserId()));}let p=await this.finalizeRecord(d);return this.json({success:true,result:p,created:l.created},l.created?201:200)}};var Rt=class extends k{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:_(this.getModelSchema(),v(this._meta.model));return z.object({items:z.array(e).min(1).max(this.maxBatchSize)})}getSchema(){return N({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:P("Validation error")}},this.schema)}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(H),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(p=>{let u=this.getRecordId(p);return u===null?null:{recordId:u,record:p}}).filter(p=>p!==null);a.length>0&&this.runAfterResponse(c.logBatch("batch_create",this._meta.model.tableName,a,this.getAuditUserId()));}let i=await this.finalizeArray(s),l={success:true,result:{created:i,count:i.length,...t.length>0&&{errors:t}}},d=t.length>0?207:201;return this.json(l,d)}};var St=class extends k{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:_(this.getModelSchema(),v(this._meta.model));return z.object({items:z.array(z.object({id:z.string(),data:e.partial()})).min(1).max(this.maxBatchSize)})}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("updated",this.getModelSchema(),"Resources updated successfully"),400:P("Validation error")}},this.schema)}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 p=this.filterUpdateData(a.data),u=await this.before(a.id,p);o.push({id:a.id,data:u});}catch(p){if(this.stopOnError)throw p;t.push({id:a.id,error:p instanceof Error?p.message:String(p)});}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(p){let u=String(a[this.lookupField]);if(this.stopOnError)throw p;t.push({id:u,error:p instanceof Error?p.message:String(p)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),p=i.map(u=>{let m=this.getRecordId(u);return m===null?null:{recordId:m,record:u}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(a.logBatch("batch_update",this._meta.model.tableName,p,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{updated:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(d,c)}};var Ot=class extends k{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return R(this.maxBatchSize)}getSchema(){let e=this.isSoftDeleteEnabled();return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("deleted",this.getModelSchema(),e?"Resources soft-deleted successfully":"Resources deleted successfully"),400:P("Validation error")}},this.schema)}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(p){if(this.stopOnError)throw p;t.push({id:a,error:p instanceof Error?p.message:String(p)});}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(p){let u=String(a[this.lookupField]);if(this.stopOnError)throw p;t.push({id:u,error:p instanceof Error?p.message:String(p)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),p=i.map(u=>{let m=this.getRecordId(u);return m===null?null:{recordId:m,previousRecord:u}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(a.logBatch("batch_delete",this._meta.model.tableName,p,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{deleted:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(d,c)}};var kt=class extends k{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return R(this.maxBatchSize)}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("restored",this.getModelSchema(),"Resources restored successfully"),400:P("Soft delete not enabled or validation error")}},this.schema)}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 b$2("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(p){if(this.stopOnError)throw p;t.push({id:a,error:p instanceof Error?p.message:String(p)});}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(p){let u=String(a[this.lookupField]);if(this.stopOnError)throw p;t.push({id:u,error:p instanceof Error?p.message:String(p)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),p=i.map(u=>{let m=this.getRecordId(u);return m===null?null:{recordId:m,record:u}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(a.logBatch("batch_restore",this._meta.model.tableName,p,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{restored:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(d,c)}};var xt=class extends k{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=v(this._meta.model,{includePrimaryKeys:false});for(let s of this._meta.model.primaryKeys)e.includes(s)||t.push(s);let o=_(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 N({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:P("Validation error")}},this.schema)}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),l;if(r){if(this.createOnlyFields)for(let c of this.createOnlyFields)delete i[c];let d=re(i,r,this.getSoftDeleteConfig());l=await this.update(r,d,o);}else {if(this.updateOnlyFields)for(let d of this.updateOnlyFields)delete i[d];l=await this.create(i,o);}return l=await this.afterItem(l,t,s,o),{data:l,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 d=0;d<e.length;d++)try{let c=await this.upsertOne(e[d],d,t);o.push(c),c.created?s++:i++;}catch(c){if(this.continueOnError)r.push({index:d,error:c instanceof Error?c.message:String(c)});else throw c}let l={items:o,createdCount:s,updatedCount:i,totalCount:o.length};return r.length>0&&(l.errors=r),l}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(H);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 jt=class extends k{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getUpdateSchema(){let e=v(this._meta.model);return _(this.getModelSchema(),e).partial()}getSchema(){let e=this.getUpdateSchema();return N({request:{body:{content:{"application/json":{schema:e.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:P("Bulk patch rejected (empty body, size limit, or missing confirmation)")}},this.schema)}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=ne(e.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),l=await this.countMatching(i);if(l===0)return this.json({success:true,matched:0,updated:0,dryRun:s});if(l>this.maxBulkSize)return this.error(`Bulk patch affects ${l} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(l>=this.confirmThreshold&&e.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${l} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(s)return this.json({success:true,matched:l,updated:0,dryRun:true});let d=o;this.beforeBulkPatch&&(d=await this.beforeBulkPatch(d,i,l));let c=await this.applyPatch(d,i),a={matched:l,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 Ct=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()}),Ft=class extends k{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 N({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(Ct),totalVersions:z.number()})})}}},400:P("Versioning not enabled"),404:P("Record not found")}},this.schema)}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 b$2("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 d(this._meta.model.tableName,e);let s=this.getVersionManager(),i=await s.getVersions(e,{limit:t,offset:o}),l=await s.getLatestVersion(e);return this.success({versions:i,totalVersions:l})}},Pt=class extends k{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:Ct})}}},400:P("Versioning not enabled"),404:P("Version not found")}},this.schema)}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 b$2("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 d(`version ${t}`,e);return this.success(r)}},It=class extends k{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 N({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:P("Versioning not enabled or invalid parameters"),404:P("Version not found")}},this.schema)}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 b$2("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})}},Et=class extends k{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return N({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:P("Versioning not enabled"),404:P("Version not found")}},this.schema)}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 b$2("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 d(`version ${t}`,e);let i=await o.getLatestVersion(e)+1,l=await this.rollback(e,r.data,i),d$1=this._meta.model.serializer?this._meta.model.serializer(l):l;return this.success(d$1)}};var Yt={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},At=class extends k{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {...Yt,...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 N({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:P("Invalid aggregation request")}},this.schema)}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return Xe(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 h(`Field '${o.field}' is not allowed for SUM aggregation`);break;case "avg":if(t.avgFields.length>0&&!t.avgFields.includes(o.field))throw new h(`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 h(`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 h(`Field '${o.field}' is not allowed for COUNT DISTINCT aggregation`);break;default:c(o.operation);}if(e.groupBy){if(e.groupBy.length>this.maxGroupByFields)throw new h(`Maximum ${this.maxGroupByFields} GROUP BY fields allowed`);for(let o of e.groupBy)if(t.groupByFields.length>0&&!t.groupByFields.includes(o))throw new h(`Field '${o}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>t.maxLimit)throw new h(`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 after(e){return e}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.after(await this.aggregate(e));return this.success(o)}},Jt={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 Xt(n,e){let t=n.get(e);if(t)return t;let o=[];return n.set(e,o),o}function zn(n,e){let{aggregations:t,groupBy:o,having:r,orderBy:s,orderDirection:i,limit:l,offset:d}=e;if(!o||o.length===0){let u={};for(let m of t){let f=_t(m);u[f]=vt(n,m);}return {values:u}}let c=new Map;for(let u of n){let f=o.map(h=>String(u[h]??"null")).join("|");Xt(c,f).push(u);}let a=[];for(let[u,m]of c){let f=u.split("|"),h={};o.forEach((g,R)=>{h[g]=f[R]==="null"?null:f[R];});let S={};for(let g of t){let R=_t(g);S[R]=vt(m,g);}a.push({key:h,values:S});}r&&(a=a.filter(u=>{for(let[m,f]of Object.entries(r)){let h=u.values[m];if(h!==null)for(let[S,g]of Object.entries(f)){let R=Jt[S];if(R&&!R(h,Number(g)))return false}}return true}));let p=a.length;if(s){let u=i==="desc"?-1:1;a.sort((m,f)=>{if(s in m.values){let h=m.values[s]??0,S=f.values[s]??0;return (h-S)*u}if(s in m.key){let h=String(m.key[s]??""),S=String(f.key[s]??"");return h.localeCompare(S)*u}return 0});}if(d!==void 0||l!==void 0){let u=d||0,m=l?u+l:void 0;a=a.slice(u,m);}return {groups:a,totalGroups:p}}function Fe(n,e){return n.map(t=>t[e]).filter(t=>typeof t=="number")}var eo={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=Fe(n,e);return t.length===0?null:t.reduce((r,s)=>r+s,0)/t.length},min:(n,e)=>{let t=Fe(n,e);return t.length===0?null:Math.min(...t)},max:(n,e)=>{let t=Fe(n,e);return t.length===0?null:Math.max(...t)}};function vt(n,e){if(n.length===0)return e.operation==="count"?0:null;let t=eo[e.operation];return t?t(n,e.field):null}function _t(n){return n.alias?n.alias:n.field==="*"?n.operation:`${n.operation}${n.field.charAt(0).toUpperCase()}${n.field.slice(1)}`}function to(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 Tt=class extends k{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 at(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,t={};for(let[o,r]of Object.entries(e))to(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$1).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 N({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:P("Invalid search request")}},this.schema)}async getSearchOptions(){let{query:e}=await this.getValidatedData(),t=this.searchParamName||"q",o=e?.[t],r=e?.fields,s=dt(e?.mode),i=e?.highlight==="true",l=e?.minScore?Math.max(0,Math.min(1,Number.parseFloat(e.minScore)||0)):this.defaultMinScore,d=this.getSearchableFields(),c=it(r,d);return {query:o,fields:c.length>0?c:Object.keys(d),mode:s??this.defaultMode,highlight:i,minScore:l}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchParamName:"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 ne(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)throw new b$2(`Search query must be at least ${this.minQueryLength} characters`,400,"INVALID_QUERY");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(u=>u.item),s),l=r.map((u,m)=>({...u,item:i[m]})),d=o.postFilteredCount??o.totalCount,c=t.options.page||1,a=t.options.per_page||this.defaultPerPage,p=Math.ceil(d/a);return this.successPaginated(l,{page:c,per_page:a,total_count:d,total_pages:p,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function Yn(n,e,t){let o=rt(e.query,e.mode),r={},s=e.fields||Object.keys(t);for(let l of s)t[l]&&(r[l]=t[l]);let i=[];for(let l of n){let{score:d,matchedFields:c}=nt(l,o,r,e.mode);if(d<e.minScore||c.length===0)continue;let a;if(e.highlight){a={};for(let p of c){let u=st(l[p],o,e.mode);u.length>0&&(a[p]=u);}}i.push({item:l,score:d,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:c});}return i.sort((l,d)=>d.score-l.score),i}function $(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 $(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 Pe(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
3
+ `,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:l={},nullValue:d="",dateFormat:c="iso"}=e;if(n.length===0)return "";let a=e.headers;a?a=a.filter(u=>!i.includes(u)):a=Object.keys(n[0]).filter(u=>!i.includes(u));let p=[];if(r){let u=a.map(m=>{let f=l[m]||m;return $(f,{delimiter:t,nullValue:d,dateFormat:c})});p.push(u.join(t));}for(let u of n){let m=a.map(f=>{let h=u[f];return s[f]&&(h=s[f](h)),$(h,{delimiter:t,nullValue:d,dateFormat:c})});p.push(m.join(t));}return p.join(o)}function Xn(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
4
+ `,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:l={},nullValue:d="",dateFormat:c="iso"}=e,a=new TextEncoder,p=0,u=false,m=e.headers;return !m&&n.length>0?m=Object.keys(n[0]).filter(f=>!i.includes(f)):m?m=m.filter(f=>!i.includes(f)):m=[],new ReadableStream({pull(f){if(r&&!u&&m.length>0){let g=m.map(R=>{let j=l[R]||R;return $(j,{delimiter:t,nullValue:d,dateFormat:c})});f.enqueue(a.encode(g.join(t)+o)),u=true;return}let h=100,S=[];for(;p<n.length&&S.length<h;){let g=n[p],R=m.map(j=>{let N=g[j];return s[j]&&(N=s[j](N)),$(N,{delimiter:t,nullValue:d,dateFormat:c})});S.push(R.join(t)),p++;}S.length>0&&f.enqueue(a.encode(S.join(o)+o)),p>=n.length&&f.close();}})}function Nt(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 oo(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 Ie(n,e={}){let{delimiter:t=",",hasHeader:o=true,trimValues:r=true,skipEmptyRows:s=true,parsers:i={},emptyValue:l="empty"}=e,d={data:[],headers:[],errors:[]},c=oo(n);if(c.length===0)return d;let a=0;if(o){let u=c[0];d.headers=Nt(u,t).map(m=>r?m.trim():m),a=1;}else e.headers&&(d.headers=e.headers);let p=e.headers||d.headers;for(let u=a;u<c.length;u++){let m=c[u],f=u+1;if(!(s&&m.trim()===""))try{let h=Nt(m,t),S={};for(let g=0;g<p.length;g++){let R=p[g],j=g<h.length?h[g]:"";if(r&&typeof j=="string"&&(j=j.trim()),j==="")switch(l){case "null":j=null;break;case "undefined":j=void 0;break}if(i[R]&&typeof j=="string")try{j=i[R](j);}catch(N){d.errors.push({row:f,message:`Failed to parse field "${R}": ${N instanceof Error?N.message:String(N)}`,content:m});}S[R]=j;}d.data.push(S);}catch(h){d.errors.push({row:f,message:`Failed to parse row: ${h instanceof Error?h.message:String(h)}`,content:m});}}return d}function Dt(n,e,t={}){let{allowUnknownFields:o=false,optionalFields:r=[]}=t,s=e.shape,i=Object.keys(s),d=i.filter(u=>r.includes(u)?false:!s[u].isOptional()).filter(u=>!n.includes(u)),c=n.filter(u=>!i.includes(u)),a=n.filter(u=>i.includes(u));return {valid:d.length===0&&(o||c.length===0),missingFields:d,unknownFields:c,validFields:a}}function es(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 ts(n,e={}){return Pe(n,e)}function os(n,e={}){return Ie(n,e).data}var Vt=class extends fe{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 N({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()}}},400:P("Validation error")}},this.schema)}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=Pe(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 l=>{if(o.header("Content-Type","text/csv; charset=utf-8"),o.header("Content-Disposition",`attachment; filename="${r}"`),e.length===0)return;let d=Object.keys(e[0]).filter(p=>!i.includes(p)),c=d.map(p=>$(p,s)).join(",")+`
8
+ `;await l.write(c);let a=100;for(let p=0;p<e.length;p+=a)for(let u of e.slice(p,p+a)){let m=d.map(f=>$(u[f],s)).join(",")+`
9
+ `;await l.write(m);}})}exportAsCsvStreamPaginated(e,t){let o=this.getExportFilename(t),r=this.streamPageSize,s=Math.min(this.maxExportRecords,1e5),i=this.excludedExportFields,l=this.csvOptions,d=null,c=new ReadableStream({start:async a=>{let p=new TextEncoder,u=1,m=0;try{for(;m<s;){let f={...e,options:{...e.options,page:u,per_page:r}},S=(await this.list(f)).result;if(S.length===0)break;S.length>s-m&&(S=S.slice(0,s-m)),S=await this.after(S),S=await this.beforeExport(S);let g=this.prepareRecordsForExport(S);if(!d&&g.length>0){d=Object.keys(g[0]).filter(j=>!i.includes(j));let R=d.map(j=>$(j,l)).join(",")+`
10
+ `;a.enqueue(p.encode(R));}if(d)for(let R of g){let j=d.map(N=>$(R[N],l)).join(",")+`
11
+ `;a.enqueue(p.encode(j));}if(m+=S.length,u++,S.length<r)break}}catch(f){a.error(f);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 Zt=class extends k{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:_(this.getModelSchema(),v(this._meta.model));return z.object({items:z.array(e.partial()).min(1).max(this.maxBatchSize)})}getSchema(){return N({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:P("Validation error")}},this.schema)}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 c$1("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 c$1("Request body is empty");if(!o.items||!Array.isArray(o.items))throw new c$1('Request body must contain an "items" array');if(o.items.length>this.maxBatchSize)throw new c$1(`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 c$1(`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 c$1("No file provided in form data");let s=await r.text();if(s.length>this.maxBodySize)throw new c$1(`Uploaded file exceeds maximum size of ${this.maxBodySize} bytes`);let i=r.name.toLowerCase();if(i.endsWith(".json")){let d;try{d=JSON.parse(s);}catch{throw new c$1("Invalid JSON content in uploaded file")}let c=Array.isArray(d)?d:d.items;if(!c||!Array.isArray(c))throw new c$1('JSON file must contain an array or an object with "items" array');if(c.length>this.maxBatchSize)throw new c$1(`Maximum ${this.maxBatchSize} items allowed per import`);return c}if(i.endsWith(".csv"))return this.parseCsvData(s);let l=s.trim();if(l.startsWith("[")||l.startsWith("{")){let d;try{d=JSON.parse(s);}catch{throw new c$1("Invalid JSON content in uploaded file")}let c=Array.isArray(d)?d:d.items;if(!c||!Array.isArray(c))throw new c$1('JSON file must contain an array or an object with "items" array');return c}return this.parseCsvData(s)}throw new c$1("Unsupported content type. Use application/json, text/csv, or multipart/form-data")}parseCsvData(e){let t=Ie(e,this.csvOptions);if(t.errors.length>0)throw new c$1(`CSV parsing errors: ${t.errors.map(s=>`Row ${s.row}: ${s.message}`).join("; ")}`);if(t.data.length===0)throw new c$1("CSV file is empty");if(t.data.length>this.maxBatchSize)throw new c$1(`Maximum ${this.maxBatchSize} items allowed per import`);let o=this._meta.fields||this.getModelSchema(),r=Dt(t.headers,o,{allowUnknownFields:true,optionalFields:this.optionalImportFields});if(!r.valid&&r.missingFields.length>0)throw new c$1(`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 v(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(d=>({path:d.path.join("."),message:d.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 d=await this.findExisting(i,r);if(d){let c=re(this.removeImmutableFields(i),d,this.getSoftDeleteConfig()),a=await this.update(d,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 l=await this.create(i,r);return {rowNumber:t,status:"created",data:l}}catch(i){let l=ke(i);return l?{rowNumber:t,status:"failed",code:"CONFLICT",error:l.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 j("importBatchSize must be a positive integer");let o={total:t.length,created:0,updated:0,skipped:0,failed:0},r=[],s=false,i=e.stopOnError?1:this.importBatchSize;for(let c=0;c<t.length&&!s;c+=i){let a=t.slice(c,c+i),p=await Promise.all(a.map(async(u,m)=>{let f=c+m+1,h=await this.processRow(u,f,e);return h=await this.after(h,f,e.mode),h}));for(let u of p){switch(r.push(u),u.status){case "created":o.created++;break;case "updated":o.updated++;break;case "skipped":o.skipped++;break;case "failed":o.failed++;break}if(e.stopOnError&&u.status==="failed"){s=true;break}}}if(this.isAuditEnabled()){let c=this.getAuditLogger(),a=r.filter(p=>p.status==="created"||p.status==="updated");if(a.length>0){let p=a.map(u=>{if(!u.data)return null;let m=this.getRecordId(u.data);return m===null?null:{recordId:m,record:u.data}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(c.logBatch(e.mode==="upsert"?"batch_upsert":"batch_create",this._meta.model.tableName,p,this.getAuditUserId()));}}let l={summary:o,results:r},d=o.failed>0&&o.failed<o.total?207:200;return this.json({success:true,result:l},d)}};var we=Symbol.for("hono-crud.resource-registry");function ws(n,e,t){let o=n;o[we]||(o[we]=[]),o[we].push({path:e,endpoints:t});}function Ms(n){return n[we]??[]}export{Ft as $,it as A,at as B,dt as C,de as D,lt as E,ct as F,Ro as G,ne as H,_ as I,So as J,je as K,pt as L,ht as M,he as N,ft as O,gt as P,bt as Q,fe as R,yt as S,wt as T,Mt as U,Rt as V,St as W,Ot as X,kt as Y,xt as Z,jt as _,no as a,Pt as aa,ie as b,It as ba,v as c,Et as ca,Qe as d,At as da,We as e,zn as ea,Ge as f,Tt as fa,Ye as g,Yn as ga,qt as h,$ as ha,ke as i,Pe as ia,H as j,Xn as ja,Ht as k,Ie as ka,lo as l,Dt as la,co as m,es as ma,ae as n,ts as na,Je as o,os as oa,oe as p,Vt as pa,pe as q,Zt as qa,fo as r,ws as ra,Xe as s,Ms as sa,et as t,re as u,ot as v,rt as w,Kt as x,nt as y,st as z};
@@ -1,9 +1,9 @@
1
1
  import 'hono';
2
2
  import 'zod';
3
- export { a4 as AdapterBundle, a7 as AggregateEndpointConfig, a8 as BatchCreateEndpointConfig, a9 as BatchDeleteEndpointConfig, aa as BatchRestoreEndpointConfig, ab as BatchUpdateEndpointConfig, ac as BatchUpsertEndpointConfig, ad as BulkPatchEndpointConfig, ae as CloneEndpointConfig, af as CreateEndpointConfig, ag as DeleteEndpointConfig, ah as EndpointsConfig, ai as ExportEndpointConfig, G as GeneratedEndpoints, aj as ImportEndpointConfig, ak as ListEndpointConfig, al as ReadEndpointConfig, am as RestoreEndpointConfig, an as SearchEndpointConfig, ao as UpdateEndpointConfig, ap as UpsertEndpointConfig, aq as VersionCompareEndpointConfig, ar as VersionHistoryEndpointConfig, as as VersionReadEndpointConfig, at as VersionRollbackEndpointConfig, Q as defineEndpoints } from '../index-s1OVgHp-.js';
4
- import '../route-CrJCBJMO.js';
5
- import '../types-C2iJttg9.js';
6
- import '../types-C9boymY0.js';
3
+ export { a4 as AdapterBundle, a7 as AggregateEndpointConfig, a8 as BatchCreateEndpointConfig, a9 as BatchDeleteEndpointConfig, aa as BatchRestoreEndpointConfig, ab as BatchUpdateEndpointConfig, ac as BatchUpsertEndpointConfig, ad as BulkPatchEndpointConfig, ae as CloneEndpointConfig, af as CreateEndpointConfig, ag as DeleteEndpointConfig, ah as EndpointsConfig, ai as ExportEndpointConfig, G as GeneratedEndpoints, aj as ImportEndpointConfig, ak as ListEndpointConfig, al as ReadEndpointConfig, am as RestoreEndpointConfig, an as SearchEndpointConfig, ao as UpdateEndpointConfig, ap as UpsertEndpointConfig, aq as VersionCompareEndpointConfig, ar as VersionHistoryEndpointConfig, as as VersionReadEndpointConfig, at as VersionRollbackEndpointConfig, Q as defineEndpoints } from '../index-B2punCHK.js';
4
+ import '../route-CVsl4dg3.js';
5
+ import '../types-D72szrPV.js';
6
+ import '../types-BTRpRT28.js';
7
7
  import '@hono/zod-openapi';
8
8
  import '../audit/index.js';
9
9
  import '../registry-DYXgzGt0.js';
@@ -1,8 +1,8 @@
1
- import { a1 as PaginatedResult, $ as NormalizedSoftDeleteConfig, ai as SoftDeleteConfig, M as MetaInput, y as HookMode, O as OpenAPIRouteSchema, w as HookContext, a5 as RelationConfig, z as IncludeOptions, V as NestedUpdateInput, X as NestedWriteResult, o as CascadeAction, t as FilterConfig, ak as SortSpec, L as ListFilters, h as AggregateConfig, a as AggregateOptions, A as AggregateField, j as AggregateResult, b as SearchFieldConfig, c as SearchMode, af as SearchOptions, ah as SearchResultItem, ag as SearchResult } from './types-C2iJttg9.js';
1
+ import { a1 as PaginatedResult, $ as NormalizedSoftDeleteConfig, ai as SoftDeleteConfig, M as MetaInput, y as HookMode, O as OpenAPIRouteSchema, w as HookContext, a5 as RelationConfig, z as IncludeOptions, V as NestedUpdateInput, X as NestedWriteResult, o as CascadeAction, t as FilterConfig, ak as SortSpec, L as ListFilters, h as AggregateConfig, a as AggregateOptions, A as AggregateField, j as AggregateResult, b as SearchFieldConfig, c as SearchMode, af as SearchOptions, ah as SearchResultItem, ag as SearchResult } from './types-D72szrPV.js';
2
2
  import { Env } from 'hono';
3
3
  import { ZodObject, ZodRawShape, z } from 'zod';
4
- import { a6 as CrudEndpoint, i as CsvGenerateOptions } from './index-s1OVgHp-.js';
5
- import { M as ModelObject, F as FieldSelection } from './types-C9boymY0.js';
4
+ import { a6 as CrudEndpoint, i as CsvGenerateOptions } from './index-B2punCHK.js';
5
+ import { M as ModelObject, F as FieldSelection } from './types-BTRpRT28.js';
6
6
 
7
7
  /**
8
8
  * Cursor-pagination codec. Opaque base64 wrapper around a cursor value.
@@ -1,7 +1,7 @@
1
1
  import { Env, MiddlewareHandler } from 'hono';
2
2
  import { ZodObject, ZodRawShape } from 'zod';
3
- import { M as MetaInput, O as OpenAPIRouteSchema, w as HookContext, y as HookMode, f as AfterDeleteHook, t as FilterConfig, ak as SortSpec, g as AfterUpdateHook } from '../types-C2iJttg9.js';
4
- import { M as ModelObject } from '../types-C9boymY0.js';
3
+ import { M as MetaInput, O as OpenAPIRouteSchema, w as HookContext, y as HookMode, f as AfterDeleteHook, t as FilterConfig, ak as SortSpec, g as AfterUpdateHook } from '../types-D72szrPV.js';
4
+ import { M as ModelObject } from '../types-BTRpRT28.js';
5
5
  import '../path-match-DGLu6wld.js';
6
6
  import '../types-B5wq2iKZ.js';
7
7
  import '../types-lAPVBoYa.js';
@@ -1,14 +1,14 @@
1
1
  import { Env, Context, MiddlewareHandler, Hono } from 'hono';
2
2
  import { ZodError, z, ZodObject, ZodRawShape } from 'zod';
3
3
  import { OpenAPIHono } from '@hono/zod-openapi';
4
- import { O as OpenAPIRoute } from './route-CrJCBJMO.js';
5
- import { O as OpenAPIRouteSchema, R as ResponseEnvelope, E as ErrorResponse, K as Model, M as MetaInput, Z as NormalizedAuditConfig, a0 as NormalizedVersioningConfig, $ as NormalizedSoftDeleteConfig, _ as NormalizedMultiTenantConfig, N as ModelPolicies, a3 as PolicyContext, s as FilterCondition, w as HookContext, ao as ValidatedData, y as HookMode, t as FilterConfig, aj as SortDirection, g as AfterUpdateHook, f as AfterDeleteHook, ah as SearchResultItem, j as AggregateResult } from './types-C2iJttg9.js';
4
+ import { O as OpenAPIRoute } from './route-CVsl4dg3.js';
5
+ import { O as OpenAPIRouteSchema, R as ResponseEnvelope, E as ErrorResponse, K as Model, M as MetaInput, Z as NormalizedAuditConfig, a0 as NormalizedVersioningConfig, $ as NormalizedSoftDeleteConfig, _ as NormalizedMultiTenantConfig, aA as RelationRequestScope, N as ModelPolicies, a3 as PolicyContext, s as FilterCondition, w as HookContext, ao as ValidatedData, y as HookMode, t as FilterConfig, aj as SortDirection, g as AfterUpdateHook, f as AfterDeleteHook, ah as SearchResultItem, j as AggregateResult } from './types-D72szrPV.js';
6
6
  import { AuditLogger } from './audit/index.js';
7
7
  import { HTTPException } from 'hono/http-exception';
8
8
  import { ContentfulStatusCode } from 'hono/utils/http-status';
9
9
  import { C as CrudEventType } from './types-ChLYHg52.js';
10
10
  import { VersionManager } from './versioning/index.js';
11
- import { M as ModelObject, F as FieldSelection } from './types-C9boymY0.js';
11
+ import { M as ModelObject, F as FieldSelection } from './types-BTRpRT28.js';
12
12
 
13
13
  interface OpenAPIConfig$1 {
14
14
  openapi?: string;
@@ -635,6 +635,14 @@ declare abstract class CrudEndpoint<E extends Env = Env, M extends MetaInput = M
635
635
  */
636
636
  protected getTimestampsConfig(): NormalizedTimestampsConfig;
637
637
  protected getTenantId(): string | undefined;
638
+ /**
639
+ * Build the request-scoped access scope for relation includes — the parent
640
+ * request's resolved tenant id plus whether soft-deleted related rows are
641
+ * wanted. Threaded into `IncludeOptions.scope` so the relation loader can
642
+ * constrain included related rows per each relation's `scope` config
643
+ * (owner-scope + soft-delete), preventing cross-tenant exposure via `?include=`.
644
+ */
645
+ protected getRelationScope(includeDeleted?: boolean): RelationRequestScope;
638
646
  /**
639
647
  * Validates that tenant ID is present when required.
640
648
  * Throws a 400 `TENANT_REQUIRED` ApiException if missing and required.
package/dist/index.d.ts CHANGED
@@ -1,17 +1,17 @@
1
1
  import { A as ApiVersionEnv } from './types-COJwpQfh.js';
2
- import { S as SchemaResolveContext, R as ResponseEnvelope, C as ComputedFieldsConfig, A as AggregateField, a as AggregateOptions, b as SearchFieldConfig, c as SearchMode, O as OpenAPIRouteSchema, d as AuthEnv } from './types-C2iJttg9.js';
3
- export { e as AGGREGATE_OPERATIONS, f as AfterDeleteHook, g as AfterUpdateHook, h as AggregateConfig, i as AggregateOperation, j as AggregateResult, k as AuditAction, l as AuditConfig, m as AuditFieldChange, n as AuditLogEntry, o as CascadeAction, p as CascadeConfig, q as ComputedFieldConfig, r as ComputedFieldFn, E as ErrorResponse, F as FILTER_OPERATORS, s as FilterCondition, t as FilterConfig, u as FilterOperator, H as HandleArgs, v as HookConfig, w as HookContext, x as HookFn, y as HookMode, I as IdStrategy, z as IncludeOptions, B as InferMeta, D as InferModel, G as InferSchema, L as ListFilters, J as ListOptions, M as MetaInput, K as Model, N as ModelPolicies, P as ModelTable, Q as MultiTenantConfig, T as NestedCreateManyInput, U as NestedCreateOneInput, V as NestedUpdateInput, W as NestedWriteConfig, X as NestedWriteResult, Y as NestedWritesConfig, Z as NormalizedAuditConfig, _ as NormalizedMultiTenantConfig, $ as NormalizedSoftDeleteConfig, a0 as NormalizedVersioningConfig, a1 as PaginatedResult, a2 as PartialBy, a3 as PolicyContext, a4 as RESPONSE_ENVELOPE_CONTEXT_KEY, a5 as RelationConfig, a6 as RelationType, a7 as RelationsConfig, a8 as RequiredBy, a9 as ResponseEnvelopeInfo, aa as RouteOptions, ab as SEARCH_MODES, ac as SORT_DIRECTIONS, ad as SchemaKeys, ae as SearchConfig, af as SearchOptions, ag as SearchResult, ah as SearchResultItem, ai as SoftDeleteConfig, aj as SortDirection, ak as SortSpec, al as StructuredError, am as SuccessResponse, an as TenantIdSource, ao as ValidatedData, ap as ValidationIssue, aq as VersionHistoryEntry, ar as VersioningConfig, as as assertNever, at as defineMeta, au as defineModel, av as errorEnvelopeSchema, aw as isFilterOperator, ax as structuredErrorSchema, ay as successEnvelopeSchema, az as validationIssueSchema } from './types-C2iJttg9.js';
2
+ import { S as SchemaResolveContext, R as ResponseEnvelope, C as ComputedFieldsConfig, A as AggregateField, a as AggregateOptions, b as SearchFieldConfig, c as SearchMode, O as OpenAPIRouteSchema, d as AuthEnv } from './types-D72szrPV.js';
3
+ export { e as AGGREGATE_OPERATIONS, f as AfterDeleteHook, g as AfterUpdateHook, h as AggregateConfig, i as AggregateOperation, j as AggregateResult, k as AuditAction, l as AuditConfig, m as AuditFieldChange, n as AuditLogEntry, o as CascadeAction, p as CascadeConfig, q as ComputedFieldConfig, r as ComputedFieldFn, E as ErrorResponse, F as FILTER_OPERATORS, s as FilterCondition, t as FilterConfig, u as FilterOperator, H as HandleArgs, v as HookConfig, w as HookContext, x as HookFn, y as HookMode, I as IdStrategy, z as IncludeOptions, B as InferMeta, D as InferModel, G as InferSchema, L as ListFilters, J as ListOptions, M as MetaInput, K as Model, N as ModelPolicies, P as ModelTable, Q as MultiTenantConfig, T as NestedCreateManyInput, U as NestedCreateOneInput, V as NestedUpdateInput, W as NestedWriteConfig, X as NestedWriteResult, Y as NestedWritesConfig, Z as NormalizedAuditConfig, _ as NormalizedMultiTenantConfig, $ as NormalizedSoftDeleteConfig, a0 as NormalizedVersioningConfig, a1 as PaginatedResult, a2 as PartialBy, a3 as PolicyContext, a4 as RESPONSE_ENVELOPE_CONTEXT_KEY, a5 as RelationConfig, a6 as RelationType, a7 as RelationsConfig, a8 as RequiredBy, a9 as ResponseEnvelopeInfo, aa as RouteOptions, ab as SEARCH_MODES, ac as SORT_DIRECTIONS, ad as SchemaKeys, ae as SearchConfig, af as SearchOptions, ag as SearchResult, ah as SearchResultItem, ai as SoftDeleteConfig, aj as SortDirection, ak as SortSpec, al as StructuredError, am as SuccessResponse, an as TenantIdSource, ao as ValidatedData, ap as ValidationIssue, aq as VersionHistoryEntry, ar as VersioningConfig, as as assertNever, at as defineMeta, au as defineModel, av as errorEnvelopeSchema, aw as isFilterOperator, ax as structuredErrorSchema, ay as successEnvelopeSchema, az as validationIssueSchema } from './types-D72szrPV.js';
4
4
  import { L as LoggingEnv } from './types-B3XBv6XB.js';
5
5
  import { TenantEnv } from './multi-tenant/index.js';
6
- import { S as StorageEnv } from './types-ByPjCs4O.js';
7
- export { O as OpenAPIRoute, i as isRouteClass } from './route-CrJCBJMO.js';
8
- import { O as OpenAPIConfig, H as HonoOpenAPIApp, G as GeneratedEndpoints, A as ApiException } from './index-s1OVgHp-.js';
9
- export { a as AdapterKind, b as AggregationException, B as BatchUpsertEndpoint, c as BatchUpsertItemResult, d as BatchUpsertResult, C as CacheException, e as ConfigurationException, f as ConflictException, g as CrudEndpointName, h as CrudEndpoints, i as CsvGenerateOptions, j as CsvParseError, k as CsvParseOptions, l as CsvParseResult, m as CsvValidationResult, E as EndpointClass, n as EndpointMiddlewares, F as ForbiddenException, o as HonoOpenAPIHandler, I as ImportEndpoint, p as ImportMode, q as ImportOptions, r as ImportResult, s as ImportRowResult, t as ImportRowStatus, u as ImportSummary, v as InputValidationException, N as NormalizedTimestampsConfig, w as NotFoundException, R as RegisterCrudOptions, x as RegisteredRoute, y as RouterOptions, U as UnauthorizedException, z as applyManagedInsertFields, D as applyManagedUpdateFields, J as assertIdStrategySupported, K as causeChain, L as contentJson, M as createCsvStream, P as csvToJson, Q as defineEndpoints, S as escapeCsvValue, T as fromHono, V as generateCsv, W as getManagedInputExclusions, X as getTimestampsConfig, Y as inferCsvContentType, Z as jsonToCsv, _ as mapUniqueViolation, $ as parseCsv, a0 as registerCrud, a1 as rethrowAsConstraintError, a2 as stripManagedInsertFields, a3 as validateCsvHeaders } from './index-s1OVgHp-.js';
6
+ import { S as StorageEnv } from './types-xNoq2dk9.js';
7
+ export { O as OpenAPIRoute, i as isRouteClass } from './route-CVsl4dg3.js';
8
+ import { O as OpenAPIConfig, H as HonoOpenAPIApp, G as GeneratedEndpoints, A as ApiException } from './index-B2punCHK.js';
9
+ export { a as AdapterKind, b as AggregationException, B as BatchUpsertEndpoint, c as BatchUpsertItemResult, d as BatchUpsertResult, C as CacheException, e as ConfigurationException, f as ConflictException, g as CrudEndpointName, h as CrudEndpoints, i as CsvGenerateOptions, j as CsvParseError, k as CsvParseOptions, l as CsvParseResult, m as CsvValidationResult, E as EndpointClass, n as EndpointMiddlewares, F as ForbiddenException, o as HonoOpenAPIHandler, I as ImportEndpoint, p as ImportMode, q as ImportOptions, r as ImportResult, s as ImportRowResult, t as ImportRowStatus, u as ImportSummary, v as InputValidationException, N as NormalizedTimestampsConfig, w as NotFoundException, R as RegisterCrudOptions, x as RegisteredRoute, y as RouterOptions, U as UnauthorizedException, z as applyManagedInsertFields, D as applyManagedUpdateFields, J as assertIdStrategySupported, K as causeChain, L as contentJson, M as createCsvStream, P as csvToJson, Q as defineEndpoints, S as escapeCsvValue, T as fromHono, V as generateCsv, W as getManagedInputExclusions, X as getTimestampsConfig, Y as inferCsvContentType, Z as jsonToCsv, _ as mapUniqueViolation, $ as parseCsv, a0 as registerCrud, a1 as rethrowAsConstraintError, a2 as stripManagedInsertFields, a3 as validateCsvHeaders } from './index-B2punCHK.js';
10
10
  import { Env, Context, ErrorHandler } from 'hono';
11
- export { A as AggregateEndpoint, B as BatchCreateEndpoint, a as BatchDeleteEndpoint, b as BatchDeleteResult, c as BatchRestoreEndpoint, d as BatchRestoreResult, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpdateResult, h as BulkPatchEndpoint, i as BulkPatchResult, C as CONTEXT_KEYS, j as CascadeResult, k as CloneEndpoint, l as ContextKey, m as CreateEndpoint, D as DeleteEndpoint, E as ExportEndpoint, n as ExportFormat, o as ExportOptions, p as ExportResult, L as ListEndpoint, q as Logger, R as ReadEndpoint, r as RestoreEndpoint, S as SearchEndpoint, U as UpdateEndpoint, s as UpsertEndpoint, t as UpsertResult, V as VersionCompareEndpoint, u as VersionHistoryEndpoint, v as VersionReadEndpoint, w as VersionRollbackEndpoint, x as applyUpsertRestore, y as computeAggregations, z as decodeCursor, F as encodeCursor, G as getLogger, H as getSoftDeleteConfig, I as searchInMemory, J as setLogger } from './context-keys-9Q1takVn.js';
11
+ export { A as AggregateEndpoint, B as BatchCreateEndpoint, a as BatchDeleteEndpoint, b as BatchDeleteResult, c as BatchRestoreEndpoint, d as BatchRestoreResult, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpdateResult, h as BulkPatchEndpoint, i as BulkPatchResult, C as CONTEXT_KEYS, j as CascadeResult, k as CloneEndpoint, l as ContextKey, m as CreateEndpoint, D as DeleteEndpoint, E as ExportEndpoint, n as ExportFormat, o as ExportOptions, p as ExportResult, L as ListEndpoint, q as Logger, R as ReadEndpoint, r as RestoreEndpoint, S as SearchEndpoint, U as UpdateEndpoint, s as UpsertEndpoint, t as UpsertResult, V as VersionCompareEndpoint, u as VersionHistoryEndpoint, v as VersionReadEndpoint, w as VersionRollbackEndpoint, x as applyUpsertRestore, y as computeAggregations, z as decodeCursor, F as encodeCursor, G as getLogger, H as getSoftDeleteConfig, I as searchInMemory, J as setLogger } from './context-keys-Dxyh3NuH.js';
12
12
  import { C as CrudEventEmitter } from './emitter-B8EL76d3.js';
13
13
  import { C as CrudEventType, a as CrudEventPayload } from './types-ChLYHg52.js';
14
- export { F as FieldSelection, a as FieldSelectionConfig, L as ListFilterParseOptions, M as ModelObject, S as SingleEndpointConfig, U as UpdateEndpointConfig, b as applyFieldSelection, c as applyFieldSelectionToArray, g as getSchemaFields, p as parseFieldSelection, d as parseFilterValue, e as parseListFilters } from './types-C9boymY0.js';
14
+ export { F as FieldSelection, a as FieldSelectionConfig, L as ListFilterParseOptions, M as ModelObject, S as SingleEndpointConfig, U as UpdateEndpointConfig, b as applyFieldSelection, c as applyFieldSelectionToArray, g as getSchemaFields, p as parseFieldSelection, d as parseFilterValue, e as parseListFilters } from './types-BTRpRT28.js';
15
15
  export { g as generateRequestId, a as getContextVar, b as getRequestId, c as getTenantId, s as setContextVar } from './context-m0qIRK5d.js';
16
16
  import { Hook } from '@hono/zod-openapi';
17
17
  import { z, ZodObject } from 'zod';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {q as q$2}from'./chunk-O62WFEW2.js';export{c as getErrorMessage,a as toError,b as wrapError}from'./chunk-O62WFEW2.js';import {a,qa}from'./chunk-O6D3QREM.js';export{ca as AggregateEndpoint,U as BatchCreateEndpoint,W as BatchDeleteEndpoint,X as BatchRestoreEndpoint,V as BatchUpdateEndpoint,Y as BatchUpsertEndpoint,Z as BulkPatchEndpoint,R as CloneEndpoint,M as CreateEndpoint,P as DeleteEndpoint,oa as ExportEndpoint,pa as ImportEndpoint,Q as ListEndpoint,N as ReadEndpoint,S as RestoreEndpoint,ea as SearchEndpoint,O as UpdateEndpoint,T as UpsertEndpoint,aa as VersionCompareEndpoint,_ as VersionHistoryEndpoint,$ as VersionReadEndpoint,ba as VersionRollbackEndpoint,n as applyComputedFields,o as applyComputedFieldsToArray,K as applyFieldSelection,L as applyFieldSelectionToArray,d as applyManagedInsertFields,e as applyManagedUpdateFields,u as applyUpsertRestore,f as assertIdStrategySupported,B as buildSearchConfig,y as calculateScore,h as causeChain,da as computeAggregations,ia as createCsvStream,na as csvToJson,l as decodeCursor,k as encodeCursor,ga as escapeCsvValue,p as extractNestedData,ha as generateCsv,D as generateETag,z as generateHighlights,c as getManagedInputExclusions,I as getSchemaFields,t as getSoftDeleteConfig,b as getTimestampsConfig,la as inferCsvContentType,q as isDirectNestedData,ma as jsonToCsv,i as mapUniqueViolation,F as matchesIfMatch,E as matchesIfNoneMatch,r as parseAggregateField,s as parseAggregateQuery,ja as parseCsv,J as parseFieldSelection,G as parseFilterValue,H as parseListFilters,A as parseSearchFields,C as parseSearchMode,j as rethrowAsConstraintError,fa as searchInMemory,g as stripManagedInsertFields,x as termFrequency,v as tokenize,w as tokenizeQuery,ka as validateCsvHeaders}from'./chunk-O6D3QREM.js';import'./chunk-P7HU2KIE.js';import {e}from'./chunk-H3VBYIDA.js';import'./chunk-CWQSQUV4.js';import'./chunk-SDNXN7M5.js';import'./chunk-HYXDMJ4K.js';import'./chunk-WBHWKOTP.js';import'./chunk-L5CVVJQH.js';import {n,o,q as q$1,m}from'./chunk-JBKQLYEU.js';export{f as AGGREGATE_OPERATIONS,a as FILTER_OPERATORS,p as OpenAPIRoute,m as RESPONSE_ENVELOPE_CONTEXT_KEY,e as SEARCH_MODES,d as SORT_DIRECTIONS,c as assertNever,h as defineMeta,g as defineModel,k as errorEnvelopeSchema,P as errorResponseSchema,O as errorResponseZodSchema,Q as errorResponses,b as isFilterOperator,q as isRouteClass,N as mergeRouteSchema,j as structuredErrorSchema,l as successEnvelopeSchema,i as validationIssueSchema}from'./chunk-JBKQLYEU.js';import'./chunk-V7ABUFW5.js';import {b as b$1}from'./chunk-DMGP7QDL.js';export{b as getLogger,a as setLogger}from'./chunk-DMGP7QDL.js';import'./chunk-5P4RVSHT.js';import {b as b$2}from'./chunk-TLI3TRUA.js';export{e as generateRequestId,a as getContextVar,c as getRequestId,d as getTenantId,b as setContextVar}from'./chunk-TLI3TRUA.js';import {c,b}from'./chunk-XR6JRDGX.js';export{h as AggregationException,b as ApiException,a as CONTEXT_KEYS,i as CacheException,j as ConfigurationException,e as ConflictException,g as ForbiddenException,c as InputValidationException,d as NotFoundException,f as UnauthorizedException}from'./chunk-XR6JRDGX.js';import {a as a$1}from'./chunk-NWOJZP4P.js';export{a as defineEndpoints}from'./chunk-E3MK476S.js';import'./chunk-6GZBIUE2.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE}from'hono/streaming';function I(t){return t.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function Vt(t,e){return {content:{"application/json":{schema:t}},description:e}}function jt(t,e){return {content:{"application/json":{schema:t}},description:e,required:true}}var N=t=>{if(!t.success)throw c.fromZodError(t.error)};function Lt(t,e=400){return (o,r)=>{if(!o.success)return r.json(t(o.error),e)}}var V=new WeakMap;function j(t){return V.get(t)}var S=class{app;options;routes=new Map;constructor(e,o={}){this.app=e,this.options={openapi_url:"/openapi.json",...o};}registerRoute(e,o$1,r,p=[]){let f=`${e.toUpperCase()} ${o$1}`,l=r,d=new l().getSchema();this.routes.set(f,{method:e,path:o$1,schema:d,routeClass:r});let i=createRoute({method:e,path:I(o$1),...d,responses:d.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(p.length>0)for(let c of p)this.app.use(o$1,async(s,n)=>{if(s.req.method.toLowerCase()===e)return c(s,n);await n();});this.app.openapi(i,async c=>{let s=new l;s.setContext(c);try{return await s.handle()}catch(n$1){if(n$1 instanceof b){let a=n$1.toJSON(),E=n(c);return E?o(c,E.error(a.error),n$1.status):o(c,a,n$1.status)}throw n$1}});}setupDocs(e,o){let r=e??this.options.openapi_url??"/openapi.json";this.app.doc(r,{openapi:o.openapi||"3.1.0",info:o.info,servers:o.servers,security:o.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return I(e)}};function Bt(t=new OpenAPIHono,e={}){let o="openAPIRegistry"in t?t:new OpenAPIHono;o.defaultHook??=N;let r=new S(o,e),p=["get","post","put","patch","delete","options","head"],f=new Proxy(o,{get(l,m){if(p.includes(m))return (i,...c)=>{let s=c[c.length-1];if(q$1(s)){let n=c.slice(0,-1);return r.registerRoute(m,i,s,n),f}return l[m](i,...c)};if(m==="doc")return (i,c)=>{r.setupDocs(i,c);};if(m==="use")return (...i)=>(l[m](...i),f);let d=l[m];return typeof d=="function"?d.bind(l):d}});return V.set(f,r),f}var Kt=6e4,Wt={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Jt(t,e,o={}){let r=j(t);if(!r)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let p=o.config??Wt,f=`openapi:${e.tenantId??"global"}:${p.info.version}`;if(o.cache){let i=await o.cache.get(f);if(i!=null)return i}let l=new OpenAPIHono;for(let i of r.getRegisteredRoutes().values()){let c=i.routeClass,s=new c,n=Yt(e);s.setContext(n),typeof s.resolveModelSchema=="function"&&await s.resolveModelSchema();let a=s.getSchema(),E=createRoute({...a,method:i.method,path:r.toOpenApiPath(i.path),responses:a.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});l.openapi(E,()=>new Response);}let m={openapi:p.openapi??"3.1.0",info:p.info,servers:p.servers,security:p.security},d=o.spec==="3.0"?l.getOpenAPIDocument(m):l.getOpenAPI31Document(m);return o.cache&&await o.cache.set(f,d,o.cacheTtlMs??Kt),d}function Yt(t){let e={};t.tenantId!==void 0&&(e.tenantId=t.tenantId),t.organizationId!==void 0&&(e.organizationId=t.organizationId);let o=t.request??new Request("http://localhost/");return {var:e,env:t.env,req:{raw:o,header:()=>{},query:()=>{},param:()=>{}},set(r,p){e[r]=p;},get(r){return e[r]},executionCtx:void 0}}function Xt(t){return {async get(e){let o=await t.get(e);return o?o.data:void 0},async set(e,o,r){await t.set(e,o,r!=null?{ttlMs:r}:void 0);}}}function oo(t,e){let r=`/${t}/${e}`.replace(/\/{2,}/g,"/");return r.length>1&&r.endsWith("/")?r.slice(0,-1):r}function no(t,e={}){let o=e.basePath??"",r=e.tag,p=new OpenAPIHono,f=0,l=t;for(let[i,c,s]of a){let n=l[i];if(!n)continue;let E=new n().getSchema(),g=r!==void 0?{...E,tags:[r]}:E,h=oo(o,I(s)),C=createRoute({...g,method:c,path:h,responses:g.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});p.openapi(C,()=>new Response),f+=1;}return f===0?{}:p.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var L=t=>{if(t instanceof ZodError)return c.fromZodError(t)};function po(t={}){let{mappers:e=[],hooks:o$1=[],includeRequestId:r=true,includeStackTrace:p=false,defaultErrorCode:f="INTERNAL_ERROR",defaultErrorMessage:l="An internal error occurred",logUnmappedErrors:m=true,onHookError:d,responseEnvelope:i}=t,c=[...e,L];return async(s,n)=>{let a;if(s instanceof b)a=s;else if(s instanceof HTTPException)a=new b(s.message,s.status,"HTTP_ERROR");else {for(let y of c)try{let R=await y(s,n);if(R){a=R;break}}catch{}!a&&m&&b$1().error("Unmapped error",{error:s instanceof Error?s.message:String(s)});}let E=a??new b(l,500,f),g=a$1(n);for(let y of o$1)try{let R=y(s,n,E);if(R instanceof Promise){let B=R.catch(Z=>{d&&d(Z,s,n);});g?.(B);}}catch(R){d&&d(R,s,n);}let h=E.toJSON();if(r){let y=q$2(n);y&&(h.error.requestId=y);}p&&s.stack&&(h.error.stack=s.stack);let C=q(n,i),u=C?C.error(h.error):h;return o(n,u,E.status)}}function q(t,e){return n(t)??e}var v=new Map,ao=["password","token","secret","apiKey","creditCard","ssn"];function H(t,e){if(t==null||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>H(r,e));let o={};for(let[r,p]of Object.entries(t))e.includes(r)||(o[r]=typeof p=="object"&&p!==null?H(p,e):p);return o}function co(t){let{table:e$1,events:o,emitter:r,filter:p,heartbeatIntervalMs:f=3e4,maxConnections:l=1e3,connectionTimeoutMs:m=3e5,excludeFields:d=ao}=t;return i=>{let c=e(i,r);if(!c)throw new b("Event emitter not configured",500,"EVENT_EMITTER_NOT_CONFIGURED");let s=v.get(e$1)||0;if(s>=l)throw new b("Too many SSE connections",503,"TOO_MANY_CONNECTIONS");return v.set(e$1,s+1),streamSSE(i,async n=>{let a,E=async u=>{if(o&&o.length>0&&!o.includes(u.type)||p&&!p(u,i))return;let y=d.length>0?H(u.data,d):u.data,R=u.previousData&&d.length>0?H(u.previousData,d):u.previousData;try{await n.writeSSE({event:`${u.table}.${u.type}`,data:JSON.stringify({type:u.type,table:u.table,recordId:u.recordId,data:y,previousData:R,timestamp:u.timestamp}),id:`${u.table}-${u.recordId}-${Date.now()}`});}catch{}};a=c.onTable(e$1,E);let g=()=>{a.unsubscribe();let u=v.get(e$1)||1;u<=1?v.delete(e$1):v.set(e$1,u-1);};n.onAbort(()=>{g();});let h=Date.now(),C=h;for(;!n.closed;){await n.sleep(1e3);let u=Date.now();if(u-h>=m){n.abort();break}if(u-C>=f){C=u;try{await n.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}})}}function uo(t,e,o,r={}){let p=e.endsWith("/")?e.slice(0,-1):e,f=t,{middlewares:l=[],endpointMiddlewares:m$1={},responseEnvelope:d}=r,i=d?async(n,a)=>{b$2(n,m,d),await a();}:void 0,c=n=>{let a=o[n],E=a&&"_middlewares"in a?a._middlewares||[]:[];return [...i?[i]:[],...l,...m$1[n]||[],...E]},s=(n,a,E,g)=>{let h=c(E),C=f[n];h.length>0?C(a,...h,g):C(a,g);};for(let[n,a$1,E]of a){let g=o[n];g&&s(a$1,`${p}${E}`,n,g);}qa(t,p,o);}function lo(t){return {content:{"application/json":{schema:t}}}}
1
+ import {q as q$2}from'./chunk-O62WFEW2.js';export{c as getErrorMessage,a as toError,b as wrapError}from'./chunk-O62WFEW2.js';import {a,ra}from'./chunk-QWMISKGR.js';export{da as AggregateEndpoint,V as BatchCreateEndpoint,X as BatchDeleteEndpoint,Y as BatchRestoreEndpoint,W as BatchUpdateEndpoint,Z as BatchUpsertEndpoint,_ as BulkPatchEndpoint,S as CloneEndpoint,M as CreateEndpoint,Q as DeleteEndpoint,pa as ExportEndpoint,qa as ImportEndpoint,R as ListEndpoint,O as ReadEndpoint,T as RestoreEndpoint,fa as SearchEndpoint,P as UpdateEndpoint,U as UpsertEndpoint,ba as VersionCompareEndpoint,$ as VersionHistoryEndpoint,aa as VersionReadEndpoint,ca as VersionRollbackEndpoint,n as applyComputedFields,o as applyComputedFieldsToArray,K as applyFieldSelection,L as applyFieldSelectionToArray,d as applyManagedInsertFields,e as applyManagedUpdateFields,u as applyUpsertRestore,f as assertIdStrategySupported,B as buildSearchConfig,y as calculateScore,h as causeChain,ea as computeAggregations,ja as createCsvStream,oa as csvToJson,l as decodeCursor,k as encodeCursor,ha as escapeCsvValue,p as extractNestedData,ia as generateCsv,D as generateETag,z as generateHighlights,c as getManagedInputExclusions,I as getSchemaFields,t as getSoftDeleteConfig,b as getTimestampsConfig,ma as inferCsvContentType,q as isDirectNestedData,na as jsonToCsv,i as mapUniqueViolation,F as matchesIfMatch,E as matchesIfNoneMatch,r as parseAggregateField,s as parseAggregateQuery,ka as parseCsv,J as parseFieldSelection,G as parseFilterValue,H as parseListFilters,A as parseSearchFields,C as parseSearchMode,j as rethrowAsConstraintError,ga as searchInMemory,g as stripManagedInsertFields,x as termFrequency,v as tokenize,w as tokenizeQuery,la as validateCsvHeaders}from'./chunk-QWMISKGR.js';import'./chunk-P7HU2KIE.js';import {e}from'./chunk-H3VBYIDA.js';import'./chunk-CWQSQUV4.js';import'./chunk-SDNXN7M5.js';import'./chunk-HYXDMJ4K.js';import'./chunk-WBHWKOTP.js';import'./chunk-L5CVVJQH.js';import {n,o,q as q$1,m}from'./chunk-A27HDYSF.js';export{f as AGGREGATE_OPERATIONS,a as FILTER_OPERATORS,p as OpenAPIRoute,m as RESPONSE_ENVELOPE_CONTEXT_KEY,e as SEARCH_MODES,d as SORT_DIRECTIONS,c as assertNever,h as defineMeta,g as defineModel,k as errorEnvelopeSchema,P as errorResponseSchema,O as errorResponseZodSchema,Q as errorResponses,b as isFilterOperator,q as isRouteClass,N as mergeRouteSchema,j as structuredErrorSchema,l as successEnvelopeSchema,i as validationIssueSchema}from'./chunk-A27HDYSF.js';import'./chunk-V7ABUFW5.js';import {b as b$1}from'./chunk-DMGP7QDL.js';export{b as getLogger,a as setLogger}from'./chunk-DMGP7QDL.js';import'./chunk-5P4RVSHT.js';import {b as b$2}from'./chunk-TLI3TRUA.js';export{e as generateRequestId,a as getContextVar,c as getRequestId,d as getTenantId,b as setContextVar}from'./chunk-TLI3TRUA.js';import {c,b}from'./chunk-XR6JRDGX.js';export{h as AggregationException,b as ApiException,a as CONTEXT_KEYS,i as CacheException,j as ConfigurationException,e as ConflictException,g as ForbiddenException,c as InputValidationException,d as NotFoundException,f as UnauthorizedException}from'./chunk-XR6JRDGX.js';import {a as a$1}from'./chunk-NWOJZP4P.js';export{a as defineEndpoints}from'./chunk-E3MK476S.js';import'./chunk-6GZBIUE2.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE}from'hono/streaming';function I(t){return t.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function Vt(t,e){return {content:{"application/json":{schema:t}},description:e}}function jt(t,e){return {content:{"application/json":{schema:t}},description:e,required:true}}var N=t=>{if(!t.success)throw c.fromZodError(t.error)};function Lt(t,e=400){return (o,r)=>{if(!o.success)return r.json(t(o.error),e)}}var V=new WeakMap;function j(t){return V.get(t)}var S=class{app;options;routes=new Map;constructor(e,o={}){this.app=e,this.options={openapi_url:"/openapi.json",...o};}registerRoute(e,o$1,r,p=[]){let f=`${e.toUpperCase()} ${o$1}`,l=r,d=new l().getSchema();this.routes.set(f,{method:e,path:o$1,schema:d,routeClass:r});let i=createRoute({method:e,path:I(o$1),...d,responses:d.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(p.length>0)for(let c of p)this.app.use(o$1,async(s,n)=>{if(s.req.method.toLowerCase()===e)return c(s,n);await n();});this.app.openapi(i,async c=>{let s=new l;s.setContext(c);try{return await s.handle()}catch(n$1){if(n$1 instanceof b){let a=n$1.toJSON(),E=n(c);return E?o(c,E.error(a.error),n$1.status):o(c,a,n$1.status)}throw n$1}});}setupDocs(e,o){let r=e??this.options.openapi_url??"/openapi.json";this.app.doc(r,{openapi:o.openapi||"3.1.0",info:o.info,servers:o.servers,security:o.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return I(e)}};function Bt(t=new OpenAPIHono,e={}){let o="openAPIRegistry"in t?t:new OpenAPIHono;o.defaultHook??=N;let r=new S(o,e),p=["get","post","put","patch","delete","options","head"],f=new Proxy(o,{get(l,m){if(p.includes(m))return (i,...c)=>{let s=c[c.length-1];if(q$1(s)){let n=c.slice(0,-1);return r.registerRoute(m,i,s,n),f}return l[m](i,...c)};if(m==="doc")return (i,c)=>{r.setupDocs(i,c);};if(m==="use")return (...i)=>(l[m](...i),f);let d=l[m];return typeof d=="function"?d.bind(l):d}});return V.set(f,r),f}var Kt=6e4,Wt={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Jt(t,e,o={}){let r=j(t);if(!r)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let p=o.config??Wt,f=`openapi:${e.tenantId??"global"}:${p.info.version}`;if(o.cache){let i=await o.cache.get(f);if(i!=null)return i}let l=new OpenAPIHono;for(let i of r.getRegisteredRoutes().values()){let c=i.routeClass,s=new c,n=Yt(e);s.setContext(n),typeof s.resolveModelSchema=="function"&&await s.resolveModelSchema();let a=s.getSchema(),E=createRoute({...a,method:i.method,path:r.toOpenApiPath(i.path),responses:a.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});l.openapi(E,()=>new Response);}let m={openapi:p.openapi??"3.1.0",info:p.info,servers:p.servers,security:p.security},d=o.spec==="3.0"?l.getOpenAPIDocument(m):l.getOpenAPI31Document(m);return o.cache&&await o.cache.set(f,d,o.cacheTtlMs??Kt),d}function Yt(t){let e={};t.tenantId!==void 0&&(e.tenantId=t.tenantId),t.organizationId!==void 0&&(e.organizationId=t.organizationId);let o=t.request??new Request("http://localhost/");return {var:e,env:t.env,req:{raw:o,header:()=>{},query:()=>{},param:()=>{}},set(r,p){e[r]=p;},get(r){return e[r]},executionCtx:void 0}}function Xt(t){return {async get(e){let o=await t.get(e);return o?o.data:void 0},async set(e,o,r){await t.set(e,o,r!=null?{ttlMs:r}:void 0);}}}function oo(t,e){let r=`/${t}/${e}`.replace(/\/{2,}/g,"/");return r.length>1&&r.endsWith("/")?r.slice(0,-1):r}function no(t,e={}){let o=e.basePath??"",r=e.tag,p=new OpenAPIHono,f=0,l=t;for(let[i,c,s]of a){let n=l[i];if(!n)continue;let E=new n().getSchema(),g=r!==void 0?{...E,tags:[r]}:E,h=oo(o,I(s)),C=createRoute({...g,method:c,path:h,responses:g.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});p.openapi(C,()=>new Response),f+=1;}return f===0?{}:p.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var L=t=>{if(t instanceof ZodError)return c.fromZodError(t)};function po(t={}){let{mappers:e=[],hooks:o$1=[],includeRequestId:r=true,includeStackTrace:p=false,defaultErrorCode:f="INTERNAL_ERROR",defaultErrorMessage:l="An internal error occurred",logUnmappedErrors:m=true,onHookError:d,responseEnvelope:i}=t,c=[...e,L];return async(s,n)=>{let a;if(s instanceof b)a=s;else if(s instanceof HTTPException)a=new b(s.message,s.status,"HTTP_ERROR");else {for(let y of c)try{let R=await y(s,n);if(R){a=R;break}}catch{}!a&&m&&b$1().error("Unmapped error",{error:s instanceof Error?s.message:String(s)});}let E=a??new b(l,500,f),g=a$1(n);for(let y of o$1)try{let R=y(s,n,E);if(R instanceof Promise){let B=R.catch(Z=>{d&&d(Z,s,n);});g?.(B);}}catch(R){d&&d(R,s,n);}let h=E.toJSON();if(r){let y=q$2(n);y&&(h.error.requestId=y);}p&&s.stack&&(h.error.stack=s.stack);let C=q(n,i),u=C?C.error(h.error):h;return o(n,u,E.status)}}function q(t,e){return n(t)??e}var v=new Map,ao=["password","token","secret","apiKey","creditCard","ssn"];function H(t,e){if(t==null||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>H(r,e));let o={};for(let[r,p]of Object.entries(t))e.includes(r)||(o[r]=typeof p=="object"&&p!==null?H(p,e):p);return o}function co(t){let{table:e$1,events:o,emitter:r,filter:p,heartbeatIntervalMs:f=3e4,maxConnections:l=1e3,connectionTimeoutMs:m=3e5,excludeFields:d=ao}=t;return i=>{let c=e(i,r);if(!c)throw new b("Event emitter not configured",500,"EVENT_EMITTER_NOT_CONFIGURED");let s=v.get(e$1)||0;if(s>=l)throw new b("Too many SSE connections",503,"TOO_MANY_CONNECTIONS");return v.set(e$1,s+1),streamSSE(i,async n=>{let a,E=async u=>{if(o&&o.length>0&&!o.includes(u.type)||p&&!p(u,i))return;let y=d.length>0?H(u.data,d):u.data,R=u.previousData&&d.length>0?H(u.previousData,d):u.previousData;try{await n.writeSSE({event:`${u.table}.${u.type}`,data:JSON.stringify({type:u.type,table:u.table,recordId:u.recordId,data:y,previousData:R,timestamp:u.timestamp}),id:`${u.table}-${u.recordId}-${Date.now()}`});}catch{}};a=c.onTable(e$1,E);let g=()=>{a.unsubscribe();let u=v.get(e$1)||1;u<=1?v.delete(e$1):v.set(e$1,u-1);};n.onAbort(()=>{g();});let h=Date.now(),C=h;for(;!n.closed;){await n.sleep(1e3);let u=Date.now();if(u-h>=m){n.abort();break}if(u-C>=f){C=u;try{await n.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}})}}function uo(t,e,o,r={}){let p=e.endsWith("/")?e.slice(0,-1):e,f=t,{middlewares:l=[],endpointMiddlewares:m$1={},responseEnvelope:d}=r,i=d?async(n,a)=>{b$2(n,m,d),await a();}:void 0,c=n=>{let a=o[n],E=a&&"_middlewares"in a?a._middlewares||[]:[];return [...i?[i]:[],...l,...m$1[n]||[],...E]},s=(n,a,E,g)=>{let h=c(E),C=f[n];h.length>0?C(a,...h,g):C(a,g);};for(let[n,a$1,E]of a){let g=o[n];g&&s(a$1,`${p}${E}`,n,g);}ra(t,p,o);}function lo(t){return {content:{"application/json":{schema:t}}}}
2
2
  export{S as HonoOpenAPIHandler,Jt as buildPerTenantOpenApi,lo as contentJson,po as createErrorHandler,co as createSubscribeHandler,Lt as createValidationHook,Bt as fromHono,Vt as jsonContent,jt as jsonContentRequired,N as openApiValidationHook,uo as registerCrud,q as resolveErrorEnvelope,no as toOpenApiPaths,Xt as wrapCacheStorageForOpenApi,L as zodErrorMapper};
@@ -1,20 +1,20 @@
1
- import { a5 as RelationConfig, M as MetaInput, z as IncludeOptions } from './types-C2iJttg9.js';
2
- export { aA as AbstractConstructor, A as AggregateField, a as AggregateOptions, j as AggregateResult, aB as Constructor, E as ErrorResponse, s as FilterCondition, u as FilterOperator, L as ListFilters, V as NestedUpdateInput, X as NestedWriteResult, O as OpenAPIRouteSchema, a1 as PaginatedResult, a7 as RelationsConfig, a9 as ResponseEnvelopeInfo, af as SearchOptions, ag as SearchResult, ah as SearchResultItem, as as assertNever, aw as isFilterOperator } from './types-C2iJttg9.js';
3
- export { M as ModelObject } from './types-C9boymY0.js';
4
- export { O as OpenAPIRoute } from './route-CrJCBJMO.js';
5
- import { h as CrudEndpoints } from './index-s1OVgHp-.js';
6
- export { a4 as AdapterBundle, A as ApiException, B as BatchUpsertEndpoint, c as BatchUpsertItemResult, d as BatchUpsertResult, a5 as CRUD_ROUTES, e as ConfigurationException, g as CrudEndpointName, G as GeneratedEndpoints, I as ImportEndpoint, p as ImportMode, q as ImportOptions, r as ImportResult, s as ImportRowResult, t as ImportRowStatus, u as ImportSummary, w as NotFoundException, U as UnauthorizedException } from './index-s1OVgHp-.js';
1
+ import { a5 as RelationConfig, M as MetaInput, z as IncludeOptions, aA as RelationRequestScope } from './types-D72szrPV.js';
2
+ export { aB as AbstractConstructor, A as AggregateField, a as AggregateOptions, j as AggregateResult, aC as Constructor, E as ErrorResponse, s as FilterCondition, u as FilterOperator, L as ListFilters, V as NestedUpdateInput, X as NestedWriteResult, O as OpenAPIRouteSchema, a1 as PaginatedResult, a7 as RelationsConfig, a9 as ResponseEnvelopeInfo, af as SearchOptions, ag as SearchResult, ah as SearchResultItem, as as assertNever, aw as isFilterOperator } from './types-D72szrPV.js';
3
+ export { M as ModelObject } from './types-BTRpRT28.js';
4
+ export { O as OpenAPIRoute } from './route-CVsl4dg3.js';
5
+ import { h as CrudEndpoints } from './index-B2punCHK.js';
6
+ export { a4 as AdapterBundle, A as ApiException, B as BatchUpsertEndpoint, c as BatchUpsertItemResult, d as BatchUpsertResult, a5 as CRUD_ROUTES, e as ConfigurationException, g as CrudEndpointName, G as GeneratedEndpoints, I as ImportEndpoint, p as ImportMode, q as ImportOptions, r as ImportResult, s as ImportRowResult, t as ImportRowStatus, u as ImportSummary, w as NotFoundException, U as UnauthorizedException } from './index-B2punCHK.js';
7
7
  import { Env } from 'hono';
8
- export { A as AggregateEndpoint, B as BatchCreateEndpoint, a as BatchDeleteEndpoint, b as BatchDeleteResult, c as BatchRestoreEndpoint, d as BatchRestoreResult, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpdateResult, h as BulkPatchEndpoint, i as BulkPatchResult, C as CONTEXT_KEYS, j as CascadeResult, k as CloneEndpoint, l as ContextKey, m as CreateEndpoint, K as CursorPage, M as CursorPageInput, D as DeleteEndpoint, E as ExportEndpoint, n as ExportFormat, o as ExportOptions, p as ExportResult, L as ListEndpoint, q as Logger, R as ReadEndpoint, r as RestoreEndpoint, S as SearchEndpoint, U as UpdateEndpoint, s as UpsertEndpoint, t as UpsertResult, V as VersionCompareEndpoint, u as VersionHistoryEndpoint, v as VersionReadEndpoint, w as VersionRollbackEndpoint, x as applyUpsertRestore, N as buildCursorPage, y as computeAggregations, z as decodeCursor, F as encodeCursor, G as getLogger, I as searchInMemory } from './context-keys-9Q1takVn.js';
8
+ export { A as AggregateEndpoint, B as BatchCreateEndpoint, a as BatchDeleteEndpoint, b as BatchDeleteResult, c as BatchRestoreEndpoint, d as BatchRestoreResult, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpdateResult, h as BulkPatchEndpoint, i as BulkPatchResult, C as CONTEXT_KEYS, j as CascadeResult, k as CloneEndpoint, l as ContextKey, m as CreateEndpoint, K as CursorPage, M as CursorPageInput, D as DeleteEndpoint, E as ExportEndpoint, n as ExportFormat, o as ExportOptions, p as ExportResult, L as ListEndpoint, q as Logger, R as ReadEndpoint, r as RestoreEndpoint, S as SearchEndpoint, U as UpdateEndpoint, s as UpsertEndpoint, t as UpsertResult, V as VersionCompareEndpoint, u as VersionHistoryEndpoint, v as VersionReadEndpoint, w as VersionRollbackEndpoint, x as applyUpsertRestore, N as buildCursorPage, y as computeAggregations, z as decodeCursor, F as encodeCursor, G as getLogger, I as searchInMemory } from './context-keys-Dxyh3NuH.js';
9
+ import { ZodObject, ZodRawShape } from 'zod';
9
10
  export { a as getContextVar, s as setContextVar } from './context-m0qIRK5d.js';
10
11
  export { C as ClientIpOptions, g as getClientIp, a as getUserId } from './request-info-OQ40JnWp.js';
11
- export { d as extractBearerToken } from './jwt--gbnOqR-.js';
12
+ export { d as extractBearerToken } from './jwt-DhJ3yOR6.js';
12
13
  export { M as MemoryTtlStore, a as MemoryTtlStoreOptions, S as StorageFeature, b as StorageFeatureOptions, c as createStorageFeature } from './memory-ttl-store-D2Bbo-do.js';
13
14
  export { S as StorageRegistry } from './registry-DYXgzGt0.js';
14
15
  export { C as CacheEntry, a as CacheSetOptions, b as CacheStats, c as CacheStorage, F as FixedWindowEntry, I as IdempotencyEntry, d as IdempotencyStorage, R as RateLimitEntry, e as RateLimitStorage, S as SlidingWindowEntry } from './contracts-C3YJpWrM.js';
15
16
  export { KVNamespace } from './cloudflare/index.js';
16
17
  export { P as PathPattern, i as isPathIncluded, m as matchAny, a as matchPath } from './path-match-DGLu6wld.js';
17
- import 'zod';
18
18
  import './types-B5wq2iKZ.js';
19
19
  import './types-lAPVBoYa.js';
20
20
  import '@hono/zod-openapi';
@@ -74,8 +74,8 @@ declare function batchLoadRelations<T extends Record<string, unknown>, M extends
74
74
  /** Resolve ONE relation for ONE item; returns the relation value (record/array/
75
75
  * null), NOT a merged item. Always-set semantics: when the gate value is null/
76
76
  * undefined, the reducer runs over an empty list. */
77
- declare function resolveRelationValueAsync<Handle>(item: Record<string, unknown>, config: RelationConfig, handle: Handle, fetchRelated: FetchRelated<Handle>): Promise<unknown>;
78
- declare function resolveRelationValueSync<Handle>(item: Record<string, unknown>, config: RelationConfig, handle: Handle, fetchRelated: SyncFetchRelated<Handle>): unknown;
77
+ declare function resolveRelationValueAsync<Handle>(item: Record<string, unknown>, config: RelationConfig, handle: Handle, fetchRelated: FetchRelated<Handle>, requestScope?: RelationRequestScope): Promise<unknown>;
78
+ declare function resolveRelationValueSync<Handle>(item: Record<string, unknown>, config: RelationConfig, handle: Handle, fetchRelated: SyncFetchRelated<Handle>, requestScope?: RelationRequestScope): unknown;
79
79
  /** Load all requested relations for ONE item (async). Always sets the relation
80
80
  * key (hasOne/belongsTo -> record-or-null, hasMany -> array), including when the
81
81
  * gate value is null. Clones the item. */
@@ -83,4 +83,21 @@ declare function loadRelationsForItem<T extends Record<string, unknown>, M exten
83
83
  /** Synchronous variant for memory (no microtask; keeps memory callers sync). */
84
84
  declare function loadRelationsForItemSync<T extends Record<string, unknown>, M extends MetaInput, Handle>(item: T, meta: M, adapter: SyncRelationLoaderAdapter<Handle>, includeOptions?: IncludeOptions): T;
85
85
 
86
- export { CrudEndpoints, type FetchRelated, IncludeOptions, MetaInput, type RegisteredCrudResource, type RelatedRecord, RelationConfig, type RelationLoaderAdapter, type ResolveRelation, type SyncFetchRelated, type SyncRelationLoaderAdapter, type SyncResolveRelation, batchLoadRelations, getRegisteredCrudResources, loadRelationsForItem, loadRelationsForItemSync, resolveRelationValueAsync, resolveRelationValueSync };
86
+ /**
87
+ * Extend a List/Read response **item** schema with the model's includable
88
+ * relations, so the OpenAPI response documents what `?include=<relation>`
89
+ * returns — and generated typed clients auto-type the embedded related data
90
+ * instead of consumers having to hand-type it.
91
+ *
92
+ * A relation is added only when it is listed in `allowedIncludes` AND declares a
93
+ * `schema` (the related model's shape). The field is always OPTIONAL, since the
94
+ * relation is present only when explicitly requested via `?include=`:
95
+ * - `hasMany` → `z.array(relationSchema).optional()`
96
+ * - `belongsTo` / `hasOne` → `relationSchema.nullable().optional()`
97
+ *
98
+ * No-op (returns `itemSchema` unchanged) when there are no allowed includes or no
99
+ * included relation declares a `schema`.
100
+ */
101
+ declare function withIncludableRelations(itemSchema: ZodObject<ZodRawShape>, meta: MetaInput, allowedIncludes: readonly string[]): ZodObject<ZodRawShape>;
102
+
103
+ export { CrudEndpoints, type FetchRelated, IncludeOptions, MetaInput, type RegisteredCrudResource, type RelatedRecord, RelationConfig, type RelationLoaderAdapter, type ResolveRelation, type SyncFetchRelated, type SyncRelationLoaderAdapter, type SyncResolveRelation, batchLoadRelations, getRegisteredCrudResources, loadRelationsForItem, loadRelationsForItemSync, resolveRelationValueAsync, resolveRelationValueSync, withIncludableRelations };
package/dist/internal.js CHANGED
@@ -1 +1 @@
1
- export{a as MemoryTtlStore}from'./chunk-YB6AVUPQ.js';export{ca as AggregateEndpoint,U as BatchCreateEndpoint,W as BatchDeleteEndpoint,X as BatchRestoreEndpoint,V as BatchUpdateEndpoint,Y as BatchUpsertEndpoint,Z as BulkPatchEndpoint,a as CRUD_ROUTES,R as CloneEndpoint,M as CreateEndpoint,P as DeleteEndpoint,oa as ExportEndpoint,pa as ImportEndpoint,Q as ListEndpoint,N as ReadEndpoint,S as RestoreEndpoint,ea as SearchEndpoint,O as UpdateEndpoint,T as UpsertEndpoint,aa as VersionCompareEndpoint,_ as VersionHistoryEndpoint,$ as VersionReadEndpoint,ba as VersionRollbackEndpoint,u as applyUpsertRestore,m as buildCursorPage,da as computeAggregations,l as decodeCursor,k as encodeCursor,ra as getRegisteredCrudResources,fa as searchInMemory}from'./chunk-O6D3QREM.js';import'./chunk-P7HU2KIE.js';import'./chunk-H3VBYIDA.js';import'./chunk-CWQSQUV4.js';import'./chunk-SDNXN7M5.js';import'./chunk-HYXDMJ4K.js';import'./chunk-WBHWKOTP.js';import'./chunk-L5CVVJQH.js';export{p as extractBearerToken}from'./chunk-CTOFQ5RC.js';export{p as OpenAPIRoute,c as assertNever,b as isFilterOperator}from'./chunk-JBKQLYEU.js';export{a as getClientIp,b as getUserId,e as isPathIncluded,d as matchAny,c as matchPath}from'./chunk-V7ABUFW5.js';export{b as getLogger}from'./chunk-DMGP7QDL.js';export{a as StorageRegistry,b as createStorageFeature}from'./chunk-5P4RVSHT.js';export{a as getContextVar,b as setContextVar}from'./chunk-TLI3TRUA.js';export{b as ApiException,a as CONTEXT_KEYS,j as ConfigurationException,d as NotFoundException,f as UnauthorizedException}from'./chunk-XR6JRDGX.js';import'./chunk-NWOJZP4P.js';async function Re(e,o,r,a){if(!e.length||!a?.relations?.length||!o.model.relations)return e;let t=e.map(n=>({...n}));for(let n of a.relations){let l=o.model.relations[n];if(!l)continue;let s=await r.resolveRelation(l);s!=null&&(t=await ye[l.type](t,n,l,s,r));}return t}function f(e){return async(o,r,a,t,n)=>{let l=a.localKey||"id",s=[...new Set(o.map(p=>p[l]).filter(p=>p!=null))];if(s.length===0)return o.map(p=>({...p,[r]:e?null:[]}));let c=await n.fetchRelated(t,a.foreignKey,s),i=new Map;for(let p of c){let d=p[a.foreignKey],u=i.get(d);u?u.push(p):i.set(d,[p]);}return o.map(p=>{let d=i.get(p[l])||[];return {...p,[r]:e?d[0]||null:d}})}}function me(){return async(e,o,r,a,t)=>{let n=r.localKey||"id",l=[...new Set(e.map(i=>i[r.foreignKey]).filter(i=>i!=null))];if(l.length===0)return e.map(i=>({...i,[o]:null}));let s=await t.fetchRelated(a,n,l),c=new Map;for(let i of s)c.set(i[n],i);return e.map(i=>({...i,[o]:c.get(i[r.foreignKey])||null}))}}var ye={hasOne:f(true),hasMany:f(false),belongsTo:me()},R={hasOne:e=>e[0]??null,hasMany:e=>e,belongsTo:e=>e[0]??null};function m(e,o){let r=e.localKey||"id";if(e.type==="belongsTo"){let t=o[e.foreignKey];return t==null?null:{gateValue:t,keyField:r}}let a=o[r];return a==null?null:{gateValue:a,keyField:e.foreignKey}}async function y(e,o,r,a){let t=R[o.type],n=m(o,e);if(!n)return t([]);let l=await a(r,n.keyField,[n.gateValue]);return t(l)}function g(e,o,r,a){let t=R[o.type],n=m(o,e);if(!n)return t([]);let l=a(r,n.keyField,[n.gateValue]);return t(l)}async function ge(e,o,r,a){if(!a?.relations?.length||!o.model.relations)return e;let t={...e};for(let n of a.relations){let l=o.model.relations[n];if(!l)continue;let s=await r.resolveRelation(l);s!=null&&(t[n]=await y(t,l,s,r.fetchRelated));}return t}function xe(e,o,r,a){if(!a?.relations?.length||!o.model.relations)return e;let t={...e};for(let n of a.relations){let l=o.model.relations[n];if(!l)continue;let s=r.resolveRelation(l);s!=null&&(t[n]=g(t,l,s,r.fetchRelated));}return t}export{Re as batchLoadRelations,ge as loadRelationsForItem,xe as loadRelationsForItemSync,y as resolveRelationValueAsync,g as resolveRelationValueSync};
1
+ export{a as MemoryTtlStore}from'./chunk-YB6AVUPQ.js';export{da as AggregateEndpoint,V as BatchCreateEndpoint,X as BatchDeleteEndpoint,Y as BatchRestoreEndpoint,W as BatchUpdateEndpoint,Z as BatchUpsertEndpoint,_ as BulkPatchEndpoint,a as CRUD_ROUTES,S as CloneEndpoint,M as CreateEndpoint,Q as DeleteEndpoint,pa as ExportEndpoint,qa as ImportEndpoint,R as ListEndpoint,O as ReadEndpoint,T as RestoreEndpoint,fa as SearchEndpoint,P as UpdateEndpoint,U as UpsertEndpoint,ba as VersionCompareEndpoint,$ as VersionHistoryEndpoint,aa as VersionReadEndpoint,ca as VersionRollbackEndpoint,u as applyUpsertRestore,m as buildCursorPage,ea as computeAggregations,l as decodeCursor,k as encodeCursor,sa as getRegisteredCrudResources,ga as searchInMemory,N as withIncludableRelations}from'./chunk-QWMISKGR.js';import'./chunk-P7HU2KIE.js';import'./chunk-H3VBYIDA.js';import'./chunk-CWQSQUV4.js';import'./chunk-SDNXN7M5.js';import'./chunk-HYXDMJ4K.js';import'./chunk-WBHWKOTP.js';import'./chunk-L5CVVJQH.js';export{p as extractBearerToken}from'./chunk-CTOFQ5RC.js';export{p as OpenAPIRoute,c as assertNever,b as isFilterOperator}from'./chunk-A27HDYSF.js';export{a as getClientIp,b as getUserId,e as isPathIncluded,d as matchAny,c as matchPath}from'./chunk-V7ABUFW5.js';export{b as getLogger}from'./chunk-DMGP7QDL.js';export{a as StorageRegistry,b as createStorageFeature}from'./chunk-5P4RVSHT.js';export{a as getContextVar,b as setContextVar}from'./chunk-TLI3TRUA.js';export{b as ApiException,a as CONTEXT_KEYS,j as ConfigurationException,d as NotFoundException,f as UnauthorizedException}from'./chunk-XR6JRDGX.js';import'./chunk-NWOJZP4P.js';function f(e,o,r){let t=o.scope;if(!t||!r)return e;let{tenantField:a,softDeleteField:l}=t,{tenantId:n,includeDeleted:s}=r,d=a!=null&&n!=null,u=l!=null&&!s;return !d&&!u?e:e.filter(c=>!(d&&c[a]!==n||u&&c[l]!=null))}async function ge(e,o,r,t){if(!e.length||!t?.relations?.length||!o.model.relations)return e;let a=e.map(l=>({...l}));for(let l of t.relations){let n=o.model.relations[l];if(!n)continue;let s=await r.resolveRelation(n);s!=null&&(a=await Ee[n.type](a,l,n,s,r,t.scope));}return a}function y(e){return async(o,r,t,a,l,n)=>{let s=t.localKey||"id",d=[...new Set(o.map(p=>p[s]).filter(p=>p!=null))];if(d.length===0)return o.map(p=>({...p,[r]:e?null:[]}));let u=await l.fetchRelated(a,t.foreignKey,d),c=f(u,t,n),i=new Map;for(let p of c){let R=p[t.foreignKey],m=i.get(R);m?m.push(p):i.set(R,[p]);}return o.map(p=>{let R=i.get(p[s])||[];return {...p,[r]:e?R[0]||null:R}})}}function he(){return async(e,o,r,t,a,l)=>{let n=r.localKey||"id",s=[...new Set(e.map(i=>i[r.foreignKey]).filter(i=>i!=null))];if(s.length===0)return e.map(i=>({...i,[o]:null}));let d=await a.fetchRelated(t,n,s),u=f(d,r,l),c=new Map;for(let i of u)c.set(i[n],i);return e.map(i=>({...i,[o]:c.get(i[r.foreignKey])||null}))}}var Ee={hasOne:y(true),hasMany:y(false),belongsTo:he()},x={hasOne:e=>e[0]??null,hasMany:e=>e,belongsTo:e=>e[0]??null};function g(e,o){let r=e.localKey||"id";if(e.type==="belongsTo"){let a=o[e.foreignKey];return a==null?null:{gateValue:a,keyField:r}}let t=o[r];return t==null?null:{gateValue:t,keyField:e.foreignKey}}async function h(e,o,r,t,a){let l=x[o.type],n=g(o,e);if(!n)return l([]);let s=f(await t(r,n.keyField,[n.gateValue]),o,a);return l(s)}function E(e,o,r,t,a){let l=x[o.type],n=g(o,e);if(!n)return l([]);let s=f(t(r,n.keyField,[n.gateValue]),o,a);return l(s)}async function Ce(e,o,r,t){if(!t?.relations?.length||!o.model.relations)return e;let a={...e};for(let l of t.relations){let n=o.model.relations[l];if(!n)continue;let s=await r.resolveRelation(n);s!=null&&(a[l]=await h(a,n,s,r.fetchRelated,t.scope));}return a}function Se(e,o,r,t){if(!t?.relations?.length||!o.model.relations)return e;let a={...e};for(let l of t.relations){let n=o.model.relations[l];if(!n)continue;let s=r.resolveRelation(n);s!=null&&(a[l]=E(a,n,s,r.fetchRelated,t.scope));}return a}export{ge as batchLoadRelations,Ce as loadRelationsForItem,Se as loadRelationsForItemSync,h as resolveRelationValueAsync,E as resolveRelationValueSync};
@@ -1,5 +1,5 @@
1
1
  import { Context, MiddlewareHandler } from 'hono';
2
- import { d as AuthEnv, aT as JWTConfig, aN as JWTClaims } from './types-C2iJttg9.js';
2
+ import { d as AuthEnv, aU as JWTConfig, aO as JWTClaims } from './types-D72szrPV.js';
3
3
 
4
4
  /**
5
5
  * Default function to extract a Bearer token from the `Authorization` header.
@@ -1,6 +1,6 @@
1
1
  import { S as StorageRegistry } from './registry-DYXgzGt0.js';
2
2
  import { Env, Context } from 'hono';
3
- import { a_ as APIKeyStorage, aD as APIKeyEntry, aO as APIKeyLookupResult } from './types-C2iJttg9.js';
3
+ import { a$ as APIKeyStorage, aE as APIKeyEntry, aP as APIKeyLookupResult } from './types-D72szrPV.js';
4
4
 
5
5
  /**
6
6
  * In-memory storage for API keys.
@@ -1,5 +1,5 @@
1
1
  import { Context, Env, MiddlewareHandler } from 'hono';
2
- import { _ as NormalizedMultiTenantConfig, Q as MultiTenantConfig, an as TenantIdSource } from '../types-C2iJttg9.js';
2
+ import { _ as NormalizedMultiTenantConfig, Q as MultiTenantConfig, an as TenantIdSource } from '../types-D72szrPV.js';
3
3
  import 'zod';
4
4
  import '../path-match-DGLu6wld.js';
5
5
  import '../types-B5wq2iKZ.js';
@@ -1,7 +1,7 @@
1
1
  import { Env, Context } from 'hono';
2
2
  import { ContentfulStatusCode } from 'hono/utils/http-status';
3
3
  import { ZodObject, ZodRawShape } from 'zod';
4
- import { O as OpenAPIRouteSchema, aa as RouteOptions, ao as ValidatedData, R as ResponseEnvelope, a9 as ResponseEnvelopeInfo } from './types-C2iJttg9.js';
4
+ import { O as OpenAPIRouteSchema, aa as RouteOptions, ao as ValidatedData, R as ResponseEnvelope, a9 as ResponseEnvelopeInfo } from './types-D72szrPV.js';
5
5
 
6
6
  /**
7
7
  * Base class for OpenAPI routes.
@@ -1,13 +1,13 @@
1
- import { a as StorageMiddlewareConfig, S as StorageEnv } from '../types-ByPjCs4O.js';
1
+ import { a as StorageMiddlewareConfig, S as StorageEnv } from '../types-xNoq2dk9.js';
2
2
  export { C as CacheEntry, a as CacheSetOptions, b as CacheStats, c as CacheStorage, F as FixedWindowEntry, I as IdempotencyEntry, d as IdempotencyStorage, R as RateLimitEntry, e as RateLimitStorage, S as SlidingWindowEntry } from '../contracts-C3YJpWrM.js';
3
3
  import { Env, MiddlewareHandler, Context } from 'hono';
4
4
  export { M as MemoryTtlStore, a as MemoryTtlStoreOptions, S as StorageFeature, b as StorageFeatureOptions, c as createStorageFeature } from '../memory-ttl-store-D2Bbo-do.js';
5
5
  export { S as StorageRegistry } from '../registry-DYXgzGt0.js';
6
- export { c as getAPIKeyStorageRequired, r as resolveAPIKeyStorage } from '../memory-B50rK9-O.js';
6
+ export { c as getAPIKeyStorageRequired, r as resolveAPIKeyStorage } from '../memory-DfSspNoL.js';
7
7
  export { getAuditStorageRequired, resolveAuditStorage } from '../audit/index.js';
8
8
  export { a as getLoggingStorageRequired, r as resolveLoggingStorage } from '../middleware-CrCo6EgQ.js';
9
9
  export { getVersioningStorageRequired, resolveVersioningStorage } from '../versioning/index.js';
10
- import '../types-C2iJttg9.js';
10
+ import '../types-D72szrPV.js';
11
11
  import 'zod';
12
12
  import '../path-match-DGLu6wld.js';
13
13
  import '../types-B5wq2iKZ.js';
@@ -1,5 +1,5 @@
1
1
  import { ZodObject, ZodRawShape } from 'zod';
2
- import { K as Model, D as InferModel, t as FilterConfig, ak as SortSpec, u as FilterOperator, L as ListFilters } from './types-C2iJttg9.js';
2
+ import { K as Model, D as InferModel, t as FilterConfig, ak as SortSpec, u as FilterOperator, L as ListFilters } from './types-D72szrPV.js';
3
3
 
4
4
  interface ListFilterParseOptions {
5
5
  filterFields?: string[];
@@ -647,17 +647,63 @@ interface RelationConfig<TTable = unknown> {
647
647
  * Configuration for cascade operations when parent is deleted.
648
648
  */
649
649
  cascade?: CascadeConfig;
650
+ /**
651
+ * Access scope applied to the RELATED rows when this relation is loaded via
652
+ * `?include=`. Without it, an include loads related rows by foreign key alone —
653
+ * so a parent the caller may read can expose a related row in another tenant
654
+ * (or a soft-deleted one). Declare the related table's owner/soft-delete columns
655
+ * here to scope the include to the caller, closing that cross-tenant read.
656
+ */
657
+ scope?: RelationScopeConfig;
658
+ }
659
+ /**
660
+ * Per-relation access scope for `?include=`. Names the columns ON THE RELATED
661
+ * TABLE used to constrain loaded related rows to what the caller may read.
662
+ */
663
+ interface RelationScopeConfig {
664
+ /**
665
+ * Column on the related table holding its owner/tenant id. When set, included
666
+ * related rows are filtered to the request's resolved tenant id
667
+ * (`IncludeOptions.scope.tenantId`), so a foreign-key pointing at another
668
+ * tenant's row resolves to `null` (belongsTo/hasOne) or is omitted (hasMany).
669
+ * Use when the related model is owner-scoped by the same identity as the parent.
670
+ */
671
+ tenantField?: string;
672
+ /**
673
+ * Soft-delete column on the related table. When set, soft-deleted related rows
674
+ * (column non-null) are excluded from includes unless the request opts in via
675
+ * `?withDeleted=true` (`IncludeOptions.scope.includeDeleted`).
676
+ */
677
+ softDeleteField?: string;
650
678
  }
651
679
  /**
652
680
  * Map of relation names to their configurations.
653
681
  */
654
682
  type RelationsConfig = Record<string, RelationConfig>;
683
+ /**
684
+ * Request-scoped values that drive {@link RelationScopeConfig} filtering of
685
+ * included related rows. Populated by the endpoint from the parent request's
686
+ * resolved tenant id and `withDeleted` flag; consumed by the relation loader.
687
+ */
688
+ interface RelationRequestScope {
689
+ /** The request's resolved tenant id (parent endpoint's `getTenantId()`). */
690
+ tenantId?: unknown;
691
+ /** When true (`?withDeleted=true`), keep soft-deleted related rows. */
692
+ includeDeleted?: boolean;
693
+ }
655
694
  /**
656
695
  * Parsed include options from query string.
657
696
  */
658
697
  interface IncludeOptions {
659
698
  /** List of relation names to include */
660
699
  relations: string[];
700
+ /**
701
+ * Request-scoped access scope applied to included related rows (owner-scope +
702
+ * soft-delete), per each relation's {@link RelationScopeConfig}. Omitted when
703
+ * the request resolves no tenant — in which case only declared `softDeleteField`
704
+ * filtering (if any) applies.
705
+ */
706
+ scope?: RelationRequestScope;
661
707
  }
662
708
  /**
663
709
  * Configuration for nested write operations on a relation.
@@ -1859,4 +1905,4 @@ type Constructor<T = object> = new (...args: unknown[]) => T;
1859
1905
  */
1860
1906
  type AbstractConstructor<T = object> = abstract new (...args: unknown[]) => T;
1861
1907
 
1862
- export { type NormalizedSoftDeleteConfig as $, type AggregateField as A, type InferMeta as B, type ComputedFieldsConfig as C, type InferModel as D, type ErrorResponse as E, FILTER_OPERATORS as F, type InferSchema as G, type HandleArgs as H, type IdStrategy as I, type ListOptions as J, type Model as K, type ListFilters as L, type MetaInput as M, type ModelPolicies as N, type OpenAPIRouteSchema as O, type ModelTable as P, type MultiTenantConfig as Q, type ResponseEnvelope as R, type SchemaResolveContext as S, type NestedCreateManyInput as T, type NestedCreateOneInput as U, type NestedUpdateInput as V, type NestedWriteConfig as W, type NestedWriteResult as X, type NestedWritesConfig as Y, type NormalizedAuditConfig as Z, type NormalizedMultiTenantConfig as _, type AggregateOptions as a, type NormalizedVersioningConfig as a0, type PaginatedResult as a1, type PartialBy as a2, type PolicyContext as a3, RESPONSE_ENVELOPE_CONTEXT_KEY as a4, type RelationConfig as a5, type RelationType as a6, type RelationsConfig as a7, type RequiredBy as a8, type ResponseEnvelopeInfo as a9, type AbstractConstructor as aA, type Constructor as aB, type APIKeyConfig as aC, type APIKeyEntry as aD, type AuthConfig as aE, type Guard as aF, type ApprovalConfig as aG, type AuthorizationCheck as aH, type OwnershipExtractor as aI, type ApprovalStorage as aJ, type PendingAction as aK, type AuthUser as aL, type EndpointAuthConfig as aM, type JWTClaims as aN, type APIKeyLookupResult as aO, type ActionSource as aP, type AuthType as aQ, type JWTAlgorithm as aR, JWTClaimsSchema as aS, type JWTConfig as aT, JWT_ALGORITHMS as aU, PendingActionSchema as aV, type PendingActionStatus as aW, type ValidatedJWTClaims as aX, parseJWTClaims as aY, safeParseJWTClaims as aZ, type APIKeyStorage as a_, type RouteOptions as aa, SEARCH_MODES as ab, SORT_DIRECTIONS as ac, type SchemaKeys as ad, type SearchConfig as ae, type SearchOptions as af, type SearchResult as ag, type SearchResultItem as ah, type SoftDeleteConfig as ai, type SortDirection as aj, type SortSpec as ak, type StructuredError as al, type SuccessResponse as am, type TenantIdSource as an, type ValidatedData as ao, type ValidationIssue as ap, type VersionHistoryEntry as aq, type VersioningConfig as ar, assertNever as as, defineMeta as at, defineModel as au, errorEnvelopeSchema as av, isFilterOperator as aw, structuredErrorSchema as ax, successEnvelopeSchema as ay, validationIssueSchema as az, type SearchFieldConfig as b, type SearchMode as c, type AuthEnv as d, AGGREGATE_OPERATIONS as e, type AfterDeleteHook as f, type AfterUpdateHook as g, type AggregateConfig as h, type AggregateOperation as i, type AggregateResult as j, type AuditAction as k, type AuditConfig as l, type AuditFieldChange as m, type AuditLogEntry as n, type CascadeAction as o, type CascadeConfig as p, type ComputedFieldConfig as q, type ComputedFieldFn as r, type FilterCondition as s, type FilterConfig as t, type FilterOperator as u, type HookConfig as v, type HookContext as w, type HookFn as x, type HookMode as y, type IncludeOptions as z };
1908
+ export { type NormalizedSoftDeleteConfig as $, type AggregateField as A, type InferMeta as B, type ComputedFieldsConfig as C, type InferModel as D, type ErrorResponse as E, FILTER_OPERATORS as F, type InferSchema as G, type HandleArgs as H, type IdStrategy as I, type ListOptions as J, type Model as K, type ListFilters as L, type MetaInput as M, type ModelPolicies as N, type OpenAPIRouteSchema as O, type ModelTable as P, type MultiTenantConfig as Q, type ResponseEnvelope as R, type SchemaResolveContext as S, type NestedCreateManyInput as T, type NestedCreateOneInput as U, type NestedUpdateInput as V, type NestedWriteConfig as W, type NestedWriteResult as X, type NestedWritesConfig as Y, type NormalizedAuditConfig as Z, type NormalizedMultiTenantConfig as _, type AggregateOptions as a, type APIKeyStorage as a$, type NormalizedVersioningConfig as a0, type PaginatedResult as a1, type PartialBy as a2, type PolicyContext as a3, RESPONSE_ENVELOPE_CONTEXT_KEY as a4, type RelationConfig as a5, type RelationType as a6, type RelationsConfig as a7, type RequiredBy as a8, type ResponseEnvelopeInfo as a9, type RelationRequestScope as aA, type AbstractConstructor as aB, type Constructor as aC, type APIKeyConfig as aD, type APIKeyEntry as aE, type AuthConfig as aF, type Guard as aG, type ApprovalConfig as aH, type AuthorizationCheck as aI, type OwnershipExtractor as aJ, type ApprovalStorage as aK, type PendingAction as aL, type AuthUser as aM, type EndpointAuthConfig as aN, type JWTClaims as aO, type APIKeyLookupResult as aP, type ActionSource as aQ, type AuthType as aR, type JWTAlgorithm as aS, JWTClaimsSchema as aT, type JWTConfig as aU, JWT_ALGORITHMS as aV, PendingActionSchema as aW, type PendingActionStatus as aX, type ValidatedJWTClaims as aY, parseJWTClaims as aZ, safeParseJWTClaims as a_, type RouteOptions as aa, SEARCH_MODES as ab, SORT_DIRECTIONS as ac, type SchemaKeys as ad, type SearchConfig as ae, type SearchOptions as af, type SearchResult as ag, type SearchResultItem as ah, type SoftDeleteConfig as ai, type SortDirection as aj, type SortSpec as ak, type StructuredError as al, type SuccessResponse as am, type TenantIdSource as an, type ValidatedData as ao, type ValidationIssue as ap, type VersionHistoryEntry as aq, type VersioningConfig as ar, assertNever as as, defineMeta as at, defineModel as au, errorEnvelopeSchema as av, isFilterOperator as aw, structuredErrorSchema as ax, successEnvelopeSchema as ay, validationIssueSchema as az, type SearchFieldConfig as b, type SearchMode as c, type AuthEnv as d, AGGREGATE_OPERATIONS as e, type AfterDeleteHook as f, type AfterUpdateHook as g, type AggregateConfig as h, type AggregateOperation as i, type AggregateResult as j, type AuditAction as k, type AuditConfig as l, type AuditFieldChange as m, type AuditLogEntry as n, type CascadeAction as o, type CascadeConfig as p, type ComputedFieldConfig as q, type ComputedFieldFn as r, type FilterCondition as s, type FilterConfig as t, type FilterOperator as u, type HookConfig as v, type HookContext as w, type HookFn as x, type HookMode as y, type IncludeOptions as z };
@@ -1,6 +1,6 @@
1
1
  import { Env } from 'hono';
2
2
  import { AuditLogStorage } from './audit/index.js';
3
- import { a_ as APIKeyStorage, aJ as ApprovalStorage } from './types-C2iJttg9.js';
3
+ import { a$ as APIKeyStorage, aK as ApprovalStorage } from './types-D72szrPV.js';
4
4
  import { C as CrudEventEmitter } from './emitter-B8EL76d3.js';
5
5
  import { a as LoggingStorage } from './types-B3XBv6XB.js';
6
6
  import { VersioningStorage } from './versioning/index.js';
@@ -1,6 +1,6 @@
1
1
  import { S as StorageRegistry } from '../registry-DYXgzGt0.js';
2
2
  import { Context, Env } from 'hono';
3
- import { ar as VersioningConfig, a0 as NormalizedVersioningConfig, aq as VersionHistoryEntry, m as AuditFieldChange } from '../types-C2iJttg9.js';
3
+ import { ar as VersioningConfig, a0 as NormalizedVersioningConfig, aq as VersionHistoryEntry, m as AuditFieldChange } from '../types-D72szrPV.js';
4
4
  import 'zod';
5
5
  import '../path-match-DGLu6wld.js';
6
6
  import '../types-B5wq2iKZ.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-crud",
3
- "version": "0.13.14",
3
+ "version": "0.13.16",
4
4
  "description": "CRUD generator for Hono with Zod validation and OpenAPI generation",
5
5
  "author": "Kauan Guesser <contato@kauan.net>",
6
6
  "license": "MIT",
@@ -1,11 +0,0 @@
1
- import {e as e$3,f as f$1}from'./chunk-P7HU2KIE.js';import {e as e$2}from'./chunk-H3VBYIDA.js';import {a as a$4,b as b$3}from'./chunk-CWQSQUV4.js';import {a as a$5,b as b$4}from'./chunk-SDNXN7M5.js';import {i,a as a$3}from'./chunk-HYXDMJ4K.js';import {h as h$1}from'./chunk-WBHWKOTP.js';import {a}from'./chunk-L5CVVJQH.js';import {f,b,N,P,d as d$1,S,R,c,e as e$1,p,y}from'./chunk-JBKQLYEU.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {a as a$1,b as b$5}from'./chunk-TLI3TRUA.js';import {j,e,d,b as b$2,h,c as c$1,a as a$2,g}from'./chunk-XR6JRDGX.js';import {z}from'zod';import {stream}from'hono/streaming';var oo=[["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"],["bulkPatch","patch","/bulk"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"],["versionHistory","get","/:id/versions"],["versionCompare","get","/:id/versions/compare"],["versionRead","get","/:id/versions/:version"],["versionRollback","post","/:id/versions/:version/rollback"]];var Re="createdAt",Se="updatedAt";function ie(n){return n?n===true?{enabled:true,createdAt:Re,updatedAt:Se}:{enabled:true,createdAt:n.createdAt??Re,updatedAt:n.updatedAt??Se}:{enabled:false,createdAt:Re,updatedAt:Se}}function v(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 Zt(n){return n!=null&&n!==""}function Ke(n,e,t,o){let r={...n},s=e.primaryKeys[0];if(!Zt(r[s])){let l=e.id;if(typeof l=="function")r[s]=l();else if(l==="database"){if(t==="memory")throw new j("MemoryAdapter does not support id:'database' (no database to generate the key)");delete r[s];}else r[s]=o?o():crypto.randomUUID();}let i=ie(e.timestamps);if(i.enabled){let l=Date.now();i.createdAt in n||(r[i.createdAt]=l),i.updatedAt in n||(r[i.updatedAt]=l);}return r}function Qe(n,e){let t=ie(e.timestamps);return t.enabled?{...n,[t.updatedAt]:Date.now()}:{...n}}function We(n,e){if(e==="memory"&&n.id==="database")throw new j("MemoryAdapter does not support id:'database' (no database to generate the key)")}function Ge(n,e){let t={...n};for(let o of v(e))delete t[o];return t}var Lt=new Set(["P2002","SQLITE_CONSTRAINT_UNIQUE","SQLITE_CONSTRAINT","23505","ER_DUP_ENTRY",1062,"1062"]),Ut=/UNIQUE constraint failed|duplicate key value violates unique constraint|Duplicate entry/i;function zt(n){if(!n||typeof n!="object")return false;let{code:e,message:t}=n;return (typeof e=="string"||typeof e=="number")&&Lt.has(e)?true:typeof t=="string"&&Ut.test(t)}function*Bt(n,e=8){for(let t=n,o=0;o<e&&t!=null&&typeof t=="object";o++)yield t,t=t.cause;}function Oe(n){for(let e$1 of Bt(n))if(zt(e$1))return new e("Unique constraint violation");return null}function H(n){throw Oe(n)??n}function qt(n){return btoa(String(n))}function io(n){try{return atob(n)}catch{return null}}function ao(n){let{rows:e,limit:t,totalCount:o,cursorField:r,cursorApplied:s}=n,i=e.length>t,l=i?e.slice(0,t):e,d=l[l.length-1];return {items:l,result_info:{page:0,per_page:t,total_count:o,has_next_page:i,has_prev_page:s,next_cursor:i&&d!==void 0?qt(d[r]):void 0}}}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 Ye(n,e){return !e||Object.keys(e).length===0?n:Promise.all(n.map(t=>ae(t,e)))}function oe(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 pe(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 mo(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 Je(n){let e=[],t={};for(let a of f){let p=n[a];if(p){let u=Array.isArray(p)?p:[p];for(let m of u)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(p=>p.trim()):Array.isArray(a)&&(o=a.filter(p=>typeof p=="string"));}let r;for(let[a,p]of Object.entries(n)){let u=a.match(/^having\[(\w+)\]\[(\w+)\]$/);if(u){let[,m,f]=u;r||(r={}),r[m]||(r[m]={}),r[m][f]=p;}}let s=typeof n.orderBy=="string"?n.orderBy:void 0,i=n.orderDirection==="desc"?"desc":"asc",l=typeof n.limit=="string"?Number.parseInt(n.limit,10):void 0,d=typeof n.offset=="string"?Number.parseInt(n.offset,10):void 0,c=[...f,"groupBy","orderBy","orderDirection","limit","offset"];for(let[a,p]of Object.entries(n))!c.includes(a)&&!a.startsWith("having[")&&(t[a]=p);return {aggregations:e,groupBy:o,filters:Object.keys(t).length>0?t:void 0,having:r,orderBy:s,orderDirection:i,limit:l,offset:d}}function Xe(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 re(n,e,t){return t.enabled&&e[t.field]!=null?{...n,[t.field]:null}:n}var Ht=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 tt(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=>!Ht.has(o)&&o.length>1):t}function ot(n,e){return e==="phrase"?[n.toLowerCase().trim()]:tt(n)}function $t(n,e){return e.length===0?0:e.filter(o=>o===n||o.includes(n)).length/e.length}function rt(n,e,t,o){if(e.length===0)return {score:0,matchedFields:[]};let r=0,s=0,i=[];for(let[d,c]of Object.entries(t)){let a=n[d];if(a==null)continue;let p=c.weight??1;s+=p;let u;c.type==="array"&&Array.isArray(a)?u=a.join(" "):u=String(a);let m=tt(u,false),f=u.toLowerCase(),h=0,S=0;if(o==="phrase"){let g=e[0];f.includes(g)&&(h=1,S=1);}else {for(let g of e){let R=$t(g,m);R>0?(S++,h+=R):f.includes(g)&&(S++,h+=.5/e.length);}e.length>0&&(h=h/e.length);}o==="all"&&S<e.length&&(h=0),h>0&&(i.push(d),r+=h*p);}return {score:s>0?Math.min(1,r/s):0,matchedFields:i}}function nt(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=[],l=s.toLowerCase();if(t==="phrase"){let d=e[0],c=l.indexOf(d);if(c!==-1){let a=et(s,c,d.length,r,o);a&&i.push(a);}}else {let d=[];for(let a of e){let p=0;for(;p<l.length;){let u=l.indexOf(a,p);if(u===-1)break;d.push({start:u,length:a.length}),p=u+1;}}d.sort((a,p)=>a.start-p.start);let c=new Set;for(let a of d){if(Array.from(c).some(m=>Math.abs(m-a.start)<r))continue;let u=et(s,a.start,a.length,r,o);if(u&&(i.push(u),c.add(a.start)),i.length>=3)break}}return i}function et(n,e,t,o,r){let s=Math.floor(o/2),i=Math.max(0,e-s),l=Math.min(n.length,e+t+s);if(i>0){let a=n.indexOf(" ",i);a!==-1&&a<e&&(i=a+1);}if(l<n.length){let a=n.lastIndexOf(" ",l);a!==-1&&a>e+t&&(l=a);}let d=n.slice(i,l);return i>0&&(d="..."+d),l<n.length&&(d=d+"..."),Kt(d,[n.slice(e,e+t)],r)}function Kt(n,e,t){let o=n,r=n.toLowerCase(),s=[...e].sort((i,l)=>l.length-i.length);for(let i of s){let l=i.toLowerCase(),d=0,c="",a=0;for(;a<r.length;){let p=r.indexOf(l,a);if(p===-1)break;c+=o.slice(d,p),c+=`<${t}>${o.slice(p,p+i.length)}</${t}>`,d=p+i.length,a=d;}c&&(c+=o.slice(d),o=c);}return o}function st(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 it(n,e){let t={};for(let o of n)t[o]={weight:e?.[o]??1};return t}function at(n){return n==="all"||n==="phrase"?n:"any"}function ke(n){if(n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(ke);let e={};for(let t of Object.keys(n).sort())e[t]=ke(n[t]);return e}async function de(n){let e=JSON.stringify(ke(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 dt(n,e){return n?n==="*"?true:n.split(",").map(t=>t.trim()).includes(e):false}function lt(n,e){return !n||n==="*"?true:n.split(",").map(t=>t.trim()).includes(e)}function ct(n,e){return n==="in"||n==="nin"||n==="between"?e.split(",").map(t=>t.trim()):n==="null"?e.toLowerCase()==="true":e}function wo(n){let e=n.match(/^\[([a-z]+)\](.*)$/);if(e&&b(e[1])){let t=e[1];return {operator:t,value:ct(t,e[2])}}return {operator:"eq",value:n}}function ne(n,e){let t=[],o={},{filterFields:r=[],filterConfig:s={},searchFields:i=[],searchParamName:l="search",sortFields:d=[],defaultSort:c,defaultPerPage:a=20,maxPerPage:p=100,cursorPaginationEnabled:u=false,cursorField:m,softDeleteQueryParam:f="withDeleted",allowedIncludes:h=[],fieldSelectionEnabled:S=false,allowedSelectFields:g=[],blockedSelectFields:R=[],alwaysIncludeFields:j=[],defaultSelectFields:N=[]}=e,J={};for(let C of r)J[C]=["eq"];Object.assign(J,s);for(let[C,we]of Object.entries(n)){if(we==null)continue;let D=String(we);if(u&&C==="cursor"){o.cursor=D;continue}if(u&&C==="limit"){o.limit=Math.min(p,Math.max(1,Number.parseInt(D,10)||a));continue}if(C==="page"){o.page=Math.max(1,Number.parseInt(D,10)||1);continue}if(C==="per_page"){o.per_page=Math.min(p,Math.max(1,Number.parseInt(D,10)||a));continue}if(C==="sort"){(d.length===0||d.includes(D))&&(o.order_by=D);continue}if(C==="order"){(D==="asc"||D==="desc")&&(o.order_by_direction=D);continue}if(C===l&&i.length>0){o.search=D;continue}if(C===f){o.withDeleted=D.toLowerCase()==="true";continue}if(C==="onlyDeleted"){o.onlyDeleted=D.toLowerCase()==="true";continue}if(C==="include"){let X=D.split(",").map(U=>U.trim()).filter(Boolean);h&&h.length>0?o.include=X.filter(U=>h.includes(U)):o.include=X;continue}if(C==="fields"&&S){let U=D.split(",").map(se=>se.trim()).filter(Boolean);g.length>0&&(U=U.filter(se=>g.includes(se))),R.length>0&&(U=U.filter(se=>!R.includes(se))),j.length>0&&(U=[...new Set([...j,...U])]),o.fields=U;continue}let Me=C.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(Me){let X=Me[1],U=Me[2];J[X]?.includes(U)&&t.push({field:X,operator:U,value:ct(U,D)});continue}J[C]&&t.push({field:C,operator:"eq",value:D});}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"),u&&(o.cursor!==void 0||o.limit!==void 0)&&(o.order_by=m??"id",o.order_by_direction="asc"),S&&!o.fields&&N.length>0){let C=[...N];j.length>0&&(C=[...new Set([...j,...C])]),o.fields=C;}return {filters:t,options:o}}function _(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 Mo(n,e={},t=[],o=[],r=[]){let{allowedFields:s=[],blockedFields:i=[],alwaysIncludeFields:l=[],defaultFields:d=[],allowComputedFields:c=true,allowRelationFields:a=true}=e;if(!n||typeof n!="string"||n.trim()==="")return d.length>0?{fields:[...new Set([...l,...d])],isActive:false}:{fields:[],isActive:false};let p=n.split(",").map(h=>h.trim()).filter(Boolean),u=new Set;for(let h of t)(s.length===0||s.includes(h))&&(i.includes(h)||u.add(h));if(c)for(let h of o)(s.length===0||s.includes(h))&&(i.includes(h)||u.add(h));if(a)for(let h of r)(s.length===0||s.includes(h))&&(i.includes(h)||u.add(h));let m=p.filter(h=>u.has(h));return {fields:[...new Set([...l,...m])],isActive:true}}function xe(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 ut(n,e){return !e.isActive||e.fields.length===0?n:n.map(t=>xe(t,e))}var pt="__honoCrudResolvedSchema:";function Qt(n){return typeof n.getBodySchema=="function"}var k=class extends p{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=h$1(this._meta.model.audit,void 0,this.context??void 0)),this._auditLogger}getAuditConfig(){return a(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$2.userId):void 0}getVersionManager(){return this._versionManager||(this._versionManager=i(this._meta.model.versioning,this._meta.model.tableName,void 0,this.context??void 0)),this._versionManager}getVersioningConfig(){return a$3(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$2.userId):void 0}getSoftDeleteConfig(){return Xe(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return a$4(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,t,o){return Ke(e,this._meta.model,t,o)}applyManagedUpdateFields(e){return Qe(e,this._meta.model)}assertIdStrategySupported(e){We(this._meta.model,e);}getTimestampsConfig(){return ie(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return b$3(this.context,e)}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();if(!t&&e.required)throw new b$2(e.errorMessage,400,"TENANT_REQUIRED");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=e$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$2.organizationId):void 0,timestamp:new Date().toISOString(),metadata:t.metadata});}async encryptOnWrite(e){let t=this._meta.model.fieldEncryption;return t?await e$3(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$5(e,t):e}applyProfileToArray(e){let t=this._meta.model.serializationProfile;return t?b$4(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),l=this.transform(i);return t?.isActive&&t.fields.length>0?xe(l,t):l}async finalizeArray(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await Ye(r,o.computedFields));let s=o.serializer?r.map(d=>o.serializer(d)):r,l=this.applyProfileToArray(s).map(d=>this.transform(d));return t?.isActive&&t.fields.length>0?ut(l,t):l}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,y);if(e)return e}return this._meta.model.policies}buildPolicyContext(){let e=this.context;return {user:e?a$1(e,a$2.user):void 0,userId:e?a$1(e,a$2.userId):void 0,tenantId:e?a$1(e,a$2.tenantId):void 0,organizationId:e?a$1(e,a$2.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 g("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$2.organizationId):void 0,userId:e?a$1(e,a$2.userId):void 0,agentId:e?a$1(e,a$2.agentId):void 0,agentRunId:e?a$1(e,a$2.agentRunId):void 0}}getModelSchema(){if(this.context&&this._meta.model.resolveSchema){let e=a$1(this.context,pt+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=pt+this._meta.model.tableName,o=a$1(this.context,t);if(o)return o;let r={tenantId:a$1(this.context,a$2.tenantId),organizationId:a$1(this.context,a$2.organizationId),request:this.context.req?.raw,env:this.context.env},s;try{s=await e(r);}catch(i){throw new b$2(i instanceof Error?i.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",i instanceof Error?{cause:i.message}:void 0)}return b$5(this.context,t,s),s}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&Qt(this)){let t=e.body;try{t=await this.context.req.json();}catch{}let r=this.getBodySchema().safeParse(t);if(!r.success)throw c$1.fromZodError(r.error);e.body=r.data;}return e}};var mt=class extends k{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,t=v(this._meta.model),o=this.getMultiTenantConfig();o.enabled&&t.push(o.field),this._meta.fields?e=this._meta.fields:e=_(this.getModelSchema(),t);let r=this.getNestedWritableRelations();if(r.length===0)return e;let s={...e.shape};for(let i of r){let l=this._meta.model.relations?.[i];if(!l?.schema)continue;let d=["id",l.foreignKey],c=_(l.schema,d);l.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 oe(e,t)}getSchema(){let e=this.getBodySchema();return N({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:P("Validation error")}},this.schema)}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(H),r=await this.decryptOnRead(r);let i=this.getParentId(r),l={};if(Object.keys(o).length>0&&i!==null)for(let[c,a]of Object.entries(o)){if(a==null)continue;let p=this._meta.model.relations?.[c];if(!p)continue;let u=await this.createNested(i,c,p,a);l[c]=u;}if(Object.keys(l).length>0){let c={};for(let[a,p]of Object.entries(l)){let u=this._meta.model.relations?.[a];u&&(u.type==="hasMany"?c[a]=p:c[a]=p[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 d=await this.finalizeRecord(r);return this.success(d,201)}};var ht=class extends k{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 N({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:P("Resource not found")}},this.schema)}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 d(this._meta.model.tableName,t);i=await this.decryptOnRead(i);let l=await this.applyReadPolicy(i);if(l===null)throw new d(this._meta.model.tableName,t);i=l,i=await this.after(i);let d$1=await this.finalizeRecord(i,s);if(this.etagEnabled){let c=await de(d$1),a=this.getContext(),p=a.req.header("If-None-Match");if(dt(p,c))return new Response(null,{status:304,headers:{ETag:c}});a.header("ETag",c);}return this.success(d$1)}};var ft=class extends k{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=v(this._meta.model);this.blockedUpdateFields&&(r=[...r,...this.blockedUpdateFields]);let s=_(this.getModelSchema(),r);if(this.allowedUpdateFields){let i={};for(let l of this.allowedUpdateFields)i[l]=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,l=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]=l;}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 oe(e,t)}getSchema(){return N({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:P("Validation error"),404:P("Resource not found")}},this.schema)}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 g=this.getMultiTenantConfig();o[g.field]=e;}let r=await this.getObject(),{mainData:s,nestedData:i}=this.extractNestedData(r),l=this.getPolicies(),d$1=await this.findExisting(t,o,this._tx);if(d$1&&l?.write&&await this.applyWritePolicy(d$1),this.etagEnabled&&d$1){let g=this.getContext().req.header("If-Match");if(g){let R=await de(d$1);if(!lt(g,R))return this.error("Resource has been modified by another request","CONFLICT",409)}}let c;if(this.isVersioningEnabled()&&d$1){let g=this.getVersionManager(),R=this.getParentId(d$1);R!==null&&(c=await g.saveVersion(R,d$1,void 0,this.getVersioningUserId()));}let a=s;if(this.isVersioningEnabled()&&c!==void 0){let g=this.getVersioningConfig().field;a[g]=c;}let p=this.buildHookContext();a=await this.before(a,p),a=await this.encryptOnWrite(a);let u=await this.update(t,a,o,p.db.tx);if(!u)throw new d(this._meta.model.tableName,t);u=await this.decryptOnRead(u);let m=this.getParentId(u),f={};if(Object.keys(i).length>0&&m!==null)for(let[g,R]of Object.entries(i)){if(R==null)continue;let j=this._meta.model.relations?.[g];if(!j)continue;let N;pe(R)?N={create:R}:N=R;let J=await this.processNestedWrites(m,g,j,N);f[g]=J;}if(Object.keys(f).length>0)for(let[g,R]of Object.entries(f)){let j=this._meta.model.relations?.[g];j&&(j.type==="hasMany"?u[g]=[...R.created,...R.updated]:u[g]=R.created[0]||R.updated[0]||null);}let h=d$1??u;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(h,u,p)));else {let g=await this.after(h,u,p);g!=null&&(u=g);}if(this.isAuditEnabled()&&m!==null&&d$1){let g=this.getAuditLogger();this.runAfterResponse(g.logUpdate(this._meta.model.tableName,m,d$1,u,this.getAuditUserId()));}m!==null&&this.runAfterResponse(this.emitEvent("updated",{recordId:m,data:u,previousData:d$1??void 0}));let S=await this.finalizeRecord(u);if(this.etagEnabled){let g=await de(S);this.getContext().header("ETag",g);}return this.success(S)}};var gt=class extends k{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 N({request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:P("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()})})}}}}},this.schema)}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:l,config:d,action:c}of s)if(c==="cascade"){let a=await this.deleteRelated(e,l,d,o);a>0&&(i.deleted[l]=a);}else if(c==="setNull"){let a=await this.nullifyRelated(e,l,d,o);a>0&&(i.nullified[l]=a);}return i}async checkRestrictConstraints(e$1,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r);for(let{name:i,config:l,action:d}of s)if(d==="restrict"){let c=await this.countRelated(e$1,i,l,o);if(c>0)throw new e(`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 p=this.getMultiTenantConfig();o[p.field]=e;}let r=this.isSoftDeleteEnabled(),s=await this.findForDelete(t,o,this._tx);if(!s)throw new d(this._meta.model.tableName,t);let i=this.getParentId(s);i!==null&&await this.checkRestrictConstraints(i,r),await this.applyWritePolicy(s);let l=this.buildHookContext();if(await this.before(t,l),!await this.delete(t,o,l.db.tx))throw new d(this._meta.model.tableName,t);let c;if(i!==null&&(c=await this.processCascade(i,r)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(s,l))):await this.after(s,l),this.isAuditEnabled()&&i!==null){let p=this.getAuditLogger();this.runAfterResponse(p.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){let p=Object.keys(c.deleted).length>0,u=Object.keys(c.nullified).length>0;(p||u)&&(a.cascade=c);}return this.success(a)}};var he=class extends k{filterFields=[];filterConfig;searchFields=[];searchParamName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;supportsCursorPagination=false;cursorField;isCursorPaginationActive(){return this.cursorPaginationEnabled&&this.supportsCursorPagination}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.searchParamName]=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.isCursorPaginationActive()&&(e.cursor=z.string().optional().meta({description:"Opaque cursor for fetching the next page. During a cursor walk, results are ordered by the cursor field ascending and sort/order are ignored."}),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(){let e={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()};return this.isCursorPaginationActive()&&(e.next_cursor=z.string().optional()),N({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(e)})}}},400:P("Validation error")}},this.schema)}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:this.searchFields,searchParamName:this.searchParamName,sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,cursorPaginationEnabled:this.isCursorPaginationActive(),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 ne(e||{},o)}async after(e){return e}transform(e){return e}async handle(){if(this.cursorPaginationEnabled&&!this.supportsCursorPagination)throw new j("cursorPaginationEnabled is true but this adapter's List endpoint does not implement cursor pagination (supportsCursorPagination is false). Use an adapter List endpoint that supports it, or disable cursorPaginationEnabled.");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),l=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?{fields:t.options.fields,isActive:true}:void 0,d=await this.finalizeArray(i,l);return this.successPaginated(d,o.result_info)}};var bt=class extends k{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...v(this._meta.model),...this.excludeFromClone];return _(this.getModelSchema(),e).partial()}getSchema(){return N({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:P("Source resource not found"),409:P("Unique-constraint violation (e.g. natural-key collision)")}},this.schema)}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 d(this._meta.model.tableName,t);let i=Ge(s,this._meta.model);for(let a of this.excludeFromClone)delete i[a];Object.assign(i,o);let l=await this.before(i),d$1=await this.createClone(l).catch(H);d$1=await this.after(d$1);let c=await this.finalizeRecord(d$1);return this.success(c,201)}};var yt=class extends k{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:P("Soft delete not enabled or record not deleted"),404:P("Resource not found")}},this.schema)}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 b$2("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 d(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 wt=class extends k{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=v(this._meta.model,{includePrimaryKeys:false});for(let d of this._meta.model.primaryKeys)r.includes(d)||s.push(d);let i=_(this.getModelSchema(),s),l={};for(let[d,c]of Object.entries(i.shape))r.includes(d)?l[d]=c:l[d]=c.optional();e=z.object(l);}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,l=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]=l;}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 oe(e,t)}getSchema(){return N({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:P("Validation error")}},this.schema)}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),r=re(r,o,this.getSoftDeleteConfig()),{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 l=await this.upsert(r).catch(H),d=l.data,c=this.getParentId(d),a={};if(Object.keys(o).length>0&&c!==null)for(let[u,m]of Object.entries(o)){if(m==null)continue;let f=this._meta.model.relations?.[u];if(!f)continue;let h;pe(m)?h={create:m}:h=m;let S=await this.processNestedWrites(c,u,f,h);a[u]=S;}if(Object.keys(a).length>0)for(let[u,m]of Object.entries(a)){let f=this._meta.model.relations?.[u];f&&(f.type==="hasMany"?d[u]=[...m.created,...m.updated]:d[u]=m.created[0]||m.updated[0]||null);}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(d,l.created))):d=await this.after(d,l.created),this.isAuditEnabled()&&c!==null){let u=this.getAuditLogger();this.runAfterResponse(u.logUpsert(this._meta.model.tableName,c,d,s,l.created,this.getAuditUserId()));}let p=await this.finalizeRecord(d);return this.json({success:true,result:p,created:l.created},l.created?201:200)}};var Mt=class extends k{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:_(this.getModelSchema(),v(this._meta.model));return z.object({items:z.array(e).min(1).max(this.maxBatchSize)})}getSchema(){return N({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:P("Validation error")}},this.schema)}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(H),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(p=>{let u=this.getRecordId(p);return u===null?null:{recordId:u,record:p}}).filter(p=>p!==null);a.length>0&&this.runAfterResponse(c.logBatch("batch_create",this._meta.model.tableName,a,this.getAuditUserId()));}let i=await this.finalizeArray(s),l={success:true,result:{created:i,count:i.length,...t.length>0&&{errors:t}}},d=t.length>0?207:201;return this.json(l,d)}};var Rt=class extends k{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:_(this.getModelSchema(),v(this._meta.model));return z.object({items:z.array(z.object({id:z.string(),data:e.partial()})).min(1).max(this.maxBatchSize)})}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("updated",this.getModelSchema(),"Resources updated successfully"),400:P("Validation error")}},this.schema)}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 p=this.filterUpdateData(a.data),u=await this.before(a.id,p);o.push({id:a.id,data:u});}catch(p){if(this.stopOnError)throw p;t.push({id:a.id,error:p instanceof Error?p.message:String(p)});}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(p){let u=String(a[this.lookupField]);if(this.stopOnError)throw p;t.push({id:u,error:p instanceof Error?p.message:String(p)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),p=i.map(u=>{let m=this.getRecordId(u);return m===null?null:{recordId:m,record:u}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(a.logBatch("batch_update",this._meta.model.tableName,p,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{updated:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(d,c)}};var St=class extends k{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return R(this.maxBatchSize)}getSchema(){let e=this.isSoftDeleteEnabled();return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("deleted",this.getModelSchema(),e?"Resources soft-deleted successfully":"Resources deleted successfully"),400:P("Validation error")}},this.schema)}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(p){if(this.stopOnError)throw p;t.push({id:a,error:p instanceof Error?p.message:String(p)});}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(p){let u=String(a[this.lookupField]);if(this.stopOnError)throw p;t.push({id:u,error:p instanceof Error?p.message:String(p)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),p=i.map(u=>{let m=this.getRecordId(u);return m===null?null:{recordId:m,previousRecord:u}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(a.logBatch("batch_delete",this._meta.model.tableName,p,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{deleted:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(d,c)}};var Ot=class extends k{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return R(this.maxBatchSize)}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("restored",this.getModelSchema(),"Resources restored successfully"),400:P("Soft delete not enabled or validation error")}},this.schema)}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 b$2("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(p){if(this.stopOnError)throw p;t.push({id:a,error:p instanceof Error?p.message:String(p)});}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(p){let u=String(a[this.lookupField]);if(this.stopOnError)throw p;t.push({id:u,error:p instanceof Error?p.message:String(p)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),p=i.map(u=>{let m=this.getRecordId(u);return m===null?null:{recordId:m,record:u}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(a.logBatch("batch_restore",this._meta.model.tableName,p,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{restored:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(d,c)}};var kt=class extends k{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=v(this._meta.model,{includePrimaryKeys:false});for(let s of this._meta.model.primaryKeys)e.includes(s)||t.push(s);let o=_(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 N({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:P("Validation error")}},this.schema)}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),l;if(r){if(this.createOnlyFields)for(let c of this.createOnlyFields)delete i[c];let d=re(i,r,this.getSoftDeleteConfig());l=await this.update(r,d,o);}else {if(this.updateOnlyFields)for(let d of this.updateOnlyFields)delete i[d];l=await this.create(i,o);}return l=await this.afterItem(l,t,s,o),{data:l,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 d=0;d<e.length;d++)try{let c=await this.upsertOne(e[d],d,t);o.push(c),c.created?s++:i++;}catch(c){if(this.continueOnError)r.push({index:d,error:c instanceof Error?c.message:String(c)});else throw c}let l={items:o,createdCount:s,updatedCount:i,totalCount:o.length};return r.length>0&&(l.errors=r),l}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(H);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 xt=class extends k{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getUpdateSchema(){let e=v(this._meta.model);return _(this.getModelSchema(),e).partial()}getSchema(){let e=this.getUpdateSchema();return N({request:{body:{content:{"application/json":{schema:e.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:P("Bulk patch rejected (empty body, size limit, or missing confirmation)")}},this.schema)}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=ne(e.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),l=await this.countMatching(i);if(l===0)return this.json({success:true,matched:0,updated:0,dryRun:s});if(l>this.maxBulkSize)return this.error(`Bulk patch affects ${l} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(l>=this.confirmThreshold&&e.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${l} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(s)return this.json({success:true,matched:l,updated:0,dryRun:true});let d=o;this.beforeBulkPatch&&(d=await this.beforeBulkPatch(d,i,l));let c=await this.applyPatch(d,i),a={matched:l,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 Et=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()}),jt=class extends k{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 N({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(Et),totalVersions:z.number()})})}}},400:P("Versioning not enabled"),404:P("Record not found")}},this.schema)}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 b$2("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 d(this._meta.model.tableName,e);let s=this.getVersionManager(),i=await s.getVersions(e,{limit:t,offset:o}),l=await s.getLatestVersion(e);return this.success({versions:i,totalVersions:l})}},Ft=class extends k{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:Et})}}},400:P("Versioning not enabled"),404:P("Version not found")}},this.schema)}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 b$2("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 d(`version ${t}`,e);return this.success(r)}},Pt=class extends k{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 N({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:P("Versioning not enabled or invalid parameters"),404:P("Version not found")}},this.schema)}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 b$2("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})}},It=class extends k{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return N({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:P("Versioning not enabled"),404:P("Version not found")}},this.schema)}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 b$2("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 d(`version ${t}`,e);let i=await o.getLatestVersion(e)+1,l=await this.rollback(e,r.data,i),d$1=this._meta.model.serializer?this._meta.model.serializer(l):l;return this.success(d$1)}};var Wt={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},Ct=class extends k{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {...Wt,...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 N({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:P("Invalid aggregation request")}},this.schema)}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return Je(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 h(`Field '${o.field}' is not allowed for SUM aggregation`);break;case "avg":if(t.avgFields.length>0&&!t.avgFields.includes(o.field))throw new h(`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 h(`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 h(`Field '${o.field}' is not allowed for COUNT DISTINCT aggregation`);break;default:c(o.operation);}if(e.groupBy){if(e.groupBy.length>this.maxGroupByFields)throw new h(`Maximum ${this.maxGroupByFields} GROUP BY fields allowed`);for(let o of e.groupBy)if(t.groupByFields.length>0&&!t.groupByFields.includes(o))throw new h(`Field '${o}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>t.maxLimit)throw new h(`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 after(e){return e}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.after(await this.aggregate(e));return this.success(o)}},Gt={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 Yt(n,e){let t=n.get(e);if(t)return t;let o=[];return n.set(e,o),o}function Nn(n,e){let{aggregations:t,groupBy:o,having:r,orderBy:s,orderDirection:i,limit:l,offset:d}=e;if(!o||o.length===0){let u={};for(let m of t){let f=vt(m);u[f]=At(n,m);}return {values:u}}let c=new Map;for(let u of n){let f=o.map(h=>String(u[h]??"null")).join("|");Yt(c,f).push(u);}let a=[];for(let[u,m]of c){let f=u.split("|"),h={};o.forEach((g,R)=>{h[g]=f[R]==="null"?null:f[R];});let S={};for(let g of t){let R=vt(g);S[R]=At(m,g);}a.push({key:h,values:S});}r&&(a=a.filter(u=>{for(let[m,f]of Object.entries(r)){let h=u.values[m];if(h!==null)for(let[S,g]of Object.entries(f)){let R=Gt[S];if(R&&!R(h,Number(g)))return false}}return true}));let p=a.length;if(s){let u=i==="desc"?-1:1;a.sort((m,f)=>{if(s in m.values){let h=m.values[s]??0,S=f.values[s]??0;return (h-S)*u}if(s in m.key){let h=String(m.key[s]??""),S=String(f.key[s]??"");return h.localeCompare(S)*u}return 0});}if(d!==void 0||l!==void 0){let u=d||0,m=l?u+l:void 0;a=a.slice(u,m);}return {groups:a,totalGroups:p}}function je(n,e){return n.map(t=>t[e]).filter(t=>typeof t=="number")}var Jt={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=je(n,e);return t.length===0?null:t.reduce((r,s)=>r+s,0)/t.length},min:(n,e)=>{let t=je(n,e);return t.length===0?null:Math.min(...t)},max:(n,e)=>{let t=je(n,e);return t.length===0?null:Math.max(...t)}};function At(n,e){if(n.length===0)return e.operation==="count"?0:null;let t=Jt[e.operation];return t?t(n,e.field):null}function vt(n){return n.alias?n.alias:n.field==="*"?n.operation:`${n.operation}${n.field.charAt(0).toUpperCase()}${n.field.slice(1)}`}function Xt(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 _t=class extends k{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 it(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,t={};for(let[o,r]of Object.entries(e))Xt(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$1).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 N({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:P("Invalid search request")}},this.schema)}async getSearchOptions(){let{query:e}=await this.getValidatedData(),t=this.searchParamName||"q",o=e?.[t],r=e?.fields,s=at(e?.mode),i=e?.highlight==="true",l=e?.minScore?Math.max(0,Math.min(1,Number.parseFloat(e.minScore)||0)):this.defaultMinScore,d=this.getSearchableFields(),c=st(r,d);return {query:o,fields:c.length>0?c:Object.keys(d),mode:s??this.defaultMode,highlight:i,minScore:l}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchParamName:"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 ne(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)throw new b$2(`Search query must be at least ${this.minQueryLength} characters`,400,"INVALID_QUERY");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(u=>u.item),s),l=r.map((u,m)=>({...u,item:i[m]})),d=o.postFilteredCount??o.totalCount,c=t.options.page||1,a=t.options.per_page||this.defaultPerPage,p=Math.ceil(d/a);return this.successPaginated(l,{page:c,per_page:a,total_count:d,total_pages:p,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function Hn(n,e,t){let o=ot(e.query,e.mode),r={},s=e.fields||Object.keys(t);for(let l of s)t[l]&&(r[l]=t[l]);let i=[];for(let l of n){let{score:d,matchedFields:c}=rt(l,o,r,e.mode);if(d<e.minScore||c.length===0)continue;let a;if(e.highlight){a={};for(let p of c){let u=nt(l[p],o,e.mode);u.length>0&&(a[p]=u);}}i.push({item:l,score:d,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:c});}return i.sort((l,d)=>d.score-l.score),i}function $(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 $(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 Fe(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
3
- `,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:l={},nullValue:d="",dateFormat:c="iso"}=e;if(n.length===0)return "";let a=e.headers;a?a=a.filter(u=>!i.includes(u)):a=Object.keys(n[0]).filter(u=>!i.includes(u));let p=[];if(r){let u=a.map(m=>{let f=l[m]||m;return $(f,{delimiter:t,nullValue:d,dateFormat:c})});p.push(u.join(t));}for(let u of n){let m=a.map(f=>{let h=u[f];return s[f]&&(h=s[f](h)),$(h,{delimiter:t,nullValue:d,dateFormat:c})});p.push(m.join(t));}return p.join(o)}function Kn(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
4
- `,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:l={},nullValue:d="",dateFormat:c="iso"}=e,a=new TextEncoder,p=0,u=false,m=e.headers;return !m&&n.length>0?m=Object.keys(n[0]).filter(f=>!i.includes(f)):m?m=m.filter(f=>!i.includes(f)):m=[],new ReadableStream({pull(f){if(r&&!u&&m.length>0){let g=m.map(R=>{let j=l[R]||R;return $(j,{delimiter:t,nullValue:d,dateFormat:c})});f.enqueue(a.encode(g.join(t)+o)),u=true;return}let h=100,S=[];for(;p<n.length&&S.length<h;){let g=n[p],R=m.map(j=>{let N=g[j];return s[j]&&(N=s[j](N)),$(N,{delimiter:t,nullValue:d,dateFormat:c})});S.push(R.join(t)),p++;}S.length>0&&f.enqueue(a.encode(S.join(o)+o)),p>=n.length&&f.close();}})}function Tt(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 eo(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:l="empty"}=e,d={data:[],headers:[],errors:[]},c=eo(n);if(c.length===0)return d;let a=0;if(o){let u=c[0];d.headers=Tt(u,t).map(m=>r?m.trim():m),a=1;}else e.headers&&(d.headers=e.headers);let p=e.headers||d.headers;for(let u=a;u<c.length;u++){let m=c[u],f=u+1;if(!(s&&m.trim()===""))try{let h=Tt(m,t),S={};for(let g=0;g<p.length;g++){let R=p[g],j=g<h.length?h[g]:"";if(r&&typeof j=="string"&&(j=j.trim()),j==="")switch(l){case "null":j=null;break;case "undefined":j=void 0;break}if(i[R]&&typeof j=="string")try{j=i[R](j);}catch(N){d.errors.push({row:f,message:`Failed to parse field "${R}": ${N instanceof Error?N.message:String(N)}`,content:m});}S[R]=j;}d.data.push(S);}catch(h){d.errors.push({row:f,message:`Failed to parse row: ${h instanceof Error?h.message:String(h)}`,content:m});}}return d}function Nt(n,e,t={}){let{allowUnknownFields:o=false,optionalFields:r=[]}=t,s=e.shape,i=Object.keys(s),d=i.filter(u=>r.includes(u)?false:!s[u].isOptional()).filter(u=>!n.includes(u)),c=n.filter(u=>!i.includes(u)),a=n.filter(u=>i.includes(u));return {valid:d.length===0&&(o||c.length===0),missingFields:d,unknownFields:c,validFields:a}}function Qn(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 Wn(n,e={}){return Fe(n,e)}function Gn(n,e={}){return Pe(n,e).data}var Dt=class extends he{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 N({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()}}},400:P("Validation error")}},this.schema)}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=Fe(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 l=>{if(o.header("Content-Type","text/csv; charset=utf-8"),o.header("Content-Disposition",`attachment; filename="${r}"`),e.length===0)return;let d=Object.keys(e[0]).filter(p=>!i.includes(p)),c=d.map(p=>$(p,s)).join(",")+`
8
- `;await l.write(c);let a=100;for(let p=0;p<e.length;p+=a)for(let u of e.slice(p,p+a)){let m=d.map(f=>$(u[f],s)).join(",")+`
9
- `;await l.write(m);}})}exportAsCsvStreamPaginated(e,t){let o=this.getExportFilename(t),r=this.streamPageSize,s=Math.min(this.maxExportRecords,1e5),i=this.excludedExportFields,l=this.csvOptions,d=null,c=new ReadableStream({start:async a=>{let p=new TextEncoder,u=1,m=0;try{for(;m<s;){let f={...e,options:{...e.options,page:u,per_page:r}},S=(await this.list(f)).result;if(S.length===0)break;S.length>s-m&&(S=S.slice(0,s-m)),S=await this.after(S),S=await this.beforeExport(S);let g=this.prepareRecordsForExport(S);if(!d&&g.length>0){d=Object.keys(g[0]).filter(j=>!i.includes(j));let R=d.map(j=>$(j,l)).join(",")+`
10
- `;a.enqueue(p.encode(R));}if(d)for(let R of g){let j=d.map(N=>$(R[N],l)).join(",")+`
11
- `;a.enqueue(p.encode(j));}if(m+=S.length,u++,S.length<r)break}}catch(f){a.error(f);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 Vt=class extends k{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:_(this.getModelSchema(),v(this._meta.model));return z.object({items:z.array(e.partial()).min(1).max(this.maxBatchSize)})}getSchema(){return N({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:P("Validation error")}},this.schema)}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 c$1("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 c$1("Request body is empty");if(!o.items||!Array.isArray(o.items))throw new c$1('Request body must contain an "items" array');if(o.items.length>this.maxBatchSize)throw new c$1(`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 c$1(`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 c$1("No file provided in form data");let s=await r.text();if(s.length>this.maxBodySize)throw new c$1(`Uploaded file exceeds maximum size of ${this.maxBodySize} bytes`);let i=r.name.toLowerCase();if(i.endsWith(".json")){let d;try{d=JSON.parse(s);}catch{throw new c$1("Invalid JSON content in uploaded file")}let c=Array.isArray(d)?d:d.items;if(!c||!Array.isArray(c))throw new c$1('JSON file must contain an array or an object with "items" array');if(c.length>this.maxBatchSize)throw new c$1(`Maximum ${this.maxBatchSize} items allowed per import`);return c}if(i.endsWith(".csv"))return this.parseCsvData(s);let l=s.trim();if(l.startsWith("[")||l.startsWith("{")){let d;try{d=JSON.parse(s);}catch{throw new c$1("Invalid JSON content in uploaded file")}let c=Array.isArray(d)?d:d.items;if(!c||!Array.isArray(c))throw new c$1('JSON file must contain an array or an object with "items" array');return c}return this.parseCsvData(s)}throw new c$1("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 c$1(`CSV parsing errors: ${t.errors.map(s=>`Row ${s.row}: ${s.message}`).join("; ")}`);if(t.data.length===0)throw new c$1("CSV file is empty");if(t.data.length>this.maxBatchSize)throw new c$1(`Maximum ${this.maxBatchSize} items allowed per import`);let o=this._meta.fields||this.getModelSchema(),r=Nt(t.headers,o,{allowUnknownFields:true,optionalFields:this.optionalImportFields});if(!r.valid&&r.missingFields.length>0)throw new c$1(`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 v(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(d=>({path:d.path.join("."),message:d.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 d=await this.findExisting(i,r);if(d){let c=re(this.removeImmutableFields(i),d,this.getSoftDeleteConfig()),a=await this.update(d,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 l=await this.create(i,r);return {rowNumber:t,status:"created",data:l}}catch(i){let l=Oe(i);return l?{rowNumber:t,status:"failed",code:"CONFLICT",error:l.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 j("importBatchSize must be a positive integer");let o={total:t.length,created:0,updated:0,skipped:0,failed:0},r=[],s=false,i=e.stopOnError?1:this.importBatchSize;for(let c=0;c<t.length&&!s;c+=i){let a=t.slice(c,c+i),p=await Promise.all(a.map(async(u,m)=>{let f=c+m+1,h=await this.processRow(u,f,e);return h=await this.after(h,f,e.mode),h}));for(let u of p){switch(r.push(u),u.status){case "created":o.created++;break;case "updated":o.updated++;break;case "skipped":o.skipped++;break;case "failed":o.failed++;break}if(e.stopOnError&&u.status==="failed"){s=true;break}}}if(this.isAuditEnabled()){let c=this.getAuditLogger(),a=r.filter(p=>p.status==="created"||p.status==="updated");if(a.length>0){let p=a.map(u=>{if(!u.data)return null;let m=this.getRecordId(u.data);return m===null?null:{recordId:m,record:u.data}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(c.logBatch(e.mode==="upsert"?"batch_upsert":"batch_create",this._meta.model.tableName,p,this.getAuditUserId()));}}let l={summary:o,results:r},d=o.failed>0&&o.failed<o.total?207:200;return this.json({success:true,result:l},d)}};var ye=Symbol.for("hono-crud.resource-registry");function ms(n,e,t){let o=n;o[ye]||(o[ye]=[]),o[ye].push({path:e,endpoints:t});}function hs(n){return n[ye]??[]}export{Ft as $,st as A,it as B,at as C,de as D,dt as E,lt as F,wo as G,ne as H,_ as I,Mo as J,xe as K,ut as L,mt as M,ht as N,ft as O,gt as P,he as Q,bt as R,yt as S,wt as T,Mt as U,Rt as V,St as W,Ot as X,kt as Y,xt as Z,jt as _,oo as a,Pt as aa,ie as b,It as ba,v as c,Ct as ca,Ke as d,Nn as da,Qe as e,_t as ea,We as f,Hn as fa,Ge as g,$ as ga,Bt as h,Fe as ha,Oe as i,Kn as ia,H as j,Pe as ja,qt as k,Nt as ka,io as l,Qn as la,ao as m,Wn as ma,ae as n,Gn as na,Ye as o,Dt as oa,oe as p,Vt as pa,pe as q,ms as qa,mo as r,hs as ra,Je as s,Xe as t,re as u,tt as v,ot as w,$t as x,rt as y,nt as z};