hono-crud 0.13.7 → 0.13.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/api-version/index.js +1 -1
  3. package/dist/audit/index.d.ts +2 -2
  4. package/dist/auth/index.d.ts +4 -4
  5. package/dist/auth/index.js +1 -1
  6. package/dist/{chunk-65NCGRBB.js → chunk-2T3DGA4L.js} +1 -1
  7. package/dist/chunk-6MS7YXSZ.js +1 -0
  8. package/dist/chunk-A3O6KC4L.js +1 -0
  9. package/dist/chunk-J6WCEEO4.js +1 -0
  10. package/dist/chunk-MGYAQGMG.js +1 -0
  11. package/dist/{chunk-5UM6RIIB.js → chunk-MKMMXMDX.js} +1 -1
  12. package/dist/chunk-PTJBZTQA.js +11 -0
  13. package/dist/{chunk-BPBFNTBM.js → chunk-STAO4FWC.js} +1 -1
  14. package/dist/{chunk-SC5G6HH3.js → chunk-WKCG5D5U.js} +1 -1
  15. package/dist/{chunk-CVNB5GB5.js → chunk-XCDY63Q6.js} +1 -1
  16. package/dist/config/index.d.ts +5 -5
  17. package/dist/config/index.js +1 -1
  18. package/dist/{emitter-CmtYDwNp.d.ts → emitter-B7QIE5f9.d.ts} +7 -2
  19. package/dist/encryption/index.d.ts +3 -2
  20. package/dist/encryption/index.js +1 -1
  21. package/dist/events/index.d.ts +4 -4
  22. package/dist/events/index.js +1 -1
  23. package/dist/functional/index.d.ts +5 -8
  24. package/dist/functional/index.js +1 -1
  25. package/dist/{index-Biz6ZLmk.d.ts → index-Coira0ZO.d.ts} +158 -38
  26. package/dist/{index-DJAdPTsm.d.ts → index-DVizFuqF.d.ts} +15 -180
  27. package/dist/{index-B6a8YXS1.d.ts → index-Rm1UKAWZ.d.ts} +2 -2
  28. package/dist/index.d.ts +8 -8
  29. package/dist/index.js +1 -1
  30. package/dist/internal.d.ts +10 -10
  31. package/dist/internal.js +1 -1
  32. package/dist/multi-tenant/index.js +1 -1
  33. package/dist/{route-cu4t0BCp.d.ts → route-BsBxrEW1.d.ts} +1 -1
  34. package/dist/storage/index.d.ts +3 -3
  35. package/dist/{types-BK-mxapm.d.ts → types-Bfdb_zwM.d.ts} +2 -5
  36. package/dist/{types-CR_0ycjq.d.ts → types-CmzJjItf.d.ts} +143 -60
  37. package/dist/{types-BAcN7U0B.d.ts → types-Drjma4gp.d.ts} +16 -11
  38. package/dist/versioning/index.d.ts +2 -2
  39. package/package.json +1 -1
  40. package/dist/chunk-5FV7DBVK.js +0 -1
  41. package/dist/chunk-5WYS3YRT.js +0 -1
  42. package/dist/chunk-CKUGVMFX.js +0 -1
  43. package/dist/chunk-DZ3EM3AE.js +0 -1
  44. package/dist/chunk-FCBFFSE3.js +0 -11
package/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.8
4
+
5
+ ### Patch Changes
6
+
7
+ - f8e5208: `multiTenant()` now fails fast on an inconsistent configuration. Previously, `source: 'custom'` without an `extractor` silently extracted `undefined` on every request and surfaced as a misleading `400 "Tenant ID is required"` (a misconfiguration masquerading as a client error). It now throws a clear setup-time error pointing at the missing `extractor`.
8
+ - 3ab0514: Internal: complete the OpenAPI metadata migration to Zod v4's `.meta()` registry — the remaining `.describe()` calls (read/export/import endpoint query parameters) now use `.meta()`, so the entire core no longer uses `.describe()`. The OpenAPI snapshot fixture was expanded to cover the export/import endpoints, and the generated output is unchanged (the snapshot is byte-for-byte identical after the migration). No consumer-facing change.
9
+ - 0538c4a: Internal: migrate the list/search query-parameter OpenAPI metadata from `.describe()` to Zod v4's `.meta()` metadata registry, and add a byte-for-byte OpenAPI snapshot test that guards the generated document against regressions. The emitted OpenAPI output is unchanged (the snapshot proves it) — this is a modernization to the canonical Zod v4 metadata API with no consumer-facing impact.
10
+ - b880e53: Type-safety hardening (phase 1): eliminate type/schema drift and silent fall-throughs.
11
+
12
+ - **Unify `HonoOpenAPIApp`.** The publicly re-exported type was a 4-verb subset that disagreed with the 7-verb superset `fromHono` actually returns; both now resolve to one canonical definition, so typing the documented `HonoOpenAPIApp` and calling `.options()`/`.head()`/`.doc()` type-checks.
13
+ - **Closed-union exhaustiveness.** Filter-operator handling now goes through a single shared `matchesFilter` in the in-memory adapter (the four copy-pasted switches had drifted — one was missing `between` and silently matched every row), and the Drizzle/Prisma/aggregate switches gained `assertNever` exhaustiveness guards so a future operator is a compile error rather than a silent gap.
14
+ - **Validate untrusted filter operators.** `parseFilterValue` no longer blindly casts an unrecognized `field[op]=value` token to `FilterOperator` (which downstream adapters silently ignored, disabling the filter); unknown operators now fall back to literal equality. `FilterOperator` is now derived from a single `as const` `FILTER_OPERATORS` source with an `isFilterOperator` guard.
15
+ - **Scalar config.** `@hono-crud/scalar` no longer escapes its own typing via `as Record<string, unknown>`; `ScalarTheme` is derived from the upstream `ApiReferenceConfiguration` and `scalarUI` has an explicit return type.
16
+ - **De-duplicated casts.** Added a localized `readResponseEnvelope(ctx)` accessor and a Drizzle `readCount`/`CountRow` helper, removing repeated inline casts.
17
+
18
+ New exports: `FILTER_OPERATORS`, `isFilterOperator`, `assertNever`, `readResponseEnvelope` (from `hono-crud`); `readCount`/`CountRow` (from `@hono-crud/drizzle`). All additive; no breaking changes.
19
+
20
+ - a41b5d7: Type-safety hardening (phase 2, deferred items): validate the JWT trust boundary and single-source the error envelope.
21
+
22
+ - **Validate JWT claims (security).** The JWT middleware previously coerced the verified payload to `JWTClaims` with a blind `payload as unknown as JWTClaims` cast — Hono's `verify` checks the signature and `exp`/`nbf` timing but not claim _shapes_, so a structurally malformed payload was trusted. The verified payload now runs through `safeParseJWTClaims`; a payload that fails the schema is rejected with `401 Invalid token claims`. `JWTClaimsSchema` was extended with the identity claims the default extractor reads (`email`, `role`, `roles`, `permissions`, `metadata`), and `JWTClaims` is now derived from it (single source). The wrong `secret as string` cast (which mistyped a `CryptoKey` secret) was removed.
23
+ - **Fix role normalization.** `defaultExtractUser` previously assigned a singular `role` claim straight to `AuthUser.roles`, producing a value mistyped as `string[]`. `role` / single-string `roles` claims are now normalized to a string array.
24
+ - **Single-source the error envelope.** The `{ success: false, error: { code, message, details? } }` contract was hand-restated as TS types in `core/types.ts`, as the return type of `ApiException.toJSON()`, and inline in the idempotency middleware. There is now one `structuredErrorSchema` / `errorEnvelopeSchema` (plus a `successEnvelopeSchema(result)` factory); `StructuredError` and `ErrorResponse` are derived from them via `z.infer`, `ApiException.toJSON()` returns the shared `ErrorResponse`, and the idempotency bodies use a typed helper bound to it.
25
+
26
+ New additive exports: `structuredErrorSchema`, `errorEnvelopeSchema`, `successEnvelopeSchema` (from `hono-crud`).
27
+
28
+ **Behavior change:** JWT tokens whose payloads do not match `JWTClaimsSchema` (e.g. a non-numeric `exp`, a non-string `sub`) are now rejected rather than accepted. This is the intended security tightening; the identity claims are typed leniently (`roles`/`permissions` accept a string or array) to avoid rejecting common real-world token shapes.
29
+
30
+ - 18a86c2: Type-safety hardening (phase 2): derive types from single `as const` / Zod sources so the compile-time union and its runtime validators can no longer drift.
31
+
32
+ - **Union single-sources.** `SortDirection`, `SearchMode`, `AggregateOperation`, `JWTAlgorithm` (core) and `DrizzleDialect` (drizzle) are now derived from exported `as const` arrays (`SORT_DIRECTIONS`, `SEARCH_MODES`, `AGGREGATE_OPERATIONS`, `JWT_ALGORITHMS`, `DRIZZLE_DIALECTS`). The three `z.enum(['asc','desc'])` schemas and the `z.enum(['any','all','phrase'])` schema now reference these arrays, and the aggregate query parser derives its runtime operation lists from `AGGREGATE_OPERATIONS` instead of hand-maintained copies.
33
+ - **Removed a redundant type.** The JWT middleware's `HonoAlgorithm` type and its hand-maintained `supported` allow-list were exact duplicates of `JWTAlgorithm`; both are gone (and with them two casts) — `validateAlgorithm` checks against `JWT_ALGORITHMS` directly.
34
+ - **`SortSpec`.** The repeated inline `{ field: string; order: 'asc' | 'desc' }` shape across list/search/builder/functional/config is now the named `SortSpec` type.
35
+ - **Schema-derived shapes.** `EncryptedValue` is inferred from a new `encryptedValueSchema` and `isEncryptedValue` validates with `.safeParse` (one shape, not a hand-written twin). `CrudEventType` is single-sourced from `CRUD_EVENT_TYPES`, and the webhook event-filter template-literal type derives from it, so a new event type can't silently become unfilterable.
36
+
37
+ New additive exports: `SORT_DIRECTIONS`, `SEARCH_MODES`, `AGGREGATE_OPERATIONS`, `SortDirection`, `SortSpec`, `JWT_ALGORITHMS`, `CRUD_EVENT_TYPES`, `encryptedValueSchema` (from `hono-crud`); `DRIZZLE_DIALECTS`, `readCount`, `CountRow` (from `@hono-crud/drizzle`). All derived types are structurally identical to what they replaced — no breaking changes.
38
+
3
39
  ## 0.13.7
4
40
 
5
41
  ### Patch Changes
@@ -1 +1 @@
1
- export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'../chunk-5UM6RIIB.js';import'../chunk-5FV7DBVK.js';import'../chunk-IJBJE4G2.js';
1
+ export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'../chunk-MKMMXMDX.js';import'../chunk-A3O6KC4L.js';import'../chunk-IJBJE4G2.js';
@@ -1,9 +1,9 @@
1
1
  import { Context, Env } from 'hono';
2
- import { A as AuditConfig, e as AuditLogEntry, f as AuditAction } from '../types-CR_0ycjq.js';
2
+ import { A as AuditConfig, f as AuditLogEntry, g as AuditAction } from '../types-CmzJjItf.js';
3
3
  import { S as StorageRegistry } from '../registry-PNJjvSvm.js';
4
4
  import 'zod';
5
5
  import '../types-DcRAcexC.js';
6
- import '../types-BAcN7U0B.js';
6
+ import '../types-Drjma4gp.js';
7
7
  import '@hono/zod-openapi';
8
8
 
