hono-crud 0.13.4 → 0.13.5
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 +6 -0
- package/dist/api-version/index.js +1 -1
- package/dist/audit/index.d.ts +2 -2
- package/dist/audit/index.js +1 -1
- package/dist/auth/index.d.ts +3 -3
- package/dist/auth/index.js +1 -1
- package/dist/{chunk-KKLMXJY4.js → chunk-3AZC7JY2.js} +1 -1
- package/dist/{chunk-VTIGDVUR.js → chunk-4RRFBZNM.js} +1 -1
- package/dist/{chunk-FC56WWPB.js → chunk-5FV7DBVK.js} +1 -1
- package/dist/{chunk-CTU6AAXM.js → chunk-6FJGKK2V.js} +1 -1
- package/dist/chunk-AQ7KOBMY.js +11 -0
- package/dist/chunk-DFQF3UK7.js +1 -0
- package/dist/chunk-DZ24U5LK.js +1 -0
- package/dist/chunk-IIMTJZBX.js +1 -0
- package/dist/chunk-OKY6VLJS.js +1 -0
- package/dist/chunk-YU6P3NGZ.js +1 -0
- package/dist/{index-_ymQzFJo.d.ts → index-Cw32yI8b.d.ts} +9 -3
- package/dist/index.d.ts +117 -128
- package/dist/index.js +1 -1
- package/dist/internal.d.ts +27 -6
- package/dist/internal.js +1 -1
- package/dist/logging/index.js +1 -1
- package/dist/serialization/index.d.ts +1 -1
- package/dist/storage/index.d.ts +4 -4
- package/dist/storage/index.js +1 -1
- package/dist/{types-DcRAcexC.d.ts → types-B5wq2iKZ.d.ts} +1 -1
- package/dist/{types-38Hj6wN4.d.ts → types-TTTI3ADY.d.ts} +1 -1
- package/dist/versioning/index.d.ts +2 -2
- package/dist/versioning/index.js +1 -1
- package/package.json +3 -2
- package/dist/chunk-25YGWSRQ.js +0 -11
- package/dist/chunk-3UHAENW7.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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.13.5
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
|
|
3
9
|
## 0.13.4
|
|
4
10
|
|
|
5
11
|
### 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-3AZC7JY2.js';import'../chunk-5FV7DBVK.js';
|
package/dist/audit/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Context, Env } from 'hono';
|
|
2
|
-
import { A as AuditConfig, a as AuditLogEntry, b as AuditAction } from '../types-
|
|
2
|
+
import { A as AuditConfig, a as AuditLogEntry, b as AuditAction } from '../types-TTTI3ADY.js';
|
|
3
3
|
import { S as StorageRegistry } from '../registry-PNJjvSvm.js';
|
|
4
4
|
import 'zod';
|
|
5
|
-
import '../types-
|
|
5
|
+
import '../types-B5wq2iKZ.js';
|
|
6
6
|
import '../types-BAcN7U0B.js';
|
|
7
7
|
import '@hono/zod-openapi';
|
|
8
8
|
|
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-6FJGKK2V.js';import'../chunk-YU6P3NGZ.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { e as APIKeyConfig, f as APIKeyEntry, g as APIKeyLookupResult, h as ActionSource, p as ApprovalConfig, q as ApprovalStorage, r as AuthConfig, s as AuthEnv, t as AuthType, u as AuthUser, v as AuthorizationCheck, E as EndpointAuthConfig, I as Guard, T as JWTAlgorithm, U as JWTClaims, W as JWTClaimsSchema, X as JWTConfig, ae as OwnershipExtractor, aY as PathPattern, ah as PendingAction, ai as PendingActionStatus, aE as ValidatedJWTClaims, aV as parseJWTClaims, aX as safeParseJWTClaims } from '../types-
|
|
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 { e as APIKeyConfig, f as APIKeyEntry, g as APIKeyLookupResult, h as ActionSource, p as ApprovalConfig, q as ApprovalStorage, r as AuthConfig, s as AuthEnv, t as AuthType, u as AuthUser, v as AuthorizationCheck, E as EndpointAuthConfig, I as Guard, T as JWTAlgorithm, U as JWTClaims, W as JWTClaimsSchema, X as JWTConfig, ae as OwnershipExtractor, aY as PathPattern, ah as PendingAction, ai as PendingActionStatus, aE as ValidatedJWTClaims, aV as parseJWTClaims, aX as safeParseJWTClaims } from '../types-TTTI3ADY.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, q as isValidAPIKeyFormat, r as optionalAuth, s as parseIso8601Duration, t as requireAllRoles, u as requireAnyPermission, v as requireApproval, w as requireAuth, x as requireAuthenticated, y as requireAuthentication, z as requireOwnership, B as requireOwnershipOrRole, C as requirePermissions, D as requirePolicy, E as requireRoles, F as setAPIKeyStorage, G as validateAPIKey, H as validateAPIKeyEntry, I as validateJWTClaims, K as verifyJWT, L as withAuth } from '../index-Cw32yI8b.js';
|
|
3
3
|
import 'hono';
|
|
4
4
|
import 'zod';
|
|
5
|
-
import '../types-
|
|
5
|
+
import '../types-B5wq2iKZ.js';
|
|
6
6
|
import '../types-BAcN7U0B.js';
|
|
7
7
|
import '@hono/zod-openapi';
|
|
8
8
|
import 'hono/utils/http-status';
|
package/dist/auth/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{J as AuthenticatedEndpoint,u as JWTClaimsSchema,d as MemoryApprovalStorage,f as POLICIES_CONTEXT_KEY,n as allOf,q as allowAll,o as anyOf,E as createAPIKeyMiddleware,G as createAuthMiddleware,z as createJWTMiddleware,B as decodeJWT,D as defaultHashAPIKey,p as denyAll,H as optionalAuth,e as parseIso8601Duration,v as parseJWTClaims,h as requireAllRoles,j as requireAnyPermission,t as requireApproval,k as requireAuth,r as requireAuthenticated,I as requireAuthentication,l as requireOwnership,m as requireOwnershipOrRole,i as requirePermissions,s as requirePolicy,g as requireRoles,w as safeParseJWTClaims,F as validateAPIKey,C as validateAPIKeyEntry,x as validateJWTClaims,A as verifyJWT,K as withAuth}from'../chunk-DFQF3UK7.js';import'../chunk-5FV7DBVK.js';export{a as MemoryAPIKeyStorage,b as generateAPIKey,f as getAPIKeyStorage,c as hashAPIKey,d as isValidAPIKeyFormat,g as setAPIKeyStorage}from'../chunk-IIMTJZBX.js';import'../chunk-YU6P3NGZ.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-5FV7DBVK.js';function l(e,i){return e.req.header(i)??void 0}function w(e,i){return e.req.query(i)??void 0}function h(e,i){let t=e.req.path,s=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\{version\\}","([^/]+)"),a=new RegExp(`^${s}`);return t.match(a)?.[1]}function C(e){let{versions:i,strategy:t="header",headerName:d="Accept-Version",queryParam:s="version",urlPattern:a$1="/v{version}",extractVersion:p,addHeaders:u=true}=e,c=e.defaultVersion??i[0]?.version,g=new Map;for(let n of i)g.set(n.version,n);return async(n,V)=>{let r;if(p)r=p(n);else switch(t){case "header":r=l(n,d);break;case "query":r=w(n,s);break;case "url":r=h(n,a$1);break}if(r=r??c,!r)throw new a("API version is required",400,"VERSION_REQUIRED");let o=g.get(r);if(!o)throw new a(`Unsupported API version: ${r}`,400,"UNSUPPORTED_VERSION");if(n.set("apiVersion",r),n.set("apiVersionConfig",o),u&&(n.header("X-API-Version",r),o.deprecated&&n.header("Deprecation",o.deprecated),o.sunset&&n.header("Sunset",o.sunset)),o.middleware&&o.middleware.length>0)for(let m of o.middleware)await m(n,async()=>{});await V();}}function y(e){return e.get("apiVersion")}function v(e){return e.get("apiVersionConfig")}function A(){return async(e,i)=>{await i();let t=e.get("apiVersionConfig");if(!(!t?.responseTransformer||!e.res.headers.get("content-type")?.includes("application/json")))try{let s=await e.res.json(),a=t.responseTransformer(s);e.res=new Response(JSON.stringify(a),{status:e.res.status,headers:e.res.headers});}catch{}}}export{C as a,y as b,v as c,A as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {u,g,f}from'./chunk-
|
|
1
|
+
import {u,g,f}from'./chunk-YU6P3NGZ.js';var d=class{versions=new Map;getKey(e,n){return `${e}:${n}`}async save(e){let n=this.getKey(e.tableName||e.id.split(":")[0]||"unknown",e.recordId),r={...e,tableName:n.split(":")[0]},t=this.versions.get(n)||[];t.push(r),this.versions.set(n,t);}async store(e,n){let r=this.getKey(e,n.recordId),t=this.versions.get(r)||[];t.push({...n,tableName:e}),this.versions.set(r,t);}async getByRecordId(e,n,r){let t=this.getKey(e,n),i=[...this.versions.get(t)||[]].sort((c,o)=>o.version-c.version),g=r?.offset||0,a=r?.limit||i.length;return i.slice(g,g+a)}async getVersion(e,n,r){let t=this.getKey(e,n);return (this.versions.get(t)||[]).find(i=>i.version===r)||null}async getLatestVersion(e,n){let r=this.getKey(e,n),t=this.versions.get(r)||[];return t.length===0?0:Math.max(...t.map(s=>s.version))}async pruneVersions(e,n,r){let t=this.getKey(e,n),s=this.versions.get(t)||[];if(s.length<=r)return 0;let i=[...s].sort((c,o)=>o.version-c.version),g=i.slice(0,r),a=i.length-g.length;return this.versions.set(t,g),a}async deleteAllVersions(e,n){let r=this.getKey(e,n),s=(this.versions.get(r)||[]).length;return this.versions.delete(r),s}getAllVersions(){let e=[];for(let n of this.versions.values())e.push(...n);return e}clear(){this.versions.clear();}},h=u("versioningStorage",()=>new d);function p(u){h.set(u);}function E(){return h.getRequired()}var y=class{config;storage;tableName;constructor(e,n,r,t){this.config=g(e,n),this.tableName=n,this.storage=h.resolve(t,r);}getStorage(){if(!this.storage)throw new Error("Versioning storage not configured. Pass storage explicitly or inject versioningStorage with createCrudMiddleware().");return this.storage}isEnabled(){return this.config.enabled}getVersionField(){return this.config.field}getHistoryTable(){return this.config.historyTable}async saveVersion(e,n,r,t,s){if(!this.isEnabled())return n[this.config.field]||1;let i=n[this.config.field]||0,g=i+1,a;r&&(a=f(r,n,this.config.excludeFields));let c=this.filterFields(n),o={id:crypto.randomUUID(),recordId:e,version:i,data:c,createdAt:new Date,changes:a};this.config.trackChangedBy&&t&&(o.changedBy=t),s&&(o.changeReason=s);let l=this.getStorage();return "store"in l&&typeof l.store=="function"?await l.store(this.tableName,o):await l.save(o),this.config.maxVersions&&l.pruneVersions&&await l.pruneVersions(this.tableName,e,this.config.maxVersions),g}async getVersions(e,n){return this.getStorage().getByRecordId(this.tableName,e,n)}async getVersion(e,n){return this.getStorage().getVersion(this.tableName,e,n)}async getVersionData(e,n){let r=await this.getVersion(e,n);return r?r.data:null}async getLatestVersion(e){return this.getStorage().getLatestVersion(this.tableName,e)}async compareVersions(e,n,r){let[t,s]=await Promise.all([this.getVersion(e,n),this.getVersion(e,r)]);return !t||!s?[]:f(t.data,s.data,this.config.excludeFields)}async deleteAllVersions(e){let n=this.getStorage();return n.deleteAllVersions?n.deleteAllVersions(this.tableName,e):0}filterFields(e){if(this.config.excludeFields.length===0)return e;let n={};for(let[r,t]of Object.entries(e))this.config.excludeFields.includes(r)||(n[r]=t);return n}};function P(u,e,n,r){return new y(u,e,n,r)}export{d as a,h as b,p as c,E as d,y as e,P as f};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {u as u$1,e,f}from'./chunk-
|
|
1
|
+
import {u as u$1,e,f}from'./chunk-YU6P3NGZ.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=u$1("auditStorage",()=>new a);function A(d){l.set(d);}function R(){return l.getRequired()}var u=class{config;storage;constructor(t,e$1,r){this.config=e(t),this.storage=l.resolve(r,e$1);}getStorage(){if(!this.storage)throw new Error("Audit storage not configured. Pass storage explicitly or inject auditStorage with createCrudMiddleware().");return this.storage}isEnabled(t){return this.config.enabled&&this.config.actions.includes(t)}async logCreate(t,e,r,n,i){if(!this.isEnabled("create"))return;let o=this.createEntry("create",t,e,n,i);this.config.storeRecord&&(o.record=this.filterFields(r)),await this.getStorage().store(o);}async logUpdate(t,e,r,n,i,o){if(!this.isEnabled("update"))return;let s=this.createEntry("update",t,e,i,o);this.config.storeRecord&&(s.record=this.filterFields(n)),this.config.storePreviousRecord&&(s.previousRecord=this.filterFields(r)),this.config.trackChanges&&(s.changes=f(r,n,this.config.excludeFields)),await this.getStorage().store(s);}async logDelete(t,e,r,n,i){if(!this.isEnabled("delete"))return;let o=this.createEntry("delete",t,e,n,i);this.config.storePreviousRecord&&(o.previousRecord=this.filterFields(r)),await this.getStorage().store(o);}async logRestore(t,e,r,n,i){if(!this.isEnabled("restore"))return;let o=this.createEntry("restore",t,e,n,i);this.config.storeRecord&&(o.record=this.filterFields(r)),await this.getStorage().store(o);}async logUpsert(t,e,r,n,i,o,s){if(!this.isEnabled("upsert"))return;let g=this.createEntry("upsert",t,e,o,{...s,created:i});this.config.storeRecord&&(g.record=this.filterFields(r)),this.config.storePreviousRecord&&n&&(g.previousRecord=this.filterFields(n)),this.config.trackChanges&&n&&(g.changes=f(n,r,this.config.excludeFields)),await this.getStorage().store(g);}async logBatch(t,e,r,n,i){if(this.isEnabled(t))for(let o of r){let s=this.createEntry(t,e,o.recordId,n,i);this.config.storeRecord&&o.record&&(s.record=this.filterFields(o.record)),this.config.storePreviousRecord&&o.previousRecord&&(s.previousRecord=this.filterFields(o.previousRecord)),this.config.trackChanges&&o.previousRecord&&o.record&&(s.changes=f(o.previousRecord,o.record,this.config.excludeFields)),await this.getStorage().store(s);}}createEntry(t,e,r,n,i){return {id:crypto.randomUUID(),timestamp:new Date,action:t,tableName:e,recordId:r,userId:n,metadata:i}}filterFields(t){if(this.config.excludeFields.length===0)return t;let e={};for(let[r,n]of Object.entries(t))this.config.excludeFields.includes(r)||(e[r]=n);return e}};function b(d,t,e){return new u(d,t,e)}export{a,l as b,A as c,R as d,u as e,b as f};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import {a as a$3,b as b$3}from'./chunk-PDHKGPGZ.js';import {a as a$1,c,b as b$2,f as f$2}from'./chunk-DFQF3UK7.js';import {a,b,i,d,c as c$2}from'./chunk-5FV7DBVK.js';import {d as d$3,e as e$1}from'./chunk-DZ3EM3AE.js';import {d as d$2}from'./chunk-YM6W23MT.js';import {w}from'./chunk-OKY6VLJS.js';import {f as f$1}from'./chunk-4RRFBZNM.js';import {f}from'./chunk-6FJGKK2V.js';import {q,c as c$1,j as j$1,d as d$1,k,i as i$1,r,e,g,n,o,p}from'./chunk-YU6P3NGZ.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {a as a$2,b as b$4}from'./chunk-VJRDAVID.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 Ut=new WeakMap;function tt(n){return Ut.get(n)}var Ee=class{app;options;routes=new Map;constructor(e,o={}){this.app=e,this.options={docs_url:"/docs",redoc_url:"/redoc",openapi_url:"/openapi.json",...o};}registerRoute(e,o,t,r=[]){let s=`${e.toUpperCase()} ${o}`,i=t,c=new i().getSchema();this.routes.set(s,{method:e,path:o,schema:c,routeClass:t});let u=createRoute({method:e,path:this.convertPath(o),...c,responses:c.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(r.length>0)for(let a of r)this.app.use(o,async(d,l)=>{if(d.req.method.toLowerCase()===e)return a(d,l);await l();});this.app.openapi(u,async a$2=>{let d=new i;d.setContext(a$2);try{return await d.handle()}catch(l){if(l instanceof a){let m=l.toJSON(),h=a$2?.var?.[q];return h?a$1(a$2,h.error(m.error),l.status):a$1(a$2,m,l.status)}throw l}});}convertPath(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}setupDocs(e,o){let t=e??this.options.openapi_url??"/openapi.json";this.app.doc(t,{openapi:o.openapi||"3.1.0",info:o.info,servers:o.servers,security:o.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return this.convertPath(e)}};function ro(n=new OpenAPIHono,e={}){let o="openAPIRegistry"in n?n:new OpenAPIHono,t=new Ee(o,e),r=["get","post","put","patch","delete","options","head"],s=new Proxy(o,{get(i,p){if(r.includes(p))return (u,...a)=>{let d=a[a.length-1];if(c(d)){let l=a.slice(0,-1);return t.registerRoute(p,u,d,l),s}return i[p](u,...a)};if(p==="doc")return (u,a)=>{t.setupDocs(u,a);};if(p==="use")return (...u)=>(i[p](...u),s);let c$1=i[p];return typeof c$1=="function"?c$1.bind(i):c$1}});return Ut.set(s,t),s}var lo=6e4,co={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function po(n,e,o={}){let t=tt(n);if(!t)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let r=o.config??co,s=`openapi:${e.tenantId??"global"}:${r.info.version}`;if(o.cache){let u=await o.cache.get(s);if(u!=null)return u}let i=new OpenAPIHono;for(let u of t.getRegisteredRoutes().values()){let a=u.routeClass,d=new a,l=uo(e);d.setContext(l),typeof d.resolveModelSchema=="function"&&await d.resolveModelSchema();let m=d.getSchema(),h=createRoute({...m,method:u.method,path:t.toOpenApiPath(u.path),responses:m.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});i.openapi(h,()=>new Response);}let p={openapi:r.openapi??"3.1.0",info:r.info,servers:r.servers,security:r.security},c=o.spec==="3.0"?i.getOpenAPIDocument(p):i.getOpenAPI31Document(p);return o.cache&&await o.cache.set(s,c,o.cacheTtlMs??lo),c}function uo(n){let e={};n.tenantId!==void 0&&(e.tenantId=n.tenantId),n.organizationId!==void 0&&(e.organizationId=n.organizationId);let o=n.request??new Request("http://localhost/");return {var:e,env:n.env,req:{raw:o,header:()=>{},query:()=>{},param:()=>{}},set(t,r){e[t]=r;},get(t){return e[t]},executionCtx:void 0}}function mo(n){return {async get(e){let o=await n.get(e);return o?o.data:void 0},async set(e,o,t){let r=t?Math.ceil(t/1e3):void 0;await n.set(e,o,r?{ttl:r}:void 0);}}}var bo=[["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 wo(n){return n.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function Mo(n,e){let t=`/${n}/${e}`.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function yo(n,e={}){let o=e.basePath??"",t=e.tag,r=new OpenAPIHono,s=0;for(let[c,u,a]of bo){let d=n[c];if(!d)continue;let m=new d().getSchema(),h=t!==void 0?{...m,tags:[t]}:m,g=Mo(o,wo(a)),E=createRoute({...h,method:u,path:g,responses:h.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});r.openapi(E,()=>new Response),s+=1;}return s===0?{}:r.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var Zt=n=>{if(n instanceof ZodError)return b.fromZodError(n)};function xo(n={}){let{mappers:e=[],hooks:o=[],includeRequestId:t=true,includeStackTrace:r=false,defaultErrorCode:s="INTERNAL_ERROR",defaultErrorMessage:i="An internal error occurred",logUnmappedErrors:p=true,onHookError:c,responseEnvelope:u}=n,a$2=[...e,Zt];return async(d,l)=>{let m,h=false;if(d instanceof a)m=d,h=true;else if(d instanceof HTTPException)m=new a(d.message,d.status,"HTTP_ERROR"),h=true;else {for(let b of a$2)try{let w=await b(d,l);if(w){m=w,h=!0;break}}catch{}h||(p&&b$1().error("Unmapped error",{error:d instanceof Error?d.message:String(d)}),m=new a(i,500,s));}for(let b of o)try{let w=b(d,l,m);w instanceof Promise&&w.catch(C=>{c&&c(C,d,l);});}catch(w){c&&c(w,d,l);}let g=m.toJSON();if(t){let b=w(l);b&&(g.error.requestId=b);}r&&d.stack&&(g.error.stack=d.stack);let E=zt(l,u),O=E?E.error(g.error):g;return a$1(l,O,m.status)}}function zt(n,e){return n?.var?.[q]??e}var ot="createdAt",nt="updatedAt";function ce(n){return n?n===true?{enabled:true,createdAt:ot,updatedAt:nt}:{enabled:true,createdAt:n.createdAt??ot,updatedAt:n.updatedAt??nt}:{enabled:false,createdAt:ot,updatedAt:nt}}function B(n,e={}){let{includePrimaryKeys:o=true}=e,t=new Set;if(o)for(let s of n.primaryKeys)t.add(s);let r=ce(n.timestamps);return r.enabled&&(t.add(r.createdAt),t.add(r.updatedAt)),[...t]}function Oo(n){return n!=null&&n!==""}function rt(n,e,o,t){let r={...n},s=e.primaryKeys[0];if(!Oo(r[s])){let p=e.id;if(typeof p=="function")r[s]=p();else if(p==="database"){if(o==="memory")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)");delete r[s];}else r[s]=t?t():crypto.randomUUID();}let i$1=ce(e.timestamps);if(i$1.enabled){let p=Date.now();i$1.createdAt in n||(r[i$1.createdAt]=p),i$1.updatedAt in n||(r[i$1.updatedAt]=p);}return r}function st(n,e){let o=ce(e.timestamps);return o.enabled?{...n,[o.updatedAt]:Date.now()}:{...n}}function it(n,e){if(e==="memory"&&n.id==="database")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)")}function at(n,e){let o={...n};for(let t of B(e))delete o[t];return o}var So=new Set(["P2002","SQLITE_CONSTRAINT_UNIQUE","SQLITE_CONSTRAINT","23505","ER_DUP_ENTRY",1062,"1062"]),Ro=/UNIQUE constraint failed|duplicate key value violates unique constraint|Duplicate entry/i;function Co(n){if(!n||typeof n!="object")return false;let{code:e,message:o}=n;return (typeof e=="string"||typeof e=="number")&&So.has(e)?true:typeof o=="string"&&Ro.test(o)}function*Lt(n,e=8){for(let o=n,t=0;t<e&&o!=null&&typeof o=="object";t++)yield o,o=o.cause;}function ke(n){for(let e of Lt(n))if(Co(e))return new d("Unique constraint violation");return null}function J(n){throw ke(n)??n}function dt(n){if(n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(dt);let e={};for(let o of Object.keys(n).sort())e[o]=dt(n[o]);return e}async function se(n){let e=JSON.stringify(dt(n)),o=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",o);return `"${Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("").substring(0,32)}"`}function xe(n,e){return n?n==="*"?true:n.split(",").map(o=>o.trim()).includes(e):false}function Oe(n,e){return !n||n==="*"?true:n.split(",").map(o=>o.trim()).includes(e)}var $t="__honoCrudResolvedSchema:";function jo(n){return typeof n.getBodySchema=="function"}var x=class extends b$2{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=f(this._meta.model.audit)),this._auditLogger}getAuditConfig(){return e(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?.var?.userId}getVersionManager(){return this._versionManager||(this._versionManager=f$1(this._meta.model.versioning,this._meta.model.tableName)),this._versionManager}getVersioningConfig(){return g(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?.var?.userId}getSoftDeleteConfig(){return n(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return o(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,o,t){return rt(e,this._meta.model,o,t)}applyManagedUpdateFields(e){return st(e,this._meta.model)}assertIdStrategySupported(e){it(this._meta.model,e);}getTimestampsConfig(){return ce(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return p(this.context,e)}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let o=this.getTenantId();if(!o&&e.required)throw new HTTPException(400,{message:e.errorMessage});return o}injectTenantId(e){let o=this.getMultiTenantConfig();if(!o.enabled)return e;let t=this.getTenantId();return t?{...e,[o.field]:t}:e}async emitEvent(e,o){let t=d$2(this.context??void 0);t&&await t.emit({type:e,table:this._meta.model.tableName,recordId:o.recordId,data:o.data??null,previousData:o.previousData,userId:this.getAuditUserId(),tenantId:this.context?this.getTenantId():void 0,organizationId:this.context?a$2(this.context,"organizationId"):void 0,timestamp:new Date().toISOString(),metadata:o.metadata});}async encryptOnWrite(e){let o=this._meta.model.fieldEncryption;return o?await d$3(e,o.fields,o.keyProvider):e}async decryptOnRead(e){let o=this._meta.model.fieldEncryption;return o?await e$1(e,o.fields,o.keyProvider):e}applyProfile(e){let o=this._meta.model.serializationProfile;return o?a$3(e,o):e}applyProfileToArray(e){let o=this._meta.model.serializationProfile;return o?b$3(e,o):e}getRecordId(e){if(e===null||typeof e!="object")return null;let o=this._meta.model.primaryKeys[0],t=e[o];return typeof t=="string"||typeof t=="number"?t:null}getParentId(e){return this.getRecordId(e)}getPolicies(){if(this.context){let e=a$2(this.context,f$2);if(e)return e}return this._meta.model.policies}buildPolicyContext(){let e=this.context;return {user:e?a$2(e,"user"):void 0,userId:e?a$2(e,"userId"):void 0,tenantId:e?a$2(e,"tenantId"):void 0,organizationId:e?a$2(e,"organizationId"):void 0,request:e?.req?.raw??new Request("http://localhost/")}}async applyReadPolicy(e){let o=this.getPolicies();if(!o)return e;let t=this.buildPolicyContext();if(o.read&&!await o.read(t,e))return null;if(o.fields){let r=o.fields(t,e);return {...e,...r}}return e}async applyReadPolicyToArray(e){if(!this.getPolicies())return e;let t=[];for(let r of e){let s=await this.applyReadPolicy(r);s!==null&&t.push(s);}return t}async applyWritePolicy(e){let o=this.getPolicies();if(!o?.write)return;if(!await o.write(this.buildPolicyContext(),e))throw new HTTPException(403,{message:"Forbidden by policy"})}applyReadPushdown(e){let o=this.getPolicies();if(!o?.readPushdown)return;let t=o.readPushdown(this.buildPolicyContext());t&&t.length>0&&e.filters.push(...t);}buildHookContext(){let e=this.context;return {db:{tx:this._tx},request:e?.req?.raw,tenantId:e?this.getTenantId():void 0,organizationId:e?a$2(e,"organizationId"):void 0,userId:e?a$2(e,"userId"):void 0,agentId:e?a$2(e,"agentId"):void 0,agentRunId:e?a$2(e,"agentRunId"):void 0}}getModelSchema(){if(this.context&&this._meta.model.resolveSchema){let e=a$2(this.context,$t+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 o=$t+this._meta.model.tableName,t=a$2(this.context,o);if(t)return t;let r={tenantId:a$2(this.context,"tenantId"),organizationId:a$2(this.context,"organizationId"),request:this.context.req?.raw,env:this.context.env},s;try{s=await e(r);}catch(i){throw new a(i instanceof Error?i.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",i instanceof Error?{cause:i.message}:void 0)}return b$4(this.context,o,s),s}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&jo(this)){let o=e.body;try{o=await this.context.req.json();}catch{}let r=this.getBodySchema().safeParse(o);if(!r.success)throw b.fromZodError(r.error);e.body=r.data;}return e}};function Wt(n,e){return n==="in"||n==="nin"||n==="between"?e.split(",").map(o=>o.trim()):n==="null"?e.toLowerCase()==="true":e}function Po(n){let e=n.match(/^\[([a-z]+)\](.*)$/);if(e){let o=e[1];return {operator:o,value:Wt(o,e[2])}}return {operator:"eq",value:n}}function ie(n,e){let o=[],t={},{filterFields:r=[],filterConfig:s={},searchFields:i=[],searchFieldName:p="search",sortFields:c=[],defaultSort:u,defaultPerPage:a=20,maxPerPage:d=100,cursorPaginationEnabled:l=false,softDeleteQueryParam:m="withDeleted",allowedIncludes:h=[],fieldSelectionEnabled:g=false,allowedSelectFields:E=[],blockedSelectFields:O=[],alwaysIncludeFields:b=[],defaultSelectFields:w=[]}=e,C={};for(let v of r)C[v]=["eq"];Object.assign(C,s);for(let[v,oe]of Object.entries(n)){if(oe==null)continue;let D=String(oe);if(l&&v==="cursor"){t.cursor=D;continue}if(l&&v==="limit"){t.limit=Math.min(d,Math.max(1,Number.parseInt(D,10)||a));continue}if(v==="page"){t.page=Math.max(1,Number.parseInt(D,10)||1);continue}if(v==="per_page"){t.per_page=Math.min(d,Math.max(1,Number.parseInt(D,10)||a));continue}if(v==="sort"){(c.length===0||c.includes(D))&&(t.order_by=D);continue}if(v==="order"){(D==="asc"||D==="desc")&&(t.order_by_direction=D);continue}if(v===p&&i.length>0){t.search=D;continue}if(v===m){t.withDeleted=D.toLowerCase()==="true";continue}if(v==="onlyDeleted"){t.onlyDeleted=D.toLowerCase()==="true";continue}if(v==="include"){let de=D.split(",").map($=>$.trim()).filter(Boolean);h&&h.length>0?t.include=de.filter($=>h.includes($)):t.include=de;continue}if(v==="fields"&&g){let $=D.split(",").map(pe=>pe.trim()).filter(Boolean);E.length>0&&($=$.filter(pe=>E.includes(pe))),O.length>0&&($=$.filter(pe=>!O.includes(pe))),b.length>0&&($=[...new Set([...b,...$])]),t.fields=$;continue}let Ne=v.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(Ne){let de=Ne[1],$=Ne[2];C[de]?.includes($)&&o.push({field:de,operator:$,value:Wt($,D)});continue}C[v]&&o.push({field:v,operator:"eq",value:D});}if(t.page||(t.page=1),t.per_page||(t.per_page=a),!t.order_by&&u?.field&&(t.order_by=u.field),t.order_by_direction||(t.order_by_direction=u?.order??"asc"),g&&!t.fields&&w.length>0){let v=[...w];b.length>0&&(v=[...new Set([...b,...v])]),t.fields=v;}return {filters:o,options:t}}function U(n,e=[]){if(e.length===0)return n;let o=new Set(Object.keys(n.shape)),t=e.filter(s=>o.has(s));if(t.length===0)return n;let r=Object.fromEntries(t.map(s=>[s,true]));return n.omit(r)}function Fo(n,e={},o=[],t=[],r=[]){let{allowedFields:s=[],blockedFields:i=[],alwaysIncludeFields:p=[],defaultFields:c=[],allowComputedFields:u=true,allowRelationFields:a=true}=e;if(!n||typeof n!="string"||n.trim()==="")return c.length>0?{fields:[...new Set([...p,...c])],isActive:false}:{fields:[],isActive:false};let d=n.split(",").map(g=>g.trim()).filter(Boolean),l=new Set;for(let g of o)(s.length===0||s.includes(g))&&(i.includes(g)||l.add(g));if(u)for(let g of t)(s.length===0||s.includes(g))&&(i.includes(g)||l.add(g));if(a)for(let g of r)(s.length===0||s.includes(g))&&(i.includes(g)||l.add(g));let m=d.filter(g=>l.has(g));return {fields:[...new Set([...p,...m])],isActive:true}}function Se(n,e){if(!e.isActive||e.fields.length===0)return n;let o={};for(let t of e.fields)t in n&&(o[t]=n[t]);return o}function we(n,e){return !e.isActive||e.fields.length===0?n:n.map(o=>Se(o,e))}var lt=class extends x{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,o=B(this._meta.model),t=this.getMultiTenantConfig();t.enabled&&o.push(t.field),this._meta.fields?e=this._meta.fields:e=U(this.getModelSchema(),o);let r=this.getNestedWritableRelations();if(r.length===0)return e;let s={...e.shape};for(let i of r){let p=this._meta.model.relations?.[i];if(!p?.schema)continue;let c=["id",p.foreignKey],u=U(p.schema,c);p.type==="hasMany"?s[i]=z.array(u).optional():s[i]=u.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(([o,t])=>t.nestedWrites?.allowCreate===true).map(([o])=>o):[]}extractNestedData(e){let o=this.getNestedWritableRelations();return c$1(e,o)}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:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,o){return e}async after(e,o){return e}transform(e){return e}async createNested(e,o,t,r,s){return b$1().warn(`Nested writes not implemented for ${o}. Override createNested() in your adapter.`),[]}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:o,nestedData:t}=this.extractNestedData(e),r=o;r=this.injectTenantId(r);let s=this.buildHookContext();r=await this.before(r,s),r=await this.encryptOnWrite(r),r=await this.create(r,s.db.tx).catch(J),r=await this.decryptOnRead(r);let i=this.getParentId(r),p={};if(Object.keys(t).length>0&&i!==null)for(let[d,l]of Object.entries(t)){if(l==null)continue;let m=this._meta.model.relations?.[d];if(!m)continue;let h=await this.createNested(i,d,m,l);p[d]=h;}if(Object.keys(p).length>0){let d={};for(let[l,m]of Object.entries(p)){let h=this._meta.model.relations?.[l];h&&(h.type==="hasMany"?d[l]=m:d[l]=m[0]||null);}r={...r,...d};}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(r,s))):r=await this.after(r,s),this.isAuditEnabled()&&i!==null){let d=this.getAuditLogger();this.runAfterResponse(d.logCreate(this._meta.model.tableName,i,r,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("created",{recordId:i,data:r})),this._meta.model.computedFields&&(r=await j$1(r,this._meta.model.computedFields));let c=this._meta.model.serializer?this._meta.model.serializer(r):r,u=this.applyProfile(c),a=this.transform(u);return this.success(a,201)}};var ct=class extends x{lookupField="id";lookupFields;additionalFilters;etagEnabled=false;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){let e={};if(this.additionalFilters?.length)for(let o of this.additionalFilters)e[o]=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 o=this.getAvailableSelectFields();e.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${o.join(", ")}`);}if(Object.keys(e).length!==0)return z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),o=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],t=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...o,...t];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=this.getQuerySchema();return {...this.schema,request:{params:this.getParamsSchema(),...e&&{query:e}},responses:{200:{description:"Resource retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}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(),o={};for(let t of this.additionalFilters)e?.[t]&&(o[t]=String(e[t]));return o}async getIncludeOptions(){let{query:e}=await this.getValidatedData(),o=e?.include;if(!o||typeof o!="string")return {relations:[]};let t=o.split(",").map(r=>r.trim()).filter(Boolean);return this.allowedIncludes.length>0?{relations:t.filter(r=>this.allowedIncludes.includes(r))}:{relations:t}}async getFieldSelection(){if(!this.fieldSelectionEnabled)return {fields:[],isActive:false};let{query:e}=await this.getValidatedData(),o=e?.fields;if(!o||typeof o!="string"||o.trim()==="")return this.defaultSelectFields.length>0?{fields:[...new Set([...this.alwaysIncludeFields,...this.defaultSelectFields])],isActive:true}:{fields:[],isActive:false};let t=o.split(",").map(i=>i.trim()).filter(Boolean),r=new Set(this.getAvailableSelectFields()),s=t.filter(i=>r.has(i));return this.alwaysIncludeFields.length>0&&(s=[...new Set([...this.alwaysIncludeFields,...s])]),{fields:s,isActive:true}}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),o=await this.getLookupValue(),t=await this.getAdditionalFilters(),r=await this.getIncludeOptions(),s=await this.getFieldSelection();if(e){let l=this.getMultiTenantConfig();t[l.field]=e;}let i=await this.read(o,t,r);if(!i)throw new c$2(this._meta.model.tableName,o);i=await this.decryptOnRead(i);let p=await this.applyReadPolicy(i);if(p===null)throw new c$2(this._meta.model.tableName,o);i=p,i=await this.after(i),this._meta.model.computedFields&&(i=await j$1(i,this._meta.model.computedFields));let c=this._meta.model.serializer?this._meta.model.serializer(i):i,u=this.applyProfile(c),a=this.transform(u),d=s.isActive&&s.fields.length>0?Se(a,s):a;if(this.etagEnabled){let l=await se(d),m=this.getContext(),h=m.req.header("If-None-Match");if(xe(h,l))return new Response(null,{status:304,headers:{ETag:l}});m.header("ETag",l);}return this.success(d)}};var pt=class extends x{lookupField="id";lookupFields;additionalFilters;allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];etagEnabled=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields.partial();else {let r=B(this._meta.model);this.blockedUpdateFields&&(r=[...r,...this.blockedUpdateFields]);let s=U(this.getModelSchema(),r);if(this.allowedUpdateFields){let i={};for(let p of this.allowedUpdateFields)i[p]=true;s=s.pick(i);}e=s.partial();}let o=this.getNestedWritableRelations();if(o.length===0)return e;let t={...e.shape};for(let r of o){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let i=s.schema,p=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();t[r]=p;}return z.object(t)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([o,t])=>{let r=t.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([o])=>o):[]}extractNestedData(e){let o=this.getNestedWritableRelations();return c$1(e,o)}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:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}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(),o={};for(let t of this.additionalFilters)e?.[t]&&(o[t]=String(e[t]));return o}async before(e,o){return e}async after(e,o,t){return o}transform(e){return e}async findExisting(e,o,t){return null}async processNestedWrites(e,o,t,r,s){return b$1().warn(`Nested writes not implemented for ${o}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){let e=this.validateTenantId(),o=await this.getLookupValue(),t=await this.getAdditionalFilters();if(e){let w=this.getMultiTenantConfig();t[w.field]=e;}let r=await this.getObject(),{mainData:s,nestedData:i}=this.extractNestedData(r),p=this.getPolicies(),c=await this.findExisting(o,t,this._tx);if(c&&p?.write&&await this.applyWritePolicy(c),this.etagEnabled&&c){let w=this.getContext().req.header("If-Match");if(w){let C=await se(c);if(!Oe(w,C))return this.error("Resource has been modified by another request","CONFLICT",409)}}let u;if(this.isVersioningEnabled()&&c){let w=this.getVersionManager(),C=this.getParentId(c);C!==null&&(u=await w.saveVersion(C,c,void 0,this.getVersioningUserId()));}let a=s;if(this.isVersioningEnabled()&&u!==void 0){let w=this.getVersioningConfig().field;a[w]=u;}let d=this.buildHookContext();a=await this.before(a,d),a=await this.encryptOnWrite(a);let l=await this.update(o,a,t,d.db.tx);if(!l)throw new c$2(this._meta.model.tableName,o);l=await this.decryptOnRead(l);let m=this.getParentId(l),h={};if(Object.keys(i).length>0&&m!==null)for(let[w,C]of Object.entries(i)){if(C==null)continue;let v=this._meta.model.relations?.[w];if(!v)continue;let oe;d$1(C)?oe={create:C}:oe=C;let D=await this.processNestedWrites(m,w,v,oe);h[w]=D;}if(Object.keys(h).length>0)for(let[w,C]of Object.entries(h)){let v=this._meta.model.relations?.[w];v&&(v.type==="hasMany"?l[w]=[...C.created,...C.updated]:l[w]=C.created[0]||C.updated[0]||null);}let g=c??l;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(g,l,d)));else {let w=await this.after(g,l,d);w!=null&&(l=w);}if(this.isAuditEnabled()&&m!==null&&c){let w=this.getAuditLogger();this.runAfterResponse(w.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})),this._meta.model.computedFields&&(l=await j$1(l,this._meta.model.computedFields));let E=this._meta.model.serializer?this._meta.model.serializer(l):l,O=this.applyProfile(E),b=this.transform(O);if(this.etagEnabled){let w=await se(b);this.getContext().header("ETag",w);}return this.success(b)}};var ut=class extends x{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";includeCascadeResults=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getCascadeRelations(e){let o=this._meta.model.relations;return o?Object.entries(o).filter(([t,r])=>{let s=r.cascade?.[e];return s&&s!=="noAction"}).map(([t,r])=>({name:t,config:r,action:r.cascade[e]})):[]}getSchema(){let e=this.includeCascadeResults?z.object({deleted:z.literal(true),cascade:z.object({deleted:z.record(z.string(),z.number()),nullified:z.record(z.string(),z.number())}).optional()}):z.object({deleted:z.literal(true)});return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},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(),o={};for(let t of this.additionalFilters)e?.[t]&&(o[t]=String(e[t]));return o}async before(e,o){}async after(e,o){}async countRelated(e,o,t,r){return b$1().warn(`countRelated not implemented for ${o}. Override in your adapter for restrict cascade to work.`),0}async deleteRelated(e,o,t,r){return b$1().warn(`deleteRelated not implemented for ${o}. Override in your adapter for cascade delete to work.`),0}async nullifyRelated(e,o,t,r){return b$1().warn(`nullifyRelated not implemented for ${o}. Override in your adapter for setNull cascade to work.`),0}async processCascade(e,o,t){let r=o?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r),i={deleted:{},nullified:{}};for(let{name:p,config:c,action:u}of s)if(u==="cascade"){let a=await this.deleteRelated(e,p,c,t);a>0&&(i.deleted[p]=a);}else if(u==="setNull"){let a=await this.nullifyRelated(e,p,c,t);a>0&&(i.nullified[p]=a);}return i}async checkRestrictConstraints(e,o,t){let r=o?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r);for(let{name:i,config:p,action:c}of s)if(c==="restrict"){let u=await this.countRelated(e,i,p,t);if(u>0)throw new d(`Cannot delete: ${u} related ${i} record(s) exist. Remove them first or change the cascade configuration.`,{relation:i,count:u})}}async handle(){let e=this.validateTenantId(),o=await this.getLookupValue(),t=await this.getAdditionalFilters();if(e){let d=this.getMultiTenantConfig();t[d.field]=e;}let r=this.isSoftDeleteEnabled(),s=await this.findForDelete(o,t,this._tx);if(!s)throw new c$2(this._meta.model.tableName,o);let i=this.getParentId(s);i!==null&&await this.checkRestrictConstraints(i,r),await this.applyWritePolicy(s);let p=this.buildHookContext();if(await this.before(o,p),!await this.delete(o,t,p.db.tx))throw new c$2(this._meta.model.tableName,o);let u;if(i!==null&&(u=await this.processCascade(i,r)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(s,p))):await this.after(s,p),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&&u){let d=Object.keys(u.deleted).length>0,l=Object.keys(u.nullified).length>0;(d||l)&&(a.cascade=u);}return this.success(a)}};var Me=class extends x{filterFields=[];filterConfig;searchFields=[];searchFieldName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;cursorField;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getQuerySchema(){let e={page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(e.sort=z.enum(this.sortFields).optional().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 t of this.filterFields)e[t]=z.string().optional();if(this.filterConfig)for(let[t,r]of Object.entries(this.filterConfig)){for(let s of r)e[`${t}[${s}]`]=z.string().optional();e[t]=z.string().optional();}let o=this.getSoftDeleteConfig();if(o.enabled&&o.allowQueryDeleted&&(e[o.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 t=this.getAvailableSelectFields();e.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${t.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),o=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],t=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...o,...t];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"List of resources",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(this.getModelSchema()),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),has_next_page:z.boolean(),has_prev_page:z.boolean(),next_cursor:z.string().optional(),prev_cursor:z.string().optional()})})}}}}}}async getFilters(){let{query:e}=await this.getValidatedData(),o=this.getSoftDeleteConfig(),t={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:o.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return ie(e||{},t)}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),o=await this.getFilters();if(e){let a=this.getMultiTenantConfig();o.filters.push({field:a.field,operator:"eq",value:e});}this.applyReadPushdown(o);let t=await this.list(o),r=await Promise.all(t.result.map(a=>this.decryptOnRead(a))),s=await this.applyReadPolicyToArray(r),i=await this.after(s);this._meta.model.computedFields&&(i=await k(i,this._meta.model.computedFields)),this._meta.model.serializer&&(i=i.map(a=>this._meta.model.serializer(a)));let c=this.applyProfileToArray(i).map(a=>this.transform(a)),u=this.fieldSelectionEnabled&&o.options.fields&&o.options.fields.length>0?we(c,{fields:o.options.fields,isActive:true}):c;return this.successPaginated(u,t.result_info)}};var mt=class extends x{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...B(this._meta.model),...this.excludeFromClone];return U(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:{description:"Source resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},409:{description:"Unique-constraint violation (e.g. natural-key collision)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}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(),o=await this.getLookupValue(),t=await this.getOverrides(),r={};if(e){let a=this.getMultiTenantConfig();r[a.field]=e;}let s=await this.findSource(o,r);if(!s)throw new c$2(this._meta.model.tableName,o);let i=at(s,this._meta.model);for(let a of this.excludeFromClone)delete i[a];Object.assign(i,t);let p=await this.before(i),c=await this.createClone(p).catch(J);c=await this.after(c),this._meta.model.computedFields&&(c=await j$1(c,this._meta.model.computedFields));let u=this._meta.model.serializer?this._meta.model.serializer(c):c;return this.success(u,201)}};var ye=new Map,vo=["password","token","secret","apiKey","creditCard","ssn"];function Re(n,e){if(n==null||typeof n!="object")return n;if(Array.isArray(n))return n.map(t=>Re(t,e));let o={};for(let[t,r]of Object.entries(n))e.includes(t)||(o[t]=typeof r=="object"&&r!==null?Re(r,e):r);return o}function Ao(n){let{table:e,events:o,emitter:t,filter:r,heartbeatInterval:s=3e4,maxConnections:i=1e3,connectionTimeout:p=3e5,excludeFields:c=vo}=n;return u=>{let a=d$2(u,t);if(!a)return u.json({success:false,error:{code:"EVENT_EMITTER_NOT_CONFIGURED",message:"Event emitter not configured"}},500);let d=ye.get(e)||0;return d>=i?u.json({success:false,error:{code:"TOO_MANY_CONNECTIONS",message:"Too many SSE connections"}},503):(ye.set(e,d+1),streamSSE(u,async l=>{let m,h=async b=>{if(o&&o.length>0&&!o.includes(b.type)||r&&!r(b,u))return;let w=c.length>0?Re(b.data,c):b.data,C=b.previousData&&c.length>0?Re(b.previousData,c):b.previousData;try{await l.writeSSE({event:`${b.table}.${b.type}`,data:JSON.stringify({type:b.type,table:b.table,recordId:b.recordId,data:w,previousData:C,timestamp:b.timestamp}),id:`${b.table}-${b.recordId}-${Date.now()}`});}catch{}};m=a.onTable(e,h);let g=()=>{m.unsubscribe();let b=ye.get(e)||1;b<=1?ye.delete(e):ye.set(e,b-1);};l.onAbort(()=>{g();});let E=Date.now(),O=E;for(;!l.closed;){await l.sleep(1e3);let b=Date.now();if(b-E>=p){l.abort();break}if(b-O>=s){O=b;try{await l.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}}))}}var ft=class extends x{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Soft delete not enabled or record not deleted",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}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(),o={};for(let t of this.additionalFilters)e?.[t]&&(o[t]=String(e[t]));return o}async before(e,o){}async after(e,o){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(),o=await this.getAdditionalFilters();await this.before(e);let t=await this.restore(e,o);if(!t)throw new c$2(this._meta.model.tableName,e);this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(t))):t=await this.after(t);let r=this.getRecordId(t);if(this.isAuditEnabled()&&r!==null){let i=this.getAuditLogger();this.runAfterResponse(i.logRestore(this._meta.model.tableName,r,t,this.getAuditUserId()));}r!==null&&this.runAfterResponse(this.emitEvent("restored",{recordId:r,data:t}));let s=this._meta.model.serializer?this._meta.model.serializer(t):t;return this.success(s)}};var ht=class extends x{upsertKeys;useNativeUpsert=false;createOnlyFields;updateOnlyFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields;else {let r=this.getUpsertKeys(),s=B(this._meta.model,{includePrimaryKeys:false});for(let c of this._meta.model.primaryKeys)r.includes(c)||s.push(c);let i=U(this.getModelSchema(),s),p={};for(let[c,u]of Object.entries(i.shape))r.includes(c)?p[c]=u:p[c]=u.optional();e=z.object(p);}let o=this.getNestedWritableRelations();if(o.length===0)return e;let t={...e.shape};for(let r of o){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let i=s.schema,p=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();t[r]=p;}return z.object(t)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([o,t])=>{let r=t.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([o])=>o):[]}extractNestedData(e){let o=this.getNestedWritableRelations();return c$1(e,o)}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:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,o,t){return e}async beforeCreate(e,o){return e}async beforeUpdate(e,o,t){return e}async after(e,o,t){return e}async nativeUpsert(e,o){return b$1().warn("Native upsert not implemented for this adapter. Falling back to find-then-insert/update pattern."),this.performStandardUpsert(e,o)}async performStandardUpsert(e,o){let t=await this.findExisting(e,o);if(t){let r={...e};if(this.createOnlyFields)for(let i of this.createOnlyFields)delete r[i];return r=await this.beforeUpdate(r,t,o),{data:await this.update(t,r,o),created:false}}else {let r={...e};if(this.updateOnlyFields)for(let i of this.updateOnlyFields)delete r[i];return r=await this.beforeCreate(r,o),{data:await this.create(r,o),created:true}}}async upsert(e,o){return this.useNativeUpsert?this.nativeUpsert(e,o):this.performStandardUpsert(e,o)}async processNestedWrites(e,o,t,r,s){return b$1().warn(`Nested writes not implemented for ${o}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:o,nestedData:t}=this.extractNestedData(e),r=o;r=this.injectTenantId(r);let s=await this.findExisting(r),i=!s;r=await this.before(r,i);let p=await this.upsert(r).catch(J),c=p.data,u=this.getParentId(c),a={};if(Object.keys(t).length>0&&u!==null)for(let[l,m]of Object.entries(t)){if(m==null)continue;let h=this._meta.model.relations?.[l];if(!h)continue;let g;d$1(m)?g={create:m}:g=m;let E=await this.processNestedWrites(u,l,h,g);a[l]=E;}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,p.created))):c=await this.after(c,p.created),this.isAuditEnabled()&&u!==null){let l=this.getAuditLogger();this.runAfterResponse(l.logUpsert(this._meta.model.tableName,u,c,s,p.created,this.getAuditUserId()));}this._meta.model.computedFields&&(c=await j$1(c,this._meta.model.computedFields));let d=this._meta.model.serializer?this._meta.model.serializer(c):c;return this.json({success:true,result:d,created:p.created},p.created?201:200)}};var gt=class extends x{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:U(this.getModelSchema(),B(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:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}async before(e,o,t){return e}async after(e,o,t){return e}transform(e){return e}async handle(){let e=await this.getItems(),o=[],t=[];for(let a=0;a<e.length;a++)try{let d=await this.before(e[a],a);t.push(d);}catch(d){if(this.stopOnError)throw d;o.push({index:a,error:d instanceof Error?d.message:String(d)});}let r=await this.batchCreate(t).catch(J),s=[];for(let a=0;a<r.length;a++)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(r[a],a))),s.push(r[a])):s.push(await this.after(r[a],a));}catch(d){if(this.stopOnError)throw d;o.push({index:a,error:d instanceof Error?d.message:String(d)}),s.push(r[a]);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=s.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_create",this._meta.model.tableName,d,this.getAuditUserId()));}let p=(this._meta.model.serializer?s.map(a=>this._meta.model.serializer(a)):s).map(a=>this.transform(a)),c={success:true,result:{created:p,count:p.length,...o.length>0&&{errors:o}}},u=o.length>0?207:201;return this.json(c,u)}};var bt=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:U(this.getModelSchema(),B(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:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}filterUpdateData(e){let o={...e};if(this.allowedUpdateFields){let t=new Set(this.allowedUpdateFields);o=Object.fromEntries(Object.entries(o).filter(([r])=>t.has(r)));}if(this.blockedUpdateFields)for(let t of this.blockedUpdateFields)delete o[t];for(let t of this._meta.model.primaryKeys)delete o[t];return o}async before(e,o,t){return o}async after(e,o){return e}async handle(){let e=await this.getItems(),o=[],t=[];for(let a of e)try{let d=this.filterUpdateData(a.data),l=await this.before(a.id,d);t.push({id:a.id,data:l});}catch(d){if(this.stopOnError)throw d;o.push({id:a.id,error:d instanceof Error?d.message:String(d)});}let{updated:r,notFound:s}=await this.batchUpdate(t),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let l=String(a[this.lookupField]);if(this.stopOnError)throw d;o.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 p=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,c={success:true,result:{updated:p,count:p.length,...s.length>0&&{notFound:s},...o.length>0&&{errors:o}}},u=o.length>0||s.length>0?207:200;return this.json(c,u)}};var wt=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){let e=this.isSoftDeleteEnabled();return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:e?"Resources soft-deleted successfully":"Resources deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,o){}async after(e,o){return e}async handle(){let e=await this.getIds(),o=[],t=[];for(let a of e)try{await this.before(a),t.push(a);}catch(d){if(this.stopOnError)throw d;o.push({id:a,error:d instanceof Error?d.message:String(d)});}let{deleted:r,notFound:s}=await this.batchDelete(t),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let l=String(a[this.lookupField]);if(this.stopOnError)throw d;o.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 p=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,c={success:true,result:{deleted:p,count:p.length,...s.length>0&&{notFound:s},...o.length>0&&{errors:o}}},u=o.length>0||s.length>0?207:200;return this.json(c,u)}};var Mt=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:{description:"Soft delete not enabled or validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,o){}async after(e,o){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(),o=[],t=[];for(let a of e)try{await this.before(a),t.push(a);}catch(d){if(this.stopOnError)throw d;o.push({id:a,error:d instanceof Error?d.message:String(d)});}let{restored:r,notFound:s}=await this.batchRestore(t),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let l=String(a[this.lookupField]);if(this.stopOnError)throw d;o.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 p=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,c={success:true,result:{restored:p,count:p.length,...s.length>0&&{notFound:s},...o.length>0&&{errors:o}}},u=o.length>0||s.length>0?207:200;return this.json(c,u)}};var yt=class extends x{upsertKeys;createOnlyFields;updateOnlyFields;maxBatchSize=100;continueOnError=false;useNativeUpsert=false;beforeHookMode="sequential";afterHookMode="sequential";getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getItemSchema(){if(this._meta.fields)return this._meta.fields;let e=this.getUpsertKeys(),o=B(this._meta.model,{includePrimaryKeys:false});for(let s of this._meta.model.primaryKeys)e.includes(s)||o.push(s);let t=U(this.getModelSchema(),o),r={};for(let[s,i]of Object.entries(t.shape))e.includes(s)?r[s]=i:r[s]=i.optional();return z.object(r)}getBodySchema(){return z.array(this.getItemSchema()).max(this.maxBatchSize)}getSchema(){let e=z.object({data:this.getModelSchema(),created:z.boolean(),index:z.number()});return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Batch upsert completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({items:z.array(e),createdCount:z.number(),updatedCount:z.number(),totalCount:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e}async beforeItem(e,o,t,r){return e}async afterItem(e,o,t,r){return e}async beforeBatch(e,o){return e}async afterBatch(e,o){return e}async upsertOne(e,o,t){let r=await this.findExisting(e,t),s=!r,i=await this.beforeItem(e,o,s,t),p;if(r){if(this.createOnlyFields)for(let c of this.createOnlyFields)delete i[c];p=await this.update(r,i,t);}else {if(this.updateOnlyFields)for(let c of this.updateOnlyFields)delete i[c];p=await this.create(i,t);}return p=await this.afterItem(p,o,s,t),{data:p,created:s,index:o}}async nativeBatchUpsert(e,o){return b$1().warn("Native batch upsert not implemented for this adapter. Falling back to item-by-item pattern."),this.performStandardBatchUpsert(e,o)}async performStandardBatchUpsert(e,o){let t=[],r=[],s=0,i=0;for(let c=0;c<e.length;c++)try{let u=await this.upsertOne(e[c],c,o);t.push(u),u.created?s++:i++;}catch(u){if(this.continueOnError)r.push({index:c,error:u instanceof Error?u.message:String(u)});else throw u}let p={items:t,createdCount:s,updatedCount:i,totalCount:t.length};return r.length>0&&(p.errors=r),p}async batchUpsert(e,o){return this.useNativeUpsert?this.nativeBatchUpsert(e,o):this.performStandardBatchUpsert(e,o)}async handle(){let e=await this.getItems();e=await this.beforeBatch(e);let o=await this.batchUpsert(e).catch(J);if(o=await this.afterBatch(o),this._meta.model.computedFields&&(o.items=await Promise.all(o.items.map(async t=>({...t,data:await j$1(t.data,this._meta.model.computedFields)})))),this.isAuditEnabled()){let t=this.getAuditLogger(),r=o.items.map(s=>{let i=this.getRecordId(s.data);return i===null?null:{recordId:i,record:s.data}}).filter(s=>s!==null);r.length>0&&this.runAfterResponse(t.logBatch("batch_upsert",this._meta.model.tableName,r,this.getAuditUserId()));}return this._meta.model.serializer&&(o.items=o.items.map(t=>({...t,data:this._meta.model.serializer(t.data)}))),this.success(o)}};var Et=class extends x{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getSchema(){return {request:{body:{content:{"application/json":{schema:this.getUpdateSchema().partial()}}},query:z.object({dryRun:z.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z.object({success:z.boolean(),matched:z.number(),updated:z.number(),dryRun:z.boolean()})}}},400:{description:"Bad request",content:{"application/json":{schema:z.object({success:z.boolean(),error:z.string()})}}}}}}async handle(){let e=this.getContext(),t=(await this.getValidatedData()).body;if(!t||Object.keys(t).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let r=e.req.query("dryRun"),s=r==="true"||r==="1",i=ie(e.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),p=await this.countMatching(i);if(p===0)return this.json({success:true,matched:0,updated:0,dryRun:s});if(p>this.maxBulkSize)return this.error(`Bulk patch affects ${p} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(p>=this.confirmThreshold&&e.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${p} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(s)return this.json({success:true,matched:p,updated:0,dryRun:true});let c=t;this.beforeBulkPatch&&(c=await this.beforeBulkPatch(c,i,p));let u=await this.applyPatch(c,i),a={matched:p,updated:u.updated,dryRun:false,records:this.returnRecords?u.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 Kt=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()}),kt=class extends x{lookupField="id";defaultLimit=20;maxLimit=100;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({limit:z.coerce.number().min(1).max(this.maxLimit).optional(),offset:z.coerce.number().min(0).optional()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version history retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({versions:z.array(Kt),totalVersions:z.number()})})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Record not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}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:o,offset:t}=await this.getPaginationOptions();if(!await this.recordExists(e))throw new c$2(this._meta.model.tableName,e);let s=this.getVersionManager(),i=await s.getVersions(e,{limit:o,offset:t}),p=await s.getLatestVersion(e);return this.success({versions:i,totalVersions:p})}},xt=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:Kt})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}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(),o=await this.getVersionNumber(),r=await this.getVersionManager().getVersion(e,o);if(!r)throw new c$2(`version ${o}`,e);return this.success(r)}},Ot=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({from:z.coerce.number().min(1),to:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version comparison completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({from:z.number(),to:z.number(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()}))})})}}},400:{description:"Versioning not enabled or invalid parameters",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}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:o,to:t}=await this.getVersionNumbers(),s=await this.getVersionManager().compareVersions(e,o,t);return this.success({from:o,to:t,changes:s})}},St=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Record rolled back successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}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(),o=await this.getVersionNumber(),t=this.getVersionManager(),r=await t.getVersion(e,o);if(!r)throw new c$2(`version ${o}`,e);let i=await t.getLatestVersion(e)+1,p=await this.rollback(e,r.data,i),c=this._meta.model.serializer?this._meta.model.serializer(p):p;return this.success(c)}};var _o={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},Ct=class extends x{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {..._o,...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:{description:"Invalid aggregation request",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return i$1(e||{})}validateAggregations(e){let o=this.getAggregateConfig();for(let t of e.aggregations)if(!(t.operation==="count"&&t.field==="*"))switch(t.operation){case "sum":if(o.sumFields.length>0&&!o.sumFields.includes(t.field))throw new Error(`Field '${t.field}' is not allowed for SUM aggregation`);break;case "avg":if(o.avgFields.length>0&&!o.avgFields.includes(t.field))throw new Error(`Field '${t.field}' is not allowed for AVG aggregation`);break;case "min":case "max":if(o.minMaxFields.length>0&&!o.minMaxFields.includes(t.field))throw new Error(`Field '${t.field}' is not allowed for MIN/MAX aggregation`);break;case "countDistinct":if(o.countDistinctFields.length>0&&!o.countDistinctFields.includes(t.field))throw new Error(`Field '${t.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 t of e.groupBy)if(o.groupByFields.length>0&&!o.groupByFields.includes(t))throw new Error(`Field '${t}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>o.maxLimit)throw new Error(`Limit cannot exceed ${o.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 o=this.getAggregateConfig();e.groupBy&&e.groupBy.length>0&&e.limit===void 0&&(e.limit=o.defaultLimit);let t=await this.aggregate(e);return this.success(t)}},Ho={eq:(n,e)=>n===e,ne:(n,e)=>n!==e,gt:(n,e)=>n>e,gte:(n,e)=>n>=e,lt:(n,e)=>n<e,lte:(n,e)=>n<=e};function To(n,e){let o=n.get(e);if(o)return o;let t=[];return n.set(e,t),t}function No(n,e){let{aggregations:o,groupBy:t,having:r,orderBy:s,orderDirection:i,limit:p,offset:c}=e;if(!t||t.length===0){let l={};for(let m of o){let h=Qt(m);l[h]=Gt(n,m);}return {values:l}}let u=new Map;for(let l of n){let h=t.map(g=>String(l[g]??"null")).join("|");To(u,h).push(l);}let a=[];for(let[l,m]of u){let h=l.split("|"),g={};t.forEach((O,b)=>{g[O]=h[b]==="null"?null:h[b];});let E={};for(let O of o){let b=Qt(O);E[b]=Gt(m,O);}a.push({key:g,values:E});}r&&(a=a.filter(l=>{for(let[m,h]of Object.entries(r)){let g=l.values[m];if(g!==null)for(let[E,O]of Object.entries(h)){let b=Ho[E];if(b&&!b(g,Number(O)))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 g=m.values[s]??0,E=h.values[s]??0;return (g-E)*l}if(s in m.key){let g=String(m.key[s]??""),E=String(h.key[s]??"");return g.localeCompare(E)*l}return 0});}if(c!==void 0||p!==void 0){let l=c||0,m=p?l+p:void 0;a=a.slice(l,m);}return {groups:a,totalGroups:d}}function Rt(n,e){return n.map(o=>o[e]).filter(o=>typeof o=="number")}var Bo={count:(n,e)=>e==="*"?n.length:n.filter(o=>o[e]!==null&&o[e]!==void 0).length,countDistinct:(n,e)=>new Set(n.map(t=>t[e]).filter(t=>t!=null).map(t=>String(t))).size,sum:(n,e)=>{let o=0;for(let t of n){let r=t[e];typeof r=="number"&&(o+=r);}return o},avg:(n,e)=>{let o=Rt(n,e);return o.length===0?null:o.reduce((r,s)=>r+s,0)/o.length},min:(n,e)=>{let o=Rt(n,e);return o.length===0?null:Math.min(...o)},max:(n,e)=>{let o=Rt(n,e);return o.length===0?null:Math.max(...o)}};function Gt(n,e){if(n.length===0)return e.operation==="count"?0:null;let o=Bo[e.operation];return o?o(n,e.field):null}function Qt(n){return n.alias?n.alias:n.field==="*"?n.operation:`${n.operation}${n.field.charAt(0).toUpperCase()}${n.field.slice(1)}`}var Do=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 jt(n,e=true){if(!n||typeof n!="string")return [];let o=n.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(Boolean);return e?o.filter(t=>!Do.has(t)&&t.length>1):o}function Pt(n,e){return e==="phrase"?[n.toLowerCase().trim()]:jt(n)}function Yt(n,e){return e.length===0?0:e.filter(t=>t===n||t.includes(n)).length/e.length}function Ft(n,e,o,t){if(e.length===0)return {score:0,matchedFields:[]};let r=0,s=0,i=[];for(let[c,u]of Object.entries(o)){let a=n[c];if(a==null)continue;let d=u.weight??1;s+=d;let l;u.type==="array"&&Array.isArray(a)?l=a.join(" "):l=String(a);let m=jt(l,false),h=l.toLowerCase(),g=0,E=0;if(t==="phrase"){let O=e[0];h.includes(O)&&(g=1,E=1);}else {for(let O of e){let b=Yt(O,m);b>0?(E++,g+=b):h.includes(O)&&(E++,g+=.5/e.length);}e.length>0&&(g=g/e.length);}t==="all"&&E<e.length&&(g=0),g>0&&(i.push(c),r+=g*d);}return {score:s>0?Math.min(1,r/s):0,matchedFields:i}}function It(n,e,o,t="mark",r=150){if(n==null)return [];let s;if(Array.isArray(n)?s=n.join(" "):s=String(n),!s||e.length===0)return [];let i=[],p=s.toLowerCase();if(o==="phrase"){let c=e[0],u=p.indexOf(c);if(u!==-1){let a=Jt(s,u,c.length,r,t);a&&i.push(a);}}else {let c=[];for(let a of e){let d=0;for(;d<p.length;){let l=p.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 u=new Set;for(let a of c){if(Array.from(u).some(m=>Math.abs(m-a.start)<r))continue;let l=Jt(s,a.start,a.length,r,t);if(l&&(i.push(l),u.add(a.start)),i.length>=3)break}}return i}function Jt(n,e,o,t,r){let s=Math.floor(t/2),i=Math.max(0,e-s),p=Math.min(n.length,e+o+s);if(i>0){let a=n.indexOf(" ",i);a!==-1&&a<e&&(i=a+1);}if(p<n.length){let a=n.lastIndexOf(" ",p);a!==-1&&a>e+o&&(p=a);}let c=n.slice(i,p);return i>0&&(c="..."+c),p<n.length&&(c=c+"..."),Vo(c,[n.slice(e,e+o)],r)}function Vo(n,e,o){let t=n,r=n.toLowerCase(),s=[...e].sort((i,p)=>p.length-i.length);for(let i of s){let p=i.toLowerCase(),c=0,u="",a=0;for(;a<r.length;){let d=r.indexOf(p,a);if(d===-1)break;u+=t.slice(c,d),u+=`<${o}>${t.slice(d,d+i.length)}</${o}>`,c=d+i.length,a=c;}u&&(u+=t.slice(c),t=u);}return t}function vt(n,e){if(!n)return Object.keys(e);let o=n.split(",").map(r=>r.trim()).filter(Boolean),t=Object.keys(e);return o.filter(r=>t.includes(r))}function At(n,e){let o={};for(let t of n)o[t]={weight:e?.[t]??1};return o}function Uo(n){if(n instanceof z.ZodString)return true;let e=n;return e?e._def?.type==="string"||e._def?.typeName==="ZodString"||e.def?.type==="string":false}var _t=class extends x{searchableFields={};searchFields=[];fieldWeights={};defaultMode="any";minQueryLength=2;maxQueryLength=500;highlightTag="mark";snippetLength=150;defaultMinScore=0;searchParamName="q";filterFields=[];filterConfig;sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getSearchableFields(){if(Object.keys(this.searchableFields).length>0)return this.searchableFields;if(this.searchFields.length>0)return At(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,o={};for(let[t,r]of Object.entries(e))Uo(r)&&(o[t]={weight:1});return o}getQuerySchema(){let o={[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&&(o.sort=z.enum(this.sortFields).optional().describe("Field to sort by"),o.order=z.enum(["asc","desc"]).optional().describe("Sort direction (asc or desc)"));for(let r of this.filterFields)o[r]=z.string().optional();if(this.filterConfig)for(let[r,s]of Object.entries(this.filterConfig)){for(let i of s)o[`${r}[${i}]`]=z.string().optional();o[r]=z.string().optional();}let t=this.getSoftDeleteConfig();if(t.enabled&&t.allowQueryDeleted&&(o[t.queryParam]=z.enum(["true","false"]).optional(),o.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(o.include=z.string().optional().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let r=this.getAvailableSelectFields();o.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${r.join(", ")}`);}return z.object(o)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),o=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],t=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...o,...t];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=z.object({item:this.getModelSchema(),score:z.number().min(0).max(1),highlights:z.record(z.string(),z.array(z.string())).optional(),matchedFields:z.array(z.string())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Search results",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(e),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),query:z.string(),searchedFields:z.array(z.string())})})}}},400:{description:"Invalid search request",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getSearchOptions(){let{query:e}=await this.getValidatedData(),o=this.searchParamName||"q",t=e?.[o],r$1=e?.fields,s=r(e?.mode),i=e?.highlight==="true",p=e?.minScore?Math.max(0,Math.min(1,Number.parseFloat(e.minScore)||0)):this.defaultMinScore,c=this.getSearchableFields(),u=vt(r$1,c);return {query:t,fields:u.length>0?u:Object.keys(c),mode:s??this.defaultMode,highlight:i,minScore:p}}async getFilters(){let{query:e}=await this.getValidatedData(),o=this.getSoftDeleteConfig(),t={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchFieldName:"q",sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,softDeleteQueryParam:o.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return ie(e||{},t)}async beforeSearch(e){return e}async afterSearch(e){return e}async handle(){let e=await this.getSearchOptions(),o=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 t=await this.search(e,o),r=await this.afterSearch(t.items);if(this._meta.model.computedFields){let a=r.map(l=>l.item),d=await k(a,this._meta.model.computedFields);r=r.map((l,m)=>({...l,item:d[m]}));}this._meta.model.serializer&&(r=r.map(a=>({...a,item:this._meta.model.serializer(a.item)})));let s=r;this.fieldSelectionEnabled&&o.options.fields&&o.options.fields.length>0&&(s=r.map(a=>({...a,item:we([a.item],{fields:o.options.fields,isActive:true})[0]})));let i=t.postFilteredCount??t.totalCount,p=o.options.page||1,c=o.options.per_page||this.defaultPerPage,u=Math.ceil(i/c);return this.successPaginated(s,{page:p,per_page:c,total_count:i,total_pages:u,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function Zo(n,e,o){let t=Pt(e.query,e.mode),r={},s=e.fields||Object.keys(o);for(let p of s)o[p]&&(r[p]=o[p]);let i=[];for(let p of n){let{score:c,matchedFields:u}=Ft(p,t,r,e.mode);if(c<e.minScore||u.length===0)continue;let a;if(e.highlight){a={};for(let d of u){let l=It(p[d],t,e.mode);l.length>0&&(a[d]=l);}}i.push({item:p,score:c,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:u});}return i.sort((p,c)=>c.score-p.score),i}function Y(n,e={}){let{delimiter:o=",",nullValue:t="",dateFormat:r="iso"}=e;if(n==null)return t;if(n instanceof Date)switch(r){case "timestamp":return String(n.getTime());case "locale":return n.toLocaleString();default:return n.toISOString()}if(typeof n=="object")return Y(JSON.stringify(n),e);if(typeof n=="boolean")return n?"true":"false";let s=String(n),i=s.charAt(0);return i==="="||i==="+"||i==="-"||i==="@"||i===" "||i==="\r"?`" ${s.replace(/"/g,'""')}"`:s.includes(o)||s.includes('"')||s.includes(`
|
|
2
|
+
`)||s.includes("\r")?`"${s.replace(/"/g,'""')}"`:s}function Ce(n,e={}){let{delimiter:o=",",rowDelimiter:t=`\r
|
|
3
|
+
`,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:p={},nullValue:c="",dateFormat:u="iso"}=e;if(n.length===0)return "";let a=e.headers;a?a=a.filter(l=>!i.includes(l)):a=Object.keys(n[0]).filter(l=>!i.includes(l));let d=[];if(r){let l=a.map(m=>{let h=p[m]||m;return Y(h,{delimiter:o,nullValue:c,dateFormat:u})});d.push(l.join(o));}for(let l of n){let m=a.map(h=>{let g=l[h];return s[h]&&(g=s[h](g)),Y(g,{delimiter:o,nullValue:c,dateFormat:u})});d.push(m.join(o));}return d.join(t)}function zo(n,e={}){let{delimiter:o=",",rowDelimiter:t=`\r
|
|
4
|
+
`,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:p={},nullValue:c="",dateFormat:u="iso"}=e,a=new TextEncoder,d=0,l=false,m=e.headers;return !m&&n.length>0?m=Object.keys(n[0]).filter(h=>!i.includes(h)):m?m=m.filter(h=>!i.includes(h)):m=[],new ReadableStream({pull(h){if(r&&!l&&m.length>0){let O=m.map(b=>{let w=p[b]||b;return Y(w,{delimiter:o,nullValue:c,dateFormat:u})});h.enqueue(a.encode(O.join(o)+t)),l=true;return}let g=100,E=[];for(;d<n.length&&E.length<g;){let O=n[d],b=m.map(w=>{let C=O[w];return s[w]&&(C=s[w](C)),Y(C,{delimiter:o,nullValue:c,dateFormat:u})});E.push(b.join(o)),d++;}E.length>0&&h.enqueue(a.encode(E.join(t)+t)),d>=n.length&&h.close();}})}function Xt(n,e){let o=[],t="",r=false,s=0;for(;s<n.length;){let i=n[s];if(r){if(i==='"'){if(s+1<n.length&&n[s+1]==='"'){t+='"',s+=2;continue}r=false,s++;continue}t+=i,s++;}else {if(i==='"'){r=true,s++;continue}if(i===e){o.push(t),t="",s++;continue}t+=i,s++;}}return o.push(t),o}function Lo(n){let e=[],o="",t=false;for(let r=0;r<n.length;r++){let s=n[r];if(s==='"'){if(t&&r+1<n.length&&n[r+1]==='"'){o+='""',r++;continue}t=!t,o+=s;continue}if(!t&&(s===`
|
|
5
|
+
`||s==="\r")){s==="\r"&&r+1<n.length&&n[r+1]===`
|
|
6
|
+
`&&r++,o.length>0&&(e.push(o),o="");continue}o+=s;}return o.length>0&&e.push(o),e}function je(n,e={}){let{delimiter:o=",",hasHeader:t=true,trimValues:r=true,skipEmptyRows:s=true,parsers:i={},emptyValue:p="empty"}=e,c={data:[],headers:[],errors:[]},u=Lo(n);if(u.length===0)return c;let a=0;if(t){let l=u[0];c.headers=Xt(l,o).map(m=>r?m.trim():m),a=1;}else e.headers&&(c.headers=e.headers);let d=e.headers||c.headers;for(let l=a;l<u.length;l++){let m=u[l],h=l+1;if(!(s&&m.trim()===""))try{let g=Xt(m,o),E={};for(let O=0;O<d.length;O++){let b=d[O],w=O<g.length?g[O]:"";if(r&&typeof w=="string"&&(w=w.trim()),w==="")switch(p){case "null":w=null;break;case "undefined":w=void 0;break}if(i[b]&&typeof w=="string")try{w=i[b](w);}catch(C){c.errors.push({row:h,message:`Failed to parse field "${b}": ${C instanceof Error?C.message:String(C)}`,content:m});}E[b]=w;}c.data.push(E);}catch(g){c.errors.push({row:h,message:`Failed to parse row: ${g instanceof Error?g.message:String(g)}`,content:m});}}return c}function Ht(n,e,o={}){let{allowUnknownFields:t=false,optionalFields:r=[]}=o,s=e.shape,i=Object.keys(s),c=i.filter(l=>r.includes(l)?false:!s[l].isOptional()).filter(l=>!n.includes(l)),u=n.filter(l=>!i.includes(l)),a=n.filter(l=>i.includes(l));return {valid:c.length===0&&(t||u.length===0),missingFields:c,unknownFields:u,validFields:a}}function qo(n,e){if(n){let o=n.toLowerCase().split(".").pop();if(o==="csv")return "csv";if(o==="json")return "json"}if(e){let o=e.trim();if(o.startsWith("[")||o.startsWith("{"))return "json";if(o.includes(",")||o.includes(`
|
|
7
|
+
`))return "csv"}return "unknown"}function $o(n,e={}){return Ce(n,e)}function Wo(n,e={}){return je(n,e).data}var Tt=class extends Me{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(),o=e?.format||this.defaultFormat,t=e?.stream==="true"&&this.enableStreaming;return {format:o,stream:t,fields:e?.fields?String(e.fields).split(","):void 0}}getExportFilename(e){let t=(this.exportFilename||this._meta.model.tableName).replace(/[^a-zA-Z0-9_-]/g,"_"),r=new Date().toISOString().replace(/[:.]/g,"-");return `${t}-export-${r}.${e}`}prepareRecordsForExport(e){return this.excludedExportFields.length===0?e:e.map(o=>{let t={};for(let[r,s]of Object.entries(o))this.excludedExportFields.includes(r)||(t[r]=s);return t})}exportAsJson(e,o){let t={data:e,count:e.length,format:o,exportedAt:new Date().toISOString()};return new Response(JSON.stringify({success:true,result:t},null,2),{status:200,headers:{"Content-Type":"application/json","Content-Disposition":`attachment; filename="${this.getExportFilename(o)}"`}})}exportAsCsv(e,o){let t=Ce(e,{...this.csvOptions,excludeFields:this.excludedExportFields});return new Response(t,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${this.getExportFilename(o)}"`}})}exportAsCsvStream(e,o){let t=this.getContext(),r=this.getExportFilename(o),s=this.csvOptions,i=this.excludedExportFields;return stream(t,async p=>{if(t.header("Content-Type","text/csv; charset=utf-8"),t.header("Content-Disposition",`attachment; filename="${r}"`),e.length===0)return;let c=Object.keys(e[0]).filter(d=>!i.includes(d)),u=c.map(d=>Y(d,s)).join(",")+`
|
|
8
|
+
`;await p.write(u);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=>Y(l[h],s)).join(",")+`
|
|
9
|
+
`;await p.write(m);}})}exportAsCsvStreamPaginated(e,o){let t=this.getExportFilename(o),r=this.streamPageSize,s=Math.min(this.maxExportRecords,1e5),i=this.excludedExportFields,p=this.csvOptions,c=null,u=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:r}},E=(await this.list(h)).result;if(E.length===0)break;E.length>s-m&&(E=E.slice(0,s-m)),E=await this.after(E),E=await this.beforeExport(E);let O=this.prepareRecordsForExport(E);if(!c&&O.length>0){c=Object.keys(O[0]).filter(w=>!i.includes(w));let b=c.map(w=>Y(w,p)).join(",")+`
|
|
10
|
+
`;a.enqueue(d.encode(b));}if(c)for(let b of O){let w=c.map(C=>Y(b[C],p)).join(",")+`
|
|
11
|
+
`;a.enqueue(d.encode(w));}if(m+=E.length,l++,E.length<r)break}}catch(h){a.error(h);return}a.close();}});return new Response(u,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${t}"`}})}async beforeExport(e){return e}async fetchAllForExport(e){let o=Math.min(this.maxExportRecords,1e5),t={...e,options:{...e.options,page:1,per_page:o}};return (await this.list(t)).result}async handle(){let e=await this.getExportOptions(),o=await this.getFilters();if(e.format==="csv"&&e.stream)return this.exportAsCsvStreamPaginated(o,e.format);let t=await this.fetchAllForExport(o);t=await this.after(t),t=await this.beforeExport(t);let r=this.prepareRecordsForExport(t);return e.format==="csv"?this.exportAsCsv(r,e.format):this.exportAsJson(r,e.format)}};var Nt=class extends x{maxBatchSize=1e3;importBatchSize=100;stopOnError=false;skipInvalidRows=true;defaultMode="create";upsertKeys;immutableFields=[];csvOptions={};maxBodySize=10*1024*1024;optionalImportFields=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getImportSchema(){let e=this._meta.fields?this._meta.fields:U(this.getModelSchema(),B(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:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getImportOptions(){let{query:e}=await this.getValidatedData(),o=e?.skipInvalid==="true"?true:e?.skipInvalid==="false"?false:this.skipInvalidRows,t=e?.stopOnError==="true"?true:e?.stopOnError==="false"?false:this.stopOnError;return {mode:e?.mode||this.defaultMode,skipInvalidRows:o,stopOnError:t}}async parseImportData(){let e=this.context;if(!e)throw new b("No request available");let o=e.req.header("content-type")||"";if(o.includes("application/json")){let t=await e.req.json();if(!t)throw new b("Request body is empty");if(!t.items||!Array.isArray(t.items))throw new b('Request body must contain an "items" array');if(t.items.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);return t.items}if(o.includes("text/csv")){let t=await e.req.text();if(t.length>this.maxBodySize)throw new b(`Request body exceeds maximum size of ${this.maxBodySize} bytes`);return this.parseCsvData(t)}if(o.includes("multipart/form-data")){let r=(await e.req.formData()).get("file");if(!r)throw new b("No file provided in form data");let s=await r.text();if(s.length>this.maxBodySize)throw new b(`Uploaded file exceeds maximum size of ${this.maxBodySize} bytes`);let i=r.name.toLowerCase();if(i.endsWith(".json")){let c;try{c=JSON.parse(s);}catch{throw new b("Invalid JSON content in uploaded file")}let u=Array.isArray(c)?c:c.items;if(!u||!Array.isArray(u))throw new b('JSON file must contain an array or an object with "items" array');if(u.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);return u}if(i.endsWith(".csv"))return this.parseCsvData(s);let p=s.trim();if(p.startsWith("[")||p.startsWith("{")){let c;try{c=JSON.parse(s);}catch{throw new b("Invalid JSON content in uploaded file")}let u=Array.isArray(c)?c:c.items;if(!u||!Array.isArray(u))throw new b('JSON file must contain an array or an object with "items" array');return u}return this.parseCsvData(s)}throw new b("Unsupported content type. Use application/json, text/csv, or multipart/form-data")}parseCsvData(e){let o=je(e,this.csvOptions);if(o.errors.length>0)throw new b(`CSV parsing errors: ${o.errors.map(s=>`Row ${s.row}: ${s.message}`).join("; ")}`);if(o.data.length===0)throw new b("CSV file is empty");if(o.data.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);let t=this._meta.fields||this.getModelSchema(),r=Ht(o.headers,t,{allowUnknownFields:true,optionalFields:this.optionalImportFields});if(!r.valid&&r.missingFields.length>0)throw new b(`Missing required fields in CSV: ${r.missingFields.join(", ")}`);return o.data}validateRow(e,o){let t=this._meta.fields||this.getModelSchema(),r={};for(let i of B(this._meta.model))r[i]=true;for(let i of this.optionalImportFields)r[i]=true;let s=t.partial(r);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 o={};for(let[t,r]of Object.entries(e))this.immutableFields.includes(t)||(o[t]=r);return o}async before(e,o,t,r){return e}async after(e,o,t,r){return e}async processRow(e,o,t,r){let s=this.validateRow(e,o);if(!s.valid)return t.skipInvalidRows?{rowNumber:o,status:"skipped",error:"Validation failed",validationErrors:s.errors}:{rowNumber:o,status:"failed",error:"Validation failed",validationErrors:s.errors};try{let i=await this.before(e,o,t.mode,r);if(t.mode==="upsert"){let c=await this.findExisting(i,r);if(c){let u=this.removeImmutableFields(i),a=await this.update(c,u,r);return {rowNumber:o,status:"updated",data:a}}}else if(await this.findExisting(i,r))return t.skipInvalidRows?{rowNumber:o,status:"skipped",error:"Record already exists"}:{rowNumber:o,status:"failed",error:"Record already exists (duplicate key)"};let p=await this.create(i,r);return {rowNumber:o,status:"created",data:p}}catch(i){let p=ke(i);return p?{rowNumber:o,status:"failed",code:"CONFLICT",error:p.message}:{rowNumber:o,status:"failed",error:i instanceof Error?i.message:String(i)}}}async handle(){let e=await this.getImportOptions(),o=await this.parseImportData();if(!Number.isInteger(this.importBatchSize)||this.importBatchSize<1)throw new i("importBatchSize must be a positive integer");let t={total:o.length,created:0,updated:0,skipped:0,failed:0},r=[],s=false,i$1=e.stopOnError?1:this.importBatchSize;for(let u=0;u<o.length&&!s;u+=i$1){let a=o.slice(u,u+i$1),d=await Promise.all(a.map(async(l,m)=>{let h=u+m+1,g=await this.processRow(l,h,e);return g=await this.after(g,h,e.mode),g}));for(let l of d){switch(r.push(l),l.status){case "created":t.created++;break;case "updated":t.updated++;break;case "skipped":t.skipped++;break;case "failed":t.failed++;break}if(e.stopOnError&&l.status==="failed"){s=true;break}}}if(this.isAuditEnabled()){let u=this.getAuditLogger(),a=r.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(u.logBatch(e.mode==="upsert"?"batch_upsert":"batch_create",this._meta.model.tableName,d,this.getAuditUserId()));}}let p={summary:t,results:r},c=t.failed>0&&t.failed<t.total?207:200;return this.json({success:true,result:p},c)}};var Pe=Symbol.for("hono-crud.resource-registry");function eo(n,e,o){let t=n;t[Pe]||(t[Pe]=[]),t[Pe].push({path:e,endpoints:o});}function ri(n){return n[Pe]??[]}function Go(n,e,o,t={}){let r=e.endsWith("/")?e.slice(0,-1):e,s=n,{middlewares:i=[],endpointMiddlewares:p={},responseEnvelope:c}=t,u=c?async(l,m)=>{b$4(l,q,c),await m();}:void 0,a=l=>{let m=o[l],h=m&&"_middlewares"in m?m._middlewares||[]:[];return [...u?[u]:[],...i,...p[l]||[],...h]},d=(l,m,h,g)=>{let E=a(h),O=s[l];E.length>0?O(m,...E,g):O(m,g);};o.create&&d("post",r,"create",o.create),o.list&&d("get",r,"list",o.list),o.batchCreate&&d("post",`${r}/batch`,"batchCreate",o.batchCreate),o.batchUpdate&&d("patch",`${r}/batch`,"batchUpdate",o.batchUpdate),o.batchDelete&&d("delete",`${r}/batch`,"batchDelete",o.batchDelete),o.batchRestore&&d("post",`${r}/batch/restore`,"batchRestore",o.batchRestore),o.batchUpsert&&d("post",`${r}/batch/upsert`,"batchUpsert",o.batchUpsert),o.search&&d("get",`${r}/search`,"search",o.search),o.aggregate&&d("get",`${r}/aggregate`,"aggregate",o.aggregate),o.export&&d("get",`${r}/export`,"export",o.export),o.import&&d("post",`${r}/import`,"import",o.import),o.upsert&&d("post",`${r}/upsert`,"upsert",o.upsert),o.read&&d("get",`${r}/:id`,"read",o.read),o.update&&d("patch",`${r}/:id`,"update",o.update),o.delete&&d("delete",`${r}/:id`,"delete",o.delete),o.restore&&d("post",`${r}/:id/restore`,"restore",o.restore),o.clone&&d("post",`${r}/:id/clone`,"clone",o.clone),eo(n,r,o);}function Bt(n){return {content:{"application/json":{schema:n}}}}function Qo(n){return {description:"Success",...Bt({type:"object",properties:{success:{type:"boolean",enum:[true]},result:n},required:["success","result"]})}}function Jo(n="Error"){return {description:n,...Bt({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 Dt(n,e){return {content:{"application/json":{schema:n}},description:e}}function Yo(n,e){return {content:{"application/json":{schema:n}},description:e,required:true}}var to=z.object({code:z.string(),path:z.array(z.union([z.string(),z.number()])),message:z.string()}),Fe=z.object({success:z.literal(false),error:z.object({name:z.literal("ZodError"),issues:z.array(to)})});function Xo(n){return Fe}function en(...n){return Fe}var tn=(n,e)=>{if(!n.success)return e.json({success:false,error:{name:"ZodError",issues:n.error.issues}},422)};function on(n,e=422){return (o,t)=>{if(!o.success)return t.json(n(o.error),e)}}var oo=z.object({success:z.literal(false),error:z.object({message:z.string(),code:z.string().optional()})});function ae(n){return Dt(oo,n)}var nn={badRequest:ae("Bad request"),unauthorized:ae("Unauthorized"),forbidden:ae("Forbidden"),notFound:ae("Resource not found"),conflict:ae("Resource conflict"),validationError:Dt(Fe,"Validation error"),internalError:ae("Internal server error")};function rn(n){return async(e,o)=>{n.audit&&e.set("auditStorage",n.audit),n.versioning&&e.set("versioningStorage",n.versioning),n.logging&&e.set("loggingStorage",n.logging),n.events&&e.set("eventEmitter",n.events),await o();}}function j(n,e){let o=e.middlewares??[],t=e.extras,r=e.schema??{},s=Array.isArray(r.tags)&&r.tags.length>0,i=e.meta.model.tag??e.meta.model.tableName,p=s?r:{...r,tags:[i]};return class extends n{static _middlewares=o;constructor(){super(),t&&Object.assign(this,t);}_meta=e.meta;schema=p;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(...u){return e.before?e.before(...u):super.before(...u)}async after(...u){return e.after?e.after(...u):super.after(...u)}transform(u){return e.transform?e.transform(u):super.transform(u)}}}function sn(n,e){return j(e,{meta:n.meta,schema:n.schema,middlewares:n.middlewares,before:n.before,after:n.after,beforeHookMode:n.beforeHookMode,afterHookMode:n.afterHookMode,allowNestedCreate:n.allowNestedCreate})}function an(n,e){let o=n.defaultSort??(n.defaultOrderBy?{field:n.defaultOrderBy,order:n.defaultOrderDirection??"asc"}:void 0);return j(e,{meta:n.meta,schema:n.schema,middlewares:n.middlewares,after:n.after,transform:n.transform,filterFields:n.filterFields,filterConfig:n.filterConfig,searchFields:n.searchFields,searchFieldName:n.searchFieldName,sortFields:n.sortFields??n.orderByFields,defaultSort:o,defaultPerPage:n.defaultPerPage,maxPerPage:n.maxPerPage,allowedIncludes:n.allowedIncludes,fieldSelectionEnabled:n.fieldSelectionEnabled,allowedSelectFields:n.allowedSelectFields,blockedSelectFields:n.blockedSelectFields,alwaysIncludeFields:n.alwaysIncludeFields,defaultSelectFields:n.defaultSelectFields})}function dn(n,e){return j(e,{meta:n.meta,schema:n.schema,middlewares:n.middlewares,after:n.after,transform:n.transform,lookupField:n.lookupField,additionalFilters:n.additionalFilters,allowedIncludes:n.allowedIncludes,fieldSelectionEnabled:n.fieldSelectionEnabled,allowedSelectFields:n.allowedSelectFields,blockedSelectFields:n.blockedSelectFields,alwaysIncludeFields:n.alwaysIncludeFields,defaultSelectFields:n.defaultSelectFields})}function ln(n,e){return j(e,{meta:n.meta,schema:n.schema,middlewares:n.middlewares,before:n.before,after:n.after,transform:n.transform,beforeHookMode:n.beforeHookMode,afterHookMode:n.afterHookMode,lookupField:n.lookupField,additionalFilters:n.additionalFilters,allowedUpdateFields:n.allowedUpdateFields,blockedUpdateFields:n.blockedUpdateFields,allowNestedWrites:n.allowNestedWrites})}function cn(n,e){return j(e,{meta:n.meta,schema:n.schema,middlewares:n.middlewares,before:n.before,after:n.after,beforeHookMode:n.beforeHookMode,afterHookMode:n.afterHookMode,lookupField:n.lookupField,additionalFilters:n.additionalFilters,includeCascadeResults:n.includeCascadeResults})}var Ie=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 j(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})}},ve=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,o="asc"){return this._defaultSort={field:e,order:o},this}defaultOrder(e,o="asc"){return this.defaultSort(e,o)}pagination(e,o){return this._defaultPerPage=e,o!==void 0&&(this._maxPerPage=o),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 j(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchFieldName:this._searchFieldName,sortFields:this._sortFields,defaultSort:this._defaultSort,defaultPerPage:this._defaultPerPage,maxPerPage:this._maxPerPage,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},Ae=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return j(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},_e=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}allowedFields(...e){return this._allowedUpdateFields=e,this}blockedFields(...e){return this._blockedUpdateFields=e,this}nestedWrites(...e){return this._allowNestedWrites=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}transform(e){return this._transform=e,this}build(e){return j(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})}},He=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 j(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})}},Te=class{constructor(e){this.meta=e;}create(){return new Ie(this.meta)}list(){return new ve(this.meta)}read(){return new Ae(this.meta)}update(){return new _e(this.meta)}delete(){return new He(this.meta)}};function pn(n){return new Te(n)}function un(n,e){let o={};if(n.create!==void 0){let t=n.create;o.create=j(e.CreateEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,allowNestedCreate:t.nestedCreate,before:t.hooks?.before,after:t.hooks?.after});}if(n.list!==void 0){let t=n.list;o.list=j(e.ListEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,filterFields:t.filtering?.fields,filterConfig:t.filtering?.config,searchFields:t.search?.fields,searchFieldName:t.search?.paramName,sortFields:t.sorting?.fields,defaultSort:t.sorting?.default?{field:t.sorting.default,order:t.sorting.defaultOrder??t.sorting.defaultDirection??"asc"}:void 0,defaultPerPage:t.pagination?.defaultPerPage,maxPerPage:t.pagination?.maxPerPage,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(n.read!==void 0){let t=n.read;o.read=j(e.ReadEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(n.update!==void 0){let t=n.update;o.update=j(e.UpdateEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedUpdateFields:t.fields?.allowed,blockedUpdateFields:t.fields?.blocked,allowNestedWrites:t.nestedWrites,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,transform:t.hooks?.transform});}if(n.delete!==void 0){let t=n.delete;o.delete=j(e.DeleteEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,includeCascadeResults:t.includeCascadeResults,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(n.search!==void 0&&e.SearchEndpoint){let t=n.search;o.search=j(e.SearchEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{searchFields:t.fields}:{},...t.mode!==void 0?{defaultMode:t.mode}:{},...t.paramName!==void 0?{searchParamName:t.paramName}:{}}});}if(n.aggregate!==void 0&&e.AggregateEndpoint){let t=n.aggregate;o.aggregate=j(e.AggregateEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{filterFields:t.fields}:{}}});}if(n.restore!==void 0&&e.RestoreEndpoint){let t=n.restore;o.restore=j(e.RestoreEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(n.batchCreate!==void 0&&e.BatchCreateEndpoint){let t=n.batchCreate;o.batchCreate=j(e.BatchCreateEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(n.batchUpdate!==void 0&&e.BatchUpdateEndpoint){let t=n.batchUpdate;o.batchUpdate=j(e.BatchUpdateEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(n.batchDelete!==void 0&&e.BatchDeleteEndpoint){let t=n.batchDelete;o.batchDelete=j(e.BatchDeleteEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(n.batchRestore!==void 0&&e.BatchRestoreEndpoint){let t=n.batchRestore;o.batchRestore=j(e.BatchRestoreEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(n.batchUpsert!==void 0&&e.BatchUpsertEndpoint){let t=n.batchUpsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;o.batchUpsert=j(e.BatchUpsertEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{},...r!==void 0?{upsertKeys:r}:{}}});}if(n.export!==void 0&&e.ExportEndpoint){let t=n.export;o.export=j(e.ExportEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,extras:{...t.maxRows!==void 0?{maxExportRecords:t.maxRows}:{},...t.formats!==void 0&&t.formats.length>0?{defaultFormat:t.formats[0]}:{}}});}if(n.import!==void 0&&e.ImportEndpoint){let t=n.import;o.import=j(e.ImportEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxRows!==void 0?{maxBatchSize:t.maxRows}:{}}});}if(n.upsert!==void 0&&e.UpsertEndpoint){let t=n.upsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;o.upsert=j(e.UpsertEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...r!==void 0?{upsertKeys:r}:{}}});}if(n.clone!==void 0&&e.CloneEndpoint){let t=n.clone;o.clone=j(e.CloneEndpoint,{meta:n.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.fieldsToReset!==void 0?{excludeFromClone:t.fieldsToReset}:{}}});}return o}export{vt as $,we as A,oo as Aa,lt as B,ae as Ba,ct as C,nn as Ca,pt as D,rn as Da,ut as E,sn as Ea,Me as F,an as Fa,mt as G,dn as Ga,Ao as H,ln as Ha,ft as I,cn as Ia,ht as J,Ie as Ja,gt as K,ve as Ka,bt as L,Ae as La,wt as M,_e as Ma,Mt as N,He as Na,yt as O,Te as Oa,Et as P,pn as Pa,kt as Q,un as Qa,xt as R,Ot as S,St as T,Ct as U,No as V,jt as W,Pt as X,Yt as Y,Ft as Z,It as _,tt as a,At as aa,Ee as b,_t as ba,ro as c,Zo as ca,po as d,Y as da,mo as e,Ce as ea,yo as f,zo as fa,Zt as g,je as ga,xo as h,Ht as ha,zt as i,qo as ia,ce as j,$o as ja,B as k,Wo as ka,rt as l,Tt as la,st as m,Nt as ma,it as n,ri as na,at as o,Go as oa,Lt as p,Bt as pa,ke as q,Qo as qa,J as r,Jo as ra,se as s,Dt as sa,xe as t,Yo as ta,Oe as u,to as ua,Po as v,Fe as va,ie as w,Xo as wa,U as x,en as xa,Fo as y,tn as ya,Se as z,on as za};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {e,f}from'./chunk-5FV7DBVK.js';import {i}from'./chunk-IIMTJZBX.js';import {q as q$1}from'./chunk-YU6P3NGZ.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {b as b$1,a}from'./chunk-VJRDAVID.js';import {z}from'zod';import {decode,verify}from'hono/jwt';var q=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 Z(e){return q.parse(e)}function G(e){return q.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 R(e$1,t={}){let{clockTolerance:n=0,issuer:r,audience:s,skipTimeValidation:o=false}=t;if(!o){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(s!==void 0){let i=Array.isArray(s)?s:[s],u=Array.isArray(e$1.aud)?e$1.aud:[e$1.aud];if(!i.some(f=>u.includes(f)))throw new e("Invalid token audience")}}function V(e){if(!["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"].includes(e))throw new Error(`Unsupported algorithm: ${e}`);return e}function X(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 Y(e){return {id:String(e.sub||e.id||""),email:e.email,roles:e.roles||e.role,permissions:e.permissions,metadata:e.metadata}}function S(e$1){let t=V(e$1.algorithm||"HS256"),n=e$1.clockTolerance||0,r=e$1.extractToken||X,s=e$1.extractUser||Y;return async(o,i)=>{let u=r(o);if(!u)throw new e("Missing authentication token");let l=decode(u);if(!l||!l.header)throw new e("Invalid token format");if(l.header.alg!==t)throw new e("Invalid token algorithm");let f;try{f=await verify(u,e$1.secret,t);}catch(g){if(g instanceof Error){if(g.message.includes("expired")||g.name==="JwtTokenExpired")throw new e("Token has expired");if(g.message.includes("signature")||g.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(g.message.includes("not valid yet")||g.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let m=f;R(m,{clockTolerance:n,issuer:e$1.issuer,audience:e$1.audience});let h=s(m);o.set("userId",h.id),o.set("user",h),o.set("roles",h.roles||[]),o.set("permissions",h.permissions||[]),o.set("authType","jwt"),await i();}}async function Q(e$1,t){let n=V(t.algorithm||"HS256"),r=t.clockTolerance||0,s=decode(e$1);if(!s||!s.header)throw new e("Invalid token format");if(s.header.alg!==n)throw new e("Invalid token algorithm");let o;try{o=await verify(e$1,t.secret,n);}catch(u){if(u instanceof Error){if(u.message.includes("expired")||u.name==="JwtTokenExpired")throw new e("Token has expired");if(u.message.includes("signature")||u.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(u.message.includes("not valid yet")||u.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let i=o;return R(i,{clockTolerance:r,issuer:t.issuer,audience:t.audience}),i}function ee(e){try{let t=decode(e);return !t||!t.header||!t.payload?null:{header:t.header,payload:t.payload}}catch{return null}}function C(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 b(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),s=new Uint8Array(r);return Array.from(s).map(o=>o.toString(16).padStart(2,"0")).join("")}function te(e){return {id:e.userId,roles:e.roles,permissions:e.permissions,metadata:{...e.metadata,apiKeyId:e.id,apiKeyName:e.name}}}function re(e,t){return e.req.header(t)||null}function ne(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||b,s=e$1.extractUser||te;return async(o,i)=>{let u=re(o,t);if(!u&&n&&(u=ne(o,n)),!u)throw new e("Missing API key");let l=await r(u),f=await e$1.lookupKey(l),m=C(f),h=s(m);o.set("userId",h.id),o.set("user",h),o.set("roles",h.roles||[]),o.set("permissions",h.permissions||[]),o.set("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||b)(e),s=await t.lookupKey(r);return C(s)}function O(e$1){let t=e$1.requireAuth??true,n=e$1.skipPaths||[],r=e$1.unauthorizedMessage||"Unauthorized",s=e$1.authOrder||["jwt","api-key"],o=e$1.jwt?S(e$1.jwt):null,i$1=e$1.apiKey?U(e$1.apiKey):null;return async(u,l)=>{let f=u.req.path;if(i(f,n))return u.set("authType","none"),l();let m=false,h=null;for(let g of s)try{if(g==="jwt"&&o&&u.req.header("Authorization")?.toLowerCase().startsWith("bearer ")){await o(u,async()=>{}),m=!0;break}if(g==="api-key"&&i$1){let y=e$1.apiKey?.headerName||"X-API-Key",x=e$1.apiKey?.queryParam;if(u.req.header(y)||x&&u.req.query(x)){await i$1(u,async()=>{}),m=!0;break}}}catch(y){h=y instanceof Error?y:new Error(String(y));}if(!m){if(t)throw h instanceof e?h:new e(r);u.set("authType","none");}await l();}}function oe(e){return O({...e,requireAuth:false})}function ie(e){return O({...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 s=await this.get(t);if(!s)throw new Error(`Pending action ${t} not found`);if(s.status!=="pending")throw new Error(`Pending action ${t} cannot be rejected from status '${s.status}'`);this.store.set(t,{...s,status:"rejected",rejectedBy:n,rejectedReason:r});}clear(){this.store.clear();}};var ae=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;function K(e){let t=ae.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,s,o]=t,i=(n?Number(n)*864e5:0)+(r?Number(r)*36e5:0)+(s?Number(s)*6e4:0)+(o?Number(o)*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 ue(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var M,B=false;function de(){return M||(M=new E),B||(B=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.")),M}var L="__honoCrudPolicies";function le(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let s=r.roles||[];if(!e$1.some(i=>s.includes(i)))throw new f("Insufficient permissions");await n();}}function ce(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let s=r.roles||[];if(!e$1.every(i=>s.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 s=r.permissions||[];if(!e$1.every(i=>s.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 s=r.permissions||[];if(!e$1.some(i=>s.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 ge(e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let s=await e$1(t);if(r.id!==s)throw new f("Access denied: not resource owner");await n();}}function fe(e$1,...t){return async(n,r)=>{let s=n.var.user;if(!s)throw new e("Authentication required");let o=s.roles||[];if(t.some(l=>o.includes(l))){await r();return}let u=await e$1(n);if(s.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 ye(...e){return async(t,n)=>{let r=null;for(let s of e)try{await s(t,async()=>{}),await n();return}catch(o){r=o instanceof Error?o:new Error(String(o));}throw r||new f("Access denied")}}function we(e="Access denied"){return async()=>{throw new f(e)}}function Ee(){return async(e,t)=>{await t();}}function xe(){return async(e$1,t)=>{if(!e$1.var.user)throw new e("Authentication required");await t();}}function ve(e){return async(t,n)=>{b$1(t,L,e),await n();}}function Pe(e){let t=e.approvalStorage??de(),n=e.resumeMarker??"_resume_",r=K(e.expiresAfter??"P1D"),s=z.object({[n]:z.string()}).loose();return async(o,i)=>{let u={};try{let w=await o.req.json();ue(w)&&(u=w);}catch{}let l=s.safeParse(u).data?.[n];if(l){let w=await t.get(l);if(!w)throw new f(`Pending action ${l} not found`);if(w.status==="expired")throw new f(`Pending action ${l} has expired`);if(w.status!=="approved")throw new f(`Pending action ${l} is ${w.status}, cannot resume`);Re(o,w.input),await i();return}let f$1=a(o,"userId"),m=a(o,"agentId"),h=a(o,"agentRunId"),g=a(o,"onBehalfOfUserId"),y=a(o,"toolCallId"),x=a(o,"tenantId"),H=a(o,"organizationId"),F=a(o,"actionSource")??(m?"agent-mcp":"http"),W=Date.now(),v={id:crypto.randomUUID(),tenantId:x,organizationId:H,userId:f$1,actorUserId:f$1,onBehalfOfUserId:g,agentId:m,agentRunId:h,toolCallId:y,source:F,toolName:e.toolName??`${o.req.method} ${o.req.path}`,input:u,status:"pending",createdAt:new Date(W).toISOString(),expiresAt:new Date(W+r).toISOString(),reason:e.reason};return await t.create(v),o.json({status:"pending",actionId:v.id,expiresAt:v.expiresAt,reason:v.reason},202)}}function Re(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 j(e,t){try{return e.req.valid(t)}catch{return}}function I(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 s=j(t,"json");if(s===void 0)try{s=await t.req.json();}catch{}s!==void 0&&(r.body=s);}if(n.request?.query){let s=j(t,"query");s===void 0&&(s=t.req.query()),s!==void 0&&(r.query=s);}if(n.request?.params){let s=j(t,"param");s===void 0&&(s=t.req.param()),s!==void 0&&(r.params=s);}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 I(this.getContext(),t,n)}getResponseEnvelope(){return this.context?this.context?.var?.[q$1]??void 0:void 0}success(t,n=200){let r=this.getResponseEnvelope(),s=r?r.success(t):{success:true,result:t};return I(this.getContext(),s,n)}successPaginated(t,n,r=200){let s=this.getResponseEnvelope(),o=s?s.success(t,n):{success:true,result:t,result_info:n};return I(this.getContext(),o,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,s){let o={code:n,message:t};s&&(o.details=s);let i=this.getResponseEnvelope(),u=i?i.error(o):{success:false,error:o};return I(this.getContext(),u,r)}};function nt(e){return typeof e=="function"&&"isRoute"in e&&e.isRoute===true}var J=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 s=n.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(i=>s.includes(i)))throw new f(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(i=>s.includes(i)))throw new f(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let s=n.permissions||[];if(!this.requiredPermissions.every(i=>s.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 Ce(e$1){class t extends e$1{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(r,s){return true}getUser(){let s=this.getContext().var.user;if(!s)throw new e("Authentication required");return s}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 s=this.getUserOrNull();return s?(s.roles||[]).includes(r):false}hasAnyRole(...r){let s=this.getUserOrNull()?.roles||[];return r.some(o=>s.includes(o))}hasAllRoles(...r){let s=this.getUserOrNull()?.roles||[];return r.every(o=>s.includes(o))}hasPermission(r){let s=this.getUserOrNull();return s?(s.permissions||[]).includes(r):false}hasAllPermissions(...r){let s=this.getUserOrNull()?.permissions||[];return r.every(o=>s.includes(o))}hasAnyPermission(...r){let s=this.getUserOrNull()?.permissions||[];return r.some(o=>s.includes(o))}async enforceAuth(){let r=this.getContext();if(this.requiresAuth&&!r.var.user)throw new e("Authentication required");let s=r.var.user;if(!s)return;if(this.requiredRoles&&this.requiredRoles.length>0){let i=s.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(l=>i.includes(l)))throw new f(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(l=>i.includes(l)))throw new f(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let i=s.permissions||[];if(!this.requiredPermissions.every(l=>i.includes(l)))throw new f(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(s,r))throw new f("Access denied")}getSchema(){let r=super.getSchema(),s=this.requiresAuth?[{bearerAuth:[]}]:void 0,o={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:s,responses:{...r.responses,...this.requiresAuth?o:{}}}}}return t}export{Q as A,ee as B,C,b as D,U as E,se as F,O as G,oe as H,ie as I,J,Ce as K,I as a,k as b,nt as c,E as d,K as e,L as f,le as g,ce as h,pe as i,he as j,me as k,ge as l,fe as m,Ae as n,ye as o,we as p,Ee as q,xe as r,ve as s,Pe as t,q as u,Z as v,G as w,R as x,X as y,S as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {l}from'./chunk-OKY6VLJS.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&&!l(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
|
+
import {t}from'./chunk-YU6P3NGZ.js';var i=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=l(t),n=await f(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 l(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 f(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 h(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 y=t("apiKeyStorage");function P(){return y.get()}function A(r){y.set(r);}var u="\0DOUBLE_STAR\0",g="\0SINGLE_STAR\0";function p(r,e){if(e instanceof RegExp)return e.test(r);if(!e.includes("*"))return r===e;let t=e.replace(/\*\*/g,u).replace(/\*/g,g).replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(new RegExp(u,"g"),".*").replace(new RegExp(g,"g"),"[^/]*");return new RegExp(`^${t}$`).test(r)}function c(r,e){for(let t of e)if(p(r,t))return true;return false}function m(r,e,t){return c(r,t)?false:e.length===0?true:c(r,e)}export{i as a,l as b,f as c,h as d,y as e,P as f,A as g,p as h,c as i,m as j};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b as b$3}from'./chunk-4RRFBZNM.js';import {b as b$2}from'./chunk-6FJGKK2V.js';import {h,e as e$1}from'./chunk-IIMTJZBX.js';import {t}from'./chunk-YU6P3NGZ.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {e,a,b}from'./chunk-VJRDAVID.js';function C(e){return e instanceof Error?e:new Error(String(e))}function me(e,t){let n=C(e),r=new Error(`${t}: ${n.message}`);return r.cause=n,r}function Ee(e){return e instanceof Error?e.message:String(e)}function P(e,t){let n=e.toLowerCase();for(let r of t){if(r instanceof RegExp){if(r.test(e))return true;continue}let o=r.toLowerCase();if(o.includes("*")){let g=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${g}$`).test(n))return true}else if(n===o)return true}return false}function v(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(r=>v(r,t));if(typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))P(r,t)?n[r]="[REDACTED]":typeof o=="object"&&o!==null?n[r]=v(o,t):n[r]=o;return n}function J(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=P(r,t)?"[REDACTED]":o;return n}function G(e,t={}){let{ipHeader:n="X-Forwarded-For",trustProxy:r=true}=t;if(r){let g=e.req.header(n);if(g){let f=g.split(",")[0]?.trim();if(f)return f}let y=e.req.header("X-Real-IP")?.trim();if(y)return y;let l=e.req.header("CF-Connecting-IP")?.trim();if(l)return l}let o=e.req.raw;if(o&&typeof o.socket=="object"&&o.socket?.remoteAddress)return o.socket.remoteAddress;if(o?.cf?.ip)return o.cf.ip}function Y(e){return a(e,"userId")}function Te(e,t){return P(e,t)}function F(e,t){return v(e,t)}function D(e,t){return J(e,t)}function Ae(e,t){return h(e,t)}function W(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 Z(e,t="X-Forwarded-For",n=false){return G(e,{ipHeader:t,trustProxy:n||true})}function O(e){let t={};return e.forEach((n,r)=>{t[r.toLowerCase()]=n;}),t}function ee(e){let t={};return new URL(e.req.url).searchParams.forEach((r,o)=>{t[o]=r;}),t}function S(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 te(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 re(e){return Y(e)}function ne(){return e()}var q=t("loggingStorage");function Be(e){q.set(e);}function Ue(){return q.get()}var ye=["authorization","cookie","x-api-key","x-auth-token"],xe=["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 Ve(e){return a(e,"requestId")}function Me(e){return a(e,"requestStartTime")}function Ne(e={}){let t=e.enabled??true,n=e.level??"info",r=e.includePaths??[],o=e.excludePaths??he,g=e.redactHeaders??ye,y=e.redactBodyFields??xe,l=e.requestBody??{enabled:false},f=e.responseBody??{enabled:false},_=e.includeHeaders??true,se=e.includeQuery??true,ae=e.includeClientIp??true,ie=e.ipHeader??"X-Forwarded-For",de=e.trustProxy??false,ue=e.minResponseTimeMs??0,ce=e.generateRequestId??ne;return async(s,I)=>{if(!t)return I();let K=s.req.path;if(W(K,r,o))return I();let L=ce(),k=Date.now();b(s,"requestId",L),b(s,"requestStartTime",k),s.header("X-Request-ID",L);let ge=s.req.method,le=s.req.url,z;if(_){let u=O(s.req.raw.headers);z=D(u,g);}let B;se&&(B=ee(s));let U;ae&&(U=Z(s,ie,de));let fe=re(s),b$2;if(l.enabled){let u=s.req.header("content-type"),x=l.contentTypes??[];if(te(u,x))try{let E=await s.req.raw.clone().text();if(E)try{let d=JSON.parse(E);d=F(d,y);let i=l.maxSize??10240;b$2=S(d,i);}catch{let d=l.maxSize??10240;b$2=S(E,d);}}catch{}}let c,T;try{await I();}catch(u){throw c=u instanceof Error?u:new Error(String(u)),u}finally{let x=Date.now()-k;if(x<ue)return;let m=s.res.status,E;if(_){let a=O(s.res.headers);E=D(a,g);}if(f.enabled&&!c){let a=f.statusCodes??[];if(a.length===0||a.includes(m))try{let A=await s.res.clone().text();if(A)try{let h=JSON.parse(A);h=F(h,y);let pe=f.maxSize??10240;T=S(h,pe);}catch{let h=f.maxSize??10240;T=S(A,h);}}catch{}}let d=n;e.levelResolver?d=e.levelResolver(s,x,m,c):c||m>=500?d="error":m>=400&&(d="warn");let i={id:L,timestamp:new Date(k).toISOString(),level:d,request:{method:ge,path:K,url:le,headers:z,query:B,body:b$2,clientIp:U,userId:fe},response:{statusCode:m,headers:E,body:T,responseTimeMs:x}};if(c&&(i.error={message:c.message,name:c.name,stack:c.stack}),e.metadata){let a=typeof e.metadata=="function"?e.metadata(s):e.metadata;i.metadata=a;}e.formatter&&(i=e.formatter(i));let V=oe(s,e.storage);(async()=>{if(V)try{await V.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(p){e.onError&&e.onError(p instanceof Error?p:new Error(String(p)),i);}})().catch(a=>{let p=C(a);e.onError?e.onError(p,i):b$1().error("Failed to process log entry",{error:p.message});});}}}function oe(e,t){return q.resolve(e,t)}function Ge(e,t){return b$2.resolve(e,t)}function Ye(e,t){return b$3.resolve(e,t)}function We(e,t){return e$1.resolve(e,t)}export{oe as a,Ge as b,Ye as c,We as d,C as e,me as f,Ee as g,G as h,Te as i,F as j,D as k,Ae as l,W as m,Z as n,O as o,ee as p,S as q,te as r,re as s,ne as t,Be as u,Ue as v,Ve as w,Me as x,Ne as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-VJRDAVID.js';function T(e){return btoa(String(e))}function C(e){try{return atob(e)}catch{return null}}function w(e,t){let n={},r={};for(let[a,o]of Object.entries(e))t.includes(a)&&o!==void 0?r[a]=o:n[a]=o;return {mainData:n,nestedData:r}}function k(e){if(Array.isArray(e))return true;if(typeof e=="object"&&e!==null){let t=Object.keys(e),n=["create","update","delete","connect","disconnect","set"];return !t.some(r=>n.includes(r))}return false}function R(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 S(e,t,n=[]){let r=[];if(!e&&!t)return r;let a=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let o of a){if(n.includes(o))continue;let l=e?.[o],u=t?.[o],f=JSON.stringify(l),x=JSON.stringify(u);f!==x&&r.push({field:o,oldValue:l,newValue:u});}return r}function v(e,t){return !e||!e.enabled?{enabled:false,field:"version",historyTable:`${t}_history`,maxVersions:null,trackChangedBy:false,excludeFields:[]}:{enabled:true,field:e.field||"version",historyTable:e.historyTable||`${t}_history`,maxVersions:e.maxVersions??null,trackChangedBy:e.trackChangedBy??false,excludeFields:e.excludeFields||[],getUserId:e.getUserId}}function A(e){let t=e.split(":");if(t.length<2)return null;let n=t[0].toLowerCase();return ["count","sum","avg","min","max","countdistinct"].includes(n)?{operation:n==="countdistinct"?"countDistinct":n,field:t[1],alias:t[2]}:null}function I(e){let t=[],n={},r=["count","sum","avg","min","max","countDistinct"];for(let i of r){let s=e[i];if(s){let g=Array.isArray(s)?s:[s];for(let d of g)typeof d=="string"&&t.push({operation:i,field:d==="true"||d===""?"*":d});}}let a;if(e.groupBy){let i=e.groupBy;typeof i=="string"?a=i.split(",").map(s=>s.trim()):Array.isArray(i)&&(a=i.filter(s=>typeof s=="string"));}let o;for(let[i,s]of Object.entries(e)){let g=i.match(/^having\[(\w+)\]\[(\w+)\]$/);if(g){let[,d,y]=g;o||(o={}),o[d]||(o[d]={}),o[d][y]=s;}}let l=typeof e.orderBy=="string"?e.orderBy:void 0,u=e.orderDirection==="desc"?"desc":"asc",f=typeof e.limit=="string"?Number.parseInt(e.limit,10):void 0,x=typeof e.offset=="string"?Number.parseInt(e.offset,10):void 0,m=[...r,"groupBy","orderBy","orderDirection","limit","offset"];for(let[i,s]of Object.entries(e))!m.includes(i)&&!i.startsWith("having[")&&(n[i]=s);return {aggregations:t,groupBy:a,filters:Object.keys(n).length>0?n:void 0,having:o,orderBy:l,orderDirection:u,limit:f,offset:x}}async function b(e,t){if(!t||Object.keys(t).length===0)return e;let n={...e};for(let[r,a]of Object.entries(t))try{let o=await a.compute(e);n[r]=o;}catch{n[r]=void 0;}return n}async function F(e,t){return !t||Object.keys(t).length===0?e:Promise.all(e.map(n=>b(n,t)))}function P(e){return e}function O(e){return e}function M(e){return e?e===true?{enabled:true,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}:{enabled:true,field:e.field??"deletedAt",allowQueryDeleted:e.allowQueryDeleted??true,queryParam:e.queryParam??"withDeleted"}:{enabled:false,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}}function D(e){let t={enabled:false,field:"tenantId",source:"context",headerName:"X-Tenant-ID",contextKey:"tenantId",pathParam:"tenantId",required:true,errorMessage:"Tenant ID is required"};return e?e===true?{...t,enabled:true}:{enabled:true,field:e.field??t.field,source:e.source??t.source,headerName:e.headerName??t.headerName,contextKey:e.contextKey??t.contextKey,pathParam:e.pathParam??t.pathParam,getTenantId:e.getTenantId,required:e.required??t.required,errorMessage:e.errorMessage??t.errorMessage}:t}function N(e,t){if(t.enabled)switch(t.source){case "header":return e.req.header(t.headerName);case "context":return a(e,t.contextKey);case "path":return e.req.param(t.pathParam);case "custom":return t.getTenantId?t.getTenantId(e):void 0;default:return}}var E="__honoCrudResponseEnvelope__";function z(e){return e==="all"||e==="phrase"?e:"any"}var p=class{globalStorage=null;contextKey;defaultFactory;defaultInitialized=false;constructor(t,n){this.contextKey=t,this.defaultFactory=n??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,n){if(n)return n;if(t){let r=a(t,this.contextKey);if(r)return r}return this.globalStorage}resolveRequired(t,n){let r=this.resolve(t,n);if(r===null)throw new Error(`Storage not configured for '${this.contextKey}'`);return r}reset(){this.defaultInitialized=false,this.globalStorage=null;}getContextKey(){return this.contextKey}isConfigured(){return this.globalStorage!==null}};function j(e){return new p(e)}function Z(e,t){return new p(e,t)}export{T as a,C as b,w as c,k as d,R as e,S as f,v as g,A as h,I as i,b as j,F as k,P as l,O as m,M as n,D as o,N as p,E as q,z as r,p as s,j as t,Z as u};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { ad as OpenAPIRouteSchema, ar as RouteOptions, aD as ValidatedData, ap as ResponseEnvelope, aq as ResponseEnvelopeInfo, s as AuthEnv, X as JWTConfig, U as JWTClaims, e as APIKeyConfig, f as APIKeyEntry, r as AuthConfig, I as Guard, p as ApprovalConfig, v as AuthorizationCheck, ae as OwnershipExtractor, a0 as ModelPolicies, q as ApprovalStorage, ah as PendingAction, u as AuthUser, _ as MetaInput, B as Constructor, E as EndpointAuthConfig, aZ as APIKeyStorage, g as APIKeyLookupResult } from './types-
|
|
1
|
+
import { ad as OpenAPIRouteSchema, ar as RouteOptions, aD as ValidatedData, ap as ResponseEnvelope, aq as ResponseEnvelopeInfo, s as AuthEnv, X as JWTConfig, U as JWTClaims, e as APIKeyConfig, f as APIKeyEntry, r as AuthConfig, I as Guard, p as ApprovalConfig, v as AuthorizationCheck, ae as OwnershipExtractor, a0 as ModelPolicies, q as ApprovalStorage, ah as PendingAction, u as AuthUser, _ as MetaInput, B as Constructor, E as EndpointAuthConfig, aZ as APIKeyStorage, g as APIKeyLookupResult } from './types-TTTI3ADY.js';
|
|
2
2
|
import { Env, Context, MiddlewareHandler } from 'hono';
|
|
3
|
-
import { ZodObject, ZodRawShape } from 'zod';
|
|
4
3
|
import { ContentfulStatusCode } from 'hono/utils/http-status';
|
|
4
|
+
import { ZodObject, ZodRawShape } from 'zod';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Base class for OpenAPI routes.
|
|
@@ -91,6 +91,12 @@ declare function isRouteClass(cls: unknown): cls is typeof OpenAPIRoute & {
|
|
|
91
91
|
isRoute: true;
|
|
92
92
|
};
|
|
93
93
|
|
|
94
|
+
/**
|
|
95
|
+
* Default function to extract a Bearer token from the `Authorization` header.
|
|
96
|
+
* Exported via `hono-crud/internal` so first-party addons (e.g. `@hono-crud/mcp`)
|
|
97
|
+
* can reuse the same extraction logic instead of reimplementing it.
|
|
98
|
+
*/
|
|
99
|
+
declare function defaultExtractToken(ctx: Context): string | null;
|
|
94
100
|
/**
|
|
95
101
|
* Creates JWT authentication middleware using Hono's built-in JWT helpers.
|
|
96
102
|
*
|
|
@@ -761,4 +767,4 @@ declare function validateJWTClaims(claims: JWTClaims, options?: JWTClaimsValidat
|
|
|
761
767
|
*/
|
|
762
768
|
declare function validateAPIKeyEntry(entry: APIKeyEntry | null): APIKeyEntry;
|
|
763
769
|
|
|
764
|
-
export { type AuthEndpointMethods as A,
|
|
770
|
+
export { type AuthEndpointMethods as A, requireOwnershipOrRole as B, requirePermissions as C, requirePolicy as D, requireRoles as E, setAPIKeyStorage as F, validateAPIKey as G, validateAPIKeyEntry as H, validateJWTClaims as I, type JWTClaimsValidationOptions as J, verifyJWT as K, withAuth as L, MemoryAPIKeyStorage as M, OpenAPIRoute as O, POLICIES_CONTEXT_KEY as P, AuthenticatedEndpoint as a, MemoryApprovalStorage as b, allOf as c, allowAll as d, anyOf as e, createAPIKeyMiddleware as f, createAuthMiddleware as g, createJWTMiddleware as h, decodeJWT as i, defaultHashAPIKey as j, denyAll as k, defaultExtractToken as l, generateAPIKey as m, getAPIKeyStorage as n, hashAPIKey as o, isRouteClass as p, isValidAPIKeyFormat as q, optionalAuth as r, parseIso8601Duration as s, requireAllRoles as t, requireAnyPermission as u, requireApproval as v, requireAuth as w, requireAuthenticated as x, requireAuthentication as y, requireOwnership as z };
|