hono-crud 0.13.4 → 0.13.6
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 +20 -0
- package/dist/api-version/index.js +1 -1
- package/dist/audit/index.d.ts +1 -1
- package/dist/audit/index.js +1 -1
- package/dist/auth/index.d.ts +3 -2
- package/dist/auth/index.js +1 -1
- package/dist/chunk-4NKDESHS.js +1 -0
- package/dist/{chunk-FC56WWPB.js → chunk-5FV7DBVK.js} +1 -1
- package/dist/chunk-5UM6RIIB.js +1 -0
- package/dist/chunk-5WYS3YRT.js +1 -0
- package/dist/chunk-65NCGRBB.js +1 -0
- package/dist/chunk-B3II5FPG.js +1 -0
- package/dist/chunk-BPBFNTBM.js +1 -0
- package/dist/chunk-CKUGVMFX.js +1 -0
- package/dist/chunk-CVNB5GB5.js +1 -0
- package/dist/chunk-EX4S3Q4M.js +1 -0
- package/dist/chunk-FCBFFSE3.js +11 -0
- package/dist/chunk-FOJBZJRS.js +1 -0
- package/dist/chunk-HIDT3P5C.js +1 -0
- package/dist/chunk-IJBJE4G2.js +1 -0
- package/dist/chunk-P5JQKX7Z.js +1 -0
- package/dist/chunk-SC5G6HH3.js +1 -0
- package/dist/chunk-UAVAEDVS.js +1 -0
- package/dist/chunk-ZJWDAVGG.js +1 -0
- package/dist/config/index.d.ts +10 -0
- package/dist/config/index.js +1 -0
- package/dist/{emitter-BgVwpiRd.d.ts → emitter-CmtYDwNp.d.ts} +2 -6
- package/dist/events/index.d.ts +2 -2
- package/dist/events/index.js +1 -1
- package/dist/functional/index.d.ts +139 -0
- package/dist/functional/index.js +1 -0
- package/dist/{index-_ymQzFJo.d.ts → index-B6a8YXS1.d.ts} +8 -91
- package/dist/index-Biz6ZLmk.d.ts +821 -0
- package/dist/index-DJAdPTsm.d.ts +4660 -0
- package/dist/index.d.ts +17 -5553
- package/dist/index.js +1 -1
- package/dist/internal.d.ts +32 -26
- package/dist/internal.js +1 -1
- package/dist/logging/index.js +1 -1
- package/dist/multi-tenant/index.js +1 -1
- package/dist/route-cu4t0BCp.d.ts +94 -0
- package/dist/storage/index.d.ts +3 -3
- package/dist/storage/index.js +1 -1
- package/dist/types-BK-mxapm.d.ts +120 -0
- package/dist/{types-38Hj6wN4.d.ts → types-CR_0ycjq.d.ts} +1 -81
- package/dist/versioning/index.d.ts +1 -1
- package/dist/versioning/index.js +1 -1
- package/package.json +11 -2
- package/dist/chunk-25YGWSRQ.js +0 -11
- package/dist/chunk-3UHAENW7.js +0 -1
- package/dist/chunk-6EYS3CNV.js +0 -1
- package/dist/chunk-CTU6AAXM.js +0 -1
- package/dist/chunk-KKLMXJY4.js +0 -1
- package/dist/chunk-L4X7KFWN.js +0 -1
- package/dist/chunk-MDHMZPXK.js +0 -1
- package/dist/chunk-NMK4MUR3.js +0 -1
- package/dist/chunk-Q373HVMW.js +0 -1
- package/dist/chunk-RO5IUV4O.js +0 -1
- package/dist/chunk-RU3RY5SC.js +0 -1
- package/dist/chunk-VTIGDVUR.js +0 -1
- package/dist/chunk-YM6W23MT.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.13.6
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 3278d26: Internal refactor: deduplicate endpoint read-shaping, centralize context keys, and type the config "extras" bridge.
|
|
8
|
+
|
|
9
|
+
- **Fix (security):** `restore`, `search`, `clone`, `upsert`, and the batch endpoints now apply `model.serializationProfile` to their responses. Previously they serialized records without it, leaking fields the profile was meant to strip. If you relied on those endpoints returning profile-excluded fields, update your expectations.
|
|
10
|
+
- Endpoint output shaping (computed fields → serializer → serialization profile → transform → field selection) is now a single shared pipeline (`finalizeRecord` / `finalizeArray`) instead of being copy-pasted per endpoint.
|
|
11
|
+
- Centralized the Hono context-variable keys behind `CONTEXT_KEYS` and removed several internal deprecation shims; public exports are unchanged.
|
|
12
|
+
- The config-API "extras" for extended verbs are now compile-time typed, so a misspelled option key is a build error instead of being silently ignored.
|
|
13
|
+
- **Breaking (types):** the parser-side `ListEndpointConfig` type export was renamed to `ListFilterParseOptions`. The config-API list type is unchanged (still exported as `ConfigListEndpoint`). `ModelObject` is retained as a deprecated alias of `InferModel`.
|
|
14
|
+
- Added `hono-crud/config` and `hono-crud/functional` subpath exports (parity with the other feature modules).
|
|
15
|
+
- `registerCrud` now accepts `bulkPatch`, `versionHistory`, `versionRead`, `versionCompare`, and `versionRollback` slots, wiring them to their conventional routes instead of requiring manual `app.patch`/`app.get` calls.
|
|
16
|
+
|
|
17
|
+
## 0.13.5
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
21
|
+
- c95d8dc: `registerCrud(...)` now records each resource on the app instance (app-scoped, startup-time, edge-safe), and `hono-crud/internal` exports `getRegisteredCrudResources(app)` plus the `RegisteredCrudResource` type. This lets addon packages (e.g. `@hono-crud/mcp`) enumerate registered CRUD resources. `hono-crud/internal` also now exports `extractBearerToken(ctx)` (the default `Authorization: Bearer` extractor) for reuse by first-party addons. No behavior change for existing apps.
|
|
22
|
+
|
|
3
23
|
## 0.13.4
|
|
4
24
|
|
|
5
25
|
### Patch Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'../chunk-
|
|
1
|
+
export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'../chunk-5UM6RIIB.js';import'../chunk-5FV7DBVK.js';import'../chunk-IJBJE4G2.js';
|
package/dist/audit/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Context, Env } from 'hono';
|
|
2
|
-
import { A as AuditConfig,
|
|
2
|
+
import { A as AuditConfig, e as AuditLogEntry, f as AuditAction } from '../types-CR_0ycjq.js';
|
|
3
3
|
import { S as StorageRegistry } from '../registry-PNJjvSvm.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import '../types-DcRAcexC.js';
|
package/dist/audit/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{e as AuditLogger,a as MemoryAuditLogStorage,b as auditStorageRegistry,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'../chunk-
|
|
1
|
+
export{e as AuditLogger,a as MemoryAuditLogStorage,b as auditStorageRegistry,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'../chunk-UAVAEDVS.js';import'../chunk-EX4S3Q4M.js';import'../chunk-ZJWDAVGG.js';import'../chunk-VJRDAVID.js';import'../chunk-IJBJE4G2.js';
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
export {
|
|
2
|
-
export { A as AuthEndpointMethods, a as AuthenticatedEndpoint, J as JWTClaimsValidationOptions, M as MemoryAPIKeyStorage, b as MemoryApprovalStorage, P as POLICIES_CONTEXT_KEY, c as allOf, d as allowAll, e as anyOf, f as createAPIKeyMiddleware, g as createAuthMiddleware, h as createJWTMiddleware, i as decodeJWT, j as defaultHashAPIKey, k as denyAll,
|
|
1
|
+
export { j as APIKeyConfig, k as APIKeyEntry, l as APIKeyLookupResult, m as ActionSource, u as ApprovalConfig, v as ApprovalStorage, w as AuthConfig, x as AuthEnv, y as AuthType, z as AuthUser, B as AuthorizationCheck, N as EndpointAuthConfig, S as Guard, a0 as JWTAlgorithm, a1 as JWTClaims, a2 as JWTClaimsSchema, a3 as JWTConfig, ai as OwnershipExtractor, aJ as PathPattern, al as PendingAction, am as PendingActionStatus, aE as ValidatedJWTClaims, aH as parseJWTClaims, aI as safeParseJWTClaims } from '../types-CR_0ycjq.js';
|
|
2
|
+
export { A as AuthEndpointMethods, a as AuthenticatedEndpoint, J as JWTClaimsValidationOptions, M as MemoryAPIKeyStorage, b as MemoryApprovalStorage, P as POLICIES_CONTEXT_KEY, c as allOf, d as allowAll, e as anyOf, f as createAPIKeyMiddleware, g as createAuthMiddleware, h as createJWTMiddleware, i as decodeJWT, j as defaultHashAPIKey, k as denyAll, m as generateAPIKey, n as getAPIKeyStorage, o as hashAPIKey, p as isValidAPIKeyFormat, q as optionalAuth, r as parseIso8601Duration, s as requireAllRoles, t as requireAnyPermission, u as requireApproval, v as requireAuth, w as requireAuthenticated, x as requireAuthentication, y as requireOwnership, z as requireOwnershipOrRole, B as requirePermissions, C as requirePolicy, D as requireRoles, E as setAPIKeyStorage, F as validateAPIKey, G as validateAPIKeyEntry, H as validateJWTClaims, I as verifyJWT, K as withAuth } from '../index-B6a8YXS1.js';
|
|
3
3
|
import 'hono';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import '../types-DcRAcexC.js';
|
|
6
6
|
import '../types-BAcN7U0B.js';
|
|
7
7
|
import '@hono/zod-openapi';
|
|
8
|
+
import '../route-cu4t0BCp.js';
|
|
8
9
|
import 'hono/utils/http-status';
|
package/dist/auth/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{M as AuthenticatedEndpoint,x as JWTClaimsSchema,g as MemoryApprovalStorage,i as POLICIES_CONTEXT_KEY,q as allOf,t as allowAll,r as anyOf,H as createAPIKeyMiddleware,J as createAuthMiddleware,C as createJWTMiddleware,E as decodeJWT,G as defaultHashAPIKey,s as denyAll,K as optionalAuth,h as parseIso8601Duration,y as parseJWTClaims,k as requireAllRoles,m as requireAnyPermission,w as requireApproval,n as requireAuth,u as requireAuthenticated,L as requireAuthentication,o as requireOwnership,p as requireOwnershipOrRole,l as requirePermissions,v as requirePolicy,j as requireRoles,z as safeParseJWTClaims,I as validateAPIKey,F as validateAPIKeyEntry,A as validateJWTClaims,D as verifyJWT,N as withAuth}from'../chunk-CKUGVMFX.js';export{a as MemoryAPIKeyStorage,b as generateAPIKey,f as getAPIKeyStorage,c as hashAPIKey,d as isValidAPIKeyFormat,g as setAPIKeyStorage}from'../chunk-4NKDESHS.js';import'../chunk-5FV7DBVK.js';import'../chunk-DMGP7QDL.js';import'../chunk-ZJWDAVGG.js';import'../chunk-VJRDAVID.js';import'../chunk-IJBJE4G2.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {m as m$1}from'./chunk-ZJWDAVGG.js';import {a}from'./chunk-IJBJE4G2.js';var y=class{keys=new Map;hashToId=new Map;async store(e){this.keys.set(e.id,e),this.hashToId.set(e.keyHash,e.id);}async lookup(e){let t=this.hashToId.get(e);return t&&this.keys.get(t)||null}async getById(e){return this.keys.get(e)||null}async getByUserId(e){let t=[];for(let s of this.keys.values())s.userId===e&&t.push(s);return t}async revoke(e){let t=this.keys.get(e);return t?(t.active=false,true):false}async delete(e){let t=this.keys.get(e);return t?(this.hashToId.delete(t.keyHash),this.keys.delete(e),true):false}async updateLastUsed(e){let t=this.keys.get(e);t&&(t.lastUsedAt=new Date);}async generateKey(e){let t=e.prefix||"sk",s=f(t),n=await p(s),a={id:crypto.randomUUID(),keyHash:n,userId:e.userId,name:e.name,roles:e.roles,permissions:e.permissions,expiresAt:e.expiresAt??null,active:true,createdAt:new Date,metadata:e.metadata};return await this.store(a),{key:s,entry:a}}getAllKeys(){return Array.from(this.keys.values())}clear(){this.keys.clear(),this.hashToId.clear();}};function f(r="sk",e=32){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",s=new Uint8Array(e);crypto.getRandomValues(s);let n="";for(let a=0;a<e;a++)n+=t[s[a]%t.length];return `${r}_${n}`}async function p(r){let t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(s);return Array.from(n).map(a=>a.toString(16).padStart(2,"0")).join("")}function A(r,e){if(!r||typeof r!="string")return false;let t=r.split("_");if(t.length!==2)return false;let[s,n]=t;return !(e&&s!==e||!/^[A-Za-z0-9]{16,}$/.test(n))}var u=m$1(a.apiKeyStorage);function I(){return u.get()}function m(r){u.set(r);}var g="\0DOUBLE_STAR\0",c="\0SINGLE_STAR\0";function d(r,e){if(e instanceof RegExp)return e.test(r);if(!e.includes("*"))return r===e;let t=e.replace(/\*\*/g,g).replace(/\*/g,c).replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(new RegExp(g,"g"),".*").replace(new RegExp(c,"g"),"[^/]*");return new RegExp(`^${t}$`).test(r)}function l(r,e){for(let t of e)if(d(r,t))return true;return false}function x(r,e,t){return l(r,t)?false:e.length===0?true:l(r,e)}export{y as a,f as b,p as c,A as d,u as e,I as f,m as g,d as h,l as i,x as j};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {HTTPException}from'hono/http-exception';var e=class extends HTTPException{code;details;constructor(s,t=500,
|
|
1
|
+
import {HTTPException}from'hono/http-exception';var e=class extends HTTPException{code;details;constructor(s,t=500,o="INTERNAL_ERROR",m){super(t,{message:s}),this.name="ApiException",this.code=o,this.details=m;}toJSON(){let s={code:this.code,message:this.message};return this.details&&(s.details=this.details),{success:false,error:s}}get statusCode(){return this.status}},r=class n extends e{constructor(s,t){super(s,400,"VALIDATION_ERROR",t),this.name="InputValidationException";}static fromZodError(s){let t=s.issues.map(o=>({path:o.path.join("."),message:o.message,code:o.code}));return new n("Validation failed",t)}},i=class extends e{constructor(s="Resource",t){let o=t?`${s} with id '${t}' not found`:`${s} not found`;super(o,404,"NOT_FOUND"),this.name="NotFoundException";}},a=class extends e{constructor(s="Resource already exists",t){super(s,409,"CONFLICT",t),this.name="ConflictException";}},u=class extends e{constructor(s="Unauthorized"){super(s,401,"UNAUTHORIZED"),this.name="UnauthorizedException";}},c=class extends e{constructor(s="Forbidden"){super(s,403,"FORBIDDEN"),this.name="ForbiddenException";}},d=class extends e{constructor(s,t){super(s,400,"AGGREGATION_ERROR",t),this.name="AggregationException";}},p=class extends e{constructor(s,t){super(s,500,"CACHE_ERROR",t),this.name="CacheException";}},l=class extends e{constructor(s,t){super(s,500,"CONFIGURATION_ERROR",t),this.name="ConfigurationException";}};export{e as a,r as b,i as c,a as d,u as e,c as f,d as g,p as h,l as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-5FV7DBVK.js';import {a as a$1}from'./chunk-IJBJE4G2.js';function l(e,n){return e.req.header(n)??void 0}function w(e,n){return e.req.query(n)??void 0}function C(e,n){let i=e.req.path,a=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\{version\\}","([^/]+)"),d=new RegExp(`^${a}`);return i.match(d)?.[1]}function h(e){let{versions:n,strategy:i="header",headerName:p="Accept-Version",queryParam:a$2="version",urlPattern:d="/v{version}",extractVersion:f,addHeaders:c=true}=e,V=e.defaultVersion??n[0]?.version,u=new Map;for(let r of n)u.set(r.version,r);return async(r,m)=>{let t=f?f(r):{header:()=>l(r,p),query:()=>w(r,a$2),url:()=>C(r,d)}[i]();if(t=t??V,!t)throw new a("API version is required",400,"VERSION_REQUIRED");let o=u.get(t);if(!o)throw new a(`Unsupported API version: ${t}`,400,"UNSUPPORTED_VERSION");if(r.set(a$1.apiVersion,t),r.set(a$1.apiVersionConfig,o),c&&(r.header("X-API-Version",t),o.deprecated&&r.header("Deprecation",o.deprecated),o.sunset&&r.header("Sunset",o.sunset)),o.middleware&&o.middleware.length>0)for(let y of o.middleware)await y(r,async()=>{});await m();}}function v(e){return e.get(a$1.apiVersion)}function A(e){return e.get(a$1.apiVersionConfig)}function E(){return async(e,n)=>{await n();let i=e.get(a$1.apiVersionConfig);if(!(!i?.responseTransformer||!e.res.headers.get("content-type")?.includes("application/json")))try{let a=await e.res.json(),d=i.responseTransformer(a);e.res=new Response(JSON.stringify(d),{status:e.res.status,headers:e.res.headers});}catch{}}}export{h as a,v as b,A as c,E as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b}from'./chunk-VJRDAVID.js';import {a}from'./chunk-IJBJE4G2.js';import {HTTPException}from'hono/http-exception';function I(d={}){let{source:u="header",headerName:m="X-Tenant-ID",pathParam:c="tenantId",queryParam:g="tenantId",jwtClaim:l="tenantId",extractor:p,contextKey:x="tenantId",required:f=true,errorMessage:E="Tenant ID is required",onMissing:r,validate:a$1,invalidMessage:w="Invalid tenant ID"}=d,y={header:e=>e.req.header(m),path:e=>e.req.param(c),query:e=>e.req.query(g),jwt:e=>{let t=e.get(a.jwtPayload);if(t&&typeof t=="object")return t[l]},custom:e=>p?.(e)};return async(e,t)=>{let h=y[u],n=await h(e);if(!n){if(f){if(r)return r(e);throw new HTTPException(400,{message:E})}return t()}if(a$1&&!await a$1(n,e))throw new HTTPException(400,{message:w});return b(e,x,n),t()}}export{I as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-BPBFNTBM.js';function s(o,t){let d={};if(o.create!==void 0){let e=o.create;d.create=a(t.CreateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,allowNestedCreate:e.nestedCreate,before:e.hooks?.before,after:e.hooks?.after});}if(o.list!==void 0){let e=o.list;d.list=a(t.ListEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,filterFields:e.filtering?.fields,filterConfig:e.filtering?.config,searchFields:e.search?.fields,searchFieldName:e.search?.paramName,sortFields:e.sorting?.fields,defaultSort:e.sorting?.default?{field:e.sorting.default,order:e.sorting.defaultOrder??e.sorting.defaultDirection??"asc"}:void 0,defaultPerPage:e.pagination?.defaultPerPage,maxPerPage:e.pagination?.maxPerPage,allowedIncludes:e.includes,fieldSelectionEnabled:e.fieldSelection?.enabled,allowedSelectFields:e.fieldSelection?.allowed,blockedSelectFields:e.fieldSelection?.blocked,alwaysIncludeFields:e.fieldSelection?.alwaysInclude,defaultSelectFields:e.fieldSelection?.defaults,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.read!==void 0){let e=o.read;d.read=a(t.ReadEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedIncludes:e.includes,fieldSelectionEnabled:e.fieldSelection?.enabled,allowedSelectFields:e.fieldSelection?.allowed,blockedSelectFields:e.fieldSelection?.blocked,alwaysIncludeFields:e.fieldSelection?.alwaysInclude,defaultSelectFields:e.fieldSelection?.defaults,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.update!==void 0){let e=o.update;d.update=a(t.UpdateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedUpdateFields:e.fields?.allowed,blockedUpdateFields:e.fields?.blocked,allowNestedWrites:e.nestedWrites,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.delete!==void 0){let e=o.delete;d.delete=a(t.DeleteEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,lookupField:e.lookupField,additionalFilters:e.additionalFilters,includeCascadeResults:e.includeCascadeResults,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after});}if(o.search!==void 0&&t.SearchEndpoint){let e=o.search,n={};e.fields!==void 0&&(n.searchFields=e.fields),e.mode!==void 0&&(n.defaultMode=e.mode),e.paramName!==void 0&&(n.searchParamName=e.paramName),d.search=a(t.SearchEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,after:e.hooks?.after,extras:n});}if(o.aggregate!==void 0&&t.AggregateEndpoint){let e=o.aggregate,n={};e.fields!==void 0&&(n.filterFields=e.fields),d.aggregate=a(t.AggregateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,after:e.hooks?.after,extras:n});}if(o.restore!==void 0&&t.RestoreEndpoint){let e=o.restore;d.restore=a(t.RestoreEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after});}if(o.batchCreate!==void 0&&t.BatchCreateEndpoint){let e=o.batchCreate,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchCreate=a(t.BatchCreateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchUpdate!==void 0&&t.BatchUpdateEndpoint){let e=o.batchUpdate,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchUpdate=a(t.BatchUpdateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchDelete!==void 0&&t.BatchDeleteEndpoint){let e=o.batchDelete,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchDelete=a(t.BatchDeleteEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchRestore!==void 0&&t.BatchRestoreEndpoint){let e=o.batchRestore,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchRestore=a(t.BatchRestoreEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchUpsert!==void 0&&t.BatchUpsertEndpoint){let e=o.batchUpsert,n=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,r={};e.maxBatchSize!==void 0&&(r.maxBatchSize=e.maxBatchSize),n!==void 0&&(r.upsertKeys=n),d.batchUpsert=a(t.BatchUpsertEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:r});}if(o.export!==void 0&&t.ExportEndpoint){let e=o.export,n={};e.maxRows!==void 0&&(n.maxExportRecords=e.maxRows),e.formats!==void 0&&e.formats.length>0&&(n.defaultFormat=e.formats[0]),d.export=a(t.ExportEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,extras:n});}if(o.import!==void 0&&t.ImportEndpoint){let e=o.import,n={};e.maxRows!==void 0&&(n.maxBatchSize=e.maxRows),d.import=a(t.ImportEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.upsert!==void 0&&t.UpsertEndpoint){let e=o.upsert,n=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,r={};n!==void 0&&(r.upsertKeys=n),d.upsert=a(t.UpsertEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:r});}if(o.clone!==void 0&&t.CloneEndpoint){let e=o.clone,n={};e.fieldsToReset!==void 0&&(n.excludeFromClone=e.fieldsToReset),d.clone=a(t.CloneEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:n});}return d}export{s as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {k}from'./chunk-P5JQKX7Z.js';var m=class{entriesById=new Map;entryIds=[];maxEntries;maxAge;cleanupInterval;lastCleanup=0;constructor(e){this.maxEntries=e?.maxEntries??1e4,this.maxAge=e?.maxAge??864e5,this.cleanupInterval=e?.cleanupInterval??3e5;}maybeCleanup(){if(this.cleanupInterval<=0||this.maxAge<=0)return;let e=Date.now();e-this.lastCleanup>=this.cleanupInterval&&(this.lastCleanup=e,this.deleteOlderThanSync(this.maxAge));}deleteOlderThanSync(e){let s=Date.now()-e,a=0;for(let t=this.entryIds.length-1;t>=0;t--){let n=this.entryIds[t],r=this.entriesById.get(n);if(r)if(new Date(r.timestamp).getTime()<s)this.entriesById.delete(n),this.entryIds.splice(t,1),a++;else break}return a}async store(e){for(this.maybeCleanup();this.entryIds.length>=this.maxEntries;){let s=this.entryIds.pop();s&&this.entriesById.delete(s);}this.entriesById.set(e.id,e),this.entryIds.unshift(e.id);}async query(e){this.maybeCleanup();let s=this.getFilteredEntries(e);if(e?.sort){let{field:n,direction:r}=e.sort;s=s.sort((i,o)=>{let g,d;switch(n){case "timestamp":g=new Date(i.timestamp).getTime(),d=new Date(o.timestamp).getTime();break;case "responseTimeMs":g=i.response.responseTimeMs,d=o.response.responseTimeMs;break;case "statusCode":g=i.response.statusCode,d=o.response.statusCode;break;default:return 0}return r==="asc"?g-d:d-g});}let a=e?.offset??0,t=e?.limit??s.length;return s.slice(a,a+t)}async getById(e){return this.entriesById.get(e)??null}async count(e){return this.getFilteredEntries(e).length}async deleteOlderThan(e){return this.deleteOlderThanSync(e)}async clear(){let e=this.entriesById.size;return this.entriesById.clear(),this.entryIds=[],e}destroy(){this.entriesById.clear(),this.entryIds=[];}getSize(){return this.entriesById.size}getFilteredEntries(e){if(!e)return Array.from(this.entriesById.values());let s=[];for(let a of this.entryIds){let t=this.entriesById.get(a);if(t&&!(e.level&&!(Array.isArray(e.level)?e.level:[e.level]).includes(t.level))&&!(e.method&&!(Array.isArray(e.method)?e.method:[e.method]).map(r=>r.toUpperCase()).includes(t.request.method.toUpperCase()))&&!(e.path&&!k(t.request.path,e.path))){if(e.statusCode){let{min:n,max:r}=e.statusCode,i=t.response.statusCode;if(n!==void 0&&i<n||r!==void 0&&i>r)continue}if(e.timeRange){let n=new Date(t.timestamp).getTime(),{start:r,end:i}=e.timeRange;if(r){let o=typeof r=="string"?new Date(r).getTime():r.getTime();if(n<o)continue}if(i){let o=typeof i=="string"?new Date(i).getTime():i.getTime();if(n>o)continue}}e.userId&&t.request.userId!==e.userId||e.clientIp&&t.request.clientIp!==e.clientIp||e.requestId&&t.id!==e.requestId||e.errorMessage&&(!t.error?.message||!t.error.message.toLowerCase().includes(e.errorMessage.toLowerCase()))||s.push(t);}}return s}};export{m as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function c(a,e){let s=e.middlewares??[],d=e.extras,r=e.schema??{},o=Array.isArray(r.tags)&&r.tags.length>0,l=e.meta.model.tag??e.meta.model.tableName,n=o?r:{...r,tags:[l]};return class extends a{static _middlewares=s;constructor(){super(),d&&Object.assign(this,d);}_meta=e.meta;schema=n;beforeHookMode=e.beforeHookMode??"sequential";afterHookMode=e.afterHookMode??"sequential";allowNestedCreate=e.allowNestedCreate??[];lookupField=e.lookupField??"id";additionalFilters=e.additionalFilters;allowedUpdateFields=e.allowedUpdateFields;blockedUpdateFields=e.blockedUpdateFields;allowNestedWrites=e.allowNestedWrites??[];includeCascadeResults=e.includeCascadeResults??false;filterFields=e.filterFields??[];filterConfig=e.filterConfig;searchFields=e.searchFields??[];searchFieldName=e.searchFieldName??"search";sortFields=e.sortFields??[];defaultSort=e.defaultSort;defaultPerPage=e.defaultPerPage??20;maxPerPage=e.maxPerPage??100;allowedIncludes=e.allowedIncludes??[];fieldSelectionEnabled=e.fieldSelectionEnabled??false;allowedSelectFields=e.allowedSelectFields??[];blockedSelectFields=e.blockedSelectFields??[];alwaysIncludeFields=e.alwaysIncludeFields??[];defaultSelectFields=e.defaultSelectFields??[];getBodySchema(){return e.bodySchema?e.bodySchema:super.getBodySchema()}async before(...t){return e.before?e.before(...t):super.before(...t)}async after(...t){return e.after?e.after(...t):super.after(...t)}transform(t){return e.transform?e.transform(t):super.transform(t)}}}export{c as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {i}from'./chunk-4NKDESHS.js';import {e,f}from'./chunk-5FV7DBVK.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {b as b$1,a as a$1}from'./chunk-VJRDAVID.js';import {a}from'./chunk-IJBJE4G2.js';import {z}from'zod';import {decode,verify}from'hono/jwt';var I=z.object({sub:z.string().optional(),iss:z.string().optional(),aud:z.union([z.string(),z.array(z.string())]).optional(),exp:z.number().int().optional(),nbf:z.number().int().optional(),iat:z.number().int().optional(),jti:z.string().optional()}).passthrough();function X(e){return I.parse(e)}function Y(e){return I.safeParse(e)}z.object({id:z.string(),tenantId:z.string().optional(),organizationId:z.string().optional(),userId:z.string().optional(),actorUserId:z.string().optional(),onBehalfOfUserId:z.string().optional(),agentId:z.string().optional(),agentRunId:z.string().optional(),toolCallId:z.string().optional(),source:z.enum(["http","agent-mcp","agent-code-mode","workflow","job","system"]),toolName:z.string(),input:z.unknown(),status:z.enum(["pending","approved","rejected","expired"]),createdAt:z.iso.datetime(),expiresAt:z.iso.datetime(),reason:z.string(),approvedBy:z.string().optional(),approvedAt:z.iso.datetime().optional(),rejectedBy:z.string().optional(),rejectedReason:z.string().optional()});function C(e$1,t={}){let{clockTolerance:n=0,issuer:r,audience:o,skipTimeValidation:s=false}=t;if(!s){let i=Math.floor(Date.now()/1e3);if(e$1.exp!==void 0&&i>e$1.exp+n)throw new e("Token has expired");if(e$1.nbf!==void 0&&i<e$1.nbf-n)throw new e("Token not yet valid")}if(r!==void 0&&e$1.iss!==r)throw new e("Invalid token issuer");if(o!==void 0){let i=Array.isArray(o)?o:[o],u=Array.isArray(e$1.aud)?e$1.aud:[e$1.aud];if(!i.some(y=>u.includes(y)))throw new e("Invalid token audience")}}function F(e){if(!["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"].includes(e))throw new Error(`Unsupported algorithm: ${e}`);return e}function G(e){let t=e.req.header("Authorization");if(!t)return null;let n=t.split(" ");return n.length!==2||n[0].toLowerCase()!=="bearer"?null:n[1]}function Q(e){return {id:String(e.sub||e.id||""),email:e.email,roles:e.roles||e.role,permissions:e.permissions,metadata:e.metadata}}function q(e$1){let t=F(e$1.algorithm||"HS256"),n=e$1.clockTolerance||0,r=e$1.extractToken||G,o=e$1.extractUser||Q;return async(s,i)=>{let u=r(s);if(!u)throw new e("Missing authentication token");let c=decode(u);if(!c||!c.header)throw new e("Invalid token format");if(c.header.alg!==t)throw new e("Invalid token algorithm");let y;try{y=await verify(u,e$1.secret,t);}catch(f){if(f instanceof Error){if(f.message.includes("expired")||f.name==="JwtTokenExpired")throw new e("Token has expired");if(f.message.includes("signature")||f.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(f.message.includes("not valid yet")||f.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let m=y;C(m,{clockTolerance:n,issuer:e$1.issuer,audience:e$1.audience});let g=o(m);s.set(a.userId,g.id),s.set(a.user,g),s.set(a.roles,g.roles||[]),s.set(a.permissions,g.permissions||[]),s.set(a.authType,"jwt"),await i();}}async function ee(e$1,t){let n=F(t.algorithm||"HS256"),r=t.clockTolerance||0,o=decode(e$1);if(!o||!o.header)throw new e("Invalid token format");if(o.header.alg!==n)throw new e("Invalid token algorithm");let s;try{s=await verify(e$1,t.secret,n);}catch(u){if(u instanceof Error){if(u.message.includes("expired")||u.name==="JwtTokenExpired")throw new e("Token has expired");if(u.message.includes("signature")||u.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(u.message.includes("not valid yet")||u.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let i=s;return C(i,{clockTolerance:r,issuer:t.issuer,audience:t.audience}),i}function te(e){try{let t=decode(e);return !t||!t.header||!t.payload?null:{header:t.header,payload:t.payload}}catch{return null}}function P(e$1){if(!e$1)throw new e("Invalid API key");if(!e$1.active)throw new e("API key has been revoked");if(e$1.expiresAt&&new Date>e$1.expiresAt)throw new e("API key has expired");return e$1}async function O(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),o=new Uint8Array(r);return Array.from(o).map(s=>s.toString(16).padStart(2,"0")).join("")}function re(e){return {id:e.userId,roles:e.roles,permissions:e.permissions,metadata:{...e.metadata,apiKeyId:e.id,apiKeyName:e.name}}}function ne(e,t){return e.req.header(t)||null}function oe(e,t){return e.req.query(t)||null}function U(e$1){let t=e$1.headerName||"X-API-Key",n=e$1.queryParam??null,r=e$1.hashKey||O,o=e$1.extractUser||re;return async(s,i)=>{let u=ne(s,t);if(!u&&n&&(u=oe(s,n)),!u)throw new e("Missing API key");let c=await r(u),y=await e$1.lookupKey(c),m=P(y),g=o(m);s.set(a.userId,g.id),s.set(a.user,g),s.set(a.roles,g.roles||[]),s.set(a.permissions,g.permissions||[]),s.set(a.authType,"api-key"),e$1.updateLastUsed&&Promise.resolve(e$1.updateLastUsed(m.id)).catch(()=>{}),await i();}}async function se(e,t){let r=await(t.hashKey||O)(e),o=await t.lookupKey(r);return P(o)}function M(e$1){let t=e$1.requireAuth??true,n=e$1.skipPaths||[],r=e$1.unauthorizedMessage||"Unauthorized",o=e$1.authOrder||["jwt","api-key"],s=e$1.jwt?q(e$1.jwt):null,i$1=e$1.apiKey?U(e$1.apiKey):null;return async(u,c)=>{let y=u.req.path;if(i(y,n))return u.set(a.authType,"none"),c();let m=false,g=null;for(let f of o)try{if(f==="jwt"&&s&&u.req.header("Authorization")?.toLowerCase().startsWith("bearer ")){await s(u,async()=>{}),m=!0;break}if(f==="api-key"&&i$1){let w=e$1.apiKey?.headerName||"X-API-Key",T=e$1.apiKey?.queryParam;if(u.req.header(w)||T&&u.req.query(T)){await i$1(u,async()=>{}),m=!0;break}}}catch(w){g=w instanceof Error?w:new Error(String(w));}if(!m){if(t)throw g instanceof e?g:new e(r);u.set(a.authType,"none");}await c();}}function ie(e){return M({...e,requireAuth:false})}function ae(e){return M({...e,requireAuth:true})}var E=class{store=new Map;async create(t){this.store.set(t.id,{...t});}async get(t){let n=this.store.get(t);if(!n)return null;if(n.status==="pending"&&Date.parse(n.expiresAt)<=Date.now()){let r={...n,status:"expired"};return this.store.set(t,r),r}return {...n}}async approve(t,n){let r=await this.get(t);if(!r)throw new Error(`Pending action ${t} not found`);if(r.status!=="pending")throw new Error(`Pending action ${t} cannot be approved from status '${r.status}'`);this.store.set(t,{...r,status:"approved",approvedBy:n,approvedAt:new Date().toISOString()});}async reject(t,n,r){let o=await this.get(t);if(!o)throw new Error(`Pending action ${t} not found`);if(o.status!=="pending")throw new Error(`Pending action ${t} cannot be rejected from status '${o.status}'`);this.store.set(t,{...o,status:"rejected",rejectedBy:n,rejectedReason:r});}clear(){this.store.clear();}};var ue=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;function K(e){let t=ue.exec(e);if(!t)throw new Error(`Invalid ISO 8601 duration: ${e}. Use P[nD][T[nH][nM][nS]] (years and months unsupported).`);let[,n,r,o,s]=t,i=(n?Number(n)*864e5:0)+(r?Number(r)*36e5:0)+(o?Number(o)*6e4:0)+(s?Number(s)*1e3:0);if(i===0&&e!=="PT0S"&&e!=="P0D")throw new Error(`ISO 8601 duration ${e} parsed to zero milliseconds \u2014 verify the format.`);return i}function de(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var j,Z=false;function le(){return j||(j=new E),Z||(Z=true,b$2().warn("requireApproval: no approvalStorage configured \u2014 using process-local in-memory storage. NOT safe for multi-instance / serverless / edge-isolate deployments where phase 1 and phase 2 may hit different processes. Pass an explicit approvalStorage (e.g. PostgresApprovalStorage) for production. This warning is logged once per process.")),j}var B="__honoCrudPolicies";function ce(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.roles||[];if(!e$1.some(i=>o.includes(i)))throw new f("Insufficient permissions");await n();}}function pe(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.roles||[];if(!e$1.every(i=>o.includes(i)))throw new f("Insufficient permissions");await n();}}function he(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.permissions||[];if(!e$1.every(i=>o.includes(i)))throw new f("Insufficient permissions");await n();}}function ge(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.permissions||[];if(!e$1.some(i=>o.includes(i)))throw new f("Insufficient permissions");await n();}}function me(e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");if(!await e$1(r,t))throw new f("Access denied");await n();}}function fe(e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=await e$1(t);if(r.id!==o)throw new f("Access denied: not resource owner");await n();}}function ye(e$1,...t){return async(n,r)=>{let o=n.var.user;if(!o)throw new e("Authentication required");let s=o.roles||[];if(t.some(c=>s.includes(c))){await r();return}let u=await e$1(n);if(o.id===u){await r();return}throw new f("Access denied")}}function Ae(...e){return async(t,n)=>{for(let r of e)await r(t,async()=>{});await n();}}function we(...e){return async(t,n)=>{let r=null;for(let o of e)try{await o(t,async()=>{}),await n();return}catch(s){r=s instanceof Error?s:new Error(String(s));}throw r||new f("Access denied")}}function xe(e="Access denied"){return async()=>{throw new f(e)}}function Ee(){return async(e,t)=>{await t();}}function Te(){return async(e$1,t)=>{if(!e$1.var.user)throw new e("Authentication required");await t();}}function Re(e){return async(t,n)=>{b$1(t,B,e),await n();}}function ve(e){let t=e.approvalStorage??le(),n=e.resumeMarker??"_resume_",r=K(e.expiresAfter??"P1D"),o=z.object({[n]:z.string()}).loose();return async(s,i)=>{let u={};try{let x=await s.req.json();de(x)&&(u=x);}catch{}let c=o.safeParse(u).data?.[n];if(c){let x=await t.get(c);if(!x)throw new f(`Pending action ${c} not found`);if(x.status==="expired")throw new f(`Pending action ${c} has expired`);if(x.status!=="approved")throw new f(`Pending action ${c} is ${x.status}, cannot resume`);Ce(s,x.input),await i();return}let y=a$1(s,a.userId),m=a$1(s,a.agentId),g=a$1(s,a.agentRunId),f$1=a$1(s,a.onBehalfOfUserId),w=a$1(s,a.toolCallId),T=a$1(s,a.tenantId),z=a$1(s,a.organizationId),$=a$1(s,a.actionSource)??(m?"agent-mcp":"http"),J=Date.now(),R={id:crypto.randomUUID(),tenantId:T,organizationId:z,userId:y,actorUserId:y,onBehalfOfUserId:f$1,agentId:m,agentRunId:g,toolCallId:w,source:$,toolName:e.toolName??`${s.req.method} ${s.req.path}`,input:u,status:"pending",createdAt:new Date(J).toISOString(),expiresAt:new Date(J+r).toISOString(),reason:e.reason};return await t.create(R),s.json({status:"pending",actionId:R.id,expiresAt:R.expiresAt,reason:R.reason},202)}}function Ce(e,t){let n=e.req,r=Promise.resolve(JSON.stringify(t));n.bodyCache?(n.bodyCache.text=r,delete n.bodyCache.parsedBody,delete n.bodyCache.json):n.bodyCache={text:r};}function it(e){return e}function at(e){return e}var L="__honoCrudResponseEnvelope__";function H(e,t){try{return e.req.valid(t)}catch{return}}function b(e,t,n){return e.json(t,n)}var k=class{static isRoute=true;schema={};params={};context=null;getSchema(){return this.schema}async getValidatedData(){if(!this.context)throw new Error("Context not set. Call setContext() first.");let t=this.context,n=this.getSchema(),r={};if(n.request?.body){let o=H(t,"json");if(o===void 0)try{o=await t.req.json();}catch{}o!==void 0&&(r.body=o);}if(n.request?.query){let o=H(t,"query");o===void 0&&(o=t.req.query()),o!==void 0&&(r.query=o);}if(n.request?.params){let o=H(t,"param");o===void 0&&(o=t.req.param()),o!==void 0&&(r.params=o);}return r}setContext(t){this.context=t;}getContext(){if(!this.context)throw new Error("Context not set");return this.context}json(t,n=200){return b(this.getContext(),t,n)}getResponseEnvelope(){return this.context?this.context?.var?.[L]??void 0:void 0}success(t,n=200){let r=this.getResponseEnvelope(),o=r?r.success(t):{success:true,result:t};return b(this.getContext(),o,n)}successPaginated(t,n,r=200){let o=this.getResponseEnvelope(),s=o?o.success(t,n):{success:true,result:t,result_info:n};return b(this.getContext(),s,r)}runAfterResponse(t){let n;try{let r=this.getContext().executionCtx;r&&typeof r.waitUntil=="function"&&(n=r.waitUntil.bind(r));}catch{}n?n(t):t.catch(r=>{b$2().error("Background task failed",{error:r instanceof Error?r.message:String(r)});});}error(t,n="ERROR",r=400,o){let s={code:n,message:t};o&&(s.details=o);let i=this.getResponseEnvelope(),u=i?i.error(s):{success:false,error:s};return b(this.getContext(),u,r)}};function ct(e){return typeof e=="function"&&"isRoute"in e&&e.isRoute===true}var N=class extends k{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(t,n){return true}getUser(){let n=this.getContext().var.user;if(!n)throw new e("Authentication required");return n}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(t){return this.getUserRoles().includes(t)}hasAnyRole(...t){let n=this.getUserRoles();return t.some(r=>n.includes(r))}hasAllRoles(...t){let n=this.getUserRoles();return t.every(r=>n.includes(r))}hasPermission(t){return this.getUserPermissions().includes(t)}hasAllPermissions(...t){let n=this.getUserPermissions();return t.every(r=>n.includes(r))}hasAnyPermission(...t){let n=this.getUserPermissions();return t.some(r=>n.includes(r))}async enforceAuth(){let t=this.getContext();if(this.requiresAuth&&!t.var.user)throw new e("Authentication required");let n=t.var.user;if(!n)return;if(this.requiredRoles&&this.requiredRoles.length>0){let o=n.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(i=>o.includes(i)))throw new f(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(i=>o.includes(i)))throw new f(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let o=n.permissions||[];if(!this.requiredPermissions.every(i=>o.includes(i)))throw new f(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(n,t))throw new f("Access denied")}getSchema(){let t=super.getSchema(),n=this.requiresAuth?[{bearerAuth:[]}]:void 0,r={401:{description:"Unauthorized - Authentication required",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.literal("UNAUTHORIZED"),message:z.string()})})}}},403:{description:"Forbidden - Insufficient permissions",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.literal("FORBIDDEN"),message:z.string()})})}}}};return {...t,security:n,responses:{...t.responses,...this.requiresAuth?r:{}}}}};function Pe(e$1){class t extends e$1{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(r,o){return true}getUser(){let o=this.getContext().var.user;if(!o)throw new e("Authentication required");return o}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(r){let o=this.getUserOrNull();return o?(o.roles||[]).includes(r):false}hasAnyRole(...r){let o=this.getUserOrNull()?.roles||[];return r.some(s=>o.includes(s))}hasAllRoles(...r){let o=this.getUserOrNull()?.roles||[];return r.every(s=>o.includes(s))}hasPermission(r){let o=this.getUserOrNull();return o?(o.permissions||[]).includes(r):false}hasAllPermissions(...r){let o=this.getUserOrNull()?.permissions||[];return r.every(s=>o.includes(s))}hasAnyPermission(...r){let o=this.getUserOrNull()?.permissions||[];return r.some(s=>o.includes(s))}async enforceAuth(){let r=this.getContext();if(this.requiresAuth&&!r.var.user)throw new e("Authentication required");let o=r.var.user;if(!o)return;if(this.requiredRoles&&this.requiredRoles.length>0){let i=o.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(c=>i.includes(c)))throw new f(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(c=>i.includes(c)))throw new f(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let i=o.permissions||[];if(!this.requiredPermissions.every(c=>i.includes(c)))throw new f(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(o,r))throw new f("Access denied")}getSchema(){let r=super.getSchema(),o=this.requiresAuth?[{bearerAuth:[]}]:void 0,s={401:{description:"Unauthorized - Authentication required",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.literal("UNAUTHORIZED"),message:z.string()})})}}},403:{description:"Forbidden - Insufficient permissions",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.literal("FORBIDDEN"),message:z.string()})})}}}};return {...r,security:o,responses:{...r.responses,...this.requiresAuth?s:{}}}}}return t}export{C as A,G as B,q as C,ee as D,te as E,P as F,O as G,U as H,se as I,M as J,ie as K,ae as L,N as M,Pe as N,it as a,at as b,L as c,b as d,k as e,ct as f,E as g,K as h,B as i,ce as j,pe as k,he as l,ge as m,me as n,fe as o,ye as p,Ae as q,we as r,xe as s,Ee as t,Te as u,Re as v,ve as w,I as x,X as y,Y as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b as b$1}from'./chunk-DMGP7QDL.js';import {n}from'./chunk-ZJWDAVGG.js';import {a}from'./chunk-IJBJE4G2.js';var c=class{listeners=new Map;tableListeners=new Map;globalListeners=new Set;maxListeners;constructor(e){this.maxListeners=e?.maxListeners??100;}on(e,t,s){let n=`${e}:${t}`;this.listeners.has(n)||this.listeners.set(n,new Set);let i=this.listeners.get(n);return this.maxListeners>0&&i.size>=this.maxListeners?(b$1().warn(`Max listeners (${this.maxListeners}) reached for event "${n}". Listener not added.`),{unsubscribe:()=>{}}):(i.add(s),{unsubscribe:()=>{this.listeners.get(n)?.delete(s);}})}onTable(e,t){this.tableListeners.has(e)||this.tableListeners.set(e,new Set);let s=this.tableListeners.get(e);return this.maxListeners>0&&s.size>=this.maxListeners?(b$1().warn(`Max listeners (${this.maxListeners}) reached for table "${e}". Listener not added.`),{unsubscribe:()=>{}}):(s.add(t),{unsubscribe:()=>{this.tableListeners.get(e)?.delete(t);}})}onAny(e){return this.maxListeners>0&&this.globalListeners.size>=this.maxListeners?(b$1().warn(`Max global listeners (${this.maxListeners}) reached. Listener not added.`),{unsubscribe:()=>{}}):(this.globalListeners.add(e),{unsubscribe:()=>{this.globalListeners.delete(e);}})}off(e,t){this.listeners.delete(`${e}:${t}`);}removeAll(){this.listeners.clear(),this.tableListeners.clear(),this.globalListeners.clear();}async emit(e){let t=[],s=`${e.table}:${e.type}`,n=this.listeners.get(s);if(n)for(let a of n)t.push(this.safeCall(a,e));let i=this.tableListeners.get(e.table);if(i)for(let a of i)t.push(this.safeCall(a,e));for(let a of this.globalListeners)t.push(this.safeCall(a,e));await Promise.all(t);}emitAsync(e){this.emit(e).catch(t=>{b$1().error("Event emission error",{error:t instanceof Error?t.message:String(t)});});}listenerCount(){let e=this.globalListeners.size;for(let t of this.listeners.values())e+=t.size;for(let t of this.tableListeners.values())e+=t.size;return e}async safeCall(e,t){try{await e(t);}catch(s){b$1().error("Event listener error",{error:s instanceof Error?s.message:String(s)});}}},m=n(a.eventEmitter,()=>new c);function b(){return m.getRequired()}function f(r){m.set(r);}function E(r,e){return m.resolve(r,e)}async function y(r,e){let t=new TextEncoder,s=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},false,["sign"]),n=await crypto.subtle.sign("HMAC",s,t.encode(r));return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function g(r,e){if(!e||e.length===0)return true;let t=`${r.table}:${r.type}`;return e.some(s=>s==="*"||s===t)}async function C(r,e){let t=r.timeout??1e4,s=r.retries??2,n=JSON.stringify(e),i={"Content-Type":"application/json","X-Webhook-Event":`${e.table}.${e.type}`,"X-Webhook-Timestamp":e.timestamp,...r.headers??{}};if(r.secret){let o=await y(n,r.secret);i["X-Webhook-Signature"]=`sha256=${o}`;}let a;for(let o=0;o<=s;o++){try{let u=new AbortController,v=setTimeout(()=>u.abort(),t),d=await fetch(r.url,{method:"POST",headers:i,body:n,signal:u.signal});if(clearTimeout(v),d.ok)return {url:r.url,success:!0,statusCode:d.status,attempts:o+1};a=new Error(`HTTP ${d.status}: ${d.statusText}`);}catch(u){a=u instanceof Error?u:new Error(String(u));}o<s&&await new Promise(u=>setTimeout(u,1e3*Math.pow(2,o)));}return {url:r.url,success:false,error:a?.message,attempts:s+1}}function L(r){let e=E(void 0,r.emitter);if(!e)throw new Error("Event emitter not configured. Pass emitter explicitly or call setEventEmitter() first.");let t=n=>{for(let i of r.endpoints){if(!g(n,i.events))continue;let a=C(i,n).then(o=>{!o.success&&r.onError&&r.onError(i,n,new Error(o.error??"Unknown delivery error"));}).catch(o=>{r.onError&&r.onError(i,n,o instanceof Error?o:new Error(String(o)));});r.waitUntil&&r.waitUntil(a);}},s=e.onAny(t);return ()=>s.unsubscribe()}export{c as a,b,f as c,E as d,L as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function l(e){return !e||!e.enabled?{enabled:false,tableName:"audit_logs",actions:[],excludeFields:[],storeRecord:true,storePreviousRecord:true,trackChanges:true}:{enabled:true,tableName:e.tableName||"audit_logs",actions:e.actions||["create","update","delete"],excludeFields:e.excludeFields||[],storeRecord:e.storeRecord??true,storePreviousRecord:e.storePreviousRecord??true,trackChanges:e.trackChanges??true,getUserId:e.getUserId}}function c(e,r,u=[]){let n=[];if(!e&&!r)return n;let d=new Set([...Object.keys(e||{}),...Object.keys(r||{})]);for(let t of d){if(u.includes(t))continue;let s=e?.[t],i=r?.[t],o=JSON.stringify(s),a=JSON.stringify(i);o!==a&&n.push({field:t,oldValue:s,newValue:i});}return n}export{l as a,c as b};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import {a as a$6,b as b$2}from'./chunk-PDHKGPGZ.js';import {v}from'./chunk-P5JQKX7Z.js';import {g,a as a$5}from'./chunk-HIDT3P5C.js';import {f as f$1}from'./chunk-UAVAEDVS.js';import {a as a$4}from'./chunk-EX4S3Q4M.js';import {c,d,f,e,i as i$1}from'./chunk-CKUGVMFX.js';import {a,b,i,d as d$1,c as c$1}from'./chunk-5FV7DBVK.js';import {a as a$3}from'./chunk-BPBFNTBM.js';import {d as d$3,e as e$1}from'./chunk-DZ3EM3AE.js';import {d as d$2}from'./chunk-CVNB5GB5.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {a as a$1,b as b$3}from'./chunk-VJRDAVID.js';import {a as a$2}from'./chunk-IJBJE4G2.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE,stream}from'hono/streaming';var zt=new WeakMap;function Qe(r){return zt.get(r)}var ye=class{app;options;routes=new Map;constructor(e,t={}){this.app=e,this.options={docs_url:"/docs",redoc_url:"/redoc",openapi_url:"/openapi.json",...t};}registerRoute(e,t,o,n=[]){let s=`${e.toUpperCase()} ${t}`,i=o,c$1=new i().getSchema();this.routes.set(s,{method:e,path:t,schema:c$1,routeClass:o});let p=createRoute({method:e,path:this.convertPath(t),...c$1,responses:c$1.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(n.length>0)for(let a of n)this.app.use(t,async(d,l)=>{if(d.req.method.toLowerCase()===e)return a(d,l);await l();});this.app.openapi(p,async a$1=>{let d$1=new i;d$1.setContext(a$1);try{return await d$1.handle()}catch(l){if(l instanceof a){let m=l.toJSON(),h=a$1?.var?.[c];return h?d(a$1,h.error(m.error),l.status):d(a$1,m,l.status)}throw l}});}convertPath(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}setupDocs(e,t){let o=e??this.options.openapi_url??"/openapi.json";this.app.doc(o,{openapi:t.openapi||"3.1.0",info:t.info,servers:t.servers,security:t.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return this.convertPath(e)}};function ao(r=new OpenAPIHono,e={}){let t="openAPIRegistry"in r?r:new OpenAPIHono,o=new ye(t,e),n=["get","post","put","patch","delete","options","head"],s=new Proxy(t,{get(i,u){if(n.includes(u))return (p,...a)=>{let d=a[a.length-1];if(f(d)){let l=a.slice(0,-1);return o.registerRoute(u,p,d,l),s}return i[u](p,...a)};if(u==="doc")return (p,a)=>{o.setupDocs(p,a);};if(u==="use")return (...p)=>(i[u](...p),s);let c=i[u];return typeof c=="function"?c.bind(i):c}});return zt.set(s,o),s}var uo=6e4,mo={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function ho(r,e,t={}){let o=Qe(r);if(!o)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let n=t.config??mo,s=`openapi:${e.tenantId??"global"}:${n.info.version}`;if(t.cache){let p=await t.cache.get(s);if(p!=null)return p}let i=new OpenAPIHono;for(let p of o.getRegisteredRoutes().values()){let a=p.routeClass,d=new a,l=fo(e);d.setContext(l),typeof d.resolveModelSchema=="function"&&await d.resolveModelSchema();let m=d.getSchema(),h=createRoute({...m,method:p.method,path:o.toOpenApiPath(p.path),responses:m.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});i.openapi(h,()=>new Response);}let u={openapi:n.openapi??"3.1.0",info:n.info,servers:n.servers,security:n.security},c=t.spec==="3.0"?i.getOpenAPIDocument(u):i.getOpenAPI31Document(u);return t.cache&&await t.cache.set(s,c,t.cacheTtlMs??uo),c}function fo(r){let e={};r.tenantId!==void 0&&(e.tenantId=r.tenantId),r.organizationId!==void 0&&(e.organizationId=r.organizationId);let t=r.request??new Request("http://localhost/");return {var:e,env:r.env,req:{raw:t,header:()=>{},query:()=>{},param:()=>{}},set(o,n){e[o]=n;},get(o){return e[o]},executionCtx:void 0}}function go(r){return {async get(e){let t=await r.get(e);return t?t.data:void 0},async set(e,t,o){let n=o?Math.ceil(o/1e3):void 0;await r.set(e,t,n?{ttl:n}:void 0);}}}var Mo=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"]];function Eo(r){return r.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function Ro(r,e){let o=`/${r}/${e}`.replace(/\/{2,}/g,"/");return o.length>1&&o.endsWith("/")?o.slice(0,-1):o}function xo(r,e={}){let t=e.basePath??"",o=e.tag,n=new OpenAPIHono,s=0;for(let[c,p,a]of Mo){let d=r[c];if(!d)continue;let m=new d().getSchema(),h=o!==void 0?{...m,tags:[o]}:m,f=Ro(t,Eo(a)),y=createRoute({...h,method:p,path:f,responses:h.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});n.openapi(y,()=>new Response),s+=1;}return s===0?{}:n.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var qt=r=>{if(r instanceof ZodError)return b.fromZodError(r)};function ko(r={}){let{mappers:e=[],hooks:t=[],includeRequestId:o=true,includeStackTrace:n=false,defaultErrorCode:s="INTERNAL_ERROR",defaultErrorMessage:i="An internal error occurred",logUnmappedErrors:u=true,onHookError:c,responseEnvelope:p}=r,a$1=[...e,qt];return async(d$1,l)=>{let m,h=false;if(d$1 instanceof a)m=d$1,h=true;else if(d$1 instanceof HTTPException)m=new a(d$1.message,d$1.status,"HTTP_ERROR"),h=true;else {for(let g of a$1)try{let x=await g(d$1,l);if(x){m=x,h=!0;break}}catch{}h||(u&&b$1().error("Unmapped error",{error:d$1 instanceof Error?d$1.message:String(d$1)}),m=new a(i,500,s));}for(let g of t)try{let x=g(d$1,l,m);x instanceof Promise&&x.catch(F=>{c&&c(F,d$1,l);});}catch(x){c&&c(x,d$1,l);}let f=m.toJSON();if(o){let g=v(l);g&&(f.error.requestId=g);}n&&d$1.stack&&(f.error.stack=d$1.stack);let y=$t(l,p),b=y?y.error(f.error):f;return d(l,b,m.status)}}function $t(r,e){return r?.var?.[c]??e}var Ge="createdAt",Je="updatedAt";function ie(r){return r?r===true?{enabled:true,createdAt:Ge,updatedAt:Je}:{enabled:true,createdAt:r.createdAt??Ge,updatedAt:r.updatedAt??Je}:{enabled:false,createdAt:Ge,updatedAt:Je}}function D(r,e={}){let{includePrimaryKeys:t=true}=e,o=new Set;if(t)for(let s of r.primaryKeys)o.add(s);let n=ie(r.timestamps);return n.enabled&&(o.add(n.createdAt),o.add(n.updatedAt)),[...o]}function Co(r){return r!=null&&r!==""}function Ye(r,e,t,o){let n={...r},s=e.primaryKeys[0];if(!Co(n[s])){let u=e.id;if(typeof u=="function")n[s]=u();else if(u==="database"){if(t==="memory")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)");delete n[s];}else n[s]=o?o():crypto.randomUUID();}let i$1=ie(e.timestamps);if(i$1.enabled){let u=Date.now();i$1.createdAt in r||(n[i$1.createdAt]=u),i$1.updatedAt in r||(n[i$1.updatedAt]=u);}return n}function Xe(r,e){let t=ie(e.timestamps);return t.enabled?{...r,[t.updatedAt]:Date.now()}:{...r}}function et(r,e){if(e==="memory"&&r.id==="database")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)")}function tt(r,e){let t={...r};for(let o of D(e))delete t[o];return t}var Po=new Set(["P2002","SQLITE_CONSTRAINT_UNIQUE","SQLITE_CONSTRAINT","23505","ER_DUP_ENTRY",1062,"1062"]),vo=/UNIQUE constraint failed|duplicate key value violates unique constraint|Duplicate entry/i;function jo(r){if(!r||typeof r!="object")return false;let{code:e,message:t}=r;return (typeof e=="string"||typeof e=="number")&&Po.has(e)?true:typeof t=="string"&&vo.test(t)}function*Kt(r,e=8){for(let t=r,o=0;o<e&&t!=null&&typeof t=="object";o++)yield t,t=t.cause;}function we(r){for(let e of Kt(r))if(jo(e))return new d$1("Unique constraint violation");return null}function W(r){throw we(r)??r}function Fo(r){return btoa(String(r))}function Io(r){try{return atob(r)}catch{return null}}async function ae(r,e){if(!e||Object.keys(e).length===0)return r;let t={...r};for(let[o,n]of Object.entries(e))try{let s=await n.compute(r);t[o]=s;}catch{t[o]=void 0;}return t}async function ot(r,e){return !e||Object.keys(e).length===0?r:Promise.all(r.map(t=>ae(t,e)))}function ee(r,e){let t={},o={};for(let[n,s]of Object.entries(r))e.includes(n)&&s!==void 0?o[n]=s:t[n]=s;return {mainData:t,nestedData:o}}function fe(r){if(Array.isArray(r))return true;if(typeof r=="object"&&r!==null){let e=Object.keys(r),t=["create","update","delete","connect","disconnect","set"];return !e.some(o=>t.includes(o))}return false}function Ao(r){let e=r.split(":");if(e.length<2)return null;let t=e[0].toLowerCase();return ["count","sum","avg","min","max","countdistinct"].includes(t)?{operation:t==="countdistinct"?"countDistinct":t,field:e[1],alias:e[2]}:null}function rt(r){let e=[],t={},o=["count","sum","avg","min","max","countDistinct"];for(let d of o){let l=r[d];if(l){let m=Array.isArray(l)?l:[l];for(let h of m)typeof h=="string"&&e.push({operation:d,field:h==="true"||h===""?"*":h});}}let n;if(r.groupBy){let d=r.groupBy;typeof d=="string"?n=d.split(",").map(l=>l.trim()):Array.isArray(d)&&(n=d.filter(l=>typeof l=="string"));}let s;for(let[d,l]of Object.entries(r)){let m=d.match(/^having\[(\w+)\]\[(\w+)\]$/);if(m){let[,h,f]=m;s||(s={}),s[h]||(s[h]={}),s[h][f]=l;}}let i=typeof r.orderBy=="string"?r.orderBy:void 0,u=r.orderDirection==="desc"?"desc":"asc",c=typeof r.limit=="string"?Number.parseInt(r.limit,10):void 0,p=typeof r.offset=="string"?Number.parseInt(r.offset,10):void 0,a=[...o,"groupBy","orderBy","orderDirection","limit","offset"];for(let[d,l]of Object.entries(r))!a.includes(d)&&!d.startsWith("having[")&&(t[d]=l);return {aggregations:e,groupBy:n,filters:Object.keys(t).length>0?t:void 0,having:s,orderBy:i,orderDirection:u,limit:c,offset:p}}function nt(r){return r?r===true?{enabled:true,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}:{enabled:true,field:r.field??"deletedAt",allowQueryDeleted:r.allowQueryDeleted??true,queryParam:r.queryParam??"withDeleted"}:{enabled:false,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}}function st(r){let e={enabled:false,field:"tenantId",source:"context",headerName:"X-Tenant-ID",contextKey:"tenantId",pathParam:"tenantId",required:true,errorMessage:"Tenant ID is required"};return r?r===true?{...e,enabled:true}:{enabled:true,field:r.field??e.field,source:r.source??e.source,headerName:r.headerName??e.headerName,contextKey:r.contextKey??e.contextKey,pathParam:r.pathParam??e.pathParam,getTenantId:r.getTenantId,required:r.required??e.required,errorMessage:r.errorMessage??e.errorMessage}:e}function it(r,e){return e.enabled?{header:()=>r.req.header(e.headerName),context:()=>a$1(r,e.contextKey),path:()=>r.req.param(e.pathParam),custom:()=>e.getTenantId?.(r)}[e.source]?.():void 0}var _o=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 at(r,e=true){if(!r||typeof r!="string")return [];let t=r.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(Boolean);return e?t.filter(o=>!_o.has(o)&&o.length>1):t}function dt(r,e){return e==="phrase"?[r.toLowerCase().trim()]:at(r)}function Qt(r,e){return e.length===0?0:e.filter(o=>o===r||o.includes(r)).length/e.length}function lt(r,e,t,o){if(e.length===0)return {score:0,matchedFields:[]};let n=0,s=0,i=[];for(let[c,p]of Object.entries(t)){let a=r[c];if(a==null)continue;let d=p.weight??1;s+=d;let l;p.type==="array"&&Array.isArray(a)?l=a.join(" "):l=String(a);let m=at(l,false),h=l.toLowerCase(),f=0,y=0;if(o==="phrase"){let b=e[0];h.includes(b)&&(f=1,y=1);}else {for(let b of e){let g=Qt(b,m);g>0?(y++,f+=g):h.includes(b)&&(y++,f+=.5/e.length);}e.length>0&&(f=f/e.length);}o==="all"&&y<e.length&&(f=0),f>0&&(i.push(c),n+=f*d);}return {score:s>0?Math.min(1,n/s):0,matchedFields:i}}function ct(r,e,t,o="mark",n=150){if(r==null)return [];let s;if(Array.isArray(r)?s=r.join(" "):s=String(r),!s||e.length===0)return [];let i=[],u=s.toLowerCase();if(t==="phrase"){let c=e[0],p=u.indexOf(c);if(p!==-1){let a=Wt(s,p,c.length,n,o);a&&i.push(a);}}else {let c=[];for(let a of e){let d=0;for(;d<u.length;){let l=u.indexOf(a,d);if(l===-1)break;c.push({start:l,length:a.length}),d=l+1;}}c.sort((a,d)=>a.start-d.start);let p=new Set;for(let a of c){if(Array.from(p).some(m=>Math.abs(m-a.start)<n))continue;let l=Wt(s,a.start,a.length,n,o);if(l&&(i.push(l),p.add(a.start)),i.length>=3)break}}return i}function Wt(r,e,t,o,n){let s=Math.floor(o/2),i=Math.max(0,e-s),u=Math.min(r.length,e+t+s);if(i>0){let a=r.indexOf(" ",i);a!==-1&&a<e&&(i=a+1);}if(u<r.length){let a=r.lastIndexOf(" ",u);a!==-1&&a>e+t&&(u=a);}let c=r.slice(i,u);return i>0&&(c="..."+c),u<r.length&&(c=c+"..."),To(c,[r.slice(e,e+t)],n)}function To(r,e,t){let o=r,n=r.toLowerCase(),s=[...e].sort((i,u)=>u.length-i.length);for(let i of s){let u=i.toLowerCase(),c=0,p="",a=0;for(;a<n.length;){let d=n.indexOf(u,a);if(d===-1)break;p+=o.slice(c,d),p+=`<${t}>${o.slice(d,d+i.length)}</${t}>`,c=d+i.length,a=c;}p&&(p+=o.slice(c),o=p);}return o}function pt(r,e){if(!r)return Object.keys(e);let t=r.split(",").map(n=>n.trim()).filter(Boolean),o=Object.keys(e);return t.filter(n=>o.includes(n))}function ut(r,e){let t={};for(let o of r)t[o]={weight:e?.[o]??1};return t}function mt(r){return r==="all"||r==="phrase"?r:"any"}function ht(r){if(r===null||typeof r!="object")return r;if(Array.isArray(r))return r.map(ht);let e={};for(let t of Object.keys(r).sort())e[t]=ht(r[t]);return e}async function de(r){let e=JSON.stringify(ht(r)),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 ft(r,e){return r?r==="*"?true:r.split(",").map(t=>t.trim()).includes(e):false}function gt(r,e){return !r||r==="*"?true:r.split(",").map(t=>t.trim()).includes(e)}function Gt(r,e){return r==="in"||r==="nin"||r==="between"?e.split(",").map(t=>t.trim()):r==="null"?e.toLowerCase()==="true":e}function No(r){let e=r.match(/^\[([a-z]+)\](.*)$/);if(e){let t=e[1];return {operator:t,value:Gt(t,e[2])}}return {operator:"eq",value:r}}function te(r,e){let t=[],o={},{filterFields:n=[],filterConfig:s={},searchFields:i=[],searchFieldName:u="search",sortFields:c=[],defaultSort:p,defaultPerPage:a=20,maxPerPage:d=100,cursorPaginationEnabled:l=false,softDeleteQueryParam:m="withDeleted",allowedIncludes:h=[],fieldSelectionEnabled:f=false,allowedSelectFields:y=[],blockedSelectFields:b=[],alwaysIncludeFields:g=[],defaultSelectFields:x=[]}=e,F={};for(let I of n)F[I]=["eq"];Object.assign(F,s);for(let[I,Te]of Object.entries(r)){if(Te==null)continue;let B=String(Te);if(l&&I==="cursor"){o.cursor=B;continue}if(l&&I==="limit"){o.limit=Math.min(d,Math.max(1,Number.parseInt(B,10)||a));continue}if(I==="page"){o.page=Math.max(1,Number.parseInt(B,10)||1);continue}if(I==="per_page"){o.per_page=Math.min(d,Math.max(1,Number.parseInt(B,10)||a));continue}if(I==="sort"){(c.length===0||c.includes(B))&&(o.order_by=B);continue}if(I==="order"){(B==="asc"||B==="desc")&&(o.order_by_direction=B);continue}if(I===u&&i.length>0){o.search=B;continue}if(I===m){o.withDeleted=B.toLowerCase()==="true";continue}if(I==="onlyDeleted"){o.onlyDeleted=B.toLowerCase()==="true";continue}if(I==="include"){let re=B.split(",").map(K=>K.trim()).filter(Boolean);h&&h.length>0?o.include=re.filter(K=>h.includes(K)):o.include=re;continue}if(I==="fields"&&f){let K=B.split(",").map(ce=>ce.trim()).filter(Boolean);y.length>0&&(K=K.filter(ce=>y.includes(ce))),b.length>0&&(K=K.filter(ce=>!b.includes(ce))),g.length>0&&(K=[...new Set([...g,...K])]),o.fields=K;continue}let Ne=I.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(Ne){let re=Ne[1],K=Ne[2];F[re]?.includes(K)&&t.push({field:re,operator:K,value:Gt(K,B)});continue}F[I]&&t.push({field:I,operator:"eq",value:B});}if(o.page||(o.page=1),o.per_page||(o.per_page=a),!o.order_by&&p?.field&&(o.order_by=p.field),o.order_by_direction||(o.order_by_direction=p?.order??"asc"),f&&!o.fields&&x.length>0){let I=[...x];g.length>0&&(I=[...new Set([...g,...I])]),o.fields=I;}return {filters:t,options:o}}function Z(r,e=[]){if(e.length===0)return r;let t=new Set(Object.keys(r.shape)),o=e.filter(s=>t.has(s));if(o.length===0)return r;let n=Object.fromEntries(o.map(s=>[s,true]));return r.omit(n)}function Ho(r,e={},t=[],o=[],n=[]){let{allowedFields:s=[],blockedFields:i=[],alwaysIncludeFields:u=[],defaultFields:c=[],allowComputedFields:p=true,allowRelationFields:a=true}=e;if(!r||typeof r!="string"||r.trim()==="")return c.length>0?{fields:[...new Set([...u,...c])],isActive:false}:{fields:[],isActive:false};let d=r.split(",").map(f=>f.trim()).filter(Boolean),l=new Set;for(let f of t)(s.length===0||s.includes(f))&&(i.includes(f)||l.add(f));if(p)for(let f of o)(s.length===0||s.includes(f))&&(i.includes(f)||l.add(f));if(a)for(let f of n)(s.length===0||s.includes(f))&&(i.includes(f)||l.add(f));let m=d.filter(f=>l.has(f));return {fields:[...new Set([...u,...m])],isActive:true}}function Me(r,e){if(!e.isActive||e.fields.length===0)return r;let t={};for(let o of e.fields)o in r&&(t[o]=r[o]);return t}function bt(r,e){return !e.isActive||e.fields.length===0?r:r.map(t=>Me(t,e))}var Yt="__honoCrudResolvedSchema:";function Do(r){return typeof r.getBodySchema=="function"}var S=class extends e{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=f$1(this._meta.model.audit)),this._auditLogger}getAuditConfig(){return a$4(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=g(this._meta.model.versioning,this._meta.model.tableName)),this._versionManager}getVersioningConfig(){return a$5(this._meta.model.versioning,this._meta.model.tableName)}isVersioningEnabled(){return this.getVersioningConfig().enabled}getVersioningUserId(){let e=this.getVersioningConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?a$1(this.context,a$2.userId):void 0}getSoftDeleteConfig(){return nt(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return st(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,t,o){return Ye(e,this._meta.model,t,o)}applyManagedUpdateFields(e){return Xe(e,this._meta.model)}assertIdStrategySupported(e){et(this._meta.model,e);}getTimestampsConfig(){return ie(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return it(this.context,e)}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();if(!t&&e.required)throw new HTTPException(400,{message:e.errorMessage});return t}injectTenantId(e){let t=this.getMultiTenantConfig();if(!t.enabled)return e;let o=this.getTenantId();return o?{...e,[t.field]:o}:e}async emitEvent(e,t){let o=d$2(this.context??void 0);o&&await o.emit({type:e,table:this._meta.model.tableName,recordId:t.recordId,data:t.data??null,previousData:t.previousData,userId:this.getAuditUserId(),tenantId:this.context?this.getTenantId():void 0,organizationId:this.context?a$1(this.context,a$2.organizationId):void 0,timestamp:new Date().toISOString(),metadata:t.metadata});}async encryptOnWrite(e){let t=this._meta.model.fieldEncryption;return t?await d$3(e,t.fields,t.keyProvider):e}async decryptOnRead(e){let t=this._meta.model.fieldEncryption;return t?await e$1(e,t.fields,t.keyProvider):e}applyProfile(e){let t=this._meta.model.serializationProfile;return t?a$6(e,t):e}applyProfileToArray(e){let t=this._meta.model.serializationProfile;return t?b$2(e,t):e}transform(e){return e}async finalizeRecord(e,t){let o=this._meta.model,n=e;o.computedFields&&(n=await ae(n,o.computedFields));let s=o.serializer?o.serializer(n):n,i=this.applyProfile(s),u=this.transform(i);return t?.isActive&&t.fields.length>0?Me(u,t):u}async finalizeArray(e,t){let o=this._meta.model,n=e;o.computedFields&&(n=await ot(n,o.computedFields));let s=o.serializer?n.map(c=>o.serializer(c)):n,u=this.applyProfileToArray(s).map(c=>this.transform(c));return t?.isActive&&t.fields.length>0?bt(u,t):u}getRecordId(e){if(e===null||typeof e!="object")return null;let t=this._meta.model.primaryKeys[0],o=e[t];return typeof o=="string"||typeof o=="number"?o:null}getParentId(e){return this.getRecordId(e)}getPolicies(){if(this.context){let e=a$1(this.context,i$1);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 n=t.fields(o,e);return {...e,...n}}return e}async applyReadPolicyToArray(e){if(!this.getPolicies())return e;let o=[];for(let n of e){let s=await this.applyReadPolicy(n);s!==null&&o.push(s);}return o}async applyWritePolicy(e){let t=this.getPolicies();if(!t?.write)return;if(!await t.write(this.buildPolicyContext(),e))throw new HTTPException(403,{message:"Forbidden by policy"})}applyReadPushdown(e){let t=this.getPolicies();if(!t?.readPushdown)return;let o=t.readPushdown(this.buildPolicyContext());o&&o.length>0&&e.filters.push(...o);}buildHookContext(){let e=this.context;return {db:{tx:this._tx},request:e?.req?.raw,tenantId:e?this.getTenantId():void 0,organizationId:e?a$1(e,a$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,Yt+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=Yt+this._meta.model.tableName,o=a$1(this.context,t);if(o)return o;let n={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(n);}catch(i){throw new a(i instanceof Error?i.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",i instanceof Error?{cause:i.message}:void 0)}return b$3(this.context,t,s),s}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&Do(this)){let t=e.body;try{t=await this.context.req.json();}catch{}let n=this.getBodySchema().safeParse(t);if(!n.success)throw b.fromZodError(n.error);e.body=n.data;}return e}};function Vo(){return z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}function R(r){return {description:r??"Error",content:{"application/json":{schema:Vo()}}}}var yt=class extends S{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,t=D(this._meta.model),o=this.getMultiTenantConfig();o.enabled&&t.push(o.field),this._meta.fields?e=this._meta.fields:e=Z(this.getModelSchema(),t);let n=this.getNestedWritableRelations();if(n.length===0)return e;let s={...e.shape};for(let i of n){let u=this._meta.model.relations?.[i];if(!u?.schema)continue;let c=["id",u.foreignKey],p=Z(u.schema,c);u.type==="hasMany"?s[i]=z.array(p).optional():s[i]=p.optional();}return z.object(s)}getNestedWritableRelations(){if(this.allowNestedCreate.length>0)return this.allowNestedCreate;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>o.nestedWrites?.allowCreate===true).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return ee(e,t)}getSchema(){let e=this.getBodySchema();return {...this.schema,request:{body:{content:{"application/json":{schema:e}},required:true}},responses:{201:{description:"Resource created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Validation error")}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t){return e}async after(e,t){return e}transform(e){return e}async createNested(e,t,o,n,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),n=t;n=this.injectTenantId(n);let s=this.buildHookContext();n=await this.before(n,s),n=await this.encryptOnWrite(n),n=await this.create(n,s.db.tx).catch(W),n=await this.decryptOnRead(n);let i=this.getParentId(n),u={};if(Object.keys(o).length>0&&i!==null)for(let[p,a]of Object.entries(o)){if(a==null)continue;let d=this._meta.model.relations?.[p];if(!d)continue;let l=await this.createNested(i,p,d,a);u[p]=l;}if(Object.keys(u).length>0){let p={};for(let[a,d]of Object.entries(u)){let l=this._meta.model.relations?.[a];l&&(l.type==="hasMany"?p[a]=d:p[a]=d[0]||null);}n={...n,...p};}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(n,s))):n=await this.after(n,s),this.isAuditEnabled()&&i!==null){let p=this.getAuditLogger();this.runAfterResponse(p.logCreate(this._meta.model.tableName,i,n,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("created",{recordId:i,data:n}));let c=await this.finalizeRecord(n);return this.success(c,201)}};var wt=class extends S{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().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let t=this.getAvailableSelectFields();e.fields=z.string().optional().describe(`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):[],n=[...e,...t,...o];return this.allowedSelectFields.length>0&&(n=n.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(n=n.filter(s=>!this.blockedSelectFields.includes(s))),n}getSchema(){let e=this.getQuerySchema();return {...this.schema,request:{params:this.getParamsSchema(),...e&&{query:e}},responses:{200:{description:"Resource retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:R("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async getIncludeOptions(){let{query:e}=await this.getValidatedData(),t=e?.include;if(!t||typeof t!="string")return {relations:[]};let o=t.split(",").map(n=>n.trim()).filter(Boolean);return this.allowedIncludes.length>0?{relations:o.filter(n=>this.allowedIncludes.includes(n))}:{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),n=new Set(this.getAvailableSelectFields()),s=o.filter(i=>n.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(),n=await this.getIncludeOptions(),s=await this.getFieldSelection();if(e){let p=this.getMultiTenantConfig();o[p.field]=e;}let i=await this.read(t,o,n);if(!i)throw new c$1(this._meta.model.tableName,t);i=await this.decryptOnRead(i);let u=await this.applyReadPolicy(i);if(u===null)throw new c$1(this._meta.model.tableName,t);i=u,i=await this.after(i);let c=await this.finalizeRecord(i,s);if(this.etagEnabled){let p=await de(c),a=this.getContext(),d=a.req.header("If-None-Match");if(ft(d,p))return new Response(null,{status:304,headers:{ETag:p}});a.header("ETag",p);}return this.success(c)}};var Mt=class extends S{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 n=D(this._meta.model);this.blockedUpdateFields&&(n=[...n,...this.blockedUpdateFields]);let s=Z(this.getModelSchema(),n);if(this.allowedUpdateFields){let i={};for(let u of this.allowedUpdateFields)i[u]=true;s=s.pick(i);}e=s.partial();}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let n of t){let s=this._meta.model.relations?.[n];if(!s?.schema)continue;let i=s.schema,u=z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()}).optional();o[n]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let n=o.nestedWrites;return n&&(n.allowCreate||n.allowUpdate||n.allowDelete||n.allowConnect||n.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return ee(e,t)}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Validation error"),404:R("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getObject(){let{body:e}=await this.getValidatedData();return e}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){return e}async after(e,t,o){return t}transform(e){return e}async findExisting(e,t,o){return null}async processNestedWrites(e,t,o,n,s){return b$1().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let b=this.getMultiTenantConfig();o[b.field]=e;}let n=await this.getObject(),{mainData:s,nestedData:i}=this.extractNestedData(n),u=this.getPolicies(),c=await this.findExisting(t,o,this._tx);if(c&&u?.write&&await this.applyWritePolicy(c),this.etagEnabled&&c){let b=this.getContext().req.header("If-Match");if(b){let g=await de(c);if(!gt(b,g))return this.error("Resource has been modified by another request","CONFLICT",409)}}let p;if(this.isVersioningEnabled()&&c){let b=this.getVersionManager(),g=this.getParentId(c);g!==null&&(p=await b.saveVersion(g,c,void 0,this.getVersioningUserId()));}let a=s;if(this.isVersioningEnabled()&&p!==void 0){let b=this.getVersioningConfig().field;a[b]=p;}let d=this.buildHookContext();a=await this.before(a,d),a=await this.encryptOnWrite(a);let l=await this.update(t,a,o,d.db.tx);if(!l)throw new c$1(this._meta.model.tableName,t);l=await this.decryptOnRead(l);let m=this.getParentId(l),h={};if(Object.keys(i).length>0&&m!==null)for(let[b,g]of Object.entries(i)){if(g==null)continue;let x=this._meta.model.relations?.[b];if(!x)continue;let F;fe(g)?F={create:g}:F=g;let I=await this.processNestedWrites(m,b,x,F);h[b]=I;}if(Object.keys(h).length>0)for(let[b,g]of Object.entries(h)){let x=this._meta.model.relations?.[b];x&&(x.type==="hasMany"?l[b]=[...g.created,...g.updated]:l[b]=g.created[0]||g.updated[0]||null);}let f=c??l;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(f,l,d)));else {let b=await this.after(f,l,d);b!=null&&(l=b);}if(this.isAuditEnabled()&&m!==null&&c){let b=this.getAuditLogger();this.runAfterResponse(b.logUpdate(this._meta.model.tableName,m,c,l,this.getAuditUserId()));}m!==null&&this.runAfterResponse(this.emitEvent("updated",{recordId:m,data:l,previousData:c??void 0}));let y=await this.finalizeRecord(l);if(this.etagEnabled){let b=await de(y);this.getContext().header("ETag",b);}return this.success(y)}};var Et=class extends S{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,n])=>{let s=n.cascade?.[e];return s&&s!=="noAction"}).map(([o,n])=>({name:o,config:n,action:n.cascade[e]})):[]}getSchema(){let e=this.includeCascadeResults?z.object({deleted:z.literal(true),cascade:z.object({deleted:z.record(z.string(),z.number()),nullified:z.record(z.string(),z.number())}).optional()}):z.object({deleted:z.literal(true)});return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:R("Resource not found"),409:{description:"Cannot delete - related records exist (restrict)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.object({relation:z.string(),count:z.number()}).optional()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){}async countRelated(e,t,o,n){return b$1().warn(`countRelated not implemented for ${t}. Override in your adapter for restrict cascade to work.`),0}async deleteRelated(e,t,o,n){return b$1().warn(`deleteRelated not implemented for ${t}. Override in your adapter for cascade delete to work.`),0}async nullifyRelated(e,t,o,n){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 n=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(n),i={deleted:{},nullified:{}};for(let{name:u,config:c,action:p}of s)if(p==="cascade"){let a=await this.deleteRelated(e,u,c,o);a>0&&(i.deleted[u]=a);}else if(p==="setNull"){let a=await this.nullifyRelated(e,u,c,o);a>0&&(i.nullified[u]=a);}return i}async checkRestrictConstraints(e,t,o){let n=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(n);for(let{name:i,config:u,action:c}of s)if(c==="restrict"){let p=await this.countRelated(e,i,u,o);if(p>0)throw new d$1(`Cannot delete: ${p} related ${i} record(s) exist. Remove them first or change the cascade configuration.`,{relation:i,count:p})}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let d=this.getMultiTenantConfig();o[d.field]=e;}let n=this.isSoftDeleteEnabled(),s=await this.findForDelete(t,o,this._tx);if(!s)throw new c$1(this._meta.model.tableName,t);let i=this.getParentId(s);i!==null&&await this.checkRestrictConstraints(i,n),await this.applyWritePolicy(s);let u=this.buildHookContext();if(await this.before(t,u),!await this.delete(t,o,u.db.tx))throw new c$1(this._meta.model.tableName,t);let p;if(i!==null&&(p=await this.processCascade(i,n)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(s,u))):await this.after(s,u),this.isAuditEnabled()&&i!==null){let d=this.getAuditLogger();this.runAfterResponse(d.logDelete(this._meta.model.tableName,i,s,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("deleted",{recordId:i,previousData:s}));let a={deleted:true};if(this.includeCascadeResults&&p){let d=Object.keys(p.deleted).length>0,l=Object.keys(p.nullified).length>0;(d||l)&&(a.cascade=p);}return this.success(a)}};var ge=class extends S{filterFields=[];filterConfig;searchFields=[];searchFieldName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;cursorField;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getQuerySchema(){let e={page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(e.sort=z.enum(this.sortFields).optional().describe("Field to sort by"),e.order=z.enum(["asc","desc"]).optional().describe("Sort direction (asc or desc)")),this.searchFields.length>0&&(e[this.searchFieldName]=z.string().optional());for(let o of this.filterFields)e[o]=z.string().optional();if(this.filterConfig)for(let[o,n]of Object.entries(this.filterConfig)){for(let s of n)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().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let o=this.getAvailableSelectFields();e.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${o.join(", ")}`);}return this.cursorPaginationEnabled&&(e.cursor=z.string().optional().describe("Opaque cursor for fetching the next page"),e.limit=z.string().optional().describe("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):[],n=[...e,...t,...o];return this.allowedSelectFields.length>0&&(n=n.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(n=n.filter(s=>!this.blockedSelectFields.includes(s))),n}getSchema(){return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"List of resources",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(this.getModelSchema()),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),has_next_page:z.boolean(),has_prev_page:z.boolean(),next_cursor:z.string().optional(),prev_cursor:z.string().optional()})})}}}}}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:this.searchFields,searchFieldName:this.searchFieldName,sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,cursorPaginationEnabled:this.cursorPaginationEnabled,cursorField:this.cursorField,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return te(e||{},o)}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getFilters();if(e){let p=this.getMultiTenantConfig();t.filters.push({field:p.field,operator:"eq",value:e});}this.applyReadPushdown(t);let o=await this.list(t),n=await Promise.all(o.result.map(p=>this.decryptOnRead(p))),s=await this.applyReadPolicyToArray(n),i=await this.after(s),u=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?{fields:t.options.fields,isActive:true}:void 0,c=await this.finalizeArray(i,u);return this.successPaginated(c,o.result_info)}};var Rt=class extends S{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...D(this._meta.model),...this.excludeFromClone];return Z(this.getModelSchema(),e).partial()}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:false}},responses:{201:{description:"Resource cloned successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:R("Source resource not found"),409:R("Unique-constraint violation (e.g. natural-key collision)")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getOverrides(){let{body:e}=await this.getValidatedData();return e||{}}async before(e){return e}async after(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getOverrides(),n={};if(e){let a=this.getMultiTenantConfig();n[a.field]=e;}let s=await this.findSource(t,n);if(!s)throw new c$1(this._meta.model.tableName,t);let i=tt(s,this._meta.model);for(let a of this.excludeFromClone)delete i[a];Object.assign(i,o);let u=await this.before(i),c=await this.createClone(u).catch(W);c=await this.after(c);let p=await this.finalizeRecord(c);return this.success(p,201)}};var be=new Map,Lo=["password","token","secret","apiKey","creditCard","ssn"];function xe(r,e){if(r==null||typeof r!="object")return r;if(Array.isArray(r))return r.map(o=>xe(o,e));let t={};for(let[o,n]of Object.entries(r))e.includes(o)||(t[o]=typeof n=="object"&&n!==null?xe(n,e):n);return t}function Uo(r){let{table:e,events:t,emitter:o,filter:n,heartbeatInterval:s=3e4,maxConnections:i=1e3,connectionTimeout:u=3e5,excludeFields:c=Lo}=r;return p=>{let a=d$2(p,o);if(!a)return p.json({success:false,error:{code:"EVENT_EMITTER_NOT_CONFIGURED",message:"Event emitter not configured"}},500);let d=be.get(e)||0;return d>=i?p.json({success:false,error:{code:"TOO_MANY_CONNECTIONS",message:"Too many SSE connections"}},503):(be.set(e,d+1),streamSSE(p,async l=>{let m,h=async g=>{if(t&&t.length>0&&!t.includes(g.type)||n&&!n(g,p))return;let x=c.length>0?xe(g.data,c):g.data,F=g.previousData&&c.length>0?xe(g.previousData,c):g.previousData;try{await l.writeSSE({event:`${g.table}.${g.type}`,data:JSON.stringify({type:g.type,table:g.table,recordId:g.recordId,data:x,previousData:F,timestamp:g.timestamp}),id:`${g.table}-${g.recordId}-${Date.now()}`});}catch{}};m=a.onTable(e,h);let f=()=>{m.unsubscribe();let g=be.get(e)||1;g<=1?be.delete(e):be.set(e,g-1);};l.onAbort(()=>{f();});let y=Date.now(),b=y;for(;!l.closed;){await l.sleep(1e3);let g=Date.now();if(g-y>=u){l.abort();break}if(g-b>=s){b=g;try{await l.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}}))}}var xt=class extends S{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Soft delete not enabled or record not deleted"),404:R("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getAdditionalFilters();await this.before(e);let o=await this.restore(e,t);if(!o)throw new c$1(this._meta.model.tableName,e);this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(o))):o=await this.after(o);let n=this.getRecordId(o);if(this.isAuditEnabled()&&n!==null){let i=this.getAuditLogger();this.runAfterResponse(i.logRestore(this._meta.model.tableName,n,o,this.getAuditUserId()));}n!==null&&this.runAfterResponse(this.emitEvent("restored",{recordId:n,data:o}));let s=await this.finalizeRecord(o);return this.success(s)}};var St=class extends S{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 n=this.getUpsertKeys(),s=D(this._meta.model,{includePrimaryKeys:false});for(let c of this._meta.model.primaryKeys)n.includes(c)||s.push(c);let i=Z(this.getModelSchema(),s),u={};for(let[c,p]of Object.entries(i.shape))n.includes(c)?u[c]=p:u[c]=p.optional();e=z.object(u);}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let n of t){let s=this._meta.model.relations?.[n];if(!s?.schema)continue;let i=s.schema,u=z.union([s.type==="hasMany"?z.array(i.partial()):i.partial(),z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),upsert:z.union([i.partial(),z.array(i.partial())]).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()})]).optional();o[n]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let n=o.nestedWrites;return n&&(n.allowCreate||n.allowUpdate||n.allowDelete||n.allowConnect||n.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return ee(e,t)}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(false)})}}},201:{description:"Resource created (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(true)})}}},400:R("Validation error")}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t,o){return e}async beforeCreate(e,t){return e}async beforeUpdate(e,t,o){return e}async after(e,t,o){return e}async nativeUpsert(e,t){return b$1().warn("Native upsert not implemented for this adapter. Falling back to find-then-insert/update pattern."),this.performStandardUpsert(e,t)}async performStandardUpsert(e,t){let o=await this.findExisting(e,t);if(o){let n={...e};if(this.createOnlyFields)for(let i of this.createOnlyFields)delete n[i];return n=await this.beforeUpdate(n,o,t),{data:await this.update(o,n,t),created:false}}else {let n={...e};if(this.updateOnlyFields)for(let i of this.updateOnlyFields)delete n[i];return n=await this.beforeCreate(n,t),{data:await this.create(n,t),created:true}}}async upsert(e,t){return this.useNativeUpsert?this.nativeUpsert(e,t):this.performStandardUpsert(e,t)}async processNestedWrites(e,t,o,n,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),n=t;n=this.injectTenantId(n);let s=await this.findExisting(n),i=!s;n=await this.before(n,i);let u=await this.upsert(n).catch(W),c=u.data,p=this.getParentId(c),a={};if(Object.keys(o).length>0&&p!==null)for(let[l,m]of Object.entries(o)){if(m==null)continue;let h=this._meta.model.relations?.[l];if(!h)continue;let f;fe(m)?f={create:m}:f=m;let y=await this.processNestedWrites(p,l,h,f);a[l]=y;}if(Object.keys(a).length>0)for(let[l,m]of Object.entries(a)){let h=this._meta.model.relations?.[l];h&&(h.type==="hasMany"?c[l]=[...m.created,...m.updated]:c[l]=m.created[0]||m.updated[0]||null);}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(c,u.created))):c=await this.after(c,u.created),this.isAuditEnabled()&&p!==null){let l=this.getAuditLogger();this.runAfterResponse(l.logUpsert(this._meta.model.tableName,p,c,s,u.created,this.getAuditUserId()));}let d=await this.finalizeRecord(c);return this.json({success:true,result:d,created:u.created},u.created?201:200)}};var Ot=class extends S{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:Z(this.getModelSchema(),D(this._meta.model));return z.object({items:z.array(e).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{201:{description:"Resources created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number()})})}}},207:{description:"Partial success (some items failed)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}async before(e,t,o){return e}async after(e,t,o){return e}transform(e){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let p=0;p<e.length;p++)try{let a=await this.before(e[p],p);o.push(a);}catch(a){if(this.stopOnError)throw a;t.push({index:p,error:a instanceof Error?a.message:String(a)});}let n=await this.batchCreate(o).catch(W),s=[];for(let p=0;p<n.length;p++)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(n[p],p))),s.push(n[p])):s.push(await this.after(n[p],p));}catch(a){if(this.stopOnError)throw a;t.push({index:p,error:a instanceof Error?a.message:String(a)}),s.push(n[p]);}if(this.isAuditEnabled()){let p=this.getAuditLogger(),a=s.map(d=>{let l=this.getRecordId(d);return l===null?null:{recordId:l,record:d}}).filter(d=>d!==null);a.length>0&&this.runAfterResponse(p.logBatch("batch_create",this._meta.model.tableName,a,this.getAuditUserId()));}let i=await this.finalizeArray(s),u={success:true,result:{created:i,count:i.length,...t.length>0&&{errors:t}}},c=t.length>0?207:201;return this.json(u,c)}};var kt=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:Z(this.getModelSchema(),D(this._meta.model));return z.object({items:z.array(z.object({id:z.string(),data:e.partial()})).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}filterUpdateData(e){let t={...e};if(this.allowedUpdateFields){let o=new Set(this.allowedUpdateFields);t=Object.fromEntries(Object.entries(t).filter(([n])=>o.has(n)));}if(this.blockedUpdateFields)for(let o of this.blockedUpdateFields)delete t[o];for(let o of this._meta.model.primaryKeys)delete t[o];return t}async before(e,t,o){return t}async after(e,t){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let a of e)try{let d=this.filterUpdateData(a.data),l=await this.before(a.id,d);o.push({id:a.id,data:l});}catch(d){if(this.stopOnError)throw d;t.push({id:a.id,error:d instanceof Error?d.message:String(d)});}let{updated:n,notFound:s}=await this.batchUpdate(o),i=[];for(let a of n)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let l=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:l,error:d instanceof Error?d.message:String(d)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=i.map(l=>{let m=this.getRecordId(l);return m===null?null:{recordId:m,record:l}}).filter(l=>l!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_update",this._meta.model.tableName,d,this.getAuditUserId()));}let u=await this.finalizeArray(i),c={success:true,result:{updated:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},p=t.length>0||s.length>0?207:200;return this.json(c,p)}};var Ct=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){let e=this.isSoftDeleteEnabled();return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:e?"Resources soft-deleted successfully":"Resources deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(d){if(this.stopOnError)throw d;t.push({id:a,error:d instanceof Error?d.message:String(d)});}let{deleted:n,notFound:s}=await this.batchDelete(o),i=[];for(let a of n)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let l=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:l,error:d instanceof Error?d.message:String(d)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=i.map(l=>{let m=this.getRecordId(l);return m===null?null:{recordId:m,previousRecord:l}}).filter(l=>l!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_delete",this._meta.model.tableName,d,this.getAuditUserId()));}let u=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,c={success:true,result:{deleted:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},p=t.length>0||s.length>0?207:200;return this.json(c,p)}};var Pt=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:R("Soft delete not enabled or validation error")}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(d){if(this.stopOnError)throw d;t.push({id:a,error:d instanceof Error?d.message:String(d)});}let{restored:n,notFound:s}=await this.batchRestore(o),i=[];for(let a of n)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let l=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:l,error:d instanceof Error?d.message:String(d)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=i.map(l=>{let m=this.getRecordId(l);return m===null?null:{recordId:m,record:l}}).filter(l=>l!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_restore",this._meta.model.tableName,d,this.getAuditUserId()));}let u=await this.finalizeArray(i),c={success:true,result:{restored:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},p=t.length>0||s.length>0?207:200;return this.json(c,p)}};var vt=class extends S{upsertKeys;createOnlyFields;updateOnlyFields;maxBatchSize=100;continueOnError=false;useNativeUpsert=false;beforeHookMode="sequential";afterHookMode="sequential";getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getItemSchema(){if(this._meta.fields)return this._meta.fields;let e=this.getUpsertKeys(),t=D(this._meta.model,{includePrimaryKeys:false});for(let s of this._meta.model.primaryKeys)e.includes(s)||t.push(s);let o=Z(this.getModelSchema(),t),n={};for(let[s,i]of Object.entries(o.shape))e.includes(s)?n[s]=i:n[s]=i.optional();return z.object(n)}getBodySchema(){return z.array(this.getItemSchema()).max(this.maxBatchSize)}getSchema(){let e=z.object({data:this.getModelSchema(),created:z.boolean(),index:z.number()});return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Batch upsert completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({items:z.array(e),createdCount:z.number(),updatedCount:z.number(),totalCount:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e}async beforeItem(e,t,o,n){return e}async afterItem(e,t,o,n){return e}async beforeBatch(e,t){return e}async afterBatch(e,t){return e}async upsertOne(e,t,o){let n=await this.findExisting(e,o),s=!n,i=await this.beforeItem(e,t,s,o),u;if(n){if(this.createOnlyFields)for(let c of this.createOnlyFields)delete i[c];u=await this.update(n,i,o);}else {if(this.updateOnlyFields)for(let c of this.updateOnlyFields)delete i[c];u=await this.create(i,o);}return u=await this.afterItem(u,t,s,o),{data:u,created:s,index:t}}async nativeBatchUpsert(e,t){return b$1().warn("Native batch upsert not implemented for this adapter. Falling back to item-by-item pattern."),this.performStandardBatchUpsert(e,t)}async performStandardBatchUpsert(e,t){let o=[],n=[],s=0,i=0;for(let c=0;c<e.length;c++)try{let p=await this.upsertOne(e[c],c,t);o.push(p),p.created?s++:i++;}catch(p){if(this.continueOnError)n.push({index:c,error:p instanceof Error?p.message:String(p)});else throw p}let u={items:o,createdCount:s,updatedCount:i,totalCount:o.length};return n.length>0&&(u.errors=n),u}async batchUpsert(e,t){return this.useNativeUpsert?this.nativeBatchUpsert(e,t):this.performStandardBatchUpsert(e,t)}async handle(){let e=await this.getItems();e=await this.beforeBatch(e);let t=await this.batchUpsert(e).catch(W);if(t=await this.afterBatch(t),this._meta.model.computedFields&&(t.items=await Promise.all(t.items.map(async o=>({...o,data:await ae(o.data,this._meta.model.computedFields)})))),this.isAuditEnabled()){let o=this.getAuditLogger(),n=t.items.map(s=>{let i=this.getRecordId(s.data);return i===null?null:{recordId:i,record:s.data}}).filter(s=>s!==null);n.length>0&&this.runAfterResponse(o.logBatch("batch_upsert",this._meta.model.tableName,n,this.getAuditUserId()));}return t.items=t.items.map(o=>{let n=this._meta.model.serializer?this._meta.model.serializer(o.data):o.data,s=this.applyProfile(n);return {...o,data:this.transform(s)}}),this.success(t)}};var jt=class extends S{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getSchema(){return {request:{body:{content:{"application/json":{schema:this.getUpdateSchema().partial()}}},query:z.object({dryRun:z.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z.object({success:z.boolean(),matched:z.number(),updated:z.number(),dryRun:z.boolean()})}}},400:{description:"Bad request",content:{"application/json":{schema:z.object({success:z.boolean(),error:z.string()})}}}}}}async handle(){let e=this.getContext(),o=(await this.getValidatedData()).body;if(!o||Object.keys(o).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let n=e.req.query("dryRun"),s=n==="true"||n==="1",i=te(e.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),u=await this.countMatching(i);if(u===0)return this.json({success:true,matched:0,updated:0,dryRun:s});if(u>this.maxBulkSize)return this.error(`Bulk patch affects ${u} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(u>=this.confirmThreshold&&e.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${u} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(s)return this.json({success:true,matched:u,updated:0,dryRun:true});let c=o;this.beforeBulkPatch&&(c=await this.beforeBulkPatch(c,i,u));let p=await this.applyPatch(c,i),a={matched:u,updated:p.updated,dryRun:false,records:this.returnRecords?p.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 Xt=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 S{lookupField="id";defaultLimit=20;maxLimit=100;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({limit:z.coerce.number().min(1).max(this.maxLimit).optional(),offset:z.coerce.number().min(0).optional()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version history retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({versions:z.array(Xt),totalVersions:z.number()})})}}},400:R("Versioning not enabled"),404:R("Record not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getPaginationOptions(){let{query:e}=await this.getValidatedData();return {limit:e?.limit?Number(e.limit):this.defaultLimit,offset:e?.offset?Number(e.offset):0}}async recordExists(e){return true}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{limit:t,offset:o}=await this.getPaginationOptions();if(!await this.recordExists(e))throw new c$1(this._meta.model.tableName,e);let s=this.getVersionManager(),i=await s.getVersions(e,{limit:t,offset:o}),u=await s.getLatestVersion(e);return this.success({versions:i,totalVersions:u})}},It=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:Xt})}}},400:R("Versioning not enabled"),404:R("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),n=await this.getVersionManager().getVersion(e,t);if(!n)throw new c$1(`version ${t}`,e);return this.success(n)}},At=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({from:z.coerce.number().min(1),to:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version comparison completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({from:z.number(),to:z.number(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()}))})})}}},400:R("Versioning not enabled or invalid parameters"),404:R("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumbers(){let{query:e}=await this.getValidatedData();return {from:e?.from?Number(e.from):0,to:e?.to?Number(e.to):0}}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{from:t,to:o}=await this.getVersionNumbers(),s=await this.getVersionManager().compareVersions(e,t,o);return this.success({from:t,to:o,changes:s})}},_t=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Record rolled back successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Versioning not enabled"),404:R("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),o=this.getVersionManager(),n=await o.getVersion(e,t);if(!n)throw new c$1(`version ${t}`,e);let i=await o.getLatestVersion(e)+1,u=await this.rollback(e,n.data,i),c=this._meta.model.serializer?this._meta.model.serializer(u):u;return this.success(c)}};var Bo={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},Nt=class extends S{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {...Bo,...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(["asc","desc"]).optional(),limit:z.coerce.number().optional(),offset:z.coerce.number().optional(),withDeleted:z.coerce.boolean().optional()}).passthrough()}getSchema(){let e=z.object({key:z.record(z.string(),z.unknown()),values:z.record(z.string(),z.number().nullable())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Aggregation result",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({values:z.record(z.string(),z.number().nullable()).optional(),groups:z.array(e).optional(),totalGroups:z.number().optional()})})}}},400:R("Invalid aggregation request")}}}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return rt(e||{})}validateAggregations(e){let t=this.getAggregateConfig();for(let o of e.aggregations)if(!(o.operation==="count"&&o.field==="*"))switch(o.operation){case "sum":if(t.sumFields.length>0&&!t.sumFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for SUM aggregation`);break;case "avg":if(t.avgFields.length>0&&!t.avgFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for AVG aggregation`);break;case "min":case "max":if(t.minMaxFields.length>0&&!t.minMaxFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for MIN/MAX aggregation`);break;case "countDistinct":if(t.countDistinctFields.length>0&&!t.countDistinctFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for COUNT DISTINCT aggregation`);break}if(e.groupBy){if(e.groupBy.length>this.maxGroupByFields)throw new b(`Maximum ${this.maxGroupByFields} GROUP BY fields allowed`);for(let o of e.groupBy)if(t.groupByFields.length>0&&!t.groupByFields.includes(o))throw new Error(`Field '${o}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>t.maxLimit)throw new Error(`Limit cannot exceed ${t.maxLimit}`)}getAggregateAlias(e){return e.alias?e.alias:e.field==="*"?e.operation:`${e.operation}${e.field.charAt(0).toUpperCase()}${e.field.slice(1)}`}async handle(){let e=await this.getAggregateOptions();e.aggregations.length===0&&e.aggregations.push({operation:"count",field:"*"}),this.validateAggregations(e);let t=this.getAggregateConfig();e.groupBy&&e.groupBy.length>0&&e.limit===void 0&&(e.limit=t.defaultLimit);let o=await this.aggregate(e);return this.success(o)}},zo={eq:(r,e)=>r===e,ne:(r,e)=>r!==e,gt:(r,e)=>r>e,gte:(r,e)=>r>=e,lt:(r,e)=>r<e,lte:(r,e)=>r<=e};function qo(r,e){let t=r.get(e);if(t)return t;let o=[];return r.set(e,o),o}function $o(r,e){let{aggregations:t,groupBy:o,having:n,orderBy:s,orderDirection:i,limit:u,offset:c}=e;if(!o||o.length===0){let l={};for(let m of t){let h=to(m);l[h]=eo(r,m);}return {values:l}}let p=new Map;for(let l of r){let h=o.map(f=>String(l[f]??"null")).join("|");qo(p,h).push(l);}let a=[];for(let[l,m]of p){let h=l.split("|"),f={};o.forEach((b,g)=>{f[b]=h[g]==="null"?null:h[g];});let y={};for(let b of t){let g=to(b);y[g]=eo(m,b);}a.push({key:f,values:y});}n&&(a=a.filter(l=>{for(let[m,h]of Object.entries(n)){let f=l.values[m];if(f!==null)for(let[y,b]of Object.entries(h)){let g=zo[y];if(g&&!g(f,Number(b)))return false}}return true}));let d=a.length;if(s){let l=i==="desc"?-1:1;a.sort((m,h)=>{if(s in m.values){let f=m.values[s]??0,y=h.values[s]??0;return (f-y)*l}if(s in m.key){let f=String(m.key[s]??""),y=String(h.key[s]??"");return f.localeCompare(y)*l}return 0});}if(c!==void 0||u!==void 0){let l=c||0,m=u?l+u:void 0;a=a.slice(l,m);}return {groups:a,totalGroups:d}}function Tt(r,e){return r.map(t=>t[e]).filter(t=>typeof t=="number")}var Ko={count:(r,e)=>e==="*"?r.length:r.filter(t=>t[e]!==null&&t[e]!==void 0).length,countDistinct:(r,e)=>new Set(r.map(o=>o[e]).filter(o=>o!=null).map(o=>String(o))).size,sum:(r,e)=>{let t=0;for(let o of r){let n=o[e];typeof n=="number"&&(t+=n);}return t},avg:(r,e)=>{let t=Tt(r,e);return t.length===0?null:t.reduce((n,s)=>n+s,0)/t.length},min:(r,e)=>{let t=Tt(r,e);return t.length===0?null:Math.min(...t)},max:(r,e)=>{let t=Tt(r,e);return t.length===0?null:Math.max(...t)}};function eo(r,e){if(r.length===0)return e.operation==="count"?0:null;let t=Ko[e.operation];return t?t(r,e.field):null}function to(r){return r.alias?r.alias:r.field==="*"?r.operation:`${r.operation}${r.field.charAt(0).toUpperCase()}${r.field.slice(1)}`}function Wo(r){if(r instanceof z.ZodString)return true;let e=r;return e?e._def?.type==="string"||e._def?.typeName==="ZodString"||e.def?.type==="string":false}var Ht=class extends S{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 ut(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,t={};for(let[o,n]of Object.entries(e))Wo(n)&&(t[o]={weight:1});return t}getQuerySchema(){let t={[this.searchParamName||"q"]:z.string().min(this.minQueryLength).max(this.maxQueryLength).describe("Search query"),fields:z.string().optional().describe(`Comma-separated fields to search. Available: ${Object.keys(this.getSearchableFields()).join(", ")}`),mode:z.enum(["any","all","phrase"]).optional().describe("Search mode: any (OR), all (AND), phrase (exact)"),highlight:z.enum(["true","false"]).optional().describe("Include highlighted snippets"),minScore:z.string().optional().describe("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().describe("Field to sort by"),t.order=z.enum(["asc","desc"]).optional().describe("Sort direction (asc or desc)"));for(let n of this.filterFields)t[n]=z.string().optional();if(this.filterConfig)for(let[n,s]of Object.entries(this.filterConfig)){for(let i of s)t[`${n}[${i}]`]=z.string().optional();t[n]=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().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let n=this.getAvailableSelectFields();t.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${n.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):[],n=[...e,...t,...o];return this.allowedSelectFields.length>0&&(n=n.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(n=n.filter(s=>!this.blockedSelectFields.includes(s))),n}getSchema(){let e=z.object({item:this.getModelSchema(),score:z.number().min(0).max(1),highlights:z.record(z.string(),z.array(z.string())).optional(),matchedFields:z.array(z.string())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Search results",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(e),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),query:z.string(),searchedFields:z.array(z.string())})})}}},400:R("Invalid search request")}}}async getSearchOptions(){let{query:e}=await this.getValidatedData(),t=this.searchParamName||"q",o=e?.[t],n=e?.fields,s=mt(e?.mode),i=e?.highlight==="true",u=e?.minScore?Math.max(0,Math.min(1,Number.parseFloat(e.minScore)||0)):this.defaultMinScore,c=this.getSearchableFields(),p=pt(n,c);return {query:o,fields:p.length>0?p:Object.keys(c),mode:s??this.defaultMode,highlight:i,minScore:u}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchFieldName:"q",sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return te(e||{},o)}async beforeSearch(e){return e}async afterSearch(e){return e}async handle(){let e=await this.getSearchOptions(),t=await this.getFilters();if(!e.query||e.query.length<this.minQueryLength)return this.json({success:false,error:{code:"INVALID_QUERY",message:`Search query must be at least ${this.minQueryLength} characters`}},400);e=await this.beforeSearch(e);let o=await this.search(e,t),n=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(n.map(l=>l.item),s),u=n.map((l,m)=>({...l,item:i[m]})),c=o.postFilteredCount??o.totalCount,p=t.options.page||1,a=t.options.per_page||this.defaultPerPage,d=Math.ceil(c/a);return this.successPaginated(u,{page:p,per_page:a,total_count:c,total_pages:d,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function Qo(r,e,t){let o=dt(e.query,e.mode),n={},s=e.fields||Object.keys(t);for(let u of s)t[u]&&(n[u]=t[u]);let i=[];for(let u of r){let{score:c,matchedFields:p}=lt(u,o,n,e.mode);if(c<e.minScore||p.length===0)continue;let a;if(e.highlight){a={};for(let d of p){let l=ct(u[d],o,e.mode);l.length>0&&(a[d]=l);}}i.push({item:u,score:c,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:p});}return i.sort((u,c)=>c.score-u.score),i}function Q(r,e={}){let{delimiter:t=",",nullValue:o="",dateFormat:n="iso"}=e;if(r==null)return o;if(r instanceof Date)switch(n){case "timestamp":return String(r.getTime());case "locale":return r.toLocaleString();default:return r.toISOString()}if(typeof r=="object")return Q(JSON.stringify(r),e);if(typeof r=="boolean")return r?"true":"false";let s=String(r),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 Oe(r,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
|
|
3
|
+
`,includeHeader:n=true,formatters:s={},excludeFields:i=[],headerLabels:u={},nullValue:c="",dateFormat:p="iso"}=e;if(r.length===0)return "";let a=e.headers;a?a=a.filter(l=>!i.includes(l)):a=Object.keys(r[0]).filter(l=>!i.includes(l));let d=[];if(n){let l=a.map(m=>{let h=u[m]||m;return Q(h,{delimiter:t,nullValue:c,dateFormat:p})});d.push(l.join(t));}for(let l of r){let m=a.map(h=>{let f=l[h];return s[h]&&(f=s[h](f)),Q(f,{delimiter:t,nullValue:c,dateFormat:p})});d.push(m.join(t));}return d.join(o)}function Go(r,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
|
|
4
|
+
`,includeHeader:n=true,formatters:s={},excludeFields:i=[],headerLabels:u={},nullValue:c="",dateFormat:p="iso"}=e,a=new TextEncoder,d=0,l=false,m=e.headers;return !m&&r.length>0?m=Object.keys(r[0]).filter(h=>!i.includes(h)):m?m=m.filter(h=>!i.includes(h)):m=[],new ReadableStream({pull(h){if(n&&!l&&m.length>0){let b=m.map(g=>{let x=u[g]||g;return Q(x,{delimiter:t,nullValue:c,dateFormat:p})});h.enqueue(a.encode(b.join(t)+o)),l=true;return}let f=100,y=[];for(;d<r.length&&y.length<f;){let b=r[d],g=m.map(x=>{let F=b[x];return s[x]&&(F=s[x](F)),Q(F,{delimiter:t,nullValue:c,dateFormat:p})});y.push(g.join(t)),d++;}y.length>0&&h.enqueue(a.encode(y.join(o)+o)),d>=r.length&&h.close();}})}function oo(r,e){let t=[],o="",n=false,s=0;for(;s<r.length;){let i=r[s];if(n){if(i==='"'){if(s+1<r.length&&r[s+1]==='"'){o+='"',s+=2;continue}n=false,s++;continue}o+=i,s++;}else {if(i==='"'){n=true,s++;continue}if(i===e){t.push(o),o="",s++;continue}o+=i,s++;}}return t.push(o),t}function Jo(r){let e=[],t="",o=false;for(let n=0;n<r.length;n++){let s=r[n];if(s==='"'){if(o&&n+1<r.length&&r[n+1]==='"'){t+='""',n++;continue}o=!o,t+=s;continue}if(!o&&(s===`
|
|
5
|
+
`||s==="\r")){s==="\r"&&n+1<r.length&&r[n+1]===`
|
|
6
|
+
`&&n++,t.length>0&&(e.push(t),t="");continue}t+=s;}return t.length>0&&e.push(t),e}function ke(r,e={}){let{delimiter:t=",",hasHeader:o=true,trimValues:n=true,skipEmptyRows:s=true,parsers:i={},emptyValue:u="empty"}=e,c={data:[],headers:[],errors:[]},p=Jo(r);if(p.length===0)return c;let a=0;if(o){let l=p[0];c.headers=oo(l,t).map(m=>n?m.trim():m),a=1;}else e.headers&&(c.headers=e.headers);let d=e.headers||c.headers;for(let l=a;l<p.length;l++){let m=p[l],h=l+1;if(!(s&&m.trim()===""))try{let f=oo(m,t),y={};for(let b=0;b<d.length;b++){let g=d[b],x=b<f.length?f[b]:"";if(n&&typeof x=="string"&&(x=x.trim()),x==="")switch(u){case "null":x=null;break;case "undefined":x=void 0;break}if(i[g]&&typeof x=="string")try{x=i[g](x);}catch(F){c.errors.push({row:h,message:`Failed to parse field "${g}": ${F instanceof Error?F.message:String(F)}`,content:m});}y[g]=x;}c.data.push(y);}catch(f){c.errors.push({row:h,message:`Failed to parse row: ${f instanceof Error?f.message:String(f)}`,content:m});}}return c}function Dt(r,e,t={}){let{allowUnknownFields:o=false,optionalFields:n=[]}=t,s=e.shape,i=Object.keys(s),c=i.filter(l=>n.includes(l)?false:!s[l].isOptional()).filter(l=>!r.includes(l)),p=r.filter(l=>!i.includes(l)),a=r.filter(l=>i.includes(l));return {valid:c.length===0&&(o||p.length===0),missingFields:c,unknownFields:p,validFields:a}}function Yo(r,e){if(r){let t=r.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 Xo(r,e={}){return Oe(r,e)}function er(r,e={}){return ke(r,e).data}var Vt=class extends ge{maxExportRecords=1e4;enableStreaming=true;streamPageSize=500;excludedExportFields=[];defaultFormat="json";csvOptions={};exportFilename;getExportQuerySchema(){return this.getQuerySchema().extend({format:z.enum(["json","csv"]).optional().describe("Export format"),stream:z.enum(["true","false"]).optional().describe("Enable streaming for large exports")})}getSchema(){return {...this.schema,request:{query:this.getExportQuerySchema()},responses:{200:{description:"Export successful",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({data:z.array(this.getModelSchema()),count:z.number(),format:z.enum(["json","csv"]),exportedAt:z.string()})})},"text/csv":{schema:z.string()}}}}}}async getExportOptions(){let{query:e}=await this.getValidatedData(),t=e?.format||this.defaultFormat,o=e?.stream==="true"&&this.enableStreaming;return {format:t,stream:o,fields:e?.fields?String(e.fields).split(","):void 0}}getExportFilename(e){let o=(this.exportFilename||this._meta.model.tableName).replace(/[^a-zA-Z0-9_-]/g,"_"),n=new Date().toISOString().replace(/[:.]/g,"-");return `${o}-export-${n}.${e}`}prepareRecordsForExport(e){return this.excludedExportFields.length===0?e:e.map(t=>{let o={};for(let[n,s]of Object.entries(t))this.excludedExportFields.includes(n)||(o[n]=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=Oe(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(),n=this.getExportFilename(t),s=this.csvOptions,i=this.excludedExportFields;return stream(o,async u=>{if(o.header("Content-Type","text/csv; charset=utf-8"),o.header("Content-Disposition",`attachment; filename="${n}"`),e.length===0)return;let c=Object.keys(e[0]).filter(d=>!i.includes(d)),p=c.map(d=>Q(d,s)).join(",")+`
|
|
8
|
+
`;await u.write(p);let a=100;for(let d=0;d<e.length;d+=a)for(let l of e.slice(d,d+a)){let m=c.map(h=>Q(l[h],s)).join(",")+`
|
|
9
|
+
`;await u.write(m);}})}exportAsCsvStreamPaginated(e,t){let o=this.getExportFilename(t),n=this.streamPageSize,s=Math.min(this.maxExportRecords,1e5),i=this.excludedExportFields,u=this.csvOptions,c=null,p=new ReadableStream({start:async a=>{let d=new TextEncoder,l=1,m=0;try{for(;m<s;){let h={...e,options:{...e.options,page:l,per_page:n}},y=(await this.list(h)).result;if(y.length===0)break;y.length>s-m&&(y=y.slice(0,s-m)),y=await this.after(y),y=await this.beforeExport(y);let b=this.prepareRecordsForExport(y);if(!c&&b.length>0){c=Object.keys(b[0]).filter(x=>!i.includes(x));let g=c.map(x=>Q(x,u)).join(",")+`
|
|
10
|
+
`;a.enqueue(d.encode(g));}if(c)for(let g of b){let x=c.map(F=>Q(g[F],u)).join(",")+`
|
|
11
|
+
`;a.enqueue(d.encode(x));}if(m+=y.length,l++,y.length<n)break}}catch(h){a.error(h);return}a.close();}});return new Response(p,{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 n=this.prepareRecordsForExport(o);return e.format==="csv"?this.exportAsCsv(n,e.format):this.exportAsJson(n,e.format)}};var Zt=class extends S{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:Z(this.getModelSchema(),D(this._meta.model));return z.object({items:z.array(e.partial()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{query:z.object({mode:z.enum(["create","upsert"]).optional().describe("Import mode"),skipInvalid:z.enum(["true","false"]).optional().describe("Skip invalid rows"),stopOnError:z.enum(["true","false"]).optional().describe("Stop on first error")})},responses:{200:{description:"Import completed successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},207:{description:"Import completed with partial failures",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},400:R("Validation error")}}}async getImportOptions(){let{query:e}=await this.getValidatedData(),t=e?.skipInvalid==="true"?true:e?.skipInvalid==="false"?false:this.skipInvalidRows,o=e?.stopOnError==="true"?true:e?.stopOnError==="false"?false:this.stopOnError;return {mode:e?.mode||this.defaultMode,skipInvalidRows:t,stopOnError:o}}async parseImportData(){let e=this.context;if(!e)throw new b("No request available");let t=e.req.header("content-type")||"";if(t.includes("application/json")){let o=await e.req.json();if(!o)throw new b("Request body is empty");if(!o.items||!Array.isArray(o.items))throw new b('Request body must contain an "items" array');if(o.items.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);return o.items}if(t.includes("text/csv")){let o=await e.req.text();if(o.length>this.maxBodySize)throw new b(`Request body exceeds maximum size of ${this.maxBodySize} bytes`);return this.parseCsvData(o)}if(t.includes("multipart/form-data")){let n=(await e.req.formData()).get("file");if(!n)throw new b("No file provided in form data");let s=await n.text();if(s.length>this.maxBodySize)throw new b(`Uploaded file exceeds maximum size of ${this.maxBodySize} bytes`);let i=n.name.toLowerCase();if(i.endsWith(".json")){let c;try{c=JSON.parse(s);}catch{throw new b("Invalid JSON content in uploaded file")}let p=Array.isArray(c)?c:c.items;if(!p||!Array.isArray(p))throw new b('JSON file must contain an array or an object with "items" array');if(p.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);return p}if(i.endsWith(".csv"))return this.parseCsvData(s);let u=s.trim();if(u.startsWith("[")||u.startsWith("{")){let c;try{c=JSON.parse(s);}catch{throw new b("Invalid JSON content in uploaded file")}let p=Array.isArray(c)?c:c.items;if(!p||!Array.isArray(p))throw new b('JSON file must contain an array or an object with "items" array');return p}return this.parseCsvData(s)}throw new b("Unsupported content type. Use application/json, text/csv, or multipart/form-data")}parseCsvData(e){let t=ke(e,this.csvOptions);if(t.errors.length>0)throw new b(`CSV parsing errors: ${t.errors.map(s=>`Row ${s.row}: ${s.message}`).join("; ")}`);if(t.data.length===0)throw new b("CSV file is empty");if(t.data.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);let o=this._meta.fields||this.getModelSchema(),n=Dt(t.headers,o,{allowUnknownFields:true,optionalFields:this.optionalImportFields});if(!n.valid&&n.missingFields.length>0)throw new b(`Missing required fields in CSV: ${n.missingFields.join(", ")}`);return t.data}validateRow(e,t){let o=this._meta.fields||this.getModelSchema(),n={};for(let i of D(this._meta.model))n[i]=true;for(let i of this.optionalImportFields)n[i]=true;let s=o.partial(n);try{return s.parse(e),{valid:!0}}catch(i){return i instanceof z.ZodError?{valid:false,errors:i.issues.map(c=>({path:c.path.join("."),message:c.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,n]of Object.entries(e))this.immutableFields.includes(o)||(t[o]=n);return t}async before(e,t,o,n){return e}async after(e,t,o,n){return e}async processRow(e,t,o,n){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,n);if(o.mode==="upsert"){let c=await this.findExisting(i,n);if(c){let p=this.removeImmutableFields(i),a=await this.update(c,p,n);return {rowNumber:t,status:"updated",data:a}}}else if(await this.findExisting(i,n))return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Record already exists"}:{rowNumber:t,status:"failed",error:"Record already exists (duplicate key)"};let u=await this.create(i,n);return {rowNumber:t,status:"created",data:u}}catch(i){let u=we(i);return u?{rowNumber:t,status:"failed",code:"CONFLICT",error:u.message}:{rowNumber:t,status:"failed",error:i instanceof Error?i.message:String(i)}}}async handle(){let e=await this.getImportOptions(),t=await this.parseImportData();if(!Number.isInteger(this.importBatchSize)||this.importBatchSize<1)throw new i("importBatchSize must be a positive integer");let o={total:t.length,created:0,updated:0,skipped:0,failed:0},n=[],s=false,i$1=e.stopOnError?1:this.importBatchSize;for(let p=0;p<t.length&&!s;p+=i$1){let a=t.slice(p,p+i$1),d=await Promise.all(a.map(async(l,m)=>{let h=p+m+1,f=await this.processRow(l,h,e);return f=await this.after(f,h,e.mode),f}));for(let l of d){switch(n.push(l),l.status){case "created":o.created++;break;case "updated":o.updated++;break;case "skipped":o.skipped++;break;case "failed":o.failed++;break}if(e.stopOnError&&l.status==="failed"){s=true;break}}}if(this.isAuditEnabled()){let p=this.getAuditLogger(),a=n.filter(d=>d.status==="created"||d.status==="updated");if(a.length>0){let d=a.map(l=>{if(!l.data)return null;let m=this.getRecordId(l.data);return m===null?null:{recordId:m,record:l.data}}).filter(l=>l!==null);d.length>0&&this.runAfterResponse(p.logBatch(e.mode==="upsert"?"batch_upsert":"batch_create",this._meta.model.tableName,d,this.getAuditUserId()));}}let u={summary:o,results:n},c=o.failed>0&&o.failed<o.total?207:200;return this.json({success:true,result:u},c)}};var Ce=Symbol.for("hono-crud.resource-registry");function ro(r,e,t){let o=r;o[Ce]||(o[Ce]=[]),o[Ce].push({path:e,endpoints:t});}function ki(r){return r[Ce]??[]}function or(r,e,t,o={}){let n=e.endsWith("/")?e.slice(0,-1):e,s=r,{middlewares:i=[],endpointMiddlewares:u={},responseEnvelope:c$1}=o,p=c$1?async(l,m)=>{b$3(l,c,c$1),await m();}:void 0,a=l=>{let m=t[l],h=m&&"_middlewares"in m?m._middlewares||[]:[];return [...p?[p]:[],...i,...u[l]||[],...h]},d=(l,m,h,f)=>{let y=a(h),b=s[l];y.length>0?b(m,...y,f):b(m,f);};t.create&&d("post",n,"create",t.create),t.list&&d("get",n,"list",t.list),t.batchCreate&&d("post",`${n}/batch`,"batchCreate",t.batchCreate),t.batchUpdate&&d("patch",`${n}/batch`,"batchUpdate",t.batchUpdate),t.batchDelete&&d("delete",`${n}/batch`,"batchDelete",t.batchDelete),t.batchRestore&&d("post",`${n}/batch/restore`,"batchRestore",t.batchRestore),t.batchUpsert&&d("post",`${n}/batch/upsert`,"batchUpsert",t.batchUpsert),t.search&&d("get",`${n}/search`,"search",t.search),t.aggregate&&d("get",`${n}/aggregate`,"aggregate",t.aggregate),t.export&&d("get",`${n}/export`,"export",t.export),t.import&&d("post",`${n}/import`,"import",t.import),t.upsert&&d("post",`${n}/upsert`,"upsert",t.upsert),t.bulkPatch&&d("patch",`${n}/bulk`,"bulkPatch",t.bulkPatch),t.read&&d("get",`${n}/:id`,"read",t.read),t.update&&d("patch",`${n}/:id`,"update",t.update),t.delete&&d("delete",`${n}/:id`,"delete",t.delete),t.restore&&d("post",`${n}/:id/restore`,"restore",t.restore),t.clone&&d("post",`${n}/:id/clone`,"clone",t.clone),t.versionHistory&&d("get",`${n}/:id/versions`,"versionHistory",t.versionHistory),t.versionCompare&&d("get",`${n}/:id/versions/compare`,"versionCompare",t.versionCompare),t.versionRead&&d("get",`${n}/:id/versions/:version`,"versionRead",t.versionRead),t.versionRollback&&d("post",`${n}/:id/versions/:version/rollback`,"versionRollback",t.versionRollback),ro(r,n,t);}function Lt(r){return {content:{"application/json":{schema:r}}}}function rr(r){return {description:"Success",...Lt({type:"object",properties:{success:{type:"boolean",enum:[true]},result:r},required:["success","result"]})}}function nr(r="Error"){return {description:r,...Lt({type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"object",properties:{code:{type:"string"},message:{type:"string"},details:{}},required:["code","message"]}},required:["success","error"]})}}function Ut(r,e){return {content:{"application/json":{schema:r}},description:e}}function sr(r,e){return {content:{"application/json":{schema:r}},description:e,required:true}}var no=z.object({code:z.string(),path:z.array(z.union([z.string(),z.number()])),message:z.string()}),Pe=z.object({success:z.literal(false),error:z.object({name:z.literal("ZodError"),issues:z.array(no)})});function ir(r){return Pe}function ar(...r){return Pe}var dr=(r,e)=>{if(!r.success)return e.json({success:false,error:{name:"ZodError",issues:r.error.issues}},422)};function lr(r,e=422){return (t,o)=>{if(!t.success)return o.json(r(t.error),e)}}var so=z.object({success:z.literal(false),error:z.object({message:z.string(),code:z.string().optional()})});function oe(r){return Ut(so,r)}var cr={badRequest:oe("Bad request"),unauthorized:oe("Unauthorized"),forbidden:oe("Forbidden"),notFound:oe("Resource not found"),conflict:oe("Resource conflict"),validationError:Ut(Pe,"Validation error"),internalError:oe("Internal server error")};function pr(r){return async(e,t)=>{r.audit&&e.set(a$2.auditStorage,r.audit),r.versioning&&e.set(a$2.versioningStorage,r.versioning),r.logging&&e.set(a$2.loggingStorage,r.logging),r.events&&e.set(a$2.eventEmitter,r.events),await t();}}var ve=class{constructor(e){this.meta=e;}_schema={};_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_allowNestedCreate=[];_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}nestedCreate(...e){return this._allowNestedCreate=e,this}build(e){return a$3(e,{meta:this.meta,schema:this._schema,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,allowNestedCreate:this._allowNestedCreate,middlewares:this._middlewares})}},je=class{constructor(e){this.meta=e;}_schema={};_filterFields=[];_filterConfig;_searchFields=[];_searchFieldName="search";_sortFields=[];_defaultSort;_defaultPerPage=20;_maxPerPage=100;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}filter(...e){return this._filterFields=e,this}filterWith(e){return this._filterConfig=e,this}search(...e){return this._searchFields=e,this}searchParam(e){return this._searchFieldName=e,this}sortable(...e){return this._sortFields=e,this}orderBy(...e){return this.sortable(...e)}defaultSort(e,t="asc"){return this._defaultSort={field:e,order:t},this}defaultOrder(e,t="asc"){return this.defaultSort(e,t)}pagination(e,t){return this._defaultPerPage=e,t!==void 0&&(this._maxPerPage=t),this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return a$3(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchFieldName:this._searchFieldName,sortFields:this._sortFields,defaultSort:this._defaultSort,defaultPerPage:this._defaultPerPage,maxPerPage:this._maxPerPage,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},Fe=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return a$3(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},Ie=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}allowedFields(...e){return this._allowedUpdateFields=e,this}blockedFields(...e){return this._blockedUpdateFields=e,this}nestedWrites(...e){return this._allowNestedWrites=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}transform(e){return this._transform=e,this}build(e){return a$3(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedUpdateFields:this._allowedUpdateFields,blockedUpdateFields:this._blockedUpdateFields,allowNestedWrites:this._allowNestedWrites,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,transform:this._transform,middlewares:this._middlewares})}},Ae=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_includeCascadeResults=false;_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}includeCascade(e=true){return this._includeCascadeResults=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}build(e){return a$3(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,includeCascadeResults:this._includeCascadeResults,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,middlewares:this._middlewares})}},_e=class{constructor(e){this.meta=e;}create(){return new ve(this.meta)}list(){return new je(this.meta)}read(){return new Fe(this.meta)}update(){return new Ie(this.meta)}delete(){return new Ae(this.meta)}};function ur(r){return new _e(r)}export{xt as $,nt as A,or as Aa,st as B,Lt as Ba,it as C,rr as Ca,at as D,nr as Da,dt as E,Ut as Ea,Qt as F,sr as Fa,lt as G,no as Ga,ct as H,Pe as Ha,pt as I,ir as Ia,ut as J,ar as Ja,mt as K,dr as Ka,de as L,lr as La,ft as M,so as Ma,gt as N,oe as Na,No as O,cr as Oa,te as P,pr as Pa,Z as Q,ve as Qa,Ho as R,je as Ra,Me as S,Fe as Sa,bt as T,Ie as Ta,yt as U,Ae as Ua,wt as V,_e as Va,Mt as W,ur as Wa,Et as X,ge as Y,Rt as Z,Uo as _,Qe as a,St as aa,ye as b,Ot as ba,ao as c,kt as ca,ho as d,Ct as da,go as e,Pt as ea,xo as f,vt as fa,qt as g,jt as ga,ko as h,Ft as ha,$t as i,It as ia,ie as j,At as ja,D as k,_t as ka,Ye as l,Nt as la,Xe as m,$o as ma,et as n,Ht as na,tt as o,Qo as oa,Kt as p,Q as pa,we as q,Oe as qa,W as r,Go as ra,Fo as s,ke as sa,Io as t,Dt as ta,ae as u,Yo as ua,ot as v,Xo as va,ee as w,er as wa,fe as x,Vt as xa,Ao as y,Zt as ya,rt as z,ki as za};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-IJBJE4G2.js';function a(e){return async(t,o)=>{e.loggingStorage&&t.set(a$1.loggingStorage,e.loggingStorage),e.auditStorage&&t.set(a$1.auditStorage,e.auditStorage),e.versioningStorage&&t.set(a$1.versioningStorage,e.versioningStorage),e.apiKeyStorage&&t.set(a$1.apiKeyStorage,e.apiKeyStorage),e.eventEmitter&&t.set(a$1.eventEmitter,e.eventEmitter),await o();}}function g(e){return a({loggingStorage:e})}function i(e){return a({auditStorage:e})}function n(e){return a({versioningStorage:e})}function d(e){return a({apiKeyStorage:e})}export{a,g as b,i as c,n as d,d as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b as b$1}from'./chunk-EX4S3Q4M.js';import {n}from'./chunk-ZJWDAVGG.js';import {a}from'./chunk-IJBJE4G2.js';function b(t,e){return !t||!t.enabled?{enabled:false,field:"version",historyTable:`${e}_history`,maxVersions:null,trackChangedBy:false,excludeFields:[]}:{enabled:true,field:t.field||"version",historyTable:t.historyTable||`${e}_history`,maxVersions:t.maxVersions??null,trackChangedBy:t.trackChangedBy??false,excludeFields:t.excludeFields||[],getUserId:t.getUserId}}var d=class{versions=new Map;getKey(e,r){return `${e}:${r}`}async save(e){let r=this.getKey(e.tableName||e.id.split(":")[0]||"unknown",e.recordId),n={...e,tableName:r.split(":")[0]},s=this.versions.get(r)||[];s.push(n),this.versions.set(r,s);}async store(e,r){let n=this.getKey(e,r.recordId),s=this.versions.get(n)||[];s.push({...r,tableName:e}),this.versions.set(n,s);}async getByRecordId(e,r,n){let s=this.getKey(e,r),o=[...this.versions.get(s)||[]].sort((m,g)=>g.version-m.version),a=n?.offset||0,l=n?.limit||o.length;return o.slice(a,a+l)}async getVersion(e,r,n){let s=this.getKey(e,r);return (this.versions.get(s)||[]).find(o=>o.version===n)||null}async getLatestVersion(e,r){let n=this.getKey(e,r),s=this.versions.get(n)||[];return s.length===0?0:Math.max(...s.map(i=>i.version))}async pruneVersions(e,r,n){let s=this.getKey(e,r),i=this.versions.get(s)||[];if(i.length<=n)return 0;let o=[...i].sort((m,g)=>g.version-m.version),a=o.slice(0,n),l=o.length-a.length;return this.versions.set(s,a),l}async deleteAllVersions(e,r){let n=this.getKey(e,r),i=(this.versions.get(n)||[]).length;return this.versions.delete(n),i}getAllVersions(){let e=[];for(let r of this.versions.values())e.push(...r);return e}clear(){this.versions.clear();}},h=n(a.versioningStorage,()=>new d);function P(t){h.set(t);}function S(){return h.getRequired()}var y=class{config;storage;tableName;constructor(e,r,n,s){this.config=b(e,r),this.tableName=r,this.storage=h.resolve(s,n);}getStorage(){if(!this.storage)throw new Error("Versioning storage not configured. Pass storage explicitly or inject versioningStorage with createCrudMiddleware().");return this.storage}isEnabled(){return this.config.enabled}getVersionField(){return this.config.field}getHistoryTable(){return this.config.historyTable}async saveVersion(e,r,n,s,i){if(!this.isEnabled())return r[this.config.field]||1;let o=r[this.config.field]||0,a=o+1,l;n&&(l=b$1(n,r,this.config.excludeFields));let m=this.filterFields(r),g={id:crypto.randomUUID(),recordId:e,version:o,data:m,createdAt:new Date,changes:l};this.config.trackChangedBy&&s&&(g.changedBy=s),i&&(g.changeReason=i);let u=this.getStorage();return "store"in u&&typeof u.store=="function"?await u.store(this.tableName,g):await u.save(g),this.config.maxVersions&&u.pruneVersions&&await u.pruneVersions(this.tableName,e,this.config.maxVersions),a}async getVersions(e,r){return this.getStorage().getByRecordId(this.tableName,e,r)}async getVersion(e,r){return this.getStorage().getVersion(this.tableName,e,r)}async getVersionData(e,r){let n=await this.getVersion(e,r);return n?n.data:null}async getLatestVersion(e){return this.getStorage().getLatestVersion(this.tableName,e)}async compareVersions(e,r,n){let[s,i]=await Promise.all([this.getVersion(e,r),this.getVersion(e,n)]);return !s||!i?[]:b$1(s.data,i.data,this.config.excludeFields)}async deleteAllVersions(e){let r=this.getStorage();return r.deleteAllVersions?r.deleteAllVersions(this.tableName,e):0}filterFields(e){if(this.config.excludeFields.length===0)return e;let r={};for(let[n,s]of Object.entries(e))this.config.excludeFields.includes(n)||(r[n]=s);return r}};function w(t,e,r,n){return new y(t,e,r,n)}export{b as a,d as b,h as c,P as d,S as e,y as f,w as g};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e={userId:"userId",user:"user",roles:"roles",permissions:"permissions",authType:"authType",jwtPayload:"jwtPayload",organizationId:"organizationId",agentId:"agentId",agentRunId:"agentRunId",onBehalfOfUserId:"onBehalfOfUserId",toolCallId:"toolCallId",actionSource:"actionSource",tenantId:"tenantId",requestId:"requestId",requestStartTime:"requestStartTime",apiVersion:"apiVersion",apiVersionConfig:"apiVersionConfig",auditStorage:"auditStorage",versioningStorage:"versioningStorage",loggingStorage:"loggingStorage",apiKeyStorage:"apiKeyStorage",eventEmitter:"eventEmitter"};export{e as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {c}from'./chunk-HIDT3P5C.js';import {b as b$3}from'./chunk-UAVAEDVS.js';import {h,e as e$1}from'./chunk-4NKDESHS.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {m,a as a$1,b}from'./chunk-ZJWDAVGG.js';import {e,a as a$2,b as b$1}from'./chunk-VJRDAVID.js';import {a}from'./chunk-IJBJE4G2.js';function H(e){return e instanceof Error?e:new Error(String(e))}function Se(e,t){let n=H(e),r=new Error(`${t}: ${n.message}`);return r.cause=n,r}function Re(e){return e instanceof Error?e.message:String(e)}function v(e,t){let n=e.toLowerCase();for(let r of t){if(r instanceof RegExp){if(r.test(e))return true;continue}let s=r.toLowerCase();if(s.includes("*")){let h=s.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${h}$`).test(n))return true}else if(n===s)return true}return false}function w(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(r=>w(r,t));if(typeof e!="object")return e;let n={};for(let[r,s]of Object.entries(e))v(r,t)?n[r]="[REDACTED]":typeof s=="object"&&s!==null?n[r]=w(s,t):n[r]=s;return n}function W(e,t){let n={};for(let[r,s]of Object.entries(e))n[r]=v(r,t)?"[REDACTED]":s;return n}function Ie(e,t){return v(e,t)}function D(e,t){return w(e,t)}function F(e,t){return W(e,t)}function Te(e,t){return h(e,t)}function Z(e,t,n){for(let r of n)if(h(e,r))return true;if(t.length===0)return false;for(let r of t)if(h(e,r))return false;return true}function ee(e,t="X-Forwarded-For",n=false){return a$1(e,{ipHeader:t,trustProxy:n||true})}function _(e){let t={};return e.forEach((n,r)=>{t[r.toLowerCase()]=n;}),t}function te(e){let t={};return new URL(e.req.url).searchParams.forEach((r,s)=>{t[s]=r;}),t}function y(e,t){if(typeof e=="string")return e.length>t?e.substring(0,t)+"... [TRUNCATED]":e;let n=JSON.stringify(e);return n.length>t?{_truncated:true,_originalSize:n.length,_maxSize:t}:e}function re(e,t){if(!e)return false;if(t.length===0)return true;let n=e.toLowerCase();for(let r of t)if(n.includes(r.toLowerCase()))return true;return false}function ne(e){return b(e)}function oe(){return e()}var C=m(a.loggingStorage);function Oe(e){C.set(e);}function ze(){return C.get()}var Ee=["authorization","cookie","x-api-key","x-auth-token"],ye=["password","token","secret","apiKey","api_key","accessToken","access_token","refreshToken","refresh_token","creditCard","credit_card","ssn","socialSecurityNumber"],he=["/health","/healthz","/ready","/readyz","/live","/livez","/metrics","/favicon.ico"];function Be(e){return a$2(e,a.requestId)}function Ue(e){return a$2(e,a.requestStartTime)}function Ve(e={}){let t=e.enabled??true,n=e.level??"info",r=e.includePaths??[],s=e.excludePaths??he,h=e.redactHeaders??Ee,K=e.redactBodyFields??ye,x=e.requestBody??{enabled:false},S=e.responseBody??{enabled:false},O=e.includeHeaders??true,ae=e.includeQuery??true,ie=e.includeClientIp??true,de=e.ipHeader??"X-Forwarded-For",ue=e.trustProxy??false,ge=e.minResponseTimeMs??0,ce=e.generateRequestId??oe;return async(o,L)=>{if(!t)return L();let z=o.req.path;if(Z(z,r,s))return L();let P=ce(),q=Date.now();b$1(o,a.requestId,P),b$1(o,a.requestStartTime,q),o.header("X-Request-ID",P);let le=o.req.method,fe=o.req.url,B;if(O){let u=_(o.req.raw.headers);B=F(u,h);}let U;ae&&(U=te(o));let V;ie&&(V=ee(o,de,ue));let pe=ne(o),I;if(x.enabled){let u=o.req.header("content-type"),m=x.contentTypes??[];if(re(u,m))try{let f=await o.req.raw.clone().text();if(f)try{let d=JSON.parse(f);d=D(d,K);let i=x.maxSize??10240;I=y(d,i);}catch{let d=x.maxSize??10240;I=y(f,d);}}catch{}}let g,T;try{await L();}catch(u){throw g=u instanceof Error?u:new Error(String(u)),u}finally{let m=Date.now()-q;if(m<ge)return;let l=o.res.status,f;if(O){let a=_(o.res.headers);f=F(a,h);}if(S.enabled&&!g){let a=S.statusCodes??[];if(a.length===0||a.includes(l))try{let k=await o.res.clone().text();if(k)try{let E=JSON.parse(k);E=D(E,K);let me=S.maxSize??10240;T=y(E,me);}catch{let E=S.maxSize??10240;T=y(k,E);}}catch{}}let d=n;e.levelResolver?d=e.levelResolver(o,m,l,g):g||l>=500?d="error":l>=400&&(d="warn");let i={id:P,timestamp:new Date(q).toISOString(),level:d,request:{method:le,path:z,url:fe,headers:B,query:U,body:I,clientIp:V,userId:pe},response:{statusCode:l,headers:f,body:T,responseTimeMs:m}};if(g&&(i.error={message:g.message,name:g.name,stack:g.stack}),e.metadata){let a=typeof e.metadata=="function"?e.metadata(o):e.metadata;i.metadata=a;}e.formatter&&(i=e.formatter(i));let M=se(o,e.storage);(async()=>{if(M)try{await M.store(i);}catch(a){e.onError&&e.onError(a instanceof Error?a:new Error(String(a)),i);}if(e.handlers)for(let a of e.handlers)try{await a(i);}catch(c){e.onError&&e.onError(c instanceof Error?c:new Error(String(c)),i);}})().catch(a=>{let c=H(a);e.onError?e.onError(c,i):b$2().error("Failed to process log entry",{error:c.message});});}}}function se(e,t){return C.resolve(e,t)}function Je(e,t){return b$3.resolve(e,t)}function je(e,t){return c.resolve(e,t)}function Ge(e,t){return e$1.resolve(e,t)}export{se as a,Je as b,je as c,Ge as d,H as e,Se as f,Re as g,Ie as h,D as i,F as j,Te as k,Z as l,ee as m,_ as n,te as o,y as p,re as q,ne as r,oe as s,Oe as t,ze as u,Be as v,Ue as w,Ve as x};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-BPBFNTBM.js';function l(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,allowNestedCreate:e.allowNestedCreate})}function r(e,d){let a$1=e.defaultSort??(e.defaultOrderBy?{field:e.defaultOrderBy,order:e.defaultOrderDirection??"asc"}:void 0);return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,after:e.after,transform:e.transform,filterFields:e.filterFields,filterConfig:e.filterConfig,searchFields:e.searchFields,searchFieldName:e.searchFieldName,sortFields:e.sortFields??e.orderByFields,defaultSort:a$1,defaultPerPage:e.defaultPerPage,maxPerPage:e.maxPerPage,allowedIncludes:e.allowedIncludes,fieldSelectionEnabled:e.fieldSelectionEnabled,allowedSelectFields:e.allowedSelectFields,blockedSelectFields:e.blockedSelectFields,alwaysIncludeFields:e.alwaysIncludeFields,defaultSelectFields:e.defaultSelectFields})}function o(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,after:e.after,transform:e.transform,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedIncludes:e.allowedIncludes,fieldSelectionEnabled:e.fieldSelectionEnabled,allowedSelectFields:e.allowedSelectFields,blockedSelectFields:e.blockedSelectFields,alwaysIncludeFields:e.alwaysIncludeFields,defaultSelectFields:e.defaultSelectFields})}function s(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,transform:e.transform,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedUpdateFields:e.allowedUpdateFields,blockedUpdateFields:e.blockedUpdateFields,allowNestedWrites:e.allowNestedWrites})}function i(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,lookupField:e.lookupField,additionalFilters:e.additionalFilters,includeCascadeResults:e.includeCascadeResults})}export{l as a,r as b,o as c,s as d,i as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$2,b as b$1}from'./chunk-EX4S3Q4M.js';import {n}from'./chunk-ZJWDAVGG.js';import {a as a$1}from'./chunk-IJBJE4G2.js';var a=class{logs=[];async store(t){this.logs.push(t);}async getByRecordId(t,e,r){let n=this.logs.filter(s=>s.tableName===t&&s.recordId===e),i=r?.offset||0,o=r?.limit||n.length;return n.slice(i,i+o)}async getAll(t){let e=[...this.logs];t?.tableName&&(e=e.filter(i=>i.tableName===t.tableName)),t?.action&&(e=e.filter(i=>i.action===t.action)),t?.userId&&(e=e.filter(i=>i.userId===t.userId)),t?.startDate&&(e=e.filter(i=>i.timestamp>=t.startDate)),t?.endDate&&(e=e.filter(i=>i.timestamp<=t.endDate));let r=t?.offset||0,n=t?.limit||e.length;return e.slice(r,r+n)}getAllLogs(){return [...this.logs]}clear(){this.logs=[];}},l=n(a$1.auditStorage,()=>new a);function b(d){l.set(d);}function w(){return l.getRequired()}var u=class{config;storage;constructor(t,e,r){this.config=a$2(t),this.storage=l.resolve(r,e);}getStorage(){if(!this.storage)throw new Error("Audit storage not configured. Pass storage explicitly or inject auditStorage with createCrudMiddleware().");return this.storage}isEnabled(t){return this.config.enabled&&this.config.actions.includes(t)}async logCreate(t,e,r,n,i){if(!this.isEnabled("create"))return;let o=this.createEntry("create",t,e,n,i);this.config.storeRecord&&(o.record=this.filterFields(r)),await this.getStorage().store(o);}async logUpdate(t,e,r,n,i,o){if(!this.isEnabled("update"))return;let s=this.createEntry("update",t,e,i,o);this.config.storeRecord&&(s.record=this.filterFields(n)),this.config.storePreviousRecord&&(s.previousRecord=this.filterFields(r)),this.config.trackChanges&&(s.changes=b$1(r,n,this.config.excludeFields)),await this.getStorage().store(s);}async logDelete(t,e,r,n,i){if(!this.isEnabled("delete"))return;let o=this.createEntry("delete",t,e,n,i);this.config.storePreviousRecord&&(o.previousRecord=this.filterFields(r)),await this.getStorage().store(o);}async logRestore(t,e,r,n,i){if(!this.isEnabled("restore"))return;let o=this.createEntry("restore",t,e,n,i);this.config.storeRecord&&(o.record=this.filterFields(r)),await this.getStorage().store(o);}async logUpsert(t,e,r,n,i,o,s){if(!this.isEnabled("upsert"))return;let g=this.createEntry("upsert",t,e,o,{...s,created:i});this.config.storeRecord&&(g.record=this.filterFields(r)),this.config.storePreviousRecord&&n&&(g.previousRecord=this.filterFields(n)),this.config.trackChanges&&n&&(g.changes=b$1(n,r,this.config.excludeFields)),await this.getStorage().store(g);}async logBatch(t,e,r,n,i){if(this.isEnabled(t))for(let o of r){let s=this.createEntry(t,e,o.recordId,n,i);this.config.storeRecord&&o.record&&(s.record=this.filterFields(o.record)),this.config.storePreviousRecord&&o.previousRecord&&(s.previousRecord=this.filterFields(o.previousRecord)),this.config.trackChanges&&o.previousRecord&&o.record&&(s.changes=b$1(o.previousRecord,o.record,this.config.excludeFields)),await this.getStorage().store(s);}}createEntry(t,e,r,n,i){return {id:crypto.randomUUID(),timestamp:new Date,action:t,tableName:e,recordId:r,userId:n,metadata:i}}filterFields(t){if(this.config.excludeFields.length===0)return t;let e={};for(let[r,n]of Object.entries(t))this.config.excludeFields.includes(r)||(e[r]=n);return e}};function v(d,t,e){return new u(d,t,e)}export{a,l as b,b as c,w as d,u as e,v as f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-VJRDAVID.js';import {a as a$1}from'./chunk-IJBJE4G2.js';function E(e,t={}){let{ipHeader:r="X-Forwarded-For",trustProxy:n=true}=t;if(n){let a=e.req.header(r);if(a){let g=a.split(",")[0]?.trim();if(g)return g}let f=e.req.header("X-Real-IP")?.trim();if(f)return f;let d=e.req.header("CF-Connecting-IP")?.trim();if(d)return d}let s=e.req.raw;if(s&&typeof s.socket=="object"&&s.socket?.remoteAddress)return s.socket.remoteAddress;if(s?.cf?.ip)return s.cf.ip}function x(e){return a(e,"userId")}function b(e){return a(e,a$1.user)}function u(e){return a(e,a$1.roles)}function c(e){return a(e,a$1.permissions)}function S(e){return a(e,a$1.authType)}function I(e,t){return u(e)?.includes(t)??false}function R(e,t){return c(e)?.includes(t)??false}function w(e,t){let r=u(e);return r?t.every(n=>r.includes(n)):false}function q(e,t){let r=u(e);return r?t.some(n=>r.includes(n)):false}function k(e,t){let r=c(e);return r?t.every(n=>r.includes(n)):false}var l=class{globalStorage=null;contextKey;defaultFactory;defaultInitialized=false;constructor(t,r){this.contextKey=t,this.defaultFactory=r??null;}ensureDefault(){!this.defaultInitialized&&this.defaultFactory&&this.globalStorage===null&&(this.globalStorage=this.defaultFactory(),this.defaultInitialized=true);}set(t){this.globalStorage=t;}get(){return this.ensureDefault(),this.globalStorage}getConfigured(){return this.globalStorage}getRequired(){if(this.ensureDefault(),this.globalStorage===null)throw new Error(`Storage not configured for '${this.contextKey}'`);return this.globalStorage}resolve(t,r){if(r)return r;if(t){let n=a(t,this.contextKey);if(n)return n}return this.globalStorage}resolveRequired(t,r){let n=this.resolve(t,r);if(n===null)throw new Error(`Storage not configured for '${this.contextKey}'`);return n}reset(){this.defaultInitialized=false,this.globalStorage=null;}getContextKey(){return this.contextKey}isConfigured(){return this.globalStorage!==null}};function U(e){return new l(e)}function V(e,t){return new l(e,t)}export{E as a,x as b,b as c,u as d,c as e,S as f,I as g,R as h,w as i,q as j,k,l,U as m,V as n};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import 'hono';
|
|
2
|
+
import 'zod';
|
|
3
|
+
export { A as AdapterBundle, a as AggregateEndpointConfig, B as BatchCreateEndpointConfig, b as BatchDeleteEndpointConfig, c as BatchRestoreEndpointConfig, d as BatchUpdateEndpointConfig, e as BatchUpsertEndpointConfig, f as CloneEndpointConfig, g as CreateEndpointConfig, D as DeleteEndpointConfig, m as EndpointsConfig, E as ExportEndpointConfig, G as GeneratedEndpoints, I as ImportEndpointConfig, L as ListEndpointConfig, R as ReadEndpointConfig, h as RestoreEndpointConfig, S as SearchEndpointConfig, U as UpdateEndpointConfig, i as UpsertEndpointConfig, p as defineEndpoints } from '../index-Biz6ZLmk.js';
|
|
4
|
+
import '../route-cu4t0BCp.js';
|
|
5
|
+
import '../types-CR_0ycjq.js';
|
|
6
|
+
import '../types-BK-mxapm.js';
|
|
7
|
+
import '@hono/zod-openapi';
|
|
8
|
+
import 'hono/utils/http-status';
|
|
9
|
+
import '../types-DcRAcexC.js';
|
|
10
|
+
import '../types-BAcN7U0B.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as defineEndpoints}from'../chunk-65NCGRBB.js';import'../chunk-BPBFNTBM.js';
|