9
9
  /**
@@ -1,9 +1,9 @@
1
- export { j as APIKeyConfig, k as APIKeyEntry, l as APIKeyLookupResult, m as ActionSource, u as ApprovalConfig, v as ApprovalStorage, w as AuthConfig, x as AuthEnv, y as AuthType, z as AuthUser, B as AuthorizationCheck, N as EndpointAuthConfig, S as Guard, a0 as JWTAlgorithm, a1 as JWTClaims, a2 as JWTClaimsSchema, a3 as JWTConfig, ai as OwnershipExtractor, aJ as PathPattern, al as PendingAction, am as PendingActionStatus, aE as ValidatedJWTClaims, aH as parseJWTClaims, aI as safeParseJWTClaims } from '../types-CR_0ycjq.js';
2
- export { A as AuthEndpointMethods, a as AuthenticatedEndpoint, J as JWTClaimsValidationOptions, M as MemoryAPIKeyStorage, b as MemoryApprovalStorage, P as POLICIES_CONTEXT_KEY, c as allOf, d as allowAll, e as anyOf, f as createAPIKeyMiddleware, g as createAuthMiddleware, h as createJWTMiddleware, i as decodeJWT, j as defaultHashAPIKey, k as denyAll, m as generateAPIKey, n as getAPIKeyStorage, o as hashAPIKey, p as isValidAPIKeyFormat, q as optionalAuth, r as parseIso8601Duration, s as requireAllRoles, t as requireAnyPermission, u as requireApproval, v as requireAuth, w as requireAuthenticated, x as requireAuthentication, y as requireOwnership, z as requireOwnershipOrRole, B as requirePermissions, C as requirePolicy, D as requireRoles, E as setAPIKeyStorage, F as validateAPIKey, G as validateAPIKeyEntry, H as validateJWTClaims, I as verifyJWT, K as withAuth } from '../index-B6a8YXS1.js';
1
+ export { l as APIKeyConfig, m as APIKeyEntry, n as APIKeyLookupResult, o as ActionSource, w as ApprovalConfig, x as ApprovalStorage, y as AuthConfig, z as AuthEnv, B as AuthType, C as AuthUser, D as AuthorizationCheck, Q as EndpointAuthConfig, X as Guard, a4 as JWTAlgorithm, a5 as JWTClaims, a6 as JWTClaimsSchema, a7 as JWTConfig, a8 as JWT_ALGORITHMS, an as OwnershipExtractor, aV as PathPattern, aq as PendingAction, ar as PendingActionStatus, aL as ValidatedJWTClaims, aR as parseJWTClaims, aS as safeParseJWTClaims } from '../types-CmzJjItf.js';
2
+ export { A as AuthEndpointMethods, a as AuthenticatedEndpoint, J as JWTClaimsValidationOptions, M as MemoryAPIKeyStorage, b as MemoryApprovalStorage, P as POLICIES_CONTEXT_KEY, c as allOf, d as allowAll, e as anyOf, f as createAPIKeyMiddleware, g as createAuthMiddleware, h as createJWTMiddleware, i as decodeJWT, j as defaultHashAPIKey, k as denyAll, m as generateAPIKey, n as getAPIKeyStorage, o as hashAPIKey, p as isValidAPIKeyFormat, q as optionalAuth, r as parseIso8601Duration, s as requireAllRoles, t as requireAnyPermission, u as requireApproval, v as requireAuth, w as requireAuthenticated, x as requireAuthentication, y as requireOwnership, z as requireOwnershipOrRole, B as requirePermissions, C as requirePolicy, D as requireRoles, E as setAPIKeyStorage, F as validateAPIKey, G as validateAPIKeyEntry, H as validateJWTClaims, I as verifyJWT, K as withAuth } from '../index-Rm1UKAWZ.js';
3
3
  import 'hono';
4
4
  import 'zod';
5
5
  import '../types-DcRAcexC.js';
6
- import '../types-BAcN7U0B.js';
6
+ import '../types-Drjma4gp.js';
7
7
  import '@hono/zod-openapi';
8
- import '../route-cu4t0BCp.js';
8
+ import '../route-BsBxrEW1.js';
9
9
  import 'hono/utils/http-status';
@@ -1 +1 @@
1
- export{M as AuthenticatedEndpoint,x as JWTClaimsSchema,g as MemoryApprovalStorage,i as POLICIES_CONTEXT_KEY,q as allOf,t as allowAll,r as anyOf,H as createAPIKeyMiddleware,J as createAuthMiddleware,C as createJWTMiddleware,E as decodeJWT,G as defaultHashAPIKey,s as denyAll,K as optionalAuth,h as parseIso8601Duration,y as parseJWTClaims,k as requireAllRoles,m as requireAnyPermission,w as requireApproval,n as requireAuth,u as requireAuthenticated,L as requireAuthentication,o as requireOwnership,p as requireOwnershipOrRole,l as requirePermissions,v as requirePolicy,j as requireRoles,z as safeParseJWTClaims,I as validateAPIKey,F as validateAPIKeyEntry,A as validateJWTClaims,D as verifyJWT,N as withAuth}from'../chunk-CKUGVMFX.js';export{a as MemoryAPIKeyStorage,b as generateAPIKey,f as getAPIKeyStorage,c as hashAPIKey,d as isValidAPIKeyFormat,g as setAPIKeyStorage}from'../chunk-4NKDESHS.js';import'../chunk-5FV7DBVK.js';import'../chunk-DMGP7QDL.js';import'../chunk-ZJWDAVGG.js';import'../chunk-VJRDAVID.js';import'../chunk-IJBJE4G2.js';
1
+ export{X as AuthenticatedEndpoint,I as JWTClaimsSchema,H as JWT_ALGORITHMS,q as MemoryApprovalStorage,s as POLICIES_CONTEXT_KEY,A as allOf,D as allowAll,B as anyOf,S as createAPIKeyMiddleware,U as createAuthMiddleware,N as createJWTMiddleware,P as decodeJWT,R as defaultHashAPIKey,C as denyAll,V as optionalAuth,r as parseIso8601Duration,J as parseJWTClaims,u as requireAllRoles,w as requireAnyPermission,G as requireApproval,x as requireAuth,E as requireAuthenticated,W as requireAuthentication,y as requireOwnership,z as requireOwnershipOrRole,v as requirePermissions,F as requirePolicy,t as requireRoles,K as safeParseJWTClaims,T as validateAPIKey,Q as validateAPIKeyEntry,L as validateJWTClaims,O as verifyJWT,Y as withAuth}from'../chunk-J6WCEEO4.js';export{a as MemoryAPIKeyStorage,b as generateAPIKey,f as getAPIKeyStorage,c as hashAPIKey,d as isValidAPIKeyFormat,g as setAPIKeyStorage}from'../chunk-4NKDESHS.js';import'../chunk-A3O6KC4L.js';import'../chunk-DMGP7QDL.js';import'../chunk-ZJWDAVGG.js';import'../chunk-VJRDAVID.js';import'../chunk-IJBJE4G2.js';
@@ -1 +1 @@
1
- import {a}from'./chunk-BPBFNTBM.js';function s(o,t){let d={};if(o.create!==void 0){let e=o.create;d.create=a(t.CreateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,allowNestedCreate:e.nestedCreate,before:e.hooks?.before,after:e.hooks?.after});}if(o.list!==void 0){let e=o.list;d.list=a(t.ListEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,filterFields:e.filtering?.fields,filterConfig:e.filtering?.config,searchFields:e.search?.fields,searchFieldName:e.search?.paramName,sortFields:e.sorting?.fields,defaultSort:e.sorting?.default?{field:e.sorting.default,order:e.sorting.defaultOrder??e.sorting.defaultDirection??"asc"}:void 0,defaultPerPage:e.pagination?.defaultPerPage,maxPerPage:e.pagination?.maxPerPage,allowedIncludes:e.includes,fieldSelectionEnabled:e.fieldSelection?.enabled,allowedSelectFields:e.fieldSelection?.allowed,blockedSelectFields:e.fieldSelection?.blocked,alwaysIncludeFields:e.fieldSelection?.alwaysInclude,defaultSelectFields:e.fieldSelection?.defaults,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.read!==void 0){let e=o.read;d.read=a(t.ReadEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedIncludes:e.includes,fieldSelectionEnabled:e.fieldSelection?.enabled,allowedSelectFields:e.fieldSelection?.allowed,blockedSelectFields:e.fieldSelection?.blocked,alwaysIncludeFields:e.fieldSelection?.alwaysInclude,defaultSelectFields:e.fieldSelection?.defaults,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.update!==void 0){let e=o.update;d.update=a(t.UpdateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedUpdateFields:e.fields?.allowed,blockedUpdateFields:e.fields?.blocked,allowNestedWrites:e.nestedWrites,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.delete!==void 0){let e=o.delete;d.delete=a(t.DeleteEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,lookupField:e.lookupField,additionalFilters:e.additionalFilters,includeCascadeResults:e.includeCascadeResults,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after});}if(o.search!==void 0&&t.SearchEndpoint){let e=o.search,n={};e.fields!==void 0&&(n.searchFields=e.fields),e.mode!==void 0&&(n.defaultMode=e.mode),e.paramName!==void 0&&(n.searchParamName=e.paramName),d.search=a(t.SearchEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,after:e.hooks?.after,extras:n});}if(o.aggregate!==void 0&&t.AggregateEndpoint){let e=o.aggregate,n={};e.fields!==void 0&&(n.filterFields=e.fields),d.aggregate=a(t.AggregateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,after:e.hooks?.after,extras:n});}if(o.restore!==void 0&&t.RestoreEndpoint){let e=o.restore;d.restore=a(t.RestoreEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after});}if(o.batchCreate!==void 0&&t.BatchCreateEndpoint){let e=o.batchCreate,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchCreate=a(t.BatchCreateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchUpdate!==void 0&&t.BatchUpdateEndpoint){let e=o.batchUpdate,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchUpdate=a(t.BatchUpdateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchDelete!==void 0&&t.BatchDeleteEndpoint){let e=o.batchDelete,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchDelete=a(t.BatchDeleteEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchRestore!==void 0&&t.BatchRestoreEndpoint){let e=o.batchRestore,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchRestore=a(t.BatchRestoreEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchUpsert!==void 0&&t.BatchUpsertEndpoint){let e=o.batchUpsert,n=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,r={};e.maxBatchSize!==void 0&&(r.maxBatchSize=e.maxBatchSize),n!==void 0&&(r.upsertKeys=n),d.batchUpsert=a(t.BatchUpsertEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:r});}if(o.export!==void 0&&t.ExportEndpoint){let e=o.export,n={};e.maxRows!==void 0&&(n.maxExportRecords=e.maxRows),e.formats!==void 0&&e.formats.length>0&&(n.defaultFormat=e.formats[0]),d.export=a(t.ExportEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,extras:n});}if(o.import!==void 0&&t.ImportEndpoint){let e=o.import,n={};e.maxRows!==void 0&&(n.maxBatchSize=e.maxRows),d.import=a(t.ImportEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.upsert!==void 0&&t.UpsertEndpoint){let e=o.upsert,n=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,r={};n!==void 0&&(r.upsertKeys=n),d.upsert=a(t.UpsertEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:r});}if(o.clone!==void 0&&t.CloneEndpoint){let e=o.clone,n={};e.fieldsToReset!==void 0&&(n.excludeFromClone=e.fieldsToReset),d.clone=a(t.CloneEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:n});}return d}export{s as a};
1
+ import {a}from'./chunk-STAO4FWC.js';function s(o,t){let d={};if(o.create!==void 0){let e=o.create;d.create=a(t.CreateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,allowNestedCreate:e.nestedCreate,before:e.hooks?.before,after:e.hooks?.after});}if(o.list!==void 0){let e=o.list;d.list=a(t.ListEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,filterFields:e.filtering?.fields,filterConfig:e.filtering?.config,searchFields:e.search?.fields,searchFieldName:e.search?.paramName,sortFields:e.sorting?.fields,defaultSort:e.sorting?.default?{field:e.sorting.default,order:e.sorting.defaultOrder??e.sorting.defaultDirection??"asc"}:void 0,defaultPerPage:e.pagination?.defaultPerPage,maxPerPage:e.pagination?.maxPerPage,allowedIncludes:e.includes,fieldSelectionEnabled:e.fieldSelection?.enabled,allowedSelectFields:e.fieldSelection?.allowed,blockedSelectFields:e.fieldSelection?.blocked,alwaysIncludeFields:e.fieldSelection?.alwaysInclude,defaultSelectFields:e.fieldSelection?.defaults,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.read!==void 0){let e=o.read;d.read=a(t.ReadEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedIncludes:e.includes,fieldSelectionEnabled:e.fieldSelection?.enabled,allowedSelectFields:e.fieldSelection?.allowed,blockedSelectFields:e.fieldSelection?.blocked,alwaysIncludeFields:e.fieldSelection?.alwaysInclude,defaultSelectFields:e.fieldSelection?.defaults,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.update!==void 0){let e=o.update;d.update=a(t.UpdateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedUpdateFields:e.fields?.allowed,blockedUpdateFields:e.fields?.blocked,allowNestedWrites:e.nestedWrites,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.delete!==void 0){let e=o.delete;d.delete=a(t.DeleteEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,lookupField:e.lookupField,additionalFilters:e.additionalFilters,includeCascadeResults:e.includeCascadeResults,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after});}if(o.search!==void 0&&t.SearchEndpoint){let e=o.search,n={};e.fields!==void 0&&(n.searchFields=e.fields),e.mode!==void 0&&(n.defaultMode=e.mode),e.paramName!==void 0&&(n.searchParamName=e.paramName),d.search=a(t.SearchEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,after:e.hooks?.after,extras:n});}if(o.aggregate!==void 0&&t.AggregateEndpoint){let e=o.aggregate,n={};e.fields!==void 0&&(n.filterFields=e.fields),d.aggregate=a(t.AggregateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,after:e.hooks?.after,extras:n});}if(o.restore!==void 0&&t.RestoreEndpoint){let e=o.restore;d.restore=a(t.RestoreEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after});}if(o.batchCreate!==void 0&&t.BatchCreateEndpoint){let e=o.batchCreate,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchCreate=a(t.BatchCreateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchUpdate!==void 0&&t.BatchUpdateEndpoint){let e=o.batchUpdate,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchUpdate=a(t.BatchUpdateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchDelete!==void 0&&t.BatchDeleteEndpoint){let e=o.batchDelete,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchDelete=a(t.BatchDeleteEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchRestore!==void 0&&t.BatchRestoreEndpoint){let e=o.batchRestore,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchRestore=a(t.BatchRestoreEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchUpsert!==void 0&&t.BatchUpsertEndpoint){let e=o.batchUpsert,n=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,r={};e.maxBatchSize!==void 0&&(r.maxBatchSize=e.maxBatchSize),n!==void 0&&(r.upsertKeys=n),d.batchUpsert=a(t.BatchUpsertEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:r});}if(o.export!==void 0&&t.ExportEndpoint){let e=o.export,n={};e.maxRows!==void 0&&(n.maxExportRecords=e.maxRows),e.formats!==void 0&&e.formats.length>0&&(n.defaultFormat=e.formats[0]),d.export=a(t.ExportEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,extras:n});}if(o.import!==void 0&&t.ImportEndpoint){let e=o.import,n={};e.maxRows!==void 0&&(n.maxBatchSize=e.maxRows),d.import=a(t.ImportEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.upsert!==void 0&&t.UpsertEndpoint){let e=o.upsert,n=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,r={};n!==void 0&&(r.upsertKeys=n),d.upsert=a(t.UpsertEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:r});}if(o.clone!==void 0&&t.CloneEndpoint){let e=o.clone,n={};e.fieldsToReset!==void 0&&(n.excludeFromClone=e.fieldsToReset),d.clone=a(t.CloneEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:n});}return d}export{s as a};
@@ -0,0 +1 @@
1
+ import {z}from'zod';var s=z.object({ct:z.string(),iv:z.string(),kid:z.string().optional(),v:z.literal(1)});function a(t){let e=new Uint8Array(t),n="";for(let r=0;r<e.byteLength;r++)n+=String.fromCharCode(e[r]);return btoa(n)}function u(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n.buffer}async function l(t){return crypto.subtle.importKey("raw",t,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function g(t,e){let n=await e.getKey(),r=await l(n),o=crypto.getRandomValues(new Uint8Array(12)),c=new TextEncoder().encode(t),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:o},r,c),f={ct:a(d),iv:a(o.buffer),v:1};return e.getCurrentKeyId&&(f.kid=e.getCurrentKeyId()),f}async function m(t,e){let n;t.kid&&e.getKeyById?n=await e.getKeyById(t.kid):n=await e.getKey();let r=await l(n),o=u(t.iv),y=u(t.ct),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(o)},r,y);return new TextDecoder().decode(c)}function K(t){return s.safeParse(t).success}async function E(t,e,n){let r={...t};for(let o of e)if(o in r&&r[o]!=null){let y=String(r[o]);r[o]=await g(y,n);}return r}async function w(t,e,n){let r={...t};for(let o of e)o in r&&K(r[o])&&(r[o]=await m(r[o],n));return r}var p=class{key;keyId;constructor(e,n="default"){this.key=u(e),this.keyId=n;}async getKey(){return this.key}async getKeyById(e){if(e!==this.keyId)throw new Error(`Unknown key ID: ${e}`);return this.key}getCurrentKeyId(){return this.keyId}static async generateKey(){let e=crypto.getRandomValues(new Uint8Array(32));return a(e.buffer)}};export{s as a,g as b,m as c,K as d,E as e,w as f,p as g};
@@ -0,0 +1 @@
1
+ import {HTTPException}from'hono/http-exception';var e=class extends HTTPException{code;details;constructor(t,s=500,o="INTERNAL_ERROR",m){super(s,{message:t}),this.name="ApiException",this.code=o,this.details=m;}toJSON(){let t={code:this.code,message:this.message};return this.details&&(t.details=this.details),{success:false,error:t}}get statusCode(){return this.status}},n=class r extends e{constructor(t,s){super(t,400,"VALIDATION_ERROR",s),this.name="InputValidationException";}static fromZodError(t){let s=t.issues.map(o=>({path:o.path.join("."),message:o.message,code:o.code}));return new r("Validation failed",s)}},a=class extends e{constructor(t="Resource",s){let o=s?`${t} with id '${s}' not found`:`${t} not found`;super(o,404,"NOT_FOUND"),this.name="NotFoundException";}},i=class extends e{constructor(t="Resource already exists",s){super(t,409,"CONFLICT",s),this.name="ConflictException";}},u=class extends e{constructor(t="Unauthorized"){super(t,401,"UNAUTHORIZED"),this.name="UnauthorizedException";}},c=class extends e{constructor(t="Forbidden"){super(t,403,"FORBIDDEN"),this.name="ForbiddenException";}},d=class extends e{constructor(t,s){super(t,400,"AGGREGATION_ERROR",s),this.name="AggregationException";}},p=class extends e{constructor(t,s){super(t,500,"CACHE_ERROR",s),this.name="CacheException";}},l=class extends e{constructor(t,s){super(t,500,"CONFIGURATION_ERROR",s),this.name="ConfigurationException";}};export{e as a,n as b,a as c,i as d,u as e,c as f,d as g,p as h,l as i};
@@ -0,0 +1 @@
1
+ import {i}from'./chunk-4NKDESHS.js';import {e,f}from'./chunk-A3O6KC4L.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {b as b$1,a as a$1}from'./chunk-VJRDAVID.js';import {a}from'./chunk-IJBJE4G2.js';import {z as z$1}from'zod';import {decode,verify}from'hono/jwt';var S=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"],q=z$1.object({sub:z$1.string().optional(),iss:z$1.string().optional(),aud:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),exp:z$1.number().int().optional(),nbf:z$1.number().int().optional(),iat:z$1.number().int().optional(),jti:z$1.string().optional(),email:z$1.string().optional(),role:z$1.string().optional(),roles:z$1.union([z$1.array(z$1.string()),z$1.string()]).optional(),permissions:z$1.union([z$1.array(z$1.string()),z$1.string()]).optional(),metadata:z$1.record(z$1.string(),z$1.unknown()).optional()}).passthrough();function ee(e){return q.parse(e)}function O(e){return q.safeParse(e)}z$1.object({id:z$1.string(),tenantId:z$1.string().optional(),organizationId:z$1.string().optional(),userId:z$1.string().optional(),actorUserId:z$1.string().optional(),onBehalfOfUserId:z$1.string().optional(),agentId:z$1.string().optional(),agentRunId:z$1.string().optional(),toolCallId:z$1.string().optional(),source:z$1.enum(["http","agent-mcp","agent-code-mode","workflow","job","system"]),toolName:z$1.string(),input:z$1.unknown(),status:z$1.enum(["pending","approved","rejected","expired"]),createdAt:z$1.iso.datetime(),expiresAt:z$1.iso.datetime(),reason:z$1.string(),approvedBy:z$1.string().optional(),approvedAt:z$1.iso.datetime().optional(),rejectedBy:z$1.string().optional(),rejectedReason:z$1.string().optional()});function P(e$1,t={}){let{clockTolerance:n=0,issuer:r,audience:o,skipTimeValidation:s=false}=t;if(!s){let u=Math.floor(Date.now()/1e3);if(e$1.exp!==void 0&&u>e$1.exp+n)throw new e("Token has expired");if(e$1.nbf!==void 0&&u<e$1.nbf-n)throw new e("Token not yet valid")}if(r!==void 0&&e$1.iss!==r)throw new e("Invalid token issuer");if(o!==void 0){let u=Array.isArray(o)?o:[o],d=Array.isArray(e$1.aud)?e$1.aud:[e$1.aud];if(!u.some(y=>d.includes(y)))throw new e("Invalid token audience")}}function B(e){if(!S.includes(e))throw new Error(`Unsupported algorithm: ${e}`);return e}function te(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 V(e){if(e!==void 0)return Array.isArray(e)?e:[e]}function re(e){return {id:String(e.sub||e.id||""),email:e.email,roles:V(e.roles??e.role),permissions:V(e.permissions),metadata:e.metadata}}function M(e$1){let t=B(e$1.algorithm||"HS256"),n=e$1.clockTolerance||0,r=e$1.extractToken||te,o=e$1.extractUser||re;return async(s,u)=>{let d=r(s);if(!d)throw new e("Missing authentication token");let c=decode(d);if(!c||!c.header)throw new e("Invalid token format");if(c.header.alg!==t)throw new e("Invalid token algorithm");let y;try{y=await verify(d,e$1.secret,t);}catch(g){if(g instanceof Error){if(g.message.includes("expired")||g.name==="JwtTokenExpired")throw new e("Token has expired");if(g.message.includes("signature")||g.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(g.message.includes("not valid yet")||g.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let f=O(y);if(!f.success)throw new e("Invalid token claims");let m=f.data;P(m,{clockTolerance:n,issuer:e$1.issuer,audience:e$1.audience});let w=o(m);s.set(a.userId,w.id),s.set(a.user,w),s.set(a.roles,w.roles||[]),s.set(a.permissions,w.permissions||[]),s.set(a.authType,"jwt"),await u();}}async function ne(e$1,t){let n=B(t.algorithm||"HS256"),r=t.clockTolerance||0,o=decode(e$1);if(!o||!o.header)throw new e("Invalid token format");if(o.header.alg!==n)throw new e("Invalid token algorithm");let s;try{s=await verify(e$1,t.secret,n);}catch(d){if(d instanceof Error){if(d.message.includes("expired")||d.name==="JwtTokenExpired")throw new e("Token has expired");if(d.message.includes("signature")||d.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(d.message.includes("not valid yet")||d.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let u=s;return P(u,{clockTolerance:r,issuer:t.issuer,audience:t.audience}),u}function oe(e){try{let t=decode(e);return !t||!t.header||!t.payload?null:{header:t.header,payload:t.payload}}catch{return null}}function b(e$1){if(!e$1)throw new e("Invalid API key");if(!e$1.active)throw new e("API key has been revoked");if(e$1.expiresAt&&new Date>e$1.expiresAt)throw new e("API key has expired");return e$1}async function K(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),o=new Uint8Array(r);return Array.from(o).map(s=>s.toString(16).padStart(2,"0")).join("")}function se(e){return {id:e.userId,roles:e.roles,permissions:e.permissions,metadata:{...e.metadata,apiKeyId:e.id,apiKeyName:e.name}}}function ie(e,t){return e.req.header(t)||null}function ae(e,t){return e.req.query(t)||null}function j(e$1){let t=e$1.headerName||"X-API-Key",n=e$1.queryParam??null,r=e$1.hashKey||K,o=e$1.extractUser||se;return async(s,u)=>{let d=ie(s,t);if(!d&&n&&(d=ae(s,n)),!d)throw new e("Missing API key");let c=await r(d),y=await e$1.lookupKey(c),f=b(y),m=o(f);s.set(a.userId,m.id),s.set(a.user,m),s.set(a.roles,m.roles||[]),s.set(a.permissions,m.permissions||[]),s.set(a.authType,"api-key"),e$1.updateLastUsed&&Promise.resolve(e$1.updateLastUsed(f.id)).catch(()=>{}),await u();}}async function ue(e,t){let r=await(t.hashKey||K)(e),o=await t.lookupKey(r);return b(o)}function N(e$1){let t=e$1.requireAuth??true,n=e$1.skipPaths||[],r=e$1.unauthorizedMessage||"Unauthorized",o=e$1.authOrder||["jwt","api-key"],s=e$1.jwt?M(e$1.jwt):null,u=e$1.apiKey?j(e$1.apiKey):null;return async(d,c)=>{let y=d.req.path;if(i(y,n))return d.set(a.authType,"none"),c();let f=false,m=null;for(let w of o)try{if(w==="jwt"&&s&&d.req.header("Authorization")?.toLowerCase().startsWith("bearer ")){await s(d,async()=>{}),f=!0;break}if(w==="api-key"&&u){let g=e$1.apiKey?.headerName||"X-API-Key",R=e$1.apiKey?.queryParam;if(d.req.header(g)||R&&d.req.query(R)){await u(d,async()=>{}),f=!0;break}}}catch(g){m=g instanceof Error?g:new Error(String(g));}if(!f){if(t)throw m instanceof e?m:new e(r);d.set(a.authType,"none");}await c();}}function de(e){return N({...e,requireAuth:false})}function le(e){return N({...e,requireAuth:true})}var E=class{store=new Map;async create(t){this.store.set(t.id,{...t});}async get(t){let n=this.store.get(t);if(!n)return null;if(n.status==="pending"&&Date.parse(n.expiresAt)<=Date.now()){let r={...n,status:"expired"};return this.store.set(t,r),r}return {...n}}async approve(t,n){let r=await this.get(t);if(!r)throw new Error(`Pending action ${t} not found`);if(r.status!=="pending")throw new Error(`Pending action ${t} cannot be approved from status '${r.status}'`);this.store.set(t,{...r,status:"approved",approvedBy:n,approvedAt:new Date().toISOString()});}async reject(t,n,r){let o=await this.get(t);if(!o)throw new Error(`Pending action ${t} not found`);if(o.status!=="pending")throw new Error(`Pending action ${t} cannot be rejected from status '${o.status}'`);this.store.set(t,{...o,status:"rejected",rejectedBy:n,rejectedReason:r});}clear(){this.store.clear();}};var ce=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;function _(e){let t=ce.exec(e);if(!t)throw new Error(`Invalid ISO 8601 duration: ${e}. Use P[nD][T[nH][nM][nS]] (years and months unsupported).`);let[,n,r,o,s]=t,u=(n?Number(n)*864e5:0)+(r?Number(r)*36e5:0)+(o?Number(o)*6e4:0)+(s?Number(s)*1e3:0);if(u===0&&e!=="PT0S"&&e!=="P0D")throw new Error(`ISO 8601 duration ${e} parsed to zero milliseconds \u2014 verify the format.`);return u}function pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var z,G=false;function he(){return z||(z=new E),G||(G=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.")),z}var X="__honoCrudPolicies";function ge(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.roles||[];if(!e$1.some(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function me(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.roles||[];if(!e$1.every(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function fe(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.permissions||[];if(!e$1.every(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function ye(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.permissions||[];if(!e$1.some(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function Ae(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 we(e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=await e$1(t);if(r.id!==o)throw new f("Access denied: not resource owner");await n();}}function xe(e$1,...t){return async(n,r)=>{let o=n.var.user;if(!o)throw new e("Authentication required");let s=o.roles||[];if(t.some(c=>s.includes(c))){await r();return}let d=await e$1(n);if(o.id===d){await r();return}throw new f("Access denied")}}function Te(...e){return async(t,n)=>{for(let r of e)await r(t,async()=>{});await n();}}function Ee(...e){return async(t,n)=>{let r=null;for(let o of e)try{await o(t,async()=>{}),await n();return}catch(s){r=s instanceof Error?s:new Error(String(s));}throw r||new f("Access denied")}}function Re(e="Access denied"){return async()=>{throw new f(e)}}function ve(){return async(e,t)=>{await t();}}function Ce(){return async(e$1,t)=>{if(!e$1.var.user)throw new e("Authentication required");await t();}}function Pe(e){return async(t,n)=>{b$1(t,X,e),await n();}}function be(e){let t=e.approvalStorage??he(),n=e.resumeMarker??"_resume_",r=_(e.expiresAfter??"P1D"),o=z$1.object({[n]:z$1.string()}).loose();return async(s,u)=>{let d={};try{let T=await s.req.json();pe(T)&&(d=T);}catch{}let c=o.safeParse(d).data?.[n];if(c){let T=await t.get(c);if(!T)throw new f(`Pending action ${c} not found`);if(T.status==="expired")throw new f(`Pending action ${c} has expired`);if(T.status!=="approved")throw new f(`Pending action ${c} is ${T.status}, cannot resume`);ke(s,T.input),await u();return}let y=a$1(s,a.userId),f$1=a$1(s,a.agentId),m=a$1(s,a.agentRunId),w=a$1(s,a.onBehalfOfUserId),g=a$1(s,a.toolCallId),R=a$1(s,a.tenantId),H=a$1(s,a.organizationId),Q=a$1(s,a.actionSource)??(f$1?"agent-mcp":"http"),D=Date.now(),v={id:crypto.randomUUID(),tenantId:R,organizationId:H,userId:y,actorUserId:y,onBehalfOfUserId:w,agentId:f$1,agentRunId:m,toolCallId:g,source:Q,toolName:e.toolName??`${s.req.method} ${s.req.path}`,input:d,status:"pending",createdAt:new Date(D).toISOString(),expiresAt:new Date(D+r).toISOString(),reason:e.reason};return await t.create(v),s.json({status:"pending",actionId:v.id,expiresAt:v.expiresAt,reason:v.reason},202)}}function ke(e,t){let n=e.req,r=Promise.resolve(JSON.stringify(t));n.bodyCache?(n.bodyCache.text=r,delete n.bodyCache.parsedBody,delete n.bodyCache.json):n.bodyCache={text:r};}var Ie=["eq","ne","gt","gte","lt","lte","in","nin","like","ilike","null","between"];function gt(e){return Ie.includes(e)}function mt(e){throw new Error(`Unhandled discriminated union member: ${String(e)}`)}var ft=["asc","desc"],yt=["any","all","phrase"],At=["count","sum","avg","min","max","countDistinct"];function wt(e){return e}function xt(e){return e}var Se=z$1.object({code:z$1.string(),message:z$1.string(),details:z$1.unknown().optional(),requestId:z$1.string().optional(),stack:z$1.string().optional()}).passthrough(),Tt=z$1.object({success:z$1.literal(false),error:Se});function Et(e){return z$1.object({success:z$1.literal(true),result:e})}var qe="__honoCrudResponseEnvelope__";function Y(e){return e?.var?.[qe]}function J(e,t){try{return e.req.valid(t)}catch{return}}function k(e,t,n){return e.json(t,n)}var I=class{static isRoute=true;schema={};params={};context=null;getSchema(){return this.schema}async getValidatedData(){if(!this.context)throw new Error("Context not set. Call setContext() first.");let t=this.context,n=this.getSchema(),r={};if(n.request?.body){let o=J(t,"json");if(o===void 0)try{o=await t.req.json();}catch{}o!==void 0&&(r.body=o);}if(n.request?.query){let o=J(t,"query");o===void 0&&(o=t.req.query()),o!==void 0&&(r.query=o);}if(n.request?.params){let o=J(t,"param");o===void 0&&(o=t.req.param()),o!==void 0&&(r.params=o);}return r}setContext(t){this.context=t;}getContext(){if(!this.context)throw new Error("Context not set");return this.context}json(t,n=200){return k(this.getContext(),t,n)}getResponseEnvelope(){return Y(this.context)}success(t,n=200){let r=this.getResponseEnvelope(),o=r?r.success(t):{success:true,result:t};return k(this.getContext(),o,n)}successPaginated(t,n,r=200){let o=this.getResponseEnvelope(),s=o?o.success(t,n):{success:true,result:t,result_info:n};return k(this.getContext(),s,r)}runAfterResponse(t){let n;try{let r=this.getContext().executionCtx;r&&typeof r.waitUntil=="function"&&(n=r.waitUntil.bind(r));}catch{}n?n(t):t.catch(r=>{b$2().error("Background task failed",{error:r instanceof Error?r.message:String(r)});});}error(t,n="ERROR",r=400,o){let s={code:n,message:t};o&&(s.details=o);let u=this.getResponseEnvelope(),d=u?u.error(s):{success:false,error:s};return k(this.getContext(),d,r)}};function Pt(e){return typeof e=="function"&&"isRoute"in e&&e.isRoute===true}var W=class extends I{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(t,n){return true}getUser(){let n=this.getContext().var.user;if(!n)throw new e("Authentication required");return n}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(t){return this.getUserRoles().includes(t)}hasAnyRole(...t){let n=this.getUserRoles();return t.some(r=>n.includes(r))}hasAllRoles(...t){let n=this.getUserRoles();return t.every(r=>n.includes(r))}hasPermission(t){return this.getUserPermissions().includes(t)}hasAllPermissions(...t){let n=this.getUserPermissions();return t.every(r=>n.includes(r))}hasAnyPermission(...t){let n=this.getUserPermissions();return t.some(r=>n.includes(r))}async enforceAuth(){let t=this.getContext();if(this.requiresAuth&&!t.var.user)throw new e("Authentication required");let n=t.var.user;if(!n)return;if(this.requiredRoles&&this.requiredRoles.length>0){let o=n.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(u=>o.includes(u)))throw new f(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(u=>o.includes(u)))throw new f(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let o=n.permissions||[];if(!this.requiredPermissions.every(u=>o.includes(u)))throw new f(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(n,t))throw new f("Access denied")}getSchema(){let t=super.getSchema(),n=this.requiresAuth?[{bearerAuth:[]}]:void 0,r={401:{description:"Unauthorized - Authentication required",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("UNAUTHORIZED"),message:z$1.string()})})}}},403:{description:"Forbidden - Insufficient permissions",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("FORBIDDEN"),message:z$1.string()})})}}}};return {...t,security:n,responses:{...t.responses,...this.requiresAuth?r:{}}}}};function Oe(e$1){class t extends e$1{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(r,o){return true}getUser(){let o=this.getContext().var.user;if(!o)throw new e("Authentication required");return o}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(r){let o=this.getUserOrNull();return o?(o.roles||[]).includes(r):false}hasAnyRole(...r){let o=this.getUserOrNull()?.roles||[];return r.some(s=>o.includes(s))}hasAllRoles(...r){let o=this.getUserOrNull()?.roles||[];return r.every(s=>o.includes(s))}hasPermission(r){let o=this.getUserOrNull();return o?(o.permissions||[]).includes(r):false}hasAllPermissions(...r){let o=this.getUserOrNull()?.permissions||[];return r.every(s=>o.includes(s))}hasAnyPermission(...r){let o=this.getUserOrNull()?.permissions||[];return r.some(s=>o.includes(s))}async enforceAuth(){let r=this.getContext();if(this.requiresAuth&&!r.var.user)throw new e("Authentication required");let o=r.var.user;if(!o)return;if(this.requiredRoles&&this.requiredRoles.length>0){let u=o.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(c=>u.includes(c)))throw new f(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(c=>u.includes(c)))throw new f(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let u=o.permissions||[];if(!this.requiredPermissions.every(c=>u.includes(c)))throw new f(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(o,r))throw new f("Access denied")}getSchema(){let r=super.getSchema(),o=this.requiresAuth?[{bearerAuth:[]}]:void 0,s={401:{description:"Unauthorized - Authentication required",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("UNAUTHORIZED"),message:z$1.string()})})}}},403:{description:"Forbidden - Insufficient permissions",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("FORBIDDEN"),message:z$1.string()})})}}}};return {...r,security:o,responses:{...r.responses,...this.requiresAuth?s:{}}}}}return t}export{Te as A,Ee as B,Re as C,ve as D,Ce as E,Pe as F,be as G,S as H,q as I,ee as J,O as K,P as L,te as M,M as N,ne as O,oe as P,b as Q,K as R,j as S,ue as T,N as U,de as V,le as W,W as X,Oe as Y,Ie as a,gt as b,mt as c,ft as d,yt as e,At as f,wt as g,xt as h,Se as i,Tt as j,Et as k,qe as l,Y as m,k as n,I as o,Pt as p,E as q,_ as r,X as s,ge as t,me as u,fe as v,ye as w,Ae as x,we as y,xe as z};
@@ -0,0 +1 @@
1
+ import {b}from'./chunk-VJRDAVID.js';import {a}from'./chunk-IJBJE4G2.js';import {HTTPException}from'hono/http-exception';function I(c={}){let{source:r="header",headerName:m="X-Tenant-ID",pathParam:l="tenantId",queryParam:g="tenantId",jwtClaim:f="tenantId",extractor:a$1,contextKey:x="tenantId",required:p=true,errorMessage:E="Tenant ID is required",onMissing:i,validate:o,invalidMessage:w="Invalid tenant ID"}=c;if(r==="custom"&&!a$1)throw new Error("multiTenant: source 'custom' requires an `extractor` function. Provide `extractor`, or choose a different `source`.");let h={header:e=>e.req.header(m),path:e=>e.req.param(l),query:e=>e.req.query(g),jwt:e=>{let t=e.get(a.jwtPayload);if(t&&typeof t=="object")return t[f]},custom:e=>a$1?.(e)};return async(e,t)=>{let y=h[r],n=await y(e);if(!n){if(p){if(i)return i(e);throw new HTTPException(400,{message:E})}return t()}if(o&&!await o(n,e))throw new HTTPException(400,{message:w});return b(e,x,n),t()}}export{I as a};
@@ -1 +1 @@
1
- import {a}from'./chunk-5FV7DBVK.js';import {a as a$1}from'./chunk-IJBJE4G2.js';function l(e,n){return e.req.header(n)??void 0}function w(e,n){return e.req.query(n)??void 0}function C(e,n){let i=e.req.path,a=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\{version\\}","([^/]+)"),d=new RegExp(`^${a}`);return i.match(d)?.[1]}function h(e){let{versions:n,strategy:i="header",headerName:p="Accept-Version",queryParam:a$2="version",urlPattern:d="/v{version}",extractVersion:f,addHeaders:c=true}=e,V=e.defaultVersion??n[0]?.version,u=new Map;for(let r of n)u.set(r.version,r);return async(r,m)=>{let t=f?f(r):{header:()=>l(r,p),query:()=>w(r,a$2),url:()=>C(r,d)}[i]();if(t=t??V,!t)throw new a("API version is required",400,"VERSION_REQUIRED");let o=u.get(t);if(!o)throw new a(`Unsupported API version: ${t}`,400,"UNSUPPORTED_VERSION");if(r.set(a$1.apiVersion,t),r.set(a$1.apiVersionConfig,o),c&&(r.header("X-API-Version",t),o.deprecated&&r.header("Deprecation",o.deprecated),o.sunset&&r.header("Sunset",o.sunset)),o.middleware&&o.middleware.length>0)for(let y of o.middleware)await y(r,async()=>{});await m();}}function v(e){return e.get(a$1.apiVersion)}function A(e){return e.get(a$1.apiVersionConfig)}function E(){return async(e,n)=>{await n();let i=e.get(a$1.apiVersionConfig);if(!(!i?.responseTransformer||!e.res.headers.get("content-type")?.includes("application/json")))try{let a=await e.res.json(),d=i.responseTransformer(a);e.res=new Response(JSON.stringify(d),{status:e.res.status,headers:e.res.headers});}catch{}}}export{h as a,v as b,A as c,E as d};
1
+ import {a}from'./chunk-A3O6KC4L.js';import {a as a$1}from'./chunk-IJBJE4G2.js';function l(e,n){return e.req.header(n)??void 0}function w(e,n){return e.req.query(n)??void 0}function C(e,n){let i=e.req.path,a=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\{version\\}","([^/]+)"),d=new RegExp(`^${a}`);return i.match(d)?.[1]}function h(e){let{versions:n,strategy:i="header",headerName:p="Accept-Version",queryParam:a$2="version",urlPattern:d="/v{version}",extractVersion:f,addHeaders:c=true}=e,V=e.defaultVersion??n[0]?.version,u=new Map;for(let r of n)u.set(r.version,r);return async(r,m)=>{let t=f?f(r):{header:()=>l(r,p),query:()=>w(r,a$2),url:()=>C(r,d)}[i]();if(t=t??V,!t)throw new a("API version is required",400,"VERSION_REQUIRED");let o=u.get(t);if(!o)throw new a(`Unsupported API version: ${t}`,400,"UNSUPPORTED_VERSION");if(r.set(a$1.apiVersion,t),r.set(a$1.apiVersionConfig,o),c&&(r.header("X-API-Version",t),o.deprecated&&r.header("Deprecation",o.deprecated),o.sunset&&r.header("Sunset",o.sunset)),o.middleware&&o.middleware.length>0)for(let y of o.middleware)await y(r,async()=>{});await m();}}function v(e){return e.get(a$1.apiVersion)}function A(e){return e.get(a$1.apiVersionConfig)}function E(){return async(e,n)=>{await n();let i=e.get(a$1.apiVersionConfig);if(!(!i?.responseTransformer||!e.res.headers.get("content-type")?.includes("application/json")))try{let a=await e.res.json(),d=i.responseTransformer(a);e.res=new Response(JSON.stringify(d),{status:e.res.status,headers:e.res.headers});}catch{}}}export{h as a,v as b,A as c,E as d};
@@ -0,0 +1,11 @@
1
+ import {a as a$6,b as b$3}from'./chunk-PDHKGPGZ.js';import {v}from'./chunk-P5JQKX7Z.js';import {g,a as a$5}from'./chunk-HIDT3P5C.js';import {f as f$1}from'./chunk-UAVAEDVS.js';import {a as a$4}from'./chunk-EX4S3Q4M.js';import {m,n,p,f,b as b$2,d as d$1,c as c$1,e,o,s,l}from'./chunk-J6WCEEO4.js';import {a,b,i,d,c}from'./chunk-A3O6KC4L.js';import {a as a$3}from'./chunk-STAO4FWC.js';import {e as e$1,f as f$2}from'./chunk-6MS7YXSZ.js';import {d as d$2}from'./chunk-XCDY63Q6.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {a as a$1,b as b$4}from'./chunk-VJRDAVID.js';import {a as a$2}from'./chunk-IJBJE4G2.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE,stream}from'hono/streaming';var Qt=new WeakMap;function tt(n){return Qt.get(n)}var Me=class{app;options;routes=new Map;constructor(e,t={}){this.app=e,this.options={docs_url:"/docs",redoc_url:"/redoc",openapi_url:"/openapi.json",...t};}registerRoute(e,t,o,r=[]){let s=`${e.toUpperCase()} ${t}`,i=o,l=new i().getSchema();this.routes.set(s,{method:e,path:t,schema:l,routeClass:o});let c=createRoute({method:e,path:this.convertPath(t),...l,responses:l.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(r.length>0)for(let a of r)this.app.use(t,async(d,p)=>{if(d.req.method.toLowerCase()===e)return a(d,p);await p();});this.app.openapi(c,async a$1=>{let d=new i;d.setContext(a$1);try{return await d.handle()}catch(p){if(p instanceof a){let m$1=p.toJSON(),h=m(a$1);return h?n(a$1,h.error(m$1.error),p.status):n(a$1,m$1,p.status)}throw p}});}convertPath(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}setupDocs(e,t){let o=e??this.options.openapi_url??"/openapi.json";this.app.doc(o,{openapi:t.openapi||"3.1.0",info:t.info,servers:t.servers,security:t.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return this.convertPath(e)}};function ho(n=new OpenAPIHono,e={}){let t="openAPIRegistry"in n?n:new OpenAPIHono,o=new Me(t,e),r=["get","post","put","patch","delete","options","head"],s=new Proxy(t,{get(i,u){if(r.includes(u))return (c,...a)=>{let d=a[a.length-1];if(p(d)){let p=a.slice(0,-1);return o.registerRoute(u,c,d,p),s}return i[u](c,...a)};if(u==="doc")return (c,a)=>{o.setupDocs(c,a);};if(u==="use")return (...c)=>(i[u](...c),s);let l=i[u];return typeof l=="function"?l.bind(i):l}});return Qt.set(s,o),s}var yo=6e4,wo={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Mo(n,e,t={}){let o=tt(n);if(!o)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let r=t.config??wo,s=`openapi:${e.tenantId??"global"}:${r.info.version}`;if(t.cache){let c=await t.cache.get(s);if(c!=null)return c}let i=new OpenAPIHono;for(let c of o.getRegisteredRoutes().values()){let a=c.routeClass,d=new a,p=Eo(e);d.setContext(p),typeof d.resolveModelSchema=="function"&&await d.resolveModelSchema();let m=d.getSchema(),h=createRoute({...m,method:c.method,path:o.toOpenApiPath(c.path),responses:m.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});i.openapi(h,()=>new Response);}let u={openapi:r.openapi??"3.1.0",info:r.info,servers:r.servers,security:r.security},l=t.spec==="3.0"?i.getOpenAPIDocument(u):i.getOpenAPI31Document(u);return t.cache&&await t.cache.set(s,l,t.cacheTtlMs??yo),l}function Eo(n){let e={};n.tenantId!==void 0&&(e.tenantId=n.tenantId),n.organizationId!==void 0&&(e.organizationId=n.organizationId);let t=n.request??new Request("http://localhost/");return {var:e,env:n.env,req:{raw:t,header:()=>{},query:()=>{},param:()=>{}},set(o,r){e[o]=r;},get(o){return e[o]},executionCtx:void 0}}function Ro(n){return {async get(e){let t=await n.get(e);return t?t.data:void 0},async set(e,t,o){let r=o?Math.ceil(o/1e3):void 0;await n.set(e,t,r?{ttl:r}:void 0);}}}var ko=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"]];function Co(n){return n.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function Po(n,e){let o=`/${n}/${e}`.replace(/\/{2,}/g,"/");return o.length>1&&o.endsWith("/")?o.slice(0,-1):o}function vo(n,e={}){let t=e.basePath??"",o=e.tag,r=new OpenAPIHono,s=0;for(let[l,c,a]of ko){let d=n[l];if(!d)continue;let m=new d().getSchema(),h=o!==void 0?{...m,tags:[o]}:m,f=Po(t,Co(a)),y=createRoute({...h,method:c,path:f,responses:h.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});r.openapi(y,()=>new Response),s+=1;}return s===0?{}:r.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var Jt=n=>{if(n instanceof ZodError)return b.fromZodError(n)};function Io(n$1={}){let{mappers:e=[],hooks:t=[],includeRequestId:o=true,includeStackTrace:r=false,defaultErrorCode:s="INTERNAL_ERROR",defaultErrorMessage:i="An internal error occurred",logUnmappedErrors:u=true,onHookError:l,responseEnvelope:c}=n$1,a$1=[...e,Jt];return async(d,p)=>{let m,h=false;if(d instanceof a)m=d,h=true;else if(d instanceof HTTPException)m=new a(d.message,d.status,"HTTP_ERROR"),h=true;else {for(let g of a$1)try{let S=await g(d,p);if(S){m=S,h=!0;break}}catch{}h||(u&&b$1().error("Unmapped error",{error:d instanceof Error?d.message:String(d)}),m=new a(i,500,s));}for(let g of t)try{let S=g(d,p,m);S instanceof Promise&&S.catch(F=>{l&&l(F,d,p);});}catch(S){l&&l(S,d,p);}let f=m.toJSON();if(o){let g=v(p);g&&(f.error.requestId=g);}r&&d.stack&&(f.error.stack=d.stack);let y=Yt(p,c),b=y?y.error(f.error):f;return n(p,b,m.status)}}function Yt(n,e){return m(n)??e}var ot="createdAt",rt="updatedAt";function ie(n){return n?n===true?{enabled:true,createdAt:ot,updatedAt:rt}:{enabled:true,createdAt:n.createdAt??ot,updatedAt:n.updatedAt??rt}:{enabled:false,createdAt:ot,updatedAt:rt}}function H(n,e={}){let{includePrimaryKeys:t=true}=e,o=new Set;if(t)for(let s of n.primaryKeys)o.add(s);let r=ie(n.timestamps);return r.enabled&&(o.add(r.createdAt),o.add(r.updatedAt)),[...o]}function Ao(n){return n!=null&&n!==""}function nt(n,e,t,o){let r={...n},s=e.primaryKeys[0];if(!Ao(r[s])){let u=e.id;if(typeof u=="function")r[s]=u();else if(u==="database"){if(t==="memory")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)");delete r[s];}else r[s]=o?o():crypto.randomUUID();}let i$1=ie(e.timestamps);if(i$1.enabled){let u=Date.now();i$1.createdAt in n||(r[i$1.createdAt]=u),i$1.updatedAt in n||(r[i$1.updatedAt]=u);}return r}function st(n,e){let t=ie(e.timestamps);return t.enabled?{...n,[t.updatedAt]:Date.now()}:{...n}}function it(n,e){if(e==="memory"&&n.id==="database")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)")}function at(n,e){let t={...n};for(let o of H(e))delete t[o];return t}var _o=new Set(["P2002","SQLITE_CONSTRAINT_UNIQUE","SQLITE_CONSTRAINT","23505","ER_DUP_ENTRY",1062,"1062"]),To=/UNIQUE constraint failed|duplicate key value violates unique constraint|Duplicate entry/i;function No(n){if(!n||typeof n!="object")return false;let{code:e,message:t}=n;return (typeof e=="string"||typeof e=="number")&&_o.has(e)?true:typeof t=="string"&&To.test(t)}function*Xt(n,e=8){for(let t=n,o=0;o<e&&t!=null&&typeof t=="object";o++)yield t,t=t.cause;}function Ee(n){for(let e of Xt(n))if(No(e))return new d("Unique constraint violation");return null}function W(n){throw Ee(n)??n}function Do(n){return btoa(String(n))}function Ho(n){try{return atob(n)}catch{return null}}async function ae(n,e){if(!e||Object.keys(e).length===0)return n;let t={...n};for(let[o,r]of Object.entries(e))try{let s=await r.compute(n);t[o]=s;}catch{t[o]=void 0;}return t}async function dt(n,e){return !e||Object.keys(e).length===0?n:Promise.all(n.map(t=>ae(t,e)))}function ee(n,e){let t={},o={};for(let[r,s]of Object.entries(n))e.includes(r)&&s!==void 0?o[r]=s:t[r]=s;return {mainData:t,nestedData:o}}function ge(n){if(Array.isArray(n))return true;if(typeof n=="object"&&n!==null){let e=Object.keys(n),t=["create","update","delete","connect","disconnect","set"];return !e.some(o=>t.includes(o))}return false}function Vo(n){let e=n.split(":");if(e.length<2)return null;let t=e[0].toLowerCase();return f.map(s=>s.toLowerCase()).includes(t)?{operation:t==="countdistinct"?"countDistinct":t,field:e[1],alias:e[2]}:null}function lt(n){let e=[],t={};for(let a of f){let d=n[a];if(d){let p=Array.isArray(d)?d:[d];for(let m of p)typeof m=="string"&&e.push({operation:a,field:m==="true"||m===""?"*":m});}}let o;if(n.groupBy){let a=n.groupBy;typeof a=="string"?o=a.split(",").map(d=>d.trim()):Array.isArray(a)&&(o=a.filter(d=>typeof d=="string"));}let r;for(let[a,d]of Object.entries(n)){let p=a.match(/^having\[(\w+)\]\[(\w+)\]$/);if(p){let[,m,h]=p;r||(r={}),r[m]||(r[m]={}),r[m][h]=d;}}let s=typeof n.orderBy=="string"?n.orderBy:void 0,i=n.orderDirection==="desc"?"desc":"asc",u=typeof n.limit=="string"?Number.parseInt(n.limit,10):void 0,l=typeof n.offset=="string"?Number.parseInt(n.offset,10):void 0,c=[...f,"groupBy","orderBy","orderDirection","limit","offset"];for(let[a,d]of Object.entries(n))!c.includes(a)&&!a.startsWith("having[")&&(t[a]=d);return {aggregations:e,groupBy:o,filters:Object.keys(t).length>0?t:void 0,having:r,orderBy:s,orderDirection:i,limit:u,offset:l}}function ct(n){return n?n===true?{enabled:true,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}:{enabled:true,field:n.field??"deletedAt",allowQueryDeleted:n.allowQueryDeleted??true,queryParam:n.queryParam??"withDeleted"}:{enabled:false,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}}function pt(n){let e={enabled:false,field:"tenantId",source:"context",headerName:"X-Tenant-ID",contextKey:"tenantId",pathParam:"tenantId",required:true,errorMessage:"Tenant ID is required"};return n?n===true?{...e,enabled:true}:{enabled:true,field:n.field??e.field,source:n.source??e.source,headerName:n.headerName??e.headerName,contextKey:n.contextKey??e.contextKey,pathParam:n.pathParam??e.pathParam,getTenantId:n.getTenantId,required:n.required??e.required,errorMessage:n.errorMessage??e.errorMessage}:e}function ut(n,e){return e.enabled?{header:()=>n.req.header(e.headerName),context:()=>a$1(n,e.contextKey),path:()=>n.req.param(e.pathParam),custom:()=>e.getTenantId?.(n)}[e.source]?.():void 0}var Zo=new Set(["a","an","and","are","as","at","be","by","for","from","has","he","in","is","it","its","of","on","or","that","the","to","was","were","will","with"]);function mt(n,e=true){if(!n||typeof n!="string")return [];let t=n.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(Boolean);return e?t.filter(o=>!Zo.has(o)&&o.length>1):t}function ht(n,e){return e==="phrase"?[n.toLowerCase().trim()]:mt(n)}function to(n,e){return e.length===0?0:e.filter(o=>o===n||o.includes(n)).length/e.length}function ft(n,e,t,o){if(e.length===0)return {score:0,matchedFields:[]};let r=0,s=0,i=[];for(let[l,c]of Object.entries(t)){let a=n[l];if(a==null)continue;let d=c.weight??1;s+=d;let p;c.type==="array"&&Array.isArray(a)?p=a.join(" "):p=String(a);let m=mt(p,false),h=p.toLowerCase(),f=0,y=0;if(o==="phrase"){let b=e[0];h.includes(b)&&(f=1,y=1);}else {for(let b of e){let g=to(b,m);g>0?(y++,f+=g):h.includes(b)&&(y++,f+=.5/e.length);}e.length>0&&(f=f/e.length);}o==="all"&&y<e.length&&(f=0),f>0&&(i.push(l),r+=f*d);}return {score:s>0?Math.min(1,r/s):0,matchedFields:i}}function gt(n,e,t,o="mark",r=150){if(n==null)return [];let s;if(Array.isArray(n)?s=n.join(" "):s=String(n),!s||e.length===0)return [];let i=[],u=s.toLowerCase();if(t==="phrase"){let l=e[0],c=u.indexOf(l);if(c!==-1){let a=eo(s,c,l.length,r,o);a&&i.push(a);}}else {let l=[];for(let a of e){let d=0;for(;d<u.length;){let p=u.indexOf(a,d);if(p===-1)break;l.push({start:p,length:a.length}),d=p+1;}}l.sort((a,d)=>a.start-d.start);let c=new Set;for(let a of l){if(Array.from(c).some(m=>Math.abs(m-a.start)<r))continue;let p=eo(s,a.start,a.length,r,o);if(p&&(i.push(p),c.add(a.start)),i.length>=3)break}}return i}function eo(n,e,t,o,r){let s=Math.floor(o/2),i=Math.max(0,e-s),u=Math.min(n.length,e+t+s);if(i>0){let a=n.indexOf(" ",i);a!==-1&&a<e&&(i=a+1);}if(u<n.length){let a=n.lastIndexOf(" ",u);a!==-1&&a>e+t&&(u=a);}let l=n.slice(i,u);return i>0&&(l="..."+l),u<n.length&&(l=l+"..."),Lo(l,[n.slice(e,e+t)],r)}function Lo(n,e,t){let o=n,r=n.toLowerCase(),s=[...e].sort((i,u)=>u.length-i.length);for(let i of s){let u=i.toLowerCase(),l=0,c="",a=0;for(;a<r.length;){let d=r.indexOf(u,a);if(d===-1)break;c+=o.slice(l,d),c+=`<${t}>${o.slice(d,d+i.length)}</${t}>`,l=d+i.length,a=l;}c&&(c+=o.slice(l),o=c);}return o}function bt(n,e){if(!n)return Object.keys(e);let t=n.split(",").map(r=>r.trim()).filter(Boolean),o=Object.keys(e);return t.filter(r=>o.includes(r))}function yt(n,e){let t={};for(let o of n)t[o]={weight:e?.[o]??1};return t}function wt(n){return n==="all"||n==="phrase"?n:"any"}function Mt(n){if(n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(Mt);let e={};for(let t of Object.keys(n).sort())e[t]=Mt(n[t]);return e}async function de(n){let e=JSON.stringify(Mt(n)),t=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",t);return `"${Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("").substring(0,32)}"`}function Et(n,e){return n?n==="*"?true:n.split(",").map(t=>t.trim()).includes(e):false}function Rt(n,e){return !n||n==="*"?true:n.split(",").map(t=>t.trim()).includes(e)}function oo(n,e){return n==="in"||n==="nin"||n==="between"?e.split(",").map(t=>t.trim()):n==="null"?e.toLowerCase()==="true":e}function Uo(n){let e=n.match(/^\[([a-z]+)\](.*)$/);if(e&&b$2(e[1])){let t=e[1];return {operator:t,value:oo(t,e[2])}}return {operator:"eq",value:n}}function te(n,e){let t=[],o={},{filterFields:r=[],filterConfig:s={},searchFields:i=[],searchFieldName:u="search",sortFields:l=[],defaultSort:c,defaultPerPage:a=20,maxPerPage:d=100,cursorPaginationEnabled:p=false,softDeleteQueryParam:m="withDeleted",allowedIncludes:h=[],fieldSelectionEnabled:f=false,allowedSelectFields:y=[],blockedSelectFields:b=[],alwaysIncludeFields:g=[],defaultSelectFields:S=[]}=e,F={};for(let I of r)F[I]=["eq"];Object.assign(F,s);for(let[I,De]of Object.entries(n)){if(De==null)continue;let B=String(De);if(p&&I==="cursor"){o.cursor=B;continue}if(p&&I==="limit"){o.limit=Math.min(d,Math.max(1,Number.parseInt(B,10)||a));continue}if(I==="page"){o.page=Math.max(1,Number.parseInt(B,10)||1);continue}if(I==="per_page"){o.per_page=Math.min(d,Math.max(1,Number.parseInt(B,10)||a));continue}if(I==="sort"){(l.length===0||l.includes(B))&&(o.order_by=B);continue}if(I==="order"){(B==="asc"||B==="desc")&&(o.order_by_direction=B);continue}if(I===u&&i.length>0){o.search=B;continue}if(I===m){o.withDeleted=B.toLowerCase()==="true";continue}if(I==="onlyDeleted"){o.onlyDeleted=B.toLowerCase()==="true";continue}if(I==="include"){let re=B.split(",").map(K=>K.trim()).filter(Boolean);h&&h.length>0?o.include=re.filter(K=>h.includes(K)):o.include=re;continue}if(I==="fields"&&f){let K=B.split(",").map(ce=>ce.trim()).filter(Boolean);y.length>0&&(K=K.filter(ce=>y.includes(ce))),b.length>0&&(K=K.filter(ce=>!b.includes(ce))),g.length>0&&(K=[...new Set([...g,...K])]),o.fields=K;continue}let He=I.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(He){let re=He[1],K=He[2];F[re]?.includes(K)&&t.push({field:re,operator:K,value:oo(K,B)});continue}F[I]&&t.push({field:I,operator:"eq",value:B});}if(o.page||(o.page=1),o.per_page||(o.per_page=a),!o.order_by&&c?.field&&(o.order_by=c.field),o.order_by_direction||(o.order_by_direction=c?.order??"asc"),f&&!o.fields&&S.length>0){let I=[...S];g.length>0&&(I=[...new Set([...g,...I])]),o.fields=I;}return {filters:t,options:o}}function Z(n,e=[]){if(e.length===0)return n;let t=new Set(Object.keys(n.shape)),o=e.filter(s=>t.has(s));if(o.length===0)return n;let r=Object.fromEntries(o.map(s=>[s,true]));return n.omit(r)}function Bo(n,e={},t=[],o=[],r=[]){let{allowedFields:s=[],blockedFields:i=[],alwaysIncludeFields:u=[],defaultFields:l=[],allowComputedFields:c=true,allowRelationFields:a=true}=e;if(!n||typeof n!="string"||n.trim()==="")return l.length>0?{fields:[...new Set([...u,...l])],isActive:false}:{fields:[],isActive:false};let d=n.split(",").map(f=>f.trim()).filter(Boolean),p=new Set;for(let f of t)(s.length===0||s.includes(f))&&(i.includes(f)||p.add(f));if(c)for(let f of o)(s.length===0||s.includes(f))&&(i.includes(f)||p.add(f));if(a)for(let f of r)(s.length===0||s.includes(f))&&(i.includes(f)||p.add(f));let m=d.filter(f=>p.has(f));return {fields:[...new Set([...u,...m])],isActive:true}}function Re(n,e){if(!e.isActive||e.fields.length===0)return n;let t={};for(let o of e.fields)o in n&&(t[o]=n[o]);return t}function St(n,e){return !e.isActive||e.fields.length===0?n:n.map(t=>Re(t,e))}var no="__honoCrudResolvedSchema:";function zo(n){return typeof n.getBodySchema=="function"}var x=class extends o{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=f$1(this._meta.model.audit)),this._auditLogger}getAuditConfig(){return a$4(this._meta.model.audit)}isAuditEnabled(){return this.getAuditConfig().enabled}getAuditUserId(){let e=this.getAuditConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?a$1(this.context,a$2.userId):void 0}getVersionManager(){return this._versionManager||(this._versionManager=g(this._meta.model.versioning,this._meta.model.tableName)),this._versionManager}getVersioningConfig(){return a$5(this._meta.model.versioning,this._meta.model.tableName)}isVersioningEnabled(){return this.getVersioningConfig().enabled}getVersioningUserId(){let e=this.getVersioningConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?a$1(this.context,a$2.userId):void 0}getSoftDeleteConfig(){return ct(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return pt(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,t,o){return nt(e,this._meta.model,t,o)}applyManagedUpdateFields(e){return st(e,this._meta.model)}assertIdStrategySupported(e){it(this._meta.model,e);}getTimestampsConfig(){return ie(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return ut(this.context,e)}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();if(!t&&e.required)throw new HTTPException(400,{message:e.errorMessage});return t}injectTenantId(e){let t=this.getMultiTenantConfig();if(!t.enabled)return e;let o=this.getTenantId();return o?{...e,[t.field]:o}:e}async emitEvent(e,t){let o=d$2(this.context??void 0);o&&await o.emit({type:e,table:this._meta.model.tableName,recordId:t.recordId,data:t.data??null,previousData:t.previousData,userId:this.getAuditUserId(),tenantId:this.context?this.getTenantId():void 0,organizationId:this.context?a$1(this.context,a$2.organizationId):void 0,timestamp:new Date().toISOString(),metadata:t.metadata});}async encryptOnWrite(e){let t=this._meta.model.fieldEncryption;return t?await e$1(e,t.fields,t.keyProvider):e}async decryptOnRead(e){let t=this._meta.model.fieldEncryption;return t?await f$2(e,t.fields,t.keyProvider):e}applyProfile(e){let t=this._meta.model.serializationProfile;return t?a$6(e,t):e}applyProfileToArray(e){let t=this._meta.model.serializationProfile;return t?b$3(e,t):e}transform(e){return e}async finalizeRecord(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await ae(r,o.computedFields));let s=o.serializer?o.serializer(r):r,i=this.applyProfile(s),u=this.transform(i);return t?.isActive&&t.fields.length>0?Re(u,t):u}async finalizeArray(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await dt(r,o.computedFields));let s=o.serializer?r.map(l=>o.serializer(l)):r,u=this.applyProfileToArray(s).map(l=>this.transform(l));return t?.isActive&&t.fields.length>0?St(u,t):u}getRecordId(e){if(e===null||typeof e!="object")return null;let t=this._meta.model.primaryKeys[0],o=e[t];return typeof o=="string"||typeof o=="number"?o:null}getParentId(e){return this.getRecordId(e)}getPolicies(){if(this.context){let e=a$1(this.context,s);if(e)return e}return this._meta.model.policies}buildPolicyContext(){let e=this.context;return {user:e?a$1(e,a$2.user):void 0,userId:e?a$1(e,a$2.userId):void 0,tenantId:e?a$1(e,a$2.tenantId):void 0,organizationId:e?a$1(e,a$2.organizationId):void 0,request:e?.req?.raw??new Request("http://localhost/")}}async applyReadPolicy(e){let t=this.getPolicies();if(!t)return e;let o=this.buildPolicyContext();if(t.read&&!await t.read(o,e))return null;if(t.fields){let r=t.fields(o,e);return {...e,...r}}return e}async applyReadPolicyToArray(e){if(!this.getPolicies())return e;let o=[];for(let r of e){let s=await this.applyReadPolicy(r);s!==null&&o.push(s);}return o}async applyWritePolicy(e){let t=this.getPolicies();if(!t?.write)return;if(!await t.write(this.buildPolicyContext(),e))throw new HTTPException(403,{message:"Forbidden by policy"})}applyReadPushdown(e){let t=this.getPolicies();if(!t?.readPushdown)return;let o=t.readPushdown(this.buildPolicyContext());o&&o.length>0&&e.filters.push(...o);}buildHookContext(){let e=this.context;return {db:{tx:this._tx},request:e?.req?.raw,tenantId:e?this.getTenantId():void 0,organizationId:e?a$1(e,a$2.organizationId):void 0,userId:e?a$1(e,a$2.userId):void 0,agentId:e?a$1(e,a$2.agentId):void 0,agentRunId:e?a$1(e,a$2.agentRunId):void 0}}getModelSchema(){if(this.context&&this._meta.model.resolveSchema){let e=a$1(this.context,no+this._meta.model.tableName);if(e)return e}return this._meta.model.schema}async resolveModelSchema(){let e=this._meta.model.resolveSchema;if(!e||!this.context)return this._meta.model.schema;let t=no+this._meta.model.tableName,o=a$1(this.context,t);if(o)return o;let r={tenantId:a$1(this.context,a$2.tenantId),organizationId:a$1(this.context,a$2.organizationId),request:this.context.req?.raw,env:this.context.env},s;try{s=await e(r);}catch(i){throw new a(i instanceof Error?i.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",i instanceof Error?{cause:i.message}:void 0)}return b$4(this.context,t,s),s}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&zo(this)){let t=e.body;try{t=await this.context.req.json();}catch{}let r=this.getBodySchema().safeParse(t);if(!r.success)throw b.fromZodError(r.error);e.body=r.data;}return e}};function qo(){return z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}function R(n){return {description:n??"Error",content:{"application/json":{schema:qo()}}}}var xt=class extends x{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,t=H(this._meta.model),o=this.getMultiTenantConfig();o.enabled&&t.push(o.field),this._meta.fields?e=this._meta.fields:e=Z(this.getModelSchema(),t);let r=this.getNestedWritableRelations();if(r.length===0)return e;let s={...e.shape};for(let i of r){let u=this._meta.model.relations?.[i];if(!u?.schema)continue;let l=["id",u.foreignKey],c=Z(u.schema,l);u.type==="hasMany"?s[i]=z.array(c).optional():s[i]=c.optional();}return z.object(s)}getNestedWritableRelations(){if(this.allowNestedCreate.length>0)return this.allowNestedCreate;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>o.nestedWrites?.allowCreate===true).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return ee(e,t)}getSchema(){let e=this.getBodySchema();return {...this.schema,request:{body:{content:{"application/json":{schema:e}},required:true}},responses:{201:{description:"Resource created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Validation error")}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t){return e}async after(e,t){return e}transform(e){return e}async createNested(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override createNested() in your adapter.`),[]}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let s=this.buildHookContext();r=await this.before(r,s),r=await this.encryptOnWrite(r),r=await this.create(r,s.db.tx).catch(W),r=await this.decryptOnRead(r);let i=this.getParentId(r),u={};if(Object.keys(o).length>0&&i!==null)for(let[c,a]of Object.entries(o)){if(a==null)continue;let d=this._meta.model.relations?.[c];if(!d)continue;let p=await this.createNested(i,c,d,a);u[c]=p;}if(Object.keys(u).length>0){let c={};for(let[a,d]of Object.entries(u)){let p=this._meta.model.relations?.[a];p&&(p.type==="hasMany"?c[a]=d:c[a]=d[0]||null);}r={...r,...c};}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(r,s))):r=await this.after(r,s),this.isAuditEnabled()&&i!==null){let c=this.getAuditLogger();this.runAfterResponse(c.logCreate(this._meta.model.tableName,i,r,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("created",{recordId:i,data:r}));let l=await this.finalizeRecord(r);return this.success(l,201)}};var Ot=class extends x{lookupField="id";lookupFields;additionalFilters;etagEnabled=false;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){let e={};if(this.additionalFilters?.length)for(let t of this.additionalFilters)e[t]=z.string().optional();if(this.allowedIncludes.length>0&&(e.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let t=this.getAvailableSelectFields();e.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${t.join(", ")}`});}if(Object.keys(e).length!==0)return z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=this.getQuerySchema();return {...this.schema,request:{params:this.getParamsSchema(),...e&&{query:e}},responses:{200:{description:"Resource retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:R("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async getIncludeOptions(){let{query:e}=await this.getValidatedData(),t=e?.include;if(!t||typeof t!="string")return {relations:[]};let o=t.split(",").map(r=>r.trim()).filter(Boolean);return this.allowedIncludes.length>0?{relations:o.filter(r=>this.allowedIncludes.includes(r))}:{relations:o}}async getFieldSelection(){if(!this.fieldSelectionEnabled)return {fields:[],isActive:false};let{query:e}=await this.getValidatedData(),t=e?.fields;if(!t||typeof t!="string"||t.trim()==="")return this.defaultSelectFields.length>0?{fields:[...new Set([...this.alwaysIncludeFields,...this.defaultSelectFields])],isActive:true}:{fields:[],isActive:false};let o=t.split(",").map(i=>i.trim()).filter(Boolean),r=new Set(this.getAvailableSelectFields()),s=o.filter(i=>r.has(i));return this.alwaysIncludeFields.length>0&&(s=[...new Set([...this.alwaysIncludeFields,...s])]),{fields:s,isActive:true}}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters(),r=await this.getIncludeOptions(),s=await this.getFieldSelection();if(e){let c=this.getMultiTenantConfig();o[c.field]=e;}let i=await this.read(t,o,r);if(!i)throw new c(this._meta.model.tableName,t);i=await this.decryptOnRead(i);let u=await this.applyReadPolicy(i);if(u===null)throw new c(this._meta.model.tableName,t);i=u,i=await this.after(i);let l=await this.finalizeRecord(i,s);if(this.etagEnabled){let c=await de(l),a=this.getContext(),d=a.req.header("If-None-Match");if(Et(d,c))return new Response(null,{status:304,headers:{ETag:c}});a.header("ETag",c);}return this.success(l)}};var kt=class extends x{lookupField="id";lookupFields;additionalFilters;allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];etagEnabled=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields.partial();else {let r=H(this._meta.model);this.blockedUpdateFields&&(r=[...r,...this.blockedUpdateFields]);let s=Z(this.getModelSchema(),r);if(this.allowedUpdateFields){let i={};for(let u of this.allowedUpdateFields)i[u]=true;s=s.pick(i);}e=s.partial();}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let i=s.schema,u=z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()}).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return ee(e,t)}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Validation error"),404:R("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getObject(){let{body:e}=await this.getValidatedData();return e}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){return e}async after(e,t,o){return t}transform(e){return e}async findExisting(e,t,o){return null}async processNestedWrites(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let b=this.getMultiTenantConfig();o[b.field]=e;}let r=await this.getObject(),{mainData:s,nestedData:i}=this.extractNestedData(r),u=this.getPolicies(),l=await this.findExisting(t,o,this._tx);if(l&&u?.write&&await this.applyWritePolicy(l),this.etagEnabled&&l){let b=this.getContext().req.header("If-Match");if(b){let g=await de(l);if(!Rt(b,g))return this.error("Resource has been modified by another request","CONFLICT",409)}}let c$1;if(this.isVersioningEnabled()&&l){let b=this.getVersionManager(),g=this.getParentId(l);g!==null&&(c$1=await b.saveVersion(g,l,void 0,this.getVersioningUserId()));}let a=s;if(this.isVersioningEnabled()&&c$1!==void 0){let b=this.getVersioningConfig().field;a[b]=c$1;}let d=this.buildHookContext();a=await this.before(a,d),a=await this.encryptOnWrite(a);let p=await this.update(t,a,o,d.db.tx);if(!p)throw new c(this._meta.model.tableName,t);p=await this.decryptOnRead(p);let m=this.getParentId(p),h={};if(Object.keys(i).length>0&&m!==null)for(let[b,g]of Object.entries(i)){if(g==null)continue;let S=this._meta.model.relations?.[b];if(!S)continue;let F;ge(g)?F={create:g}:F=g;let I=await this.processNestedWrites(m,b,S,F);h[b]=I;}if(Object.keys(h).length>0)for(let[b,g]of Object.entries(h)){let S=this._meta.model.relations?.[b];S&&(S.type==="hasMany"?p[b]=[...g.created,...g.updated]:p[b]=g.created[0]||g.updated[0]||null);}let f=l??p;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(f,p,d)));else {let b=await this.after(f,p,d);b!=null&&(p=b);}if(this.isAuditEnabled()&&m!==null&&l){let b=this.getAuditLogger();this.runAfterResponse(b.logUpdate(this._meta.model.tableName,m,l,p,this.getAuditUserId()));}m!==null&&this.runAfterResponse(this.emitEvent("updated",{recordId:m,data:p,previousData:l??void 0}));let y=await this.finalizeRecord(p);if(this.etagEnabled){let b=await de(y);this.getContext().header("ETag",b);}return this.success(y)}};var Ct=class extends x{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";includeCascadeResults=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getCascadeRelations(e){let t=this._meta.model.relations;return t?Object.entries(t).filter(([o,r])=>{let s=r.cascade?.[e];return s&&s!=="noAction"}).map(([o,r])=>({name:o,config:r,action:r.cascade[e]})):[]}getSchema(){let e=this.includeCascadeResults?z.object({deleted:z.literal(true),cascade:z.object({deleted:z.record(z.string(),z.number()),nullified:z.record(z.string(),z.number())}).optional()}):z.object({deleted:z.literal(true)});return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:R("Resource not found"),409:{description:"Cannot delete - related records exist (restrict)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.object({relation:z.string(),count:z.number()}).optional()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){}async countRelated(e,t,o,r){return b$1().warn(`countRelated not implemented for ${t}. Override in your adapter for restrict cascade to work.`),0}async deleteRelated(e,t,o,r){return b$1().warn(`deleteRelated not implemented for ${t}. Override in your adapter for cascade delete to work.`),0}async nullifyRelated(e,t,o,r){return b$1().warn(`nullifyRelated not implemented for ${t}. Override in your adapter for setNull cascade to work.`),0}async processCascade(e,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r),i={deleted:{},nullified:{}};for(let{name:u,config:l,action:c}of s)if(c==="cascade"){let a=await this.deleteRelated(e,u,l,o);a>0&&(i.deleted[u]=a);}else if(c==="setNull"){let a=await this.nullifyRelated(e,u,l,o);a>0&&(i.nullified[u]=a);}return i}async checkRestrictConstraints(e,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r);for(let{name:i,config:u,action:l}of s)if(l==="restrict"){let c=await this.countRelated(e,i,u,o);if(c>0)throw new d(`Cannot delete: ${c} related ${i} record(s) exist. Remove them first or change the cascade configuration.`,{relation:i,count:c})}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let d=this.getMultiTenantConfig();o[d.field]=e;}let r=this.isSoftDeleteEnabled(),s=await this.findForDelete(t,o,this._tx);if(!s)throw new c(this._meta.model.tableName,t);let i=this.getParentId(s);i!==null&&await this.checkRestrictConstraints(i,r),await this.applyWritePolicy(s);let u=this.buildHookContext();if(await this.before(t,u),!await this.delete(t,o,u.db.tx))throw new c(this._meta.model.tableName,t);let c$1;if(i!==null&&(c$1=await this.processCascade(i,r)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(s,u))):await this.after(s,u),this.isAuditEnabled()&&i!==null){let d=this.getAuditLogger();this.runAfterResponse(d.logDelete(this._meta.model.tableName,i,s,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("deleted",{recordId:i,previousData:s}));let a={deleted:true};if(this.includeCascadeResults&&c$1){let d=Object.keys(c$1.deleted).length>0,p=Object.keys(c$1.nullified).length>0;(d||p)&&(a.cascade=c$1);}return this.success(a)}};var be=class extends x{filterFields=[];filterConfig;searchFields=[];searchFieldName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;cursorField;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getQuerySchema(){let e={page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(e.sort=z.enum(this.sortFields).optional().meta({description:"Field to sort by"}),e.order=z.enum(d$1).optional().meta({description:"Sort direction (asc or desc)"})),this.searchFields.length>0&&(e[this.searchFieldName]=z.string().optional());for(let o of this.filterFields)e[o]=z.string().optional();if(this.filterConfig)for(let[o,r]of Object.entries(this.filterConfig)){for(let s of r)e[`${o}[${s}]`]=z.string().optional();e[o]=z.string().optional();}let t=this.getSoftDeleteConfig();if(t.enabled&&t.allowQueryDeleted&&(e[t.queryParam]=z.enum(["true","false"]).optional(),e.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(e.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let o=this.getAvailableSelectFields();e.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${o.join(", ")}`});}return this.cursorPaginationEnabled&&(e.cursor=z.string().optional().meta({description:"Opaque cursor for fetching the next page"}),e.limit=z.string().optional().meta({description:"Number of items to return (cursor pagination)"})),z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"List of resources",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(this.getModelSchema()),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),has_next_page:z.boolean(),has_prev_page:z.boolean(),next_cursor:z.string().optional(),prev_cursor:z.string().optional()})})}}}}}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:this.searchFields,searchFieldName:this.searchFieldName,sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,cursorPaginationEnabled:this.cursorPaginationEnabled,cursorField:this.cursorField,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return te(e||{},o)}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getFilters();if(e){let c=this.getMultiTenantConfig();t.filters.push({field:c.field,operator:"eq",value:e});}this.applyReadPushdown(t);let o=await this.list(t),r=await Promise.all(o.result.map(c=>this.decryptOnRead(c))),s=await this.applyReadPolicyToArray(r),i=await this.after(s),u=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?{fields:t.options.fields,isActive:true}:void 0,l=await this.finalizeArray(i,u);return this.successPaginated(l,o.result_info)}};var Pt=class extends x{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...H(this._meta.model),...this.excludeFromClone];return Z(this.getModelSchema(),e).partial()}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:false}},responses:{201:{description:"Resource cloned successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:R("Source resource not found"),409:R("Unique-constraint violation (e.g. natural-key collision)")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getOverrides(){let{body:e}=await this.getValidatedData();return e||{}}async before(e){return e}async after(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getOverrides(),r={};if(e){let a=this.getMultiTenantConfig();r[a.field]=e;}let s=await this.findSource(t,r);if(!s)throw new c(this._meta.model.tableName,t);let i=at(s,this._meta.model);for(let a of this.excludeFromClone)delete i[a];Object.assign(i,o);let u=await this.before(i),l=await this.createClone(u).catch(W);l=await this.after(l);let c$1=await this.finalizeRecord(l);return this.success(c$1,201)}};var ye=new Map,Ko=["password","token","secret","apiKey","creditCard","ssn"];function Oe(n,e){if(n==null||typeof n!="object")return n;if(Array.isArray(n))return n.map(o=>Oe(o,e));let t={};for(let[o,r]of Object.entries(n))e.includes(o)||(t[o]=typeof r=="object"&&r!==null?Oe(r,e):r);return t}function Wo(n){let{table:e,events:t,emitter:o,filter:r,heartbeatInterval:s=3e4,maxConnections:i=1e3,connectionTimeout:u=3e5,excludeFields:l=Ko}=n;return c=>{let a=d$2(c,o);if(!a)return c.json({success:false,error:{code:"EVENT_EMITTER_NOT_CONFIGURED",message:"Event emitter not configured"}},500);let d=ye.get(e)||0;return d>=i?c.json({success:false,error:{code:"TOO_MANY_CONNECTIONS",message:"Too many SSE connections"}},503):(ye.set(e,d+1),streamSSE(c,async p=>{let m,h=async g=>{if(t&&t.length>0&&!t.includes(g.type)||r&&!r(g,c))return;let S=l.length>0?Oe(g.data,l):g.data,F=g.previousData&&l.length>0?Oe(g.previousData,l):g.previousData;try{await p.writeSSE({event:`${g.table}.${g.type}`,data:JSON.stringify({type:g.type,table:g.table,recordId:g.recordId,data:S,previousData:F,timestamp:g.timestamp}),id:`${g.table}-${g.recordId}-${Date.now()}`});}catch{}};m=a.onTable(e,h);let f=()=>{m.unsubscribe();let g=ye.get(e)||1;g<=1?ye.delete(e):ye.set(e,g-1);};p.onAbort(()=>{f();});let y=Date.now(),b=y;for(;!p.closed;){await p.sleep(1e3);let g=Date.now();if(g-y>=u){p.abort();break}if(g-b>=s){b=g;try{await p.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}}))}}var vt=class extends x{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Soft delete not enabled or record not deleted"),404:R("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getAdditionalFilters();await this.before(e);let o=await this.restore(e,t);if(!o)throw new c(this._meta.model.tableName,e);this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(o))):o=await this.after(o);let r=this.getRecordId(o);if(this.isAuditEnabled()&&r!==null){let i=this.getAuditLogger();this.runAfterResponse(i.logRestore(this._meta.model.tableName,r,o,this.getAuditUserId()));}r!==null&&this.runAfterResponse(this.emitEvent("restored",{recordId:r,data:o}));let s=await this.finalizeRecord(o);return this.success(s)}};var jt=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=H(this._meta.model,{includePrimaryKeys:false});for(let l of this._meta.model.primaryKeys)r.includes(l)||s.push(l);let i=Z(this.getModelSchema(),s),u={};for(let[l,c]of Object.entries(i.shape))r.includes(l)?u[l]=c:u[l]=c.optional();e=z.object(u);}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let i=s.schema,u=z.union([s.type==="hasMany"?z.array(i.partial()):i.partial(),z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),upsert:z.union([i.partial(),z.array(i.partial())]).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()})]).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return ee(e,t)}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(false)})}}},201:{description:"Resource created (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(true)})}}},400:R("Validation error")}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t,o){return e}async beforeCreate(e,t){return e}async beforeUpdate(e,t,o){return e}async after(e,t,o){return e}async nativeUpsert(e,t){return b$1().warn("Native upsert not implemented for this adapter. Falling back to find-then-insert/update pattern."),this.performStandardUpsert(e,t)}async performStandardUpsert(e,t){let o=await this.findExisting(e,t);if(o){let r={...e};if(this.createOnlyFields)for(let i of this.createOnlyFields)delete r[i];return r=await this.beforeUpdate(r,o,t),{data:await this.update(o,r,t),created:false}}else {let r={...e};if(this.updateOnlyFields)for(let i of this.updateOnlyFields)delete r[i];return r=await this.beforeCreate(r,t),{data:await this.create(r,t),created:true}}}async upsert(e,t){return this.useNativeUpsert?this.nativeUpsert(e,t):this.performStandardUpsert(e,t)}async processNestedWrites(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let s=await this.findExisting(r),i=!s;r=await this.before(r,i);let u=await this.upsert(r).catch(W),l=u.data,c=this.getParentId(l),a={};if(Object.keys(o).length>0&&c!==null)for(let[p,m]of Object.entries(o)){if(m==null)continue;let h=this._meta.model.relations?.[p];if(!h)continue;let f;ge(m)?f={create:m}:f=m;let y=await this.processNestedWrites(c,p,h,f);a[p]=y;}if(Object.keys(a).length>0)for(let[p,m]of Object.entries(a)){let h=this._meta.model.relations?.[p];h&&(h.type==="hasMany"?l[p]=[...m.created,...m.updated]:l[p]=m.created[0]||m.updated[0]||null);}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(l,u.created))):l=await this.after(l,u.created),this.isAuditEnabled()&&c!==null){let p=this.getAuditLogger();this.runAfterResponse(p.logUpsert(this._meta.model.tableName,c,l,s,u.created,this.getAuditUserId()));}let d=await this.finalizeRecord(l);return this.json({success:true,result:d,created:u.created},u.created?201:200)}};var Ft=class extends x{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:Z(this.getModelSchema(),H(this._meta.model));return z.object({items:z.array(e).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{201:{description:"Resources created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number()})})}}},207:{description:"Partial success (some items failed)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}async before(e,t,o){return e}async after(e,t,o){return e}transform(e){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let c=0;c<e.length;c++)try{let a=await this.before(e[c],c);o.push(a);}catch(a){if(this.stopOnError)throw a;t.push({index:c,error:a instanceof Error?a.message:String(a)});}let r=await this.batchCreate(o).catch(W),s=[];for(let c=0;c<r.length;c++)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(r[c],c))),s.push(r[c])):s.push(await this.after(r[c],c));}catch(a){if(this.stopOnError)throw a;t.push({index:c,error:a instanceof Error?a.message:String(a)}),s.push(r[c]);}if(this.isAuditEnabled()){let c=this.getAuditLogger(),a=s.map(d=>{let p=this.getRecordId(d);return p===null?null:{recordId:p,record:d}}).filter(d=>d!==null);a.length>0&&this.runAfterResponse(c.logBatch("batch_create",this._meta.model.tableName,a,this.getAuditUserId()));}let i=await this.finalizeArray(s),u={success:true,result:{created:i,count:i.length,...t.length>0&&{errors:t}}},l=t.length>0?207:201;return this.json(u,l)}};var It=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:Z(this.getModelSchema(),H(this._meta.model));return z.object({items:z.array(z.object({id:z.string(),data:e.partial()})).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}filterUpdateData(e){let t={...e};if(this.allowedUpdateFields){let o=new Set(this.allowedUpdateFields);t=Object.fromEntries(Object.entries(t).filter(([r])=>o.has(r)));}if(this.blockedUpdateFields)for(let o of this.blockedUpdateFields)delete t[o];for(let o of this._meta.model.primaryKeys)delete t[o];return t}async before(e,t,o){return t}async after(e,t){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let a of e)try{let d=this.filterUpdateData(a.data),p=await this.before(a.id,d);o.push({id:a.id,data:p});}catch(d){if(this.stopOnError)throw d;t.push({id:a.id,error:d instanceof Error?d.message:String(d)});}let{updated:r,notFound:s}=await this.batchUpdate(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let p=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:p,error:d instanceof Error?d.message:String(d)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=i.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,record:p}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_update",this._meta.model.tableName,d,this.getAuditUserId()));}let u=await this.finalizeArray(i),l={success:true,result:{updated:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(l,c)}};var At=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){let e=this.isSoftDeleteEnabled();return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:e?"Resources soft-deleted successfully":"Resources deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(d){if(this.stopOnError)throw d;t.push({id:a,error:d instanceof Error?d.message:String(d)});}let{deleted:r,notFound:s}=await this.batchDelete(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let p=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:p,error:d instanceof Error?d.message:String(d)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=i.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,previousRecord:p}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_delete",this._meta.model.tableName,d,this.getAuditUserId()));}let u=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,l={success:true,result:{deleted:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(l,c)}};var _t=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:R("Soft delete not enabled or validation error")}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(d){if(this.stopOnError)throw d;t.push({id:a,error:d instanceof Error?d.message:String(d)});}let{restored:r,notFound:s}=await this.batchRestore(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let p=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:p,error:d instanceof Error?d.message:String(d)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=i.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,record:p}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_restore",this._meta.model.tableName,d,this.getAuditUserId()));}let u=await this.finalizeArray(i),l={success:true,result:{restored:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(l,c)}};var Tt=class extends x{upsertKeys;createOnlyFields;updateOnlyFields;maxBatchSize=100;continueOnError=false;useNativeUpsert=false;beforeHookMode="sequential";afterHookMode="sequential";getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getItemSchema(){if(this._meta.fields)return this._meta.fields;let e=this.getUpsertKeys(),t=H(this._meta.model,{includePrimaryKeys:false});for(let s of this._meta.model.primaryKeys)e.includes(s)||t.push(s);let o=Z(this.getModelSchema(),t),r={};for(let[s,i]of Object.entries(o.shape))e.includes(s)?r[s]=i:r[s]=i.optional();return z.object(r)}getBodySchema(){return z.array(this.getItemSchema()).max(this.maxBatchSize)}getSchema(){let e=z.object({data:this.getModelSchema(),created:z.boolean(),index:z.number()});return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Batch upsert completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({items:z.array(e),createdCount:z.number(),updatedCount:z.number(),totalCount:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e}async beforeItem(e,t,o,r){return e}async afterItem(e,t,o,r){return e}async beforeBatch(e,t){return e}async afterBatch(e,t){return e}async upsertOne(e,t,o){let r=await this.findExisting(e,o),s=!r,i=await this.beforeItem(e,t,s,o),u;if(r){if(this.createOnlyFields)for(let l of this.createOnlyFields)delete i[l];u=await this.update(r,i,o);}else {if(this.updateOnlyFields)for(let l of this.updateOnlyFields)delete i[l];u=await this.create(i,o);}return u=await this.afterItem(u,t,s,o),{data:u,created:s,index:t}}async nativeBatchUpsert(e,t){return b$1().warn("Native batch upsert not implemented for this adapter. Falling back to item-by-item pattern."),this.performStandardBatchUpsert(e,t)}async performStandardBatchUpsert(e,t){let o=[],r=[],s=0,i=0;for(let l=0;l<e.length;l++)try{let c=await this.upsertOne(e[l],l,t);o.push(c),c.created?s++:i++;}catch(c){if(this.continueOnError)r.push({index:l,error:c instanceof Error?c.message:String(c)});else throw c}let u={items:o,createdCount:s,updatedCount:i,totalCount:o.length};return r.length>0&&(u.errors=r),u}async batchUpsert(e,t){return this.useNativeUpsert?this.nativeBatchUpsert(e,t):this.performStandardBatchUpsert(e,t)}async handle(){let e=await this.getItems();e=await this.beforeBatch(e);let t=await this.batchUpsert(e).catch(W);if(t=await this.afterBatch(t),this._meta.model.computedFields&&(t.items=await Promise.all(t.items.map(async o=>({...o,data:await ae(o.data,this._meta.model.computedFields)})))),this.isAuditEnabled()){let o=this.getAuditLogger(),r=t.items.map(s=>{let i=this.getRecordId(s.data);return i===null?null:{recordId:i,record:s.data}}).filter(s=>s!==null);r.length>0&&this.runAfterResponse(o.logBatch("batch_upsert",this._meta.model.tableName,r,this.getAuditUserId()));}return t.items=t.items.map(o=>{let r=this._meta.model.serializer?this._meta.model.serializer(o.data):o.data,s=this.applyProfile(r);return {...o,data:this.transform(s)}}),this.success(t)}};var Nt=class extends x{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getSchema(){return {request:{body:{content:{"application/json":{schema:this.getUpdateSchema().partial()}}},query:z.object({dryRun:z.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z.object({success:z.boolean(),matched:z.number(),updated:z.number(),dryRun:z.boolean()})}}},400:{description:"Bad request",content:{"application/json":{schema:z.object({success:z.boolean(),error:z.string()})}}}}}}async handle(){let e=this.getContext(),o=(await this.getValidatedData()).body;if(!o||Object.keys(o).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let r=e.req.query("dryRun"),s=r==="true"||r==="1",i=te(e.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),u=await this.countMatching(i);if(u===0)return this.json({success:true,matched:0,updated:0,dryRun:s});if(u>this.maxBulkSize)return this.error(`Bulk patch affects ${u} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(u>=this.confirmThreshold&&e.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${u} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(s)return this.json({success:true,matched:u,updated:0,dryRun:true});let l=o;this.beforeBulkPatch&&(l=await this.beforeBulkPatch(l,i,u));let c=await this.applyPatch(l,i),a={matched:u,updated:c.updated,dryRun:false,records:this.returnRecords?c.records:void 0};return this.afterBulkPatch&&await this.afterBulkPatch(a),this.json({success:true,matched:a.matched,updated:a.updated,dryRun:false,...this.returnRecords&&a.records?{records:a.records}:{}})}};var so=z.object({id:z.string(),recordId:z.union([z.string(),z.number()]),version:z.number(),data:z.record(z.string(),z.unknown()),createdAt:z.date(),changedBy:z.string().optional(),changeReason:z.string().optional(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()})).optional()}),Dt=class extends x{lookupField="id";defaultLimit=20;maxLimit=100;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({limit:z.coerce.number().min(1).max(this.maxLimit).optional(),offset:z.coerce.number().min(0).optional()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version history retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({versions:z.array(so),totalVersions:z.number()})})}}},400:R("Versioning not enabled"),404:R("Record not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getPaginationOptions(){let{query:e}=await this.getValidatedData();return {limit:e?.limit?Number(e.limit):this.defaultLimit,offset:e?.offset?Number(e.offset):0}}async recordExists(e){return true}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{limit:t,offset:o}=await this.getPaginationOptions();if(!await this.recordExists(e))throw new c(this._meta.model.tableName,e);let s=this.getVersionManager(),i=await s.getVersions(e,{limit:t,offset:o}),u=await s.getLatestVersion(e);return this.success({versions:i,totalVersions:u})}},Ht=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:so})}}},400:R("Versioning not enabled"),404:R("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),r=await this.getVersionManager().getVersion(e,t);if(!r)throw new c(`version ${t}`,e);return this.success(r)}},Vt=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({from:z.coerce.number().min(1),to:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version comparison completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({from:z.number(),to:z.number(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()}))})})}}},400:R("Versioning not enabled or invalid parameters"),404:R("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumbers(){let{query:e}=await this.getValidatedData();return {from:e?.from?Number(e.from):0,to:e?.to?Number(e.to):0}}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{from:t,to:o}=await this.getVersionNumbers(),s=await this.getVersionManager().compareVersions(e,t,o);return this.success({from:t,to:o,changes:s})}},Zt=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Record rolled back successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Versioning not enabled"),404:R("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),o=this.getVersionManager(),r=await o.getVersion(e,t);if(!r)throw new c(`version ${t}`,e);let i=await o.getLatestVersion(e)+1,u=await this.rollback(e,r.data,i),l=this._meta.model.serializer?this._meta.model.serializer(u):u;return this.success(l)}};var Go={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},Ut=class extends x{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {...Go,...this.aggregateConfig}}getQuerySchema(){return z.object({count:z.union([z.string(),z.array(z.string())]).optional(),sum:z.union([z.string(),z.array(z.string())]).optional(),avg:z.union([z.string(),z.array(z.string())]).optional(),min:z.union([z.string(),z.array(z.string())]).optional(),max:z.union([z.string(),z.array(z.string())]).optional(),countDistinct:z.union([z.string(),z.array(z.string())]).optional(),groupBy:z.string().optional(),orderBy:z.string().optional(),orderDirection:z.enum(d$1).optional(),limit:z.coerce.number().optional(),offset:z.coerce.number().optional(),withDeleted:z.coerce.boolean().optional()}).passthrough()}getSchema(){let e=z.object({key:z.record(z.string(),z.unknown()),values:z.record(z.string(),z.number().nullable())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Aggregation result",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({values:z.record(z.string(),z.number().nullable()).optional(),groups:z.array(e).optional(),totalGroups:z.number().optional()})})}}},400:R("Invalid aggregation request")}}}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return lt(e||{})}validateAggregations(e){let t=this.getAggregateConfig();for(let o of e.aggregations)if(!(o.operation==="count"&&o.field==="*"))switch(o.operation){case "count":break;case "sum":if(t.sumFields.length>0&&!t.sumFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for SUM aggregation`);break;case "avg":if(t.avgFields.length>0&&!t.avgFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for AVG aggregation`);break;case "min":case "max":if(t.minMaxFields.length>0&&!t.minMaxFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for MIN/MAX aggregation`);break;case "countDistinct":if(t.countDistinctFields.length>0&&!t.countDistinctFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for COUNT DISTINCT aggregation`);break;default:c$1(o.operation);}if(e.groupBy){if(e.groupBy.length>this.maxGroupByFields)throw new b(`Maximum ${this.maxGroupByFields} GROUP BY fields allowed`);for(let o of e.groupBy)if(t.groupByFields.length>0&&!t.groupByFields.includes(o))throw new Error(`Field '${o}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>t.maxLimit)throw new Error(`Limit cannot exceed ${t.maxLimit}`)}getAggregateAlias(e){return e.alias?e.alias:e.field==="*"?e.operation:`${e.operation}${e.field.charAt(0).toUpperCase()}${e.field.slice(1)}`}async handle(){let e=await this.getAggregateOptions();e.aggregations.length===0&&e.aggregations.push({operation:"count",field:"*"}),this.validateAggregations(e);let t=this.getAggregateConfig();e.groupBy&&e.groupBy.length>0&&e.limit===void 0&&(e.limit=t.defaultLimit);let o=await this.aggregate(e);return this.success(o)}},Qo={eq:(n,e)=>n===e,ne:(n,e)=>n!==e,gt:(n,e)=>n>e,gte:(n,e)=>n>=e,lt:(n,e)=>n<e,lte:(n,e)=>n<=e};function Jo(n,e){let t=n.get(e);if(t)return t;let o=[];return n.set(e,o),o}function Yo(n,e){let{aggregations:t,groupBy:o,having:r,orderBy:s,orderDirection:i,limit:u,offset:l}=e;if(!o||o.length===0){let p={};for(let m of t){let h=ao(m);p[h]=io(n,m);}return {values:p}}let c=new Map;for(let p of n){let h=o.map(f=>String(p[f]??"null")).join("|");Jo(c,h).push(p);}let a=[];for(let[p,m]of c){let h=p.split("|"),f={};o.forEach((b,g)=>{f[b]=h[g]==="null"?null:h[g];});let y={};for(let b of t){let g=ao(b);y[g]=io(m,b);}a.push({key:f,values:y});}r&&(a=a.filter(p=>{for(let[m,h]of Object.entries(r)){let f=p.values[m];if(f!==null)for(let[y,b]of Object.entries(h)){let g=Qo[y];if(g&&!g(f,Number(b)))return false}}return true}));let d=a.length;if(s){let p=i==="desc"?-1:1;a.sort((m,h)=>{if(s in m.values){let f=m.values[s]??0,y=h.values[s]??0;return (f-y)*p}if(s in m.key){let f=String(m.key[s]??""),y=String(h.key[s]??"");return f.localeCompare(y)*p}return 0});}if(l!==void 0||u!==void 0){let p=l||0,m=u?p+u:void 0;a=a.slice(p,m);}return {groups:a,totalGroups:d}}function Lt(n,e){return n.map(t=>t[e]).filter(t=>typeof t=="number")}var Xo={count:(n,e)=>e==="*"?n.length:n.filter(t=>t[e]!==null&&t[e]!==void 0).length,countDistinct:(n,e)=>new Set(n.map(o=>o[e]).filter(o=>o!=null).map(o=>String(o))).size,sum:(n,e)=>{let t=0;for(let o of n){let r=o[e];typeof r=="number"&&(t+=r);}return t},avg:(n,e)=>{let t=Lt(n,e);return t.length===0?null:t.reduce((r,s)=>r+s,0)/t.length},min:(n,e)=>{let t=Lt(n,e);return t.length===0?null:Math.min(...t)},max:(n,e)=>{let t=Lt(n,e);return t.length===0?null:Math.max(...t)}};function io(n,e){if(n.length===0)return e.operation==="count"?0:null;let t=Xo[e.operation];return t?t(n,e.field):null}function ao(n){return n.alias?n.alias:n.field==="*"?n.operation:`${n.operation}${n.field.charAt(0).toUpperCase()}${n.field.slice(1)}`}function er(n){if(n instanceof z.ZodString)return true;let e=n;return e?e._def?.type==="string"||e._def?.typeName==="ZodString"||e.def?.type==="string":false}var Bt=class extends x{searchableFields={};searchFields=[];fieldWeights={};defaultMode="any";minQueryLength=2;maxQueryLength=500;highlightTag="mark";snippetLength=150;defaultMinScore=0;searchParamName="q";filterFields=[];filterConfig;sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getSearchableFields(){if(Object.keys(this.searchableFields).length>0)return this.searchableFields;if(this.searchFields.length>0)return yt(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,t={};for(let[o,r]of Object.entries(e))er(r)&&(t[o]={weight:1});return t}getQuerySchema(){let t={[this.searchParamName||"q"]:z.string().min(this.minQueryLength).max(this.maxQueryLength).meta({description:"Search query"}),fields:z.string().optional().meta({description:`Comma-separated fields to search. Available: ${Object.keys(this.getSearchableFields()).join(", ")}`}),mode:z.enum(e).optional().meta({description:"Search mode: any (OR), all (AND), phrase (exact)"}),highlight:z.enum(["true","false"]).optional().meta({description:"Include highlighted snippets"}),minScore:z.string().optional().meta({description:"Minimum relevance score threshold (0-1)"}),page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(t.sort=z.enum(this.sortFields).optional().meta({description:"Field to sort by"}),t.order=z.enum(d$1).optional().meta({description:"Sort direction (asc or desc)"}));for(let r of this.filterFields)t[r]=z.string().optional();if(this.filterConfig)for(let[r,s]of Object.entries(this.filterConfig)){for(let i of s)t[`${r}[${i}]`]=z.string().optional();t[r]=z.string().optional();}let o=this.getSoftDeleteConfig();if(o.enabled&&o.allowQueryDeleted&&(t[o.queryParam]=z.enum(["true","false"]).optional(),t.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(t.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let r=this.getAvailableSelectFields();t.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${r.join(", ")}`});}return z.object(t)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=z.object({item:this.getModelSchema(),score:z.number().min(0).max(1),highlights:z.record(z.string(),z.array(z.string())).optional(),matchedFields:z.array(z.string())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Search results",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(e),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),query:z.string(),searchedFields:z.array(z.string())})})}}},400:R("Invalid search request")}}}async getSearchOptions(){let{query:e}=await this.getValidatedData(),t=this.searchParamName||"q",o=e?.[t],r=e?.fields,s=wt(e?.mode),i=e?.highlight==="true",u=e?.minScore?Math.max(0,Math.min(1,Number.parseFloat(e.minScore)||0)):this.defaultMinScore,l=this.getSearchableFields(),c=bt(r,l);return {query:o,fields:c.length>0?c:Object.keys(l),mode:s??this.defaultMode,highlight:i,minScore:u}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchFieldName:"q",sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return te(e||{},o)}async beforeSearch(e){return e}async afterSearch(e){return e}async handle(){let e=await this.getSearchOptions(),t=await this.getFilters();if(!e.query||e.query.length<this.minQueryLength)return this.json({success:false,error:{code:"INVALID_QUERY",message:`Search query must be at least ${this.minQueryLength} characters`}},400);e=await this.beforeSearch(e);let o=await this.search(e,t),r=await this.afterSearch(o.items),s=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?{fields:t.options.fields,isActive:true}:void 0,i=await this.finalizeArray(r.map(p=>p.item),s),u=r.map((p,m)=>({...p,item:i[m]})),l=o.postFilteredCount??o.totalCount,c=t.options.page||1,a=t.options.per_page||this.defaultPerPage,d=Math.ceil(l/a);return this.successPaginated(u,{page:c,per_page:a,total_count:l,total_pages:d,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function tr(n,e,t){let o=ht(e.query,e.mode),r={},s=e.fields||Object.keys(t);for(let u of s)t[u]&&(r[u]=t[u]);let i=[];for(let u of n){let{score:l,matchedFields:c}=ft(u,o,r,e.mode);if(l<e.minScore||c.length===0)continue;let a;if(e.highlight){a={};for(let d of c){let p=gt(u[d],o,e.mode);p.length>0&&(a[d]=p);}}i.push({item:u,score:l,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:c});}return i.sort((u,l)=>l.score-u.score),i}function G(n,e={}){let{delimiter:t=",",nullValue:o="",dateFormat:r="iso"}=e;if(n==null)return o;if(n instanceof Date)switch(r){case "timestamp":return String(n.getTime());case "locale":return n.toLocaleString();default:return n.toISOString()}if(typeof n=="object")return G(JSON.stringify(n),e);if(typeof n=="boolean")return n?"true":"false";let s=String(n),i=s.charAt(0);return i==="="||i==="+"||i==="-"||i==="@"||i===" "||i==="\r"?`" ${s.replace(/"/g,'""')}"`:s.includes(t)||s.includes('"')||s.includes(`
2
+ `)||s.includes("\r")?`"${s.replace(/"/g,'""')}"`:s}function Ce(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
3
+ `,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:u={},nullValue:l="",dateFormat:c="iso"}=e;if(n.length===0)return "";let a=e.headers;a?a=a.filter(p=>!i.includes(p)):a=Object.keys(n[0]).filter(p=>!i.includes(p));let d=[];if(r){let p=a.map(m=>{let h=u[m]||m;return G(h,{delimiter:t,nullValue:l,dateFormat:c})});d.push(p.join(t));}for(let p of n){let m=a.map(h=>{let f=p[h];return s[h]&&(f=s[h](f)),G(f,{delimiter:t,nullValue:l,dateFormat:c})});d.push(m.join(t));}return d.join(o)}function or(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
4
+ `,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:u={},nullValue:l="",dateFormat:c="iso"}=e,a=new TextEncoder,d=0,p=false,m=e.headers;return !m&&n.length>0?m=Object.keys(n[0]).filter(h=>!i.includes(h)):m?m=m.filter(h=>!i.includes(h)):m=[],new ReadableStream({pull(h){if(r&&!p&&m.length>0){let b=m.map(g=>{let S=u[g]||g;return G(S,{delimiter:t,nullValue:l,dateFormat:c})});h.enqueue(a.encode(b.join(t)+o)),p=true;return}let f=100,y=[];for(;d<n.length&&y.length<f;){let b=n[d],g=m.map(S=>{let F=b[S];return s[S]&&(F=s[S](F)),G(F,{delimiter:t,nullValue:l,dateFormat:c})});y.push(g.join(t)),d++;}y.length>0&&h.enqueue(a.encode(y.join(o)+o)),d>=n.length&&h.close();}})}function lo(n,e){let t=[],o="",r=false,s=0;for(;s<n.length;){let i=n[s];if(r){if(i==='"'){if(s+1<n.length&&n[s+1]==='"'){o+='"',s+=2;continue}r=false,s++;continue}o+=i,s++;}else {if(i==='"'){r=true,s++;continue}if(i===e){t.push(o),o="",s++;continue}o+=i,s++;}}return t.push(o),t}function rr(n){let e=[],t="",o=false;for(let r=0;r<n.length;r++){let s=n[r];if(s==='"'){if(o&&r+1<n.length&&n[r+1]==='"'){t+='""',r++;continue}o=!o,t+=s;continue}if(!o&&(s===`
5
+ `||s==="\r")){s==="\r"&&r+1<n.length&&n[r+1]===`
6
+ `&&r++,t.length>0&&(e.push(t),t="");continue}t+=s;}return t.length>0&&e.push(t),e}function Pe(n,e={}){let{delimiter:t=",",hasHeader:o=true,trimValues:r=true,skipEmptyRows:s=true,parsers:i={},emptyValue:u="empty"}=e,l={data:[],headers:[],errors:[]},c=rr(n);if(c.length===0)return l;let a=0;if(o){let p=c[0];l.headers=lo(p,t).map(m=>r?m.trim():m),a=1;}else e.headers&&(l.headers=e.headers);let d=e.headers||l.headers;for(let p=a;p<c.length;p++){let m=c[p],h=p+1;if(!(s&&m.trim()===""))try{let f=lo(m,t),y={};for(let b=0;b<d.length;b++){let g=d[b],S=b<f.length?f[b]:"";if(r&&typeof S=="string"&&(S=S.trim()),S==="")switch(u){case "null":S=null;break;case "undefined":S=void 0;break}if(i[g]&&typeof S=="string")try{S=i[g](S);}catch(F){l.errors.push({row:h,message:`Failed to parse field "${g}": ${F instanceof Error?F.message:String(F)}`,content:m});}y[g]=S;}l.data.push(y);}catch(f){l.errors.push({row:h,message:`Failed to parse row: ${f instanceof Error?f.message:String(f)}`,content:m});}}return l}function zt(n,e,t={}){let{allowUnknownFields:o=false,optionalFields:r=[]}=t,s=e.shape,i=Object.keys(s),l=i.filter(p=>r.includes(p)?false:!s[p].isOptional()).filter(p=>!n.includes(p)),c=n.filter(p=>!i.includes(p)),a=n.filter(p=>i.includes(p));return {valid:l.length===0&&(o||c.length===0),missingFields:l,unknownFields:c,validFields:a}}function nr(n,e){if(n){let t=n.toLowerCase().split(".").pop();if(t==="csv")return "csv";if(t==="json")return "json"}if(e){let t=e.trim();if(t.startsWith("[")||t.startsWith("{"))return "json";if(t.includes(",")||t.includes(`
7
+ `))return "csv"}return "unknown"}function sr(n,e={}){return Ce(n,e)}function ir(n,e={}){return Pe(n,e).data}var qt=class extends be{maxExportRecords=1e4;enableStreaming=true;streamPageSize=500;excludedExportFields=[];defaultFormat="json";csvOptions={};exportFilename;getExportQuerySchema(){return this.getQuerySchema().extend({format:z.enum(["json","csv"]).optional().meta({description:"Export format"}),stream:z.enum(["true","false"]).optional().meta({description:"Enable streaming for large exports"})})}getSchema(){return {...this.schema,request:{query:this.getExportQuerySchema()},responses:{200:{description:"Export successful",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({data:z.array(this.getModelSchema()),count:z.number(),format:z.enum(["json","csv"]),exportedAt:z.string()})})},"text/csv":{schema:z.string()}}}}}}async getExportOptions(){let{query:e}=await this.getValidatedData(),t=e?.format||this.defaultFormat,o=e?.stream==="true"&&this.enableStreaming;return {format:t,stream:o,fields:e?.fields?String(e.fields).split(","):void 0}}getExportFilename(e){let o=(this.exportFilename||this._meta.model.tableName).replace(/[^a-zA-Z0-9_-]/g,"_"),r=new Date().toISOString().replace(/[:.]/g,"-");return `${o}-export-${r}.${e}`}prepareRecordsForExport(e){return this.excludedExportFields.length===0?e:e.map(t=>{let o={};for(let[r,s]of Object.entries(t))this.excludedExportFields.includes(r)||(o[r]=s);return o})}exportAsJson(e,t){let o={data:e,count:e.length,format:t,exportedAt:new Date().toISOString()};return new Response(JSON.stringify({success:true,result:o},null,2),{status:200,headers:{"Content-Type":"application/json","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsv(e,t){let o=Ce(e,{...this.csvOptions,excludeFields:this.excludedExportFields});return new Response(o,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsvStream(e,t){let o=this.getContext(),r=this.getExportFilename(t),s=this.csvOptions,i=this.excludedExportFields;return stream(o,async u=>{if(o.header("Content-Type","text/csv; charset=utf-8"),o.header("Content-Disposition",`attachment; filename="${r}"`),e.length===0)return;let l=Object.keys(e[0]).filter(d=>!i.includes(d)),c=l.map(d=>G(d,s)).join(",")+`
8
+ `;await u.write(c);let a=100;for(let d=0;d<e.length;d+=a)for(let p of e.slice(d,d+a)){let m=l.map(h=>G(p[h],s)).join(",")+`
9
+ `;await u.write(m);}})}exportAsCsvStreamPaginated(e,t){let o=this.getExportFilename(t),r=this.streamPageSize,s=Math.min(this.maxExportRecords,1e5),i=this.excludedExportFields,u=this.csvOptions,l=null,c=new ReadableStream({start:async a=>{let d=new TextEncoder,p=1,m=0;try{for(;m<s;){let h={...e,options:{...e.options,page:p,per_page:r}},y=(await this.list(h)).result;if(y.length===0)break;y.length>s-m&&(y=y.slice(0,s-m)),y=await this.after(y),y=await this.beforeExport(y);let b=this.prepareRecordsForExport(y);if(!l&&b.length>0){l=Object.keys(b[0]).filter(S=>!i.includes(S));let g=l.map(S=>G(S,u)).join(",")+`
10
+ `;a.enqueue(d.encode(g));}if(l)for(let g of b){let S=l.map(F=>G(g[F],u)).join(",")+`
11
+ `;a.enqueue(d.encode(S));}if(m+=y.length,p++,y.length<r)break}}catch(h){a.error(h);return}a.close();}});return new Response(c,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${o}"`}})}async beforeExport(e){return e}async fetchAllForExport(e){let t=Math.min(this.maxExportRecords,1e5),o={...e,options:{...e.options,page:1,per_page:t}};return (await this.list(o)).result}async handle(){let e=await this.getExportOptions(),t=await this.getFilters();if(e.format==="csv"&&e.stream)return this.exportAsCsvStreamPaginated(t,e.format);let o=await this.fetchAllForExport(t);o=await this.after(o),o=await this.beforeExport(o);let r=this.prepareRecordsForExport(o);return e.format==="csv"?this.exportAsCsv(r,e.format):this.exportAsJson(r,e.format)}};var $t=class extends x{maxBatchSize=1e3;importBatchSize=100;stopOnError=false;skipInvalidRows=true;defaultMode="create";upsertKeys;immutableFields=[];csvOptions={};maxBodySize=10*1024*1024;optionalImportFields=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getImportSchema(){let e=this._meta.fields?this._meta.fields:Z(this.getModelSchema(),H(this._meta.model));return z.object({items:z.array(e.partial()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{query:z.object({mode:z.enum(["create","upsert"]).optional().meta({description:"Import mode"}),skipInvalid:z.enum(["true","false"]).optional().meta({description:"Skip invalid rows"}),stopOnError:z.enum(["true","false"]).optional().meta({description:"Stop on first error"})})},responses:{200:{description:"Import completed successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},207:{description:"Import completed with partial failures",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},400:R("Validation error")}}}async getImportOptions(){let{query:e}=await this.getValidatedData(),t=e?.skipInvalid==="true"?true:e?.skipInvalid==="false"?false:this.skipInvalidRows,o=e?.stopOnError==="true"?true:e?.stopOnError==="false"?false:this.stopOnError;return {mode:e?.mode||this.defaultMode,skipInvalidRows:t,stopOnError:o}}async parseImportData(){let e=this.context;if(!e)throw new b("No request available");let t=e.req.header("content-type")||"";if(t.includes("application/json")){let o=await e.req.json();if(!o)throw new b("Request body is empty");if(!o.items||!Array.isArray(o.items))throw new b('Request body must contain an "items" array');if(o.items.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);return o.items}if(t.includes("text/csv")){let o=await e.req.text();if(o.length>this.maxBodySize)throw new b(`Request body exceeds maximum size of ${this.maxBodySize} bytes`);return this.parseCsvData(o)}if(t.includes("multipart/form-data")){let r=(await e.req.formData()).get("file");if(!r)throw new b("No file provided in form data");let s=await r.text();if(s.length>this.maxBodySize)throw new b(`Uploaded file exceeds maximum size of ${this.maxBodySize} bytes`);let i=r.name.toLowerCase();if(i.endsWith(".json")){let l;try{l=JSON.parse(s);}catch{throw new b("Invalid JSON content in uploaded file")}let c=Array.isArray(l)?l:l.items;if(!c||!Array.isArray(c))throw new b('JSON file must contain an array or an object with "items" array');if(c.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);return c}if(i.endsWith(".csv"))return this.parseCsvData(s);let u=s.trim();if(u.startsWith("[")||u.startsWith("{")){let l;try{l=JSON.parse(s);}catch{throw new b("Invalid JSON content in uploaded file")}let c=Array.isArray(l)?l:l.items;if(!c||!Array.isArray(c))throw new b('JSON file must contain an array or an object with "items" array');return c}return this.parseCsvData(s)}throw new b("Unsupported content type. Use application/json, text/csv, or multipart/form-data")}parseCsvData(e){let t=Pe(e,this.csvOptions);if(t.errors.length>0)throw new b(`CSV parsing errors: ${t.errors.map(s=>`Row ${s.row}: ${s.message}`).join("; ")}`);if(t.data.length===0)throw new b("CSV file is empty");if(t.data.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);let o=this._meta.fields||this.getModelSchema(),r=zt(t.headers,o,{allowUnknownFields:true,optionalFields:this.optionalImportFields});if(!r.valid&&r.missingFields.length>0)throw new b(`Missing required fields in CSV: ${r.missingFields.join(", ")}`);return t.data}validateRow(e,t){let o=this._meta.fields||this.getModelSchema(),r={};for(let i of H(this._meta.model))r[i]=true;for(let i of this.optionalImportFields)r[i]=true;let s=o.partial(r);try{return s.parse(e),{valid:!0}}catch(i){return i instanceof z.ZodError?{valid:false,errors:i.issues.map(l=>({path:l.path.join("."),message:l.message}))}:{valid:false,errors:[{path:"",message:i instanceof Error?i.message:String(i)}]}}}removeImmutableFields(e){if(this.immutableFields.length===0)return e;let t={};for(let[o,r]of Object.entries(e))this.immutableFields.includes(o)||(t[o]=r);return t}async before(e,t,o,r){return e}async after(e,t,o,r){return e}async processRow(e,t,o,r){let s=this.validateRow(e,t);if(!s.valid)return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Validation failed",validationErrors:s.errors}:{rowNumber:t,status:"failed",error:"Validation failed",validationErrors:s.errors};try{let i=await this.before(e,t,o.mode,r);if(o.mode==="upsert"){let l=await this.findExisting(i,r);if(l){let c=this.removeImmutableFields(i),a=await this.update(l,c,r);return {rowNumber:t,status:"updated",data:a}}}else if(await this.findExisting(i,r))return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Record already exists"}:{rowNumber:t,status:"failed",error:"Record already exists (duplicate key)"};let u=await this.create(i,r);return {rowNumber:t,status:"created",data:u}}catch(i){let u=Ee(i);return u?{rowNumber:t,status:"failed",code:"CONFLICT",error:u.message}:{rowNumber:t,status:"failed",error:i instanceof Error?i.message:String(i)}}}async handle(){let e=await this.getImportOptions(),t=await this.parseImportData();if(!Number.isInteger(this.importBatchSize)||this.importBatchSize<1)throw new i("importBatchSize must be a positive integer");let o={total:t.length,created:0,updated:0,skipped:0,failed:0},r=[],s=false,i$1=e.stopOnError?1:this.importBatchSize;for(let c=0;c<t.length&&!s;c+=i$1){let a=t.slice(c,c+i$1),d=await Promise.all(a.map(async(p,m)=>{let h=c+m+1,f=await this.processRow(p,h,e);return f=await this.after(f,h,e.mode),f}));for(let p of d){switch(r.push(p),p.status){case "created":o.created++;break;case "updated":o.updated++;break;case "skipped":o.skipped++;break;case "failed":o.failed++;break}if(e.stopOnError&&p.status==="failed"){s=true;break}}}if(this.isAuditEnabled()){let c=this.getAuditLogger(),a=r.filter(d=>d.status==="created"||d.status==="updated");if(a.length>0){let d=a.map(p=>{if(!p.data)return null;let m=this.getRecordId(p.data);return m===null?null:{recordId:m,record:p.data}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(c.logBatch(e.mode==="upsert"?"batch_upsert":"batch_create",this._meta.model.tableName,d,this.getAuditUserId()));}}let u={summary:o,results:r},l=o.failed>0&&o.failed<o.total?207:200;return this.json({success:true,result:u},l)}};var ve=Symbol.for("hono-crud.resource-registry");function co(n,e,t){let o=n;o[ve]||(o[ve]=[]),o[ve].push({path:e,endpoints:t});}function Di(n){return n[ve]??[]}function dr(n,e,t,o={}){let r=e.endsWith("/")?e.slice(0,-1):e,s=n,{middlewares:i=[],endpointMiddlewares:u={},responseEnvelope:l$1}=o,c=l$1?async(p,m)=>{b$4(p,l,l$1),await m();}:void 0,a=p=>{let m=t[p],h=m&&"_middlewares"in m?m._middlewares||[]:[];return [...c?[c]:[],...i,...u[p]||[],...h]},d=(p,m,h,f)=>{let y=a(h),b=s[p];y.length>0?b(m,...y,f):b(m,f);};t.create&&d("post",r,"create",t.create),t.list&&d("get",r,"list",t.list),t.batchCreate&&d("post",`${r}/batch`,"batchCreate",t.batchCreate),t.batchUpdate&&d("patch",`${r}/batch`,"batchUpdate",t.batchUpdate),t.batchDelete&&d("delete",`${r}/batch`,"batchDelete",t.batchDelete),t.batchRestore&&d("post",`${r}/batch/restore`,"batchRestore",t.batchRestore),t.batchUpsert&&d("post",`${r}/batch/upsert`,"batchUpsert",t.batchUpsert),t.search&&d("get",`${r}/search`,"search",t.search),t.aggregate&&d("get",`${r}/aggregate`,"aggregate",t.aggregate),t.export&&d("get",`${r}/export`,"export",t.export),t.import&&d("post",`${r}/import`,"import",t.import),t.upsert&&d("post",`${r}/upsert`,"upsert",t.upsert),t.bulkPatch&&d("patch",`${r}/bulk`,"bulkPatch",t.bulkPatch),t.read&&d("get",`${r}/:id`,"read",t.read),t.update&&d("patch",`${r}/:id`,"update",t.update),t.delete&&d("delete",`${r}/:id`,"delete",t.delete),t.restore&&d("post",`${r}/:id/restore`,"restore",t.restore),t.clone&&d("post",`${r}/:id/clone`,"clone",t.clone),t.versionHistory&&d("get",`${r}/:id/versions`,"versionHistory",t.versionHistory),t.versionCompare&&d("get",`${r}/:id/versions/compare`,"versionCompare",t.versionCompare),t.versionRead&&d("get",`${r}/:id/versions/:version`,"versionRead",t.versionRead),t.versionRollback&&d("post",`${r}/:id/versions/:version/rollback`,"versionRollback",t.versionRollback),co(n,r,t);}function Kt(n){return {content:{"application/json":{schema:n}}}}function lr(n){return {description:"Success",...Kt({type:"object",properties:{success:{type:"boolean",enum:[true]},result:n},required:["success","result"]})}}function cr(n="Error"){return {description:n,...Kt({type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"object",properties:{code:{type:"string"},message:{type:"string"},details:{}},required:["code","message"]}},required:["success","error"]})}}function Wt(n,e){return {content:{"application/json":{schema:n}},description:e}}function pr(n,e){return {content:{"application/json":{schema:n}},description:e,required:true}}var po=z.object({code:z.string(),path:z.array(z.union([z.string(),z.number()])),message:z.string()}),je=z.object({success:z.literal(false),error:z.object({name:z.literal("ZodError"),issues:z.array(po)})});function ur(n){return je}function mr(...n){return je}var hr=(n,e)=>{if(!n.success)return e.json({success:false,error:{name:"ZodError",issues:n.error.issues}},422)};function fr(n,e=422){return (t,o)=>{if(!t.success)return o.json(n(t.error),e)}}var uo=z.object({success:z.literal(false),error:z.object({message:z.string(),code:z.string().optional()})});function oe(n){return Wt(uo,n)}var gr={badRequest:oe("Bad request"),unauthorized:oe("Unauthorized"),forbidden:oe("Forbidden"),notFound:oe("Resource not found"),conflict:oe("Resource conflict"),validationError:Wt(je,"Validation error"),internalError:oe("Internal server error")};function br(n){return async(e,t)=>{n.audit&&e.set(a$2.auditStorage,n.audit),n.versioning&&e.set(a$2.versioningStorage,n.versioning),n.logging&&e.set(a$2.loggingStorage,n.logging),n.events&&e.set(a$2.eventEmitter,n.events),await t();}}var Fe=class{constructor(e){this.meta=e;}_schema={};_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_allowNestedCreate=[];_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}nestedCreate(...e){return this._allowNestedCreate=e,this}build(e){return a$3(e,{meta:this.meta,schema:this._schema,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,allowNestedCreate:this._allowNestedCreate,middlewares:this._middlewares})}},Ie=class{constructor(e){this.meta=e;}_schema={};_filterFields=[];_filterConfig;_searchFields=[];_searchFieldName="search";_sortFields=[];_defaultSort;_defaultPerPage=20;_maxPerPage=100;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}filter(...e){return this._filterFields=e,this}filterWith(e){return this._filterConfig=e,this}search(...e){return this._searchFields=e,this}searchParam(e){return this._searchFieldName=e,this}sortable(...e){return this._sortFields=e,this}orderBy(...e){return this.sortable(...e)}defaultSort(e,t="asc"){return this._defaultSort={field:e,order:t},this}defaultOrder(e,t="asc"){return this.defaultSort(e,t)}pagination(e,t){return this._defaultPerPage=e,t!==void 0&&(this._maxPerPage=t),this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return a$3(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchFieldName:this._searchFieldName,sortFields:this._sortFields,defaultSort:this._defaultSort,defaultPerPage:this._defaultPerPage,maxPerPage:this._maxPerPage,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},Ae=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return a$3(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},_e=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}allowedFields(...e){return this._allowedUpdateFields=e,this}blockedFields(...e){return this._blockedUpdateFields=e,this}nestedWrites(...e){return this._allowNestedWrites=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}transform(e){return this._transform=e,this}build(e){return a$3(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedUpdateFields:this._allowedUpdateFields,blockedUpdateFields:this._blockedUpdateFields,allowNestedWrites:this._allowNestedWrites,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,transform:this._transform,middlewares:this._middlewares})}},Te=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_includeCascadeResults=false;_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}includeCascade(e=true){return this._includeCascadeResults=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}build(e){return a$3(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,includeCascadeResults:this._includeCascadeResults,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,middlewares:this._middlewares})}},Ne=class{constructor(e){this.meta=e;}create(){return new Fe(this.meta)}list(){return new Ie(this.meta)}read(){return new Ae(this.meta)}update(){return new _e(this.meta)}delete(){return new Te(this.meta)}};function yr(n){return new Ne(n)}export{vt as $,ct as A,dr as Aa,pt as B,Kt as Ba,ut as C,lr as Ca,mt as D,cr as Da,ht as E,Wt as Ea,to as F,pr as Fa,ft as G,po as Ga,gt as H,je as Ha,bt as I,ur as Ia,yt as J,mr as Ja,wt as K,hr as Ka,de as L,fr as La,Et as M,uo as Ma,Rt as N,oe as Na,Uo as O,gr as Oa,te as P,br as Pa,Z as Q,Fe as Qa,Bo as R,Ie as Ra,Re as S,Ae as Sa,St as T,_e as Ta,xt as U,Te as Ua,Ot as V,Ne as Va,kt as W,yr as Wa,Ct as X,be as Y,Pt as Z,Wo as _,tt as a,jt as aa,Me as b,Ft as ba,ho as c,It as ca,Mo as d,At as da,Ro as e,_t as ea,vo as f,Tt as fa,Jt as g,Nt as ga,Io as h,Dt as ha,Yt as i,Ht as ia,ie as j,Vt as ja,H as k,Zt as ka,nt as l,Ut as la,st as m,Yo as ma,it as n,Bt as na,at as o,tr as oa,Xt as p,G as pa,Ee as q,Ce as qa,W as r,or as ra,Do as s,Pe as sa,Ho as t,zt as ta,ae as u,nr as ua,dt as v,sr as va,ee as w,ir as wa,ge as x,qt as xa,Vo as y,$t as ya,lt as z,Di as za};
@@ -1 +1 @@
1
- function c(a,e){let s=e.middlewares??[],d=e.extras,r=e.schema??{},o=Array.isArray(r.tags)&&r.tags.length>0,l=e.meta.model.tag??e.meta.model.tableName,n=o?r:{...r,tags:[l]};return class extends a{static _middlewares=s;constructor(){super(),d&&Object.assign(this,d);}_meta=e.meta;schema=n;beforeHookMode=e.beforeHookMode??"sequential";afterHookMode=e.afterHookMode??"sequential";allowNestedCreate=e.allowNestedCreate??[];lookupField=e.lookupField??"id";additionalFilters=e.additionalFilters;allowedUpdateFields=e.allowedUpdateFields;blockedUpdateFields=e.blockedUpdateFields;allowNestedWrites=e.allowNestedWrites??[];includeCascadeResults=e.includeCascadeResults??false;filterFields=e.filterFields??[];filterConfig=e.filterConfig;searchFields=e.searchFields??[];searchFieldName=e.searchFieldName??"search";sortFields=e.sortFields??[];defaultSort=e.defaultSort;defaultPerPage=e.defaultPerPage??20;maxPerPage=e.maxPerPage??100;allowedIncludes=e.allowedIncludes??[];fieldSelectionEnabled=e.fieldSelectionEnabled??false;allowedSelectFields=e.allowedSelectFields??[];blockedSelectFields=e.blockedSelectFields??[];alwaysIncludeFields=e.alwaysIncludeFields??[];defaultSelectFields=e.defaultSelectFields??[];getBodySchema(){return e.bodySchema?e.bodySchema:super.getBodySchema()}async before(...t){return e.before?e.before(...t):super.before(...t)}async after(...t){return e.after?e.after(...t):super.after(...t)}transform(t){return e.transform?e.transform(t):super.transform(t)}}}export{c as a};
1
+ function c(a,e){let o=e.middlewares??[],d=e.extras,r=e.schema??{},s=Array.isArray(r.tags)&&r.tags.length>0,l=e.meta.model.tag??e.meta.model.tableName,n=s?r:{...r,tags:[l]};return class extends a{static _middlewares=o;constructor(){super(),d&&Object.assign(this,d);}_meta=e.meta;schema=n;beforeHookMode=e.beforeHookMode??"sequential";afterHookMode=e.afterHookMode??"sequential";allowNestedCreate=e.allowNestedCreate??[];lookupField=e.lookupField??"id";additionalFilters=e.additionalFilters;allowedUpdateFields=e.allowedUpdateFields;blockedUpdateFields=e.blockedUpdateFields;allowNestedWrites=e.allowNestedWrites??[];includeCascadeResults=e.includeCascadeResults??false;filterFields=e.filterFields??[];filterConfig=e.filterConfig;searchFields=e.searchFields??[];searchFieldName=e.searchFieldName??"search";sortFields=e.sortFields??[];defaultSort=e.defaultSort;defaultPerPage=e.defaultPerPage??20;maxPerPage=e.maxPerPage??100;allowedIncludes=e.allowedIncludes??[];fieldSelectionEnabled=e.fieldSelectionEnabled??false;allowedSelectFields=e.allowedSelectFields??[];blockedSelectFields=e.blockedSelectFields??[];alwaysIncludeFields=e.alwaysIncludeFields??[];defaultSelectFields=e.defaultSelectFields??[];getBodySchema(){return e.bodySchema?e.bodySchema:super.getBodySchema()}async before(...t){return e.before?e.before(...t):super.before(...t)}async after(...t){return e.after?e.after(...t):super.after(...t)}transform(t){return e.transform?e.transform(t):super.transform(t)}}}export{c as a};
@@ -1 +1 @@
1
- import {a}from'./chunk-BPBFNTBM.js';function l(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,allowNestedCreate:e.allowNestedCreate})}function r(e,d){let a$1=e.defaultSort??(e.defaultOrderBy?{field:e.defaultOrderBy,order:e.defaultOrderDirection??"asc"}:void 0);return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,after:e.after,transform:e.transform,filterFields:e.filterFields,filterConfig:e.filterConfig,searchFields:e.searchFields,searchFieldName:e.searchFieldName,sortFields:e.sortFields??e.orderByFields,defaultSort:a$1,defaultPerPage:e.defaultPerPage,maxPerPage:e.maxPerPage,allowedIncludes:e.allowedIncludes,fieldSelectionEnabled:e.fieldSelectionEnabled,allowedSelectFields:e.allowedSelectFields,blockedSelectFields:e.blockedSelectFields,alwaysIncludeFields:e.alwaysIncludeFields,defaultSelectFields:e.defaultSelectFields})}function o(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,after:e.after,transform:e.transform,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedIncludes:e.allowedIncludes,fieldSelectionEnabled:e.fieldSelectionEnabled,allowedSelectFields:e.allowedSelectFields,blockedSelectFields:e.blockedSelectFields,alwaysIncludeFields:e.alwaysIncludeFields,defaultSelectFields:e.defaultSelectFields})}function s(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,transform:e.transform,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedUpdateFields:e.allowedUpdateFields,blockedUpdateFields:e.blockedUpdateFields,allowNestedWrites:e.allowNestedWrites})}function i(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,lookupField:e.lookupField,additionalFilters:e.additionalFilters,includeCascadeResults:e.includeCascadeResults})}export{l as a,r as b,o as c,s as d,i as e};
1
+ import {a}from'./chunk-STAO4FWC.js';function l(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,allowNestedCreate:e.allowNestedCreate})}function r(e,d){let a$1=e.defaultSort??(e.defaultOrderBy?{field:e.defaultOrderBy,order:e.defaultOrderDirection??"asc"}:void 0);return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,after:e.after,transform:e.transform,filterFields:e.filterFields,filterConfig:e.filterConfig,searchFields:e.searchFields,searchFieldName:e.searchFieldName,sortFields:e.sortFields??e.orderByFields,defaultSort:a$1,defaultPerPage:e.defaultPerPage,maxPerPage:e.maxPerPage,allowedIncludes:e.allowedIncludes,fieldSelectionEnabled:e.fieldSelectionEnabled,allowedSelectFields:e.allowedSelectFields,blockedSelectFields:e.blockedSelectFields,alwaysIncludeFields:e.alwaysIncludeFields,defaultSelectFields:e.defaultSelectFields})}function o(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,after:e.after,transform:e.transform,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedIncludes:e.allowedIncludes,fieldSelectionEnabled:e.fieldSelectionEnabled,allowedSelectFields:e.allowedSelectFields,blockedSelectFields:e.blockedSelectFields,alwaysIncludeFields:e.alwaysIncludeFields,defaultSelectFields:e.defaultSelectFields})}function s(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,transform:e.transform,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedUpdateFields:e.allowedUpdateFields,blockedUpdateFields:e.blockedUpdateFields,allowNestedWrites:e.allowNestedWrites})}function i(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,lookupField:e.lookupField,additionalFilters:e.additionalFilters,includeCascadeResults:e.includeCascadeResults})}export{l as a,r as b,o as c,s as d,i as e};
@@ -1 +1 @@
1
- import {b as b$1}from'./chunk-DMGP7QDL.js';import {n}from'./chunk-ZJWDAVGG.js';import {a}from'./chunk-IJBJE4G2.js';var c=class{listeners=new Map;tableListeners=new Map;globalListeners=new Set;maxListeners;constructor(e){this.maxListeners=e?.maxListeners??100;}on(e,t,s){let n=`${e}:${t}`;this.listeners.has(n)||this.listeners.set(n,new Set);let i=this.listeners.get(n);return this.maxListeners>0&&i.size>=this.maxListeners?(b$1().warn(`Max listeners (${this.maxListeners}) reached for event "${n}". Listener not added.`),{unsubscribe:()=>{}}):(i.add(s),{unsubscribe:()=>{this.listeners.get(n)?.delete(s);}})}onTable(e,t){this.tableListeners.has(e)||this.tableListeners.set(e,new Set);let s=this.tableListeners.get(e);return this.maxListeners>0&&s.size>=this.maxListeners?(b$1().warn(`Max listeners (${this.maxListeners}) reached for table "${e}". Listener not added.`),{unsubscribe:()=>{}}):(s.add(t),{unsubscribe:()=>{this.tableListeners.get(e)?.delete(t);}})}onAny(e){return this.maxListeners>0&&this.globalListeners.size>=this.maxListeners?(b$1().warn(`Max global listeners (${this.maxListeners}) reached. Listener not added.`),{unsubscribe:()=>{}}):(this.globalListeners.add(e),{unsubscribe:()=>{this.globalListeners.delete(e);}})}off(e,t){this.listeners.delete(`${e}:${t}`);}removeAll(){this.listeners.clear(),this.tableListeners.clear(),this.globalListeners.clear();}async emit(e){let t=[],s=`${e.table}:${e.type}`,n=this.listeners.get(s);if(n)for(let a of n)t.push(this.safeCall(a,e));let i=this.tableListeners.get(e.table);if(i)for(let a of i)t.push(this.safeCall(a,e));for(let a of this.globalListeners)t.push(this.safeCall(a,e));await Promise.all(t);}emitAsync(e){this.emit(e).catch(t=>{b$1().error("Event emission error",{error:t instanceof Error?t.message:String(t)});});}listenerCount(){let e=this.globalListeners.size;for(let t of this.listeners.values())e+=t.size;for(let t of this.tableListeners.values())e+=t.size;return e}async safeCall(e,t){try{await e(t);}catch(s){b$1().error("Event listener error",{error:s instanceof Error?s.message:String(s)});}}},m=n(a.eventEmitter,()=>new c);function b(){return m.getRequired()}function f(r){m.set(r);}function E(r,e){return m.resolve(r,e)}async function y(r,e){let t=new TextEncoder,s=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},false,["sign"]),n=await crypto.subtle.sign("HMAC",s,t.encode(r));return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function g(r,e){if(!e||e.length===0)return true;let t=`${r.table}:${r.type}`;return e.some(s=>s==="*"||s===t)}async function C(r,e){let t=r.timeout??1e4,s=r.retries??2,n=JSON.stringify(e),i={"Content-Type":"application/json","X-Webhook-Event":`${e.table}.${e.type}`,"X-Webhook-Timestamp":e.timestamp,...r.headers??{}};if(r.secret){let o=await y(n,r.secret);i["X-Webhook-Signature"]=`sha256=${o}`;}let a;for(let o=0;o<=s;o++){try{let u=new AbortController,v=setTimeout(()=>u.abort(),t),d=await fetch(r.url,{method:"POST",headers:i,body:n,signal:u.signal});if(clearTimeout(v),d.ok)return {url:r.url,success:!0,statusCode:d.status,attempts:o+1};a=new Error(`HTTP ${d.status}: ${d.statusText}`);}catch(u){a=u instanceof Error?u:new Error(String(u));}o<s&&await new Promise(u=>setTimeout(u,1e3*Math.pow(2,o)));}return {url:r.url,success:false,error:a?.message,attempts:s+1}}function L(r){let e=E(void 0,r.emitter);if(!e)throw new Error("Event emitter not configured. Pass emitter explicitly or call setEventEmitter() first.");let t=n=>{for(let i of r.endpoints){if(!g(n,i.events))continue;let a=C(i,n).then(o=>{!o.success&&r.onError&&r.onError(i,n,new Error(o.error??"Unknown delivery error"));}).catch(o=>{r.onError&&r.onError(i,n,o instanceof Error?o:new Error(String(o)));});r.waitUntil&&r.waitUntil(a);}},s=e.onAny(t);return ()=>s.unsubscribe()}export{c as a,b,f as c,E as d,L as e};
1
+ import {b as b$1}from'./chunk-DMGP7QDL.js';import {n}from'./chunk-ZJWDAVGG.js';import {a}from'./chunk-IJBJE4G2.js';var c=class{listeners=new Map;tableListeners=new Map;globalListeners=new Set;maxListeners;constructor(e){this.maxListeners=e?.maxListeners??100;}on(e,t,s){let n=`${e}:${t}`;this.listeners.has(n)||this.listeners.set(n,new Set);let i=this.listeners.get(n);return this.maxListeners>0&&i.size>=this.maxListeners?(b$1().warn(`Max listeners (${this.maxListeners}) reached for event "${n}". Listener not added.`),{unsubscribe:()=>{}}):(i.add(s),{unsubscribe:()=>{this.listeners.get(n)?.delete(s);}})}onTable(e,t){this.tableListeners.has(e)||this.tableListeners.set(e,new Set);let s=this.tableListeners.get(e);return this.maxListeners>0&&s.size>=this.maxListeners?(b$1().warn(`Max listeners (${this.maxListeners}) reached for table "${e}". Listener not added.`),{unsubscribe:()=>{}}):(s.add(t),{unsubscribe:()=>{this.tableListeners.get(e)?.delete(t);}})}onAny(e){return this.maxListeners>0&&this.globalListeners.size>=this.maxListeners?(b$1().warn(`Max global listeners (${this.maxListeners}) reached. Listener not added.`),{unsubscribe:()=>{}}):(this.globalListeners.add(e),{unsubscribe:()=>{this.globalListeners.delete(e);}})}off(e,t){this.listeners.delete(`${e}:${t}`);}removeAll(){this.listeners.clear(),this.tableListeners.clear(),this.globalListeners.clear();}async emit(e){let t=[],s=`${e.table}:${e.type}`,n=this.listeners.get(s);if(n)for(let a of n)t.push(this.safeCall(a,e));let i=this.tableListeners.get(e.table);if(i)for(let a of i)t.push(this.safeCall(a,e));for(let a of this.globalListeners)t.push(this.safeCall(a,e));await Promise.all(t);}emitAsync(e){this.emit(e).catch(t=>{b$1().error("Event emission error",{error:t instanceof Error?t.message:String(t)});});}listenerCount(){let e=this.globalListeners.size;for(let t of this.listeners.values())e+=t.size;for(let t of this.tableListeners.values())e+=t.size;return e}async safeCall(e,t){try{await e(t);}catch(s){b$1().error("Event listener error",{error:s instanceof Error?s.message:String(s)});}}},E=n(a.eventEmitter,()=>new c);function b(){return E.getRequired()}function f(r){E.set(r);}function m(r,e){return E.resolve(r,e)}async function y(r,e){let t=new TextEncoder,s=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},false,["sign"]),n=await crypto.subtle.sign("HMAC",s,t.encode(r));return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function g(r,e){if(!e||e.length===0)return true;let t=`${r.table}:${r.type}`;return e.some(s=>s==="*"||s===t)}async function C(r,e){let t=r.timeout??1e4,s=r.retries??2,n=JSON.stringify(e),i={"Content-Type":"application/json","X-Webhook-Event":`${e.table}.${e.type}`,"X-Webhook-Timestamp":e.timestamp,...r.headers??{}};if(r.secret){let o=await y(n,r.secret);i["X-Webhook-Signature"]=`sha256=${o}`;}let a;for(let o=0;o<=s;o++){try{let u=new AbortController,h=setTimeout(()=>u.abort(),t),d=await fetch(r.url,{method:"POST",headers:i,body:n,signal:u.signal});if(clearTimeout(h),d.ok)return {url:r.url,success:!0,statusCode:d.status,attempts:o+1};a=new Error(`HTTP ${d.status}: ${d.statusText}`);}catch(u){a=u instanceof Error?u:new Error(String(u));}o<s&&await new Promise(u=>setTimeout(u,1e3*Math.pow(2,o)));}return {url:r.url,success:false,error:a?.message,attempts:s+1}}function L(r){let e=m(void 0,r.emitter);if(!e)throw new Error("Event emitter not configured. Pass emitter explicitly or call setEventEmitter() first.");let t=n=>{for(let i of r.endpoints){if(!g(n,i.events))continue;let a=C(i,n).then(o=>{!o.success&&r.onError&&r.onError(i,n,new Error(o.error??"Unknown delivery error"));}).catch(o=>{r.onError&&r.onError(i,n,o instanceof Error?o:new Error(String(o)));});r.waitUntil&&r.waitUntil(a);}},s=e.onAny(t);return ()=>s.unsubscribe()}var x=["created","updated","deleted","restored"];export{c as a,b,f as c,m as d,L as e,x as f};
@@ -1,10 +1,10 @@
1
1
  import 'hono';
2
2
  import 'zod';
3
- export { A as AdapterBundle, a as AggregateEndpointConfig, B as BatchCreateEndpointConfig, b as BatchDeleteEndpointConfig, c as BatchRestoreEndpointConfig, d as BatchUpdateEndpointConfig, e as BatchUpsertEndpointConfig, f as CloneEndpointConfig, g as CreateEndpointConfig, D as DeleteEndpointConfig, m as EndpointsConfig, E as ExportEndpointConfig, G as GeneratedEndpoints, I as ImportEndpointConfig, L as ListEndpointConfig, R as ReadEndpointConfig, h as RestoreEndpointConfig, S as SearchEndpointConfig, U as UpdateEndpointConfig, i as UpsertEndpointConfig, p as defineEndpoints } from '../index-Biz6ZLmk.js';
4
- import '../route-cu4t0BCp.js';
5
- import '../types-CR_0ycjq.js';
6
- import '../types-BK-mxapm.js';
3
+ export { A as AdapterBundle, a as AggregateEndpointConfig, B as BatchCreateEndpointConfig, b as BatchDeleteEndpointConfig, c as BatchRestoreEndpointConfig, d as BatchUpdateEndpointConfig, e as BatchUpsertEndpointConfig, f as CloneEndpointConfig, g as CreateEndpointConfig, D as DeleteEndpointConfig, m as EndpointsConfig, E as ExportEndpointConfig, G as GeneratedEndpoints, I as ImportEndpointConfig, L as ListEndpointConfig, R as ReadEndpointConfig, h as RestoreEndpointConfig, S as SearchEndpointConfig, U as UpdateEndpointConfig, i as UpsertEndpointConfig, s as defineEndpoints } from '../index-Coira0ZO.js';
4
+ import '../route-BsBxrEW1.js';
5
+ import '../types-CmzJjItf.js';
6
+ import '../types-Bfdb_zwM.js';
7
7
  import '@hono/zod-openapi';
8
8
  import 'hono/utils/http-status';
9
9
  import '../types-DcRAcexC.js';
10
- import '../types-BAcN7U0B.js';
10
+ import '../types-Drjma4gp.js';
@@ -1 +1 @@
1
- export{a as defineEndpoints}from'../chunk-65NCGRBB.js';import'../chunk-BPBFNTBM.js';
1
+ export{a as defineEndpoints}from'../chunk-2T3DGA4L.js';import'../chunk-STAO4FWC.js';