hono-crud 0.13.21 → 0.13.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/builder/index.js +1 -1
- package/dist/{chunk-EMXKCEPB.js → chunk-5DTBFOC3.js} +1 -1
- package/dist/chunk-AQXRF6RJ.js +1 -0
- package/dist/chunk-VOKEDJQ7.js +11 -0
- package/dist/config/index.d.ts +3 -2
- package/dist/config/index.js +1 -1
- package/dist/{context-keys-V-9AJA91.d.ts → context-keys-C7y4-168.d.ts} +1 -1
- package/dist/functional/index.js +1 -1
- package/dist/{index-Cql5Zrjl.d.ts → index-C7O-Gh59.d.ts} +220 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/internal.d.ts +3 -3
- package/dist/internal.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-O6VQTREM.js +0 -11
- package/dist/chunk-W62PHP4A.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.13.22
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- e7ecacf: feat(config): config-API response caching with invalidation
|
|
8
|
+
|
|
9
|
+
`endpoints.{list,read}.cache` enables response caching (X-Cache MISS→HIT) and
|
|
10
|
+
`endpoints.{create,update,delete}.cache.invalidate` busts it — all through the
|
|
11
|
+
config API, no subclassing. Core now owns the cache code path (key format,
|
|
12
|
+
`CacheConfig`, the cache-storage feature); `@hono-crud/cache` re-exports the
|
|
13
|
+
storage feature so the `withCache` mixin and the config path share ONE storage
|
|
14
|
+
global.
|
|
15
|
+
|
|
16
|
+
Cache keys are tenant-scoped automatically on multiTenant resources, so a
|
|
17
|
+
cached page is never served across tenants; invalidation uses the same
|
|
18
|
+
tenant-scoped prefix. Storage resolves from request context
|
|
19
|
+
(`createCacheStorageMiddleware`) or the global `setCacheStorage`.
|
|
20
|
+
|
|
3
21
|
## 0.13.21
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/dist/builder/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'../chunk-
|
|
1
|
+
import {a as a$1}from'../chunk-5DTBFOC3.js';var r=class{constructor(e){this.meta=e;}_schema={};_before;_after;_beforeHookMode;_afterHookMode;_allowNestedCreate=[];_bodySchema;_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}openapi(e){return Object.assign(this._schema,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}bodySchema(e){return this._bodySchema=e,this}build(e){return a$1(e,{meta:this.meta,schema:this._schema,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,allowNestedCreate:this._allowNestedCreate,bodySchema:this._bodySchema,middlewares:this._middlewares})}},a=class{constructor(e){this.meta=e;}_schema={};_filterFields=[];_filterConfig;_searchFields=[];_searchParamName;_sortFields=[];_defaultSort;_defaultPerPage;_maxPerPage;_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}openapi(e){return Object.assign(this._schema,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._searchParamName=e,this}sortable(...e){return this._sortFields=e,this}defaultSort(e,s="asc"){return this._defaultSort={field:e,order:s},this}pagination(e,s){return this._defaultPerPage=e,s!==void 0&&(this._maxPerPage=s),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$1(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchParamName:this._searchParamName,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})}},d=class{constructor(e){this.meta=e;}_schema={};_lookupField;_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}openapi(e){return Object.assign(this._schema,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$1(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})}},o=class{constructor(e){this.meta=e;}_schema={};_lookupField;_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode;_afterHookMode;_transform;_bodySchema;_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}openapi(e){return Object.assign(this._schema,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}bodySchema(e){return this._bodySchema=e,this}build(e){return a$1(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,bodySchema:this._bodySchema,middlewares:this._middlewares})}},l=class{constructor(e){this.meta=e;}_schema={};_lookupField;_additionalFilters;_includeCascadeResults;_before;_after;_beforeHookMode;_afterHookMode;_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}openapi(e){return Object.assign(this._schema,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$1(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})}},n=class{constructor(e){this.meta=e;}create(){return new r(this.meta)}list(){return new a(this.meta)}read(){return new d(this.meta)}update(){return new o(this.meta)}delete(){return new l(this.meta)}};function c(t){return new n(t)}export{r as CreateBuilder,n as CrudBuilder,l as DeleteBuilder,a as ListBuilder,d as ReadBuilder,o as UpdateBuilder,c as crud};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function c(d,e){let s=e.middlewares??[],r=e.extras,a=e.schema??{},n=Array.isArray(a.tags)&&a.tags.length>0,o=e.meta.model.tag??e.meta.model.tableName,l=n?a:{...a,tags:[o]};return class extends d{static _middlewares=s;constructor(){super(),r&&Object.assign(this,r),e.bodySchema&&Object.assign(this,{getBodySchema:()=>e.bodySchema}),e.searchParamName!==void 0&&Object.assign(this,{searchParamName:e.searchParamName});}_meta=e.meta;schema=l;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??[];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??[];cursorPaginationEnabled=e.cursorPaginationEnabled??false;cursorField=e.cursorField;cacheEnabled=e.cacheEnabled??false;cacheTtlSeconds=e.cacheTtlSeconds;cacheKeyFields=e.cacheKeyFields;cachePerUser=e.cachePerUser;cachePrefix=e.cachePrefix;cacheTags=e.cacheTags;cacheInvalidate=e.cacheInvalidate;async before(...t){return e.before?e.before(...t):super.before(...t)}async after(...t){return e.after?e.after(...t):super.after(...t)}transform(t){return e.transform?e.transform(t):super.transform(t)}}}export{c as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-5DTBFOC3.js';var s={search:"SearchEndpoint",aggregate:"AggregateEndpoint",restore:"RestoreEndpoint",batchCreate:"BatchCreateEndpoint",batchUpdate:"BatchUpdateEndpoint",batchDelete:"BatchDeleteEndpoint",batchRestore:"BatchRestoreEndpoint",batchUpsert:"BatchUpsertEndpoint",export:"ExportEndpoint",import:"ImportEndpoint",upsert:"UpsertEndpoint",clone:"CloneEndpoint",bulkPatch:"BulkPatchEndpoint",versionHistory:"VersionHistoryEndpoint",versionRead:"VersionReadEndpoint",versionCompare:"VersionCompareEndpoint",versionRollback:"VersionRollbackEndpoint"};function r(t,a){let n=s[a],e=t[n];if(!e)throw new Error(`defineEndpoints: "${a}" is configured but the adapter bundle has no ${n}. Use an adapter bundle that ships ${n}, or remove the "${a}" config.`);return e}function c(t,a$1){let n={};if(t.create!==void 0){let e=t.create;n.create=a(a$1.CreateEndpoint,{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,allowNestedCreate:e.nestedCreate,cacheInvalidate:e.cache?.invalidate,cachePrefix:e.cache?.prefix,before:e.hooks?.before,after:e.hooks?.after});}if(t.list!==void 0){let e=t.list;n.list=a(a$1.ListEndpoint,{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,filterFields:e.filtering?.fields,filterConfig:e.filtering?.config,searchFields:e.search?.fields,searchParamName:e.search?.paramName,sortFields:e.sorting?.fields,defaultSort:e.sorting?.default?{field:e.sorting.default,order:e.sorting.defaultOrder??"asc"}:void 0,defaultPerPage:e.pagination?.defaultPerPage,maxPerPage:e.pagination?.maxPerPage,cursorPaginationEnabled:e.pagination?.cursor?.enabled,cursorField:e.pagination?.cursor?.field,allowedIncludes:e.includes,fieldSelectionEnabled:e.fieldSelection?.enabled,allowedSelectFields:e.fieldSelection?.allowed,blockedSelectFields:e.fieldSelection?.blocked,alwaysIncludeFields:e.fieldSelection?.alwaysInclude,defaultSelectFields:e.fieldSelection?.defaults,cacheEnabled:e.cache?e.cache.enabled??true:void 0,cacheTtlSeconds:e.cache?.ttl,cacheKeyFields:e.cache?.keyFields,cachePerUser:e.cache?.perUser,cachePrefix:e.cache?.prefix,cacheTags:e.cache?.tags,after:e.hooks?.after,transform:e.hooks?.transform});}if(t.read!==void 0){let e=t.read;n.read=a(a$1.ReadEndpoint,{meta:t.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,cacheEnabled:e.cache?e.cache.enabled??true:void 0,cacheTtlSeconds:e.cache?.ttl,cacheKeyFields:e.cache?.keyFields,cachePerUser:e.cache?.perUser,cachePrefix:e.cache?.prefix,cacheTags:e.cache?.tags,after:e.hooks?.after,transform:e.hooks?.transform});}if(t.update!==void 0){let e=t.update;n.update=a(a$1.UpdateEndpoint,{meta:t.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,cacheInvalidate:e.cache?.invalidate,cachePrefix:e.cache?.prefix,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,transform:e.hooks?.transform});}if(t.delete!==void 0){let e=t.delete;n.delete=a(a$1.DeleteEndpoint,{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,lookupField:e.lookupField,additionalFilters:e.additionalFilters,includeCascadeResults:e.includeCascadeResults,cacheInvalidate:e.cache?.invalidate,cachePrefix:e.cache?.prefix,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after});}if(t.search!==void 0){let e=t.search,o={};e.fields!==void 0&&(o.searchFields=e.fields),e.mode!==void 0&&(o.defaultMode=e.mode),e.paramName!==void 0&&(o.searchParamName=e.paramName),e.hooks?.after!==void 0&&(o.afterSearch=e.hooks.after),n.search=a(r(a$1,"search"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,extras:o});}if(t.aggregate!==void 0){let e=t.aggregate,o={};e.fields!==void 0&&(o.filterFields=e.fields),n.aggregate=a(r(a$1,"aggregate"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,after:e.hooks?.after,extras:o});}if(t.restore!==void 0){let e=t.restore;n.restore=a(r(a$1,"restore"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after});}if(t.batchCreate!==void 0){let e=t.batchCreate,o={};e.maxBatchSize!==void 0&&(o.maxBatchSize=e.maxBatchSize),n.batchCreate=a(r(a$1,"batchCreate"),{meta:t.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:o});}if(t.batchUpdate!==void 0){let e=t.batchUpdate,o={};e.maxBatchSize!==void 0&&(o.maxBatchSize=e.maxBatchSize),n.batchUpdate=a(r(a$1,"batchUpdate"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:o});}if(t.batchDelete!==void 0){let e=t.batchDelete,o={};e.maxBatchSize!==void 0&&(o.maxBatchSize=e.maxBatchSize),n.batchDelete=a(r(a$1,"batchDelete"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:o});}if(t.batchRestore!==void 0){let e=t.batchRestore,o={};e.maxBatchSize!==void 0&&(o.maxBatchSize=e.maxBatchSize),n.batchRestore=a(r(a$1,"batchRestore"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:o});}if(t.batchUpsert!==void 0){let e=t.batchUpsert,o=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,i={};e.maxBatchSize!==void 0&&(i.maxBatchSize=e.maxBatchSize),o!==void 0&&(i.upsertKeys=o),e.hooks?.before!==void 0&&(i.beforeBatch=e.hooks.before),e.hooks?.after!==void 0&&(i.afterBatch=e.hooks.after),n.batchUpsert=a(r(a$1,"batchUpsert"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,extras:i});}if(t.export!==void 0){let e=t.export,o={};e.maxRows!==void 0&&(o.maxExportRecords=e.maxRows),e.formats!==void 0&&e.formats.length>0&&(o.defaultFormat=e.formats[0]),n.export=a(r(a$1,"export"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,extras:o});}if(t.import!==void 0){let e=t.import,o={};e.maxRows!==void 0&&(o.maxBatchSize=e.maxRows),n.import=a(r(a$1,"import"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:o});}if(t.upsert!==void 0){let e=t.upsert,o=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,i={};o!==void 0&&(i.upsertKeys=o),n.upsert=a(r(a$1,"upsert"),{meta:t.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:i});}if(t.clone!==void 0){let e=t.clone,o={};e.fieldsToReset!==void 0&&(o.excludeFromClone=e.fieldsToReset),n.clone=a(r(a$1,"clone"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:o});}if(t.bulkPatch!==void 0){let e=t.bulkPatch,o={};e.fields!==void 0&&(o.filterFields=e.fields),e.maxBulkSize!==void 0&&(o.maxBulkSize=e.maxBulkSize),e.confirmThreshold!==void 0&&(o.confirmThreshold=e.confirmThreshold),e.returnRecords!==void 0&&(o.returnRecords=e.returnRecords),n.bulkPatch=a(r(a$1,"bulkPatch"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,extras:o});}if(t.versionHistory!==void 0){let e=t.versionHistory,o={};e.defaultLimit!==void 0&&(o.defaultLimit=e.defaultLimit),e.maxLimit!==void 0&&(o.maxLimit=e.maxLimit),n.versionHistory=a(r(a$1,"versionHistory"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,extras:o});}if(t.versionRead!==void 0){let e=t.versionRead;n.versionRead=a(r(a$1,"versionRead"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares});}if(t.versionCompare!==void 0){let e=t.versionCompare;n.versionCompare=a(r(a$1,"versionCompare"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares});}if(t.versionRollback!==void 0){let e=t.versionRollback;n.versionRollback=a(r(a$1,"versionRollback"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares});}return n}export{c as a};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import {e as e$3,f as f$1}from'./chunk-P7HU2KIE.js';import {e as e$2}from'./chunk-H3VBYIDA.js';import {a as a$4,b as b$4}from'./chunk-CWQSQUV4.js';import {a as a$5,b as b$5}from'./chunk-SDNXN7M5.js';import {i,a as a$3}from'./chunk-HYXDMJ4K.js';import {h as h$1}from'./chunk-WBHWKOTP.js';import {a as a$1}from'./chunk-L5CVVJQH.js';import {f,b as b$2,N,P,d as d$1,S,R,c,e as e$1,p,y}from'./chunk-A27HDYSF.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {b}from'./chunk-5P4RVSHT.js';import {a as a$2,b as b$6}from'./chunk-TLI3TRUA.js';import {a,j,e,d,b as b$3,h,c as c$1,g}from'./chunk-XR6JRDGX.js';import {z}from'zod';import {stream}from'hono/streaming';var wo=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["bulkPatch","patch","/bulk"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"],["versionHistory","get","/:id/versions"],["versionCompare","get","/:id/versions/compare"],["versionRead","get","/:id/versions/:version"],["versionRollback","post","/:id/versions/:version/rollback"]];var je="createdAt",Pe="updatedAt";function le(n){return n?n===true?{enabled:true,createdAt:je,updatedAt:Pe}:{enabled:true,createdAt:n.createdAt??je,updatedAt:n.updatedAt??Pe}:{enabled:false,createdAt:je,updatedAt:Pe}}function A(n,e={}){let{includePrimaryKeys:t=true}=e,o=new Set;if(t)for(let s of n.primaryKeys)o.add(s);let r=le(n.timestamps);return r.enabled&&(o.add(r.createdAt),o.add(r.updatedAt)),[...o]}function Xt(n){return n!=null&&n!==""}function tt(n,e,t,o){let r={...n},s=e.primaryKeys[0];if(!Xt(r[s])){let l=e.id;if(typeof l=="function")r[s]=l();else if(l==="database"){if(t==="memory")throw new j("MemoryAdapter does not support id:'database' (no database to generate the key)");delete r[s];}else r[s]=o?o():crypto.randomUUID();}let i=le(e.timestamps);if(i.enabled){let l=Date.now();i.createdAt in n||(r[i.createdAt]=l),i.updatedAt in n||(r[i.updatedAt]=l);}return r}function ot(n,e){let t=le(e.timestamps);return t.enabled?{...n,[t.updatedAt]:Date.now()}:{...n}}function rt(n,e){if(e==="memory"&&n.id==="database")throw new j("MemoryAdapter does not support id:'database' (no database to generate the key)")}function nt(n,e){let t={...n};for(let o of A(e))delete t[o];return t}var Jt=new Set(["P2002","SQLITE_CONSTRAINT_UNIQUE","SQLITE_CONSTRAINT","23505","ER_DUP_ENTRY",1062,"1062"]),eo=/UNIQUE constraint failed|duplicate key value violates unique constraint|Duplicate entry/i;function to(n){if(!n||typeof n!="object")return false;let{code:e,message:t}=n;return (typeof e=="string"||typeof e=="number")&&Jt.has(e)?true:typeof t=="string"&&eo.test(t)}function*oo(n,e=8){for(let t=n,o=0;o<e&&t!=null&&typeof t=="object";o++)yield t,t=t.cause;}function Fe(n){for(let e$1 of oo(n))if(to(e$1))return new e("Unique constraint violation");return null}function H(n){throw Fe(n)??n}function ro(n){return btoa(String(n))}function xo(n){try{return atob(n)}catch{return null}}function Oo(n){let{rows:e,limit:t,totalCount:o,cursorField:r,cursorApplied:s}=n,i=e.length>t,l=i?e.slice(0,t):e,d=l[l.length-1];return {items:l,result_info:{page:0,per_page:t,total_count:o,has_next_page:i,has_prev_page:s,next_cursor:i&&d!==void 0?ro(d[r]):void 0}}}async function ce(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 st(n,e){return !e||Object.keys(e).length===0?n:Promise.all(n.map(t=>ce(t,e)))}function re(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 he(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 Io(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 it(n){let e=[],t={};for(let a of f){let u=n[a];if(u){let p=Array.isArray(u)?u:[u];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(u=>u.trim()):Array.isArray(a)&&(o=a.filter(u=>typeof u=="string"));}let r;for(let[a,u]of Object.entries(n)){let p=a.match(/^having\[(\w+)\]\[(\w+)\]$/);if(p){let[,m,f]=p;r||(r={}),r[m]||(r[m]={}),r[m][f]=u;}}let s=typeof n.orderBy=="string"?n.orderBy:void 0,i=n.orderDirection==="desc"?"desc":"asc",l=typeof n.limit=="string"?Number.parseInt(n.limit,10):void 0,d=typeof n.offset=="string"?Number.parseInt(n.offset,10):void 0,c=[...f,"groupBy","orderBy","orderDirection","limit","offset"];for(let[a,u]of Object.entries(n))!c.includes(a)&&!a.startsWith("having[")&&(t[a]=u);return {aggregations:e,groupBy:o,filters:Object.keys(t).length>0?t:void 0,having:r,orderBy:s,orderDirection:i,limit:l,offset:d}}function at(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 ne(n,e,t){return t.enabled&&e[t.field]!=null?{...n,[t.field]:null}:n}var no=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 lt(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=>!no.has(o)&&o.length>1):t}function ct(n,e){return e==="phrase"?[n.toLowerCase().trim()]:lt(n)}function so(n,e){return e.length===0?0:e.filter(o=>o===n||o.includes(n)).length/e.length}function ut(n,e,t,o){if(e.length===0)return {score:0,matchedFields:[]};let r=0,s=0,i=[];for(let[d,c]of Object.entries(t)){let a=n[d];if(a==null)continue;let u=c.weight??1;s+=u;let p;c.type==="array"&&Array.isArray(a)?p=a.join(" "):p=String(a);let m=lt(p,false),f=p.toLowerCase(),h=0,R=0;if(o==="phrase"){let g=e[0];f.includes(g)&&(h=1,R=1);}else {for(let g of e){let S=so(g,m);S>0?(R++,h+=S):f.includes(g)&&(R++,h+=.5/e.length);}e.length>0&&(h=h/e.length);}o==="all"&&R<e.length&&(h=0),h>0&&(i.push(d),r+=h*u);}return {score:s>0?Math.min(1,r/s):0,matchedFields:i}}function pt(n,e,t,o="mark",r=150){if(n==null)return [];let s;if(Array.isArray(n)?s=n.join(" "):s=String(n),!s||e.length===0)return [];let i=[],l=s.toLowerCase();if(t==="phrase"){let d=e[0],c=l.indexOf(d);if(c!==-1){let a=dt(s,c,d.length,r,o);a&&i.push(a);}}else {let d=[];for(let a of e){let u=0;for(;u<l.length;){let p=l.indexOf(a,u);if(p===-1)break;d.push({start:p,length:a.length}),u=p+1;}}d.sort((a,u)=>a.start-u.start);let c=new Set;for(let a of d){if(Array.from(c).some(m=>Math.abs(m-a.start)<r))continue;let p=dt(s,a.start,a.length,r,o);if(p&&(i.push(p),c.add(a.start)),i.length>=3)break}}return i}function dt(n,e,t,o,r){let s=Math.floor(o/2),i=Math.max(0,e-s),l=Math.min(n.length,e+t+s);if(i>0){let a=n.indexOf(" ",i);a!==-1&&a<e&&(i=a+1);}if(l<n.length){let a=n.lastIndexOf(" ",l);a!==-1&&a>e+t&&(l=a);}let d=n.slice(i,l);return i>0&&(d="..."+d),l<n.length&&(d=d+"..."),io(d,[n.slice(e,e+t)],r)}function io(n,e,t){let o=n,r=n.toLowerCase(),s=[...e].sort((i,l)=>l.length-i.length);for(let i of s){let l=i.toLowerCase(),d=0,c="",a=0;for(;a<r.length;){let u=r.indexOf(l,a);if(u===-1)break;c+=o.slice(d,u),c+=`<${t}>${o.slice(u,u+i.length)}</${t}>`,d=u+i.length,a=d;}c&&(c+=o.slice(d),o=c);}return o}function mt(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 ht(n,e){let t={};for(let o of n)t[o]={weight:e?.[o]??1};return t}function ft(n){return n==="all"||n==="phrase"?n:"any"}function Ie(n){if(n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(Ie);let e={};for(let t of Object.keys(n).sort())e[t]=Ie(n[t]);return e}async function se(n){let e=JSON.stringify(Ie(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 Ce(n,e){return n?n==="*"?true:n.split(",").map(t=>t.trim()).includes(e):false}function gt(n,e){return !n||n==="*"?true:n.split(",").map(t=>t.trim()).includes(e)}function ao(n){let{tableName:e,method:t,params:o,query:r,keyFields:s,userId:i,prefix:l}=n,d=[];if(l&&d.push(l),d.push(e),d.push(t),o&&Object.keys(o).length>0){let c=Object.keys(o).sort().map(a=>`${a}=${o[a]}`).join("&");d.push(c);}if(r&&Object.keys(r).length>0){let c=Object.keys(r).filter(a=>r[a]!==void 0&&r[a]!==null&&r[a]!=="");if(s&&s.length>0&&(c=c.filter(a=>s.includes(a)||a==="fields"||a==="include")),c.length>0){let a=c.sort().map(u=>`${u}=${String(r[u])}`).join("&");d.push(a);}}return i&&d.push(`user=${i}`),d.join(":")}function Y(n,e,t){let o=[];if(t&&o.push(t),o.push(n),!e)return o.push("*"),o.join(":");let{method:r,id:s,userId:i}=e;return r?(o.push(r),o.join(":")+"*"):(s!==void 0?(o.push("*"),o.push(`id=${s}*`)):i?(o.push("*"),o.push(`user=${i}`)):o.push("*"),o.join(":"))}function lo(n,e,t){return e.map(o=>Y(o,void 0,t))}function Do(n,e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`).test(n)}var ie=b({contextKey:a.cacheStorage}),Vo=ie.registry,Zo=ie.set,Lo=ie.get,Uo=ie.getRequired,qo=ie.resolve,bt=false;function Ee(n){let e=ie.resolve(n);return !e&&!bt&&(bt=true,b$1().warn("Cache storage not configured \u2014 caching is disabled. Inject cacheStorage with createStorageMiddleware()/createCacheStorageMiddleware() (recommended) or call setCacheStorage(). This warning is logged once per isolate.")),e}var yt=false;function wt(){yt||(yt=true,b$1().warn("Response caching is disabled for an endpoint with user-scoped read policies (read / fields / readPushdown) because the cache key is not per-user. Set `cache.perUser: true` to fold the userId into the key and re-enable caching. This warning is logged once per isolate."));}function Mt(n,e){let t=[n,e!=null?`t=${e}`:void 0].filter(o=>!!o);return t.length>0?t.join(":"):void 0}async function St(n,e){let t=n._meta?.model?.tableName;if(!t)return null;let o=await n.getValidatedData(),r=o.params,s=o.query,i=r&&Object.keys(r).length>0?"GET":"LIST",l;return n.cachePerUser&&(l=n.getContext().var?.userId),ao({tableName:t,method:i,params:r,query:s,keyFields:n.cacheKeyFields,userId:l,prefix:Mt(n.cachePrefix,e)})}async function fe(n,e){let t=await St(n,e);if(!t)return null;let o=Ee(n.getContext());return o?(await o.get(t))?.data??null:null}async function ge(n,e,t){let o=await St(n,t);if(!o)return;let r=Ee(n.getContext());if(!r)return;let s=n.cacheTags?[...n.cacheTags]:[],i=n._meta?.model?.tableName;i&&s.push(t!=null?`${i}:t=${t}`:i),await r.set(o,e,{ttlMs:n.cacheTtlSeconds!=null?n.cacheTtlSeconds*1e3:void 0,tags:s.length>0?s:void 0});}async function Rt(n,e){let t=n.cacheInvalidate;if(!t)return;let o=Ee(n.getContext());if(!o)return;let r=n._meta?.model?.tableName;if(!r)return;let s=Mt(n.cachePrefix,e),i=new Set,l=new Set;if(t===true)i.add(Y(r,void 0,s));else if(Array.isArray(t))for(let d of t)d==="all"?i.add(Y(r,void 0,s)):d==="list"?i.add(Y(r,{method:"LIST"},s)):d==="read"&&i.add(Y(r,{method:"GET"},s));else {let d=t;if(d.pattern&&i.add(d.pattern),d.tags)for(let a of d.tags)l.add(a);if(d.strategy==="tags"&&l.add(e!=null?`${r}:t=${e}`:r),d.relatedModels)for(let a of lo(r,d.relatedModels,s))i.add(a);let c=d.strategy??(d.pattern||d.tags?void 0:"all");c==="all"||c==="single"?i.add(Y(r,void 0,s)):c==="list"&&i.add(Y(r,{method:"LIST"},s));}try{if(l.size>0&&o.deleteByTag)for(let d of l)await o.deleteByTag(d);for(let d of i)await o.deletePattern(d);}catch(d){b$1().warn("Cache invalidation failed after mutation (entries will expire by TTL).",{error:d instanceof Error?d.message:String(d)});}}function xt(n,e){return n==="in"||n==="nin"||n==="between"?e.split(",").map(t=>t.trim()):n==="null"?e.toLowerCase()==="true":e}function Ho(n){let e=n.match(/^\[([a-z]+)\](.*)$/);if(e&&b$2(e[1])){let t=e[1];return {operator:t,value:xt(t,e[2])}}return {operator:"eq",value:n}}function ae(n,e){let t=[],o={},{filterFields:r=[],filterConfig:s={},searchFields:i=[],searchParamName:l="search",sortFields:d=[],defaultSort:c,defaultPerPage:a=20,maxPerPage:u=100,cursorPaginationEnabled:p=false,cursorField:m,softDeleteQueryParam:f="withDeleted",allowedIncludes:h=[],fieldSelectionEnabled:R=false,allowedSelectFields:g=[],blockedSelectFields:S=[],alwaysIncludeFields:j=[],defaultSelectFields:D=[]}=e,J={};for(let E of r)J[E]=["eq"];Object.assign(J,s);for(let[E,Oe]of Object.entries(n)){if(Oe==null)continue;let V=String(Oe);if(p&&E==="cursor"){o.cursor=V;continue}if(p&&E==="limit"){o.limit=Math.min(u,Math.max(1,Number.parseInt(V,10)||a));continue}if(E==="page"){o.page=Math.max(1,Number.parseInt(V,10)||1);continue}if(E==="per_page"){o.per_page=Math.min(u,Math.max(1,Number.parseInt(V,10)||a));continue}if(E==="sort"){(d.length===0||d.includes(V))&&(o.order_by=V);continue}if(E==="order"){(V==="asc"||V==="desc")&&(o.order_by_direction=V);continue}if(E===l&&i.length>0){o.search=V;continue}if(E===f){o.withDeleted=V.toLowerCase()==="true";continue}if(E==="onlyDeleted"){o.onlyDeleted=V.toLowerCase()==="true";continue}if(E==="include"){let ee=V.split(",").map(z=>z.trim()).filter(Boolean);h&&h.length>0?o.include=ee.filter(z=>h.includes(z)):o.include=ee;continue}if(E==="fields"&&R){let z=V.split(",").map(de=>de.trim()).filter(Boolean);g.length>0&&(z=z.filter(de=>g.includes(de))),S.length>0&&(z=z.filter(de=>!S.includes(de))),j.length>0&&(z=[...new Set([...j,...z])]),o.fields=z;continue}let ke=E.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(ke){let ee=ke[1],z=ke[2];J[ee]?.includes(z)&&t.push({field:ee,operator:z,value:xt(z,V)});continue}J[E]&&t.push({field:E,operator:"eq",value:V});}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"),p&&(o.cursor!==void 0||o.limit!==void 0)&&(o.order_by=m??"id",o.order_by_direction="asc"),R&&!o.fields&&D.length>0){let E=[...D];j.length>0&&(E=[...new Set([...j,...E])]),o.fields=E;}return {filters:t,options:o}}function _(n,e=[]){if(e.length===0)return n;let t=new Set(Object.keys(n.shape)),o=e.filter(s=>t.has(s));if(o.length===0)return n;let r=Object.fromEntries(o.map(s=>[s,true]));return n.omit(r)}function $o(n,e={},t=[],o=[],r=[]){let{allowedFields:s=[],blockedFields:i=[],alwaysIncludeFields:l=[],defaultFields:d=[],allowComputedFields:c=true,allowRelationFields:a=true}=e;if(!n||typeof n!="string"||n.trim()==="")return d.length>0?{fields:[...new Set([...l,...d])],isActive:false}:{fields:[],isActive:false};let u=n.split(",").map(h=>h.trim()).filter(Boolean),p=new Set;for(let h of t)(s.length===0||s.includes(h))&&(i.includes(h)||p.add(h));if(c)for(let h of o)(s.length===0||s.includes(h))&&(i.includes(h)||p.add(h));if(a)for(let h of r)(s.length===0||s.includes(h))&&(i.includes(h)||p.add(h));let m=u.filter(h=>p.has(h));return {fields:[...new Set([...l,...m])],isActive:true}}function ve(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 Ot(n,e){return !e.isActive||e.fields.length===0?n:n.map(t=>ve(t,e))}var kt="__honoCrudResolvedSchema:";function co(n){return typeof n.getBodySchema=="function"}var O=class extends p{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=h$1(this._meta.model.audit,void 0,this.context??void 0)),this._auditLogger}getAuditConfig(){return a$1(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$2(this.context,a.userId):void 0}getVersionManager(){return this._versionManager||(this._versionManager=i(this._meta.model.versioning,this._meta.model.tableName,void 0,this.context??void 0)),this._versionManager}getVersioningConfig(){return a$3(this._meta.model.versioning,this._meta.model.tableName)}isVersioningEnabled(){return this.getVersioningConfig().enabled}getVersioningUserId(){let e=this.getVersioningConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?a$2(this.context,a.userId):void 0}getSoftDeleteConfig(){return at(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return a$4(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,t,o){return tt(e,this._meta.model,t,o)}applyManagedUpdateFields(e){return ot(e,this._meta.model)}assertIdStrategySupported(e){rt(this._meta.model,e);}getTimestampsConfig(){return le(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return b$4(this.context,e)}getRelationScope(e=false){return {tenantId:this.getTenantId(),includeDeleted:e}}getTenantScopeFilter(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();return t==null?void 0:{field:e.field,value:t}}applyTenantScope(e){let t=this.validateTenantId();t&&e.filters.push({field:this.getMultiTenantConfig().field,operator:"eq",value:t});}applyTenantScopeToAggregateFilters(e){let t=this.validateTenantId();return t?{...e??{},[this.getMultiTenantConfig().field]:t}:e}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();if(!t&&e.required)throw new b$3(e.errorMessage,400,"TENANT_REQUIRED");return t}injectTenantId(e){let t=this.getMultiTenantConfig();if(!t.enabled)return e;let o=this.getTenantId();return o?{...e,[t.field]:o}:e}async emitEvent(e,t){let o=e$2(this.context??void 0);o&&await o.emit({type:e,table:this._meta.model.tableName,recordId:t.recordId,data:t.data??null,previousData:t.previousData,userId:this.getAuditUserId(),tenantId:this.context?this.getTenantId():void 0,organizationId:this.context?a$2(this.context,a.organizationId):void 0,timestamp:new Date().toISOString(),metadata:t.metadata});}async encryptOnWrite(e){let t=this._meta.model.fieldEncryption;return t?await e$3(e,t.fields,t.keyProvider):e}async decryptOnRead(e){let t=this._meta.model.fieldEncryption;return t?await f$1(e,t.fields,t.keyProvider):e}applyProfile(e){let t=this._meta.model.serializationProfile;return t?a$5(e,t):e}applyProfileToArray(e){let t=this._meta.model.serializationProfile;return t?b$5(e,t):e}transform(e){return e}async finalizeRecord(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await ce(r,o.computedFields));let s=o.serializer?o.serializer(r):r,i=this.applyProfile(s),l=this.transform(i);return t?.isActive&&t.fields.length>0?ve(l,t):l}async finalizeArray(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await st(r,o.computedFields));let s=o.serializer?r.map(d=>o.serializer(d)):r,l=this.applyProfileToArray(s).map(d=>this.transform(d));return t?.isActive&&t.fields.length>0?Ot(l,t):l}getRecordId(e){if(e===null||typeof e!="object")return null;let t=this._meta.model.primaryKeys[0],o=e[t];return typeof o=="string"||typeof o=="number"?o:null}getParentId(e){return this.getRecordId(e)}getPolicies(){if(this.context){let e=a$2(this.context,y);if(e)return e}return this._meta.model.policies}cacheEnabled=false;cacheTtlSeconds;cacheKeyFields;cachePerUser;cacheTags;cacheInvalidate;cachePrefix;isResponseCacheActive(){return this.cacheEnabled?this.cachePerUser?true:this.hasUserScopedReadPolicy()?(wt(),false):true:false}hasUserScopedReadPolicy(){let e=this.getPolicies();return !!(e&&(e.read||e.fields||e.readPushdown))}async invalidateModelCache(){await Rt({getContext:()=>this.getContext(),_meta:this._meta,cacheInvalidate:this.cacheInvalidate??true,cachePrefix:this.cachePrefix},this.getTenantId());}buildPolicyContext(){let e=this.context;return {user:e?a$2(e,a.user):void 0,userId:e?a$2(e,a.userId):void 0,tenantId:e?a$2(e,a.tenantId):void 0,organizationId:e?a$2(e,a.organizationId):void 0,request:e?.req?.raw??new Request("http://localhost/")}}async applyReadPolicy(e){let t=this.getPolicies();if(!t)return e;let o=this.buildPolicyContext();if(t.read&&!await t.read(o,e))return null;if(t.fields){let r=t.fields(o,e);return {...e,...r}}return e}async applyReadPolicyToArray(e){if(!this.getPolicies())return e;let o=[];for(let r of e){let s=await this.applyReadPolicy(r);s!==null&&o.push(s);}return o}async applyWritePolicy(e){let t=this.getPolicies();if(!t?.write)return;if(!await t.write(this.buildPolicyContext(),e))throw new g("Forbidden by policy")}applyReadPushdown(e){let t=this.getPolicies();if(!t?.readPushdown)return;let o=t.readPushdown(this.buildPolicyContext());o&&o.length>0&&e.filters.push(...o);}buildHookContext(){let e=this.context;return {db:{tx:this._tx},request:e?.req?.raw,tenantId:e?this.getTenantId():void 0,organizationId:e?a$2(e,a.organizationId):void 0,userId:e?a$2(e,a.userId):void 0,agentId:e?a$2(e,a.agentId):void 0,agentRunId:e?a$2(e,a.agentRunId):void 0}}getModelSchema(){if(this.context&&this._meta.model.resolveSchema){let e=a$2(this.context,kt+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=kt+this._meta.model.tableName,o=a$2(this.context,t);if(o)return o;let r={tenantId:a$2(this.context,a.tenantId),organizationId:a$2(this.context,a.organizationId),request:this.context.req?.raw,env:this.context.env},s;try{s=await e(r);}catch(i){throw new b$3(i instanceof Error?i.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",i instanceof Error?{cause:i.message}:void 0)}return b$6(this.context,t,s),s}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&co(this)){let t=e.body;try{t=await this.context.req.json();}catch{}let r=this.getBodySchema().safeParse(t);if(!r.success)throw c$1.fromZodError(r.error);e.body=r.data;}return e}};var jt=class extends O{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,t=A(this._meta.model),o=this.getMultiTenantConfig();o.enabled&&t.push(o.field),this._meta.fields?e=this._meta.fields:e=_(this.getModelSchema(),t);let r=this.getNestedWritableRelations();if(r.length===0)return e;let s={...e.shape};for(let i of r){let l=this._meta.model.relations?.[i];if(!l?.schema)continue;let d=["id",l.foreignKey],c=_(l.schema,d);l.type==="hasMany"?s[i]=z.array(c).optional():s[i]=c.optional();}return z.object(s)}getNestedWritableRelations(){if(this.allowNestedCreate.length>0)return this.allowNestedCreate;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>o.nestedWrites?.allowCreate===true).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return re(e,t)}getSchema(){let e=this.getBodySchema();return N({request:{body:{content:{"application/json":{schema:e}},required:true}},responses:{201:{description:"Resource created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:P("Validation error")}},this.schema)}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t){return e}async after(e,t){return e}transform(e){return e}async createNested(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override createNested() in your adapter.`),[]}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let s=this.buildHookContext();r=await this.before(r,s),r=await this.encryptOnWrite(r),r=await this.create(r,s.db.tx).catch(H),r=await this.decryptOnRead(r);let i=this.getParentId(r),l={};if(Object.keys(o).length>0&&i!==null)for(let[c,a]of Object.entries(o)){if(a==null)continue;let u=this._meta.model.relations?.[c];if(!u)continue;let p=await this.createNested(i,c,u,a);l[c]=p;}if(Object.keys(l).length>0){let c={};for(let[a,u]of Object.entries(l)){let p=this._meta.model.relations?.[a];p&&(p.type==="hasMany"?c[a]=u:c[a]=u[0]||null);}r={...r,...c};}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(r,s))):r=await this.after(r,s),this.isAuditEnabled()&&i!==null){let c=this.getAuditLogger();this.runAfterResponse(c.logCreate(this._meta.model.tableName,i,r,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("created",{recordId:i,data:r}));let d=await this.finalizeRecord(r);return await this.invalidateModelCache(),this.success(d,201)}};function ye(n,e,t){let o=e.model.relations;if(!o||t.length===0)return n;let r={};for(let s of t){let i=o[s],l=i?.schema;l&&(r[s]=i.type==="hasMany"?z.array(l).optional():l.nullable().optional());}return Object.keys(r).length>0?n.extend(r):n}var Pt=class extends O{lookupField="id";lookupFields;additionalFilters;etagEnabled=false;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){let e={};if(this.additionalFilters?.length)for(let t of this.additionalFilters)e[t]=z.string().optional();if(this.allowedIncludes.length>0&&(e.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let t=this.getAvailableSelectFields();e.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${t.join(", ")}`});}if(Object.keys(e).length!==0)return z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=this.getQuerySchema();return N({request:{params:this.getParamsSchema(),...e&&{query:e}},responses:{200:{description:"Resource retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:ye(this.getModelSchema(),this._meta,this.allowedIncludes)})}}},404:P("Resource not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async getIncludeOptions(){let{query:e}=await this.getValidatedData(),t=e?.include;if(!t||typeof t!="string")return {relations:[]};let o=t.split(",").map(r=>r.trim()).filter(Boolean);return this.allowedIncludes.length>0?{relations:o.filter(r=>this.allowedIncludes.includes(r))}:{relations:o}}async getFieldSelection(){if(!this.fieldSelectionEnabled)return {fields:[],isActive:false};let{query:e}=await this.getValidatedData(),t=e?.fields;if(!t||typeof t!="string"||t.trim()==="")return this.defaultSelectFields.length>0?{fields:[...new Set([...this.alwaysIncludeFields,...this.defaultSelectFields])],isActive:true}:{fields:[],isActive:false};let o=t.split(",").map(i=>i.trim()).filter(Boolean),r=new Set(this.getAvailableSelectFields()),s=o.filter(i=>r.has(i));return this.alwaysIncludeFields.length>0&&(s=[...new Set([...this.alwaysIncludeFields,...s])]),{fields:s,isActive:true}}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=this.isResponseCacheActive();if(t){let u=await fe(this,e);if(u){if(this.etagEnabled){let m=await se(u),f=this.getContext();if(Ce(f.req.header("If-None-Match"),m))return new Response(null,{status:304,headers:{ETag:m,"X-Cache":"HIT"}});f.header("ETag",m);}let p=this.success(u);return p.headers.set("X-Cache","HIT"),p}}let o=await this.getLookupValue(),r=await this.getAdditionalFilters(),s=await this.getIncludeOptions();s&&(s.scope=this.getRelationScope());let i=await this.getFieldSelection();if(e){let u=this.getMultiTenantConfig();r[u.field]=e;}let l=await this.read(o,r,s);if(!l)throw new d(this._meta.model.tableName,o);l=await this.decryptOnRead(l);let d$1=await this.applyReadPolicy(l);if(d$1===null)throw new d(this._meta.model.tableName,o);l=d$1,l=await this.after(l);let c=await this.finalizeRecord(l,i);if(t&&await ge(this,c,e),this.etagEnabled){let u=await se(c),p=this.getContext(),m=p.req.header("If-None-Match");if(Ce(m,u))return new Response(null,{status:304,headers:t?{ETag:u,"X-Cache":"MISS"}:{ETag:u}});p.header("ETag",u);}let a=this.success(c);return t&&a.headers.set("X-Cache","MISS"),a}};var Ft=class extends O{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=A(this._meta.model);this.blockedUpdateFields&&(r=[...r,...this.blockedUpdateFields]);let s=_(this.getModelSchema(),r);if(this.allowedUpdateFields){let i={};for(let l of this.allowedUpdateFields)i[l]=true;s=s.pick(i);}e=s.partial();}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let i=s.schema,l=z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()}).optional();o[r]=l;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return re(e,t)}getSchema(){return N({request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:P("Validation error"),404:P("Resource not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getObject(){let{body:e}=await this.getValidatedData();return e}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){return e}async after(e,t,o){return t}transform(e){return e}async findExisting(e,t,o){return null}async processNestedWrites(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let g=this.getMultiTenantConfig();o[g.field]=e;}let r=await this.getObject(),{mainData:s,nestedData:i}=this.extractNestedData(r),l=this.getPolicies(),d$1=await this.findExisting(t,o,this._tx);if(d$1&&l?.write&&await this.applyWritePolicy(d$1),this.etagEnabled&&d$1){let g=this.getContext().req.header("If-Match");if(g){let S=await se(d$1);if(!gt(g,S))return this.error("Resource has been modified by another request","CONFLICT",409)}}let c;if(this.isVersioningEnabled()&&d$1){let g=this.getVersionManager(),S=this.getParentId(d$1);S!==null&&(c=await g.saveVersion(S,d$1,void 0,this.getVersioningUserId()));}let a=s;if(this.isVersioningEnabled()&&c!==void 0){let g=this.getVersioningConfig().field;a[g]=c;}let u=this.buildHookContext();a=await this.before(a,u),a=await this.encryptOnWrite(a);let p=await this.update(t,a,o,u.db.tx);if(!p)throw new d(this._meta.model.tableName,t);p=await this.decryptOnRead(p);let m=this.getParentId(p),f={};if(Object.keys(i).length>0&&m!==null)for(let[g,S]of Object.entries(i)){if(S==null)continue;let j=this._meta.model.relations?.[g];if(!j)continue;let D;he(S)?D={create:S}:D=S;let J=await this.processNestedWrites(m,g,j,D);f[g]=J;}if(Object.keys(f).length>0)for(let[g,S]of Object.entries(f)){let j=this._meta.model.relations?.[g];j&&(j.type==="hasMany"?p[g]=[...S.created,...S.updated]:p[g]=S.created[0]||S.updated[0]||null);}let h=d$1??p;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(h,p,u)));else {let g=await this.after(h,p,u);g!=null&&(p=g);}if(this.isAuditEnabled()&&m!==null&&d$1){let g=this.getAuditLogger();this.runAfterResponse(g.logUpdate(this._meta.model.tableName,m,d$1,p,this.getAuditUserId()));}m!==null&&this.runAfterResponse(this.emitEvent("updated",{recordId:m,data:p,previousData:d$1??void 0}));let R=await this.finalizeRecord(p);if(this.etagEnabled){let g=await se(R);this.getContext().header("ETag",g);}return await this.invalidateModelCache(),this.success(R)}};var It=class extends O{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";includeCascadeResults=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getCascadeRelations(e){let t=this._meta.model.relations;return t?Object.entries(t).filter(([o,r])=>{let s=r.cascade?.[e];return s&&s!=="noAction"}).map(([o,r])=>({name:o,config:r,action:r.cascade[e]})):[]}getSchema(){let e=this.includeCascadeResults?z.object({deleted:z.literal(true),cascade:z.object({deleted:z.record(z.string(),z.number()),nullified:z.record(z.string(),z.number())}).optional()}):z.object({deleted:z.literal(true)});return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:P("Resource not found"),409:{description:"Cannot delete - related records exist (restrict)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.object({relation:z.string(),count:z.number()}).optional()})})}}}}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){}async countRelated(e,t,o,r){return b$1().warn(`countRelated not implemented for ${t}. Override in your adapter for restrict cascade to work.`),0}async deleteRelated(e,t,o,r){return b$1().warn(`deleteRelated not implemented for ${t}. Override in your adapter for cascade delete to work.`),0}async nullifyRelated(e,t,o,r){return b$1().warn(`nullifyRelated not implemented for ${t}. Override in your adapter for setNull cascade to work.`),0}async processCascade(e,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r),i={deleted:{},nullified:{}};for(let{name:l,config:d,action:c}of s)if(c==="cascade"){let a=await this.deleteRelated(e,l,d,o);a>0&&(i.deleted[l]=a);}else if(c==="setNull"){let a=await this.nullifyRelated(e,l,d,o);a>0&&(i.nullified[l]=a);}return i}async checkRestrictConstraints(e$1,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r);for(let{name:i,config:l,action:d}of s)if(d==="restrict"){let c=await this.countRelated(e$1,i,l,o);if(c>0)throw new e(`Cannot delete: ${c} related ${i} record(s) exist. Remove them first or change the cascade configuration.`,{relation:i,count:c})}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let u=this.getMultiTenantConfig();o[u.field]=e;}let r=this.isSoftDeleteEnabled(),s=await this.findForDelete(t,o,this._tx);if(!s)throw new d(this._meta.model.tableName,t);let i=this.getParentId(s);i!==null&&await this.checkRestrictConstraints(i,r),await this.applyWritePolicy(s);let l=this.buildHookContext();if(await this.before(t,l),!await this.delete(t,o,l.db.tx))throw new d(this._meta.model.tableName,t);let c;if(i!==null&&(c=await this.processCascade(i,r)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(s,l))):await this.after(s,l),this.isAuditEnabled()&&i!==null){let u=this.getAuditLogger();this.runAfterResponse(u.logDelete(this._meta.model.tableName,i,s,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("deleted",{recordId:i,previousData:s}));let a={deleted:true};if(this.includeCascadeResults&&c){let u=Object.keys(c.deleted).length>0,p=Object.keys(c.nullified).length>0;(u||p)&&(a.cascade=c);}return await this.invalidateModelCache(),this.success(a)}};var we=class extends O{filterFields=[];filterConfig;searchFields=[];searchParamName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;supportsCursorPagination=false;cursorField;isCursorPaginationActive(){return this.cursorPaginationEnabled&&this.supportsCursorPagination}allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getQuerySchema(){let e={page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(e.sort=z.enum(this.sortFields).optional().meta({description:"Field to sort by"}),e.order=z.enum(d$1).optional().meta({description:"Sort direction (asc or desc)"})),this.searchFields.length>0&&(e[this.searchParamName]=z.string().optional());for(let o of this.filterFields)e[o]=z.string().optional();if(this.filterConfig)for(let[o,r]of Object.entries(this.filterConfig)){for(let s of r)e[`${o}[${s}]`]=z.string().optional();e[o]=z.string().optional();}let t=this.getSoftDeleteConfig();if(t.enabled&&t.allowQueryDeleted&&(e[t.queryParam]=z.enum(["true","false"]).optional(),e.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(e.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let o=this.getAvailableSelectFields();e.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${o.join(", ")}`});}return this.isCursorPaginationActive()&&(e.cursor=z.string().optional().meta({description:"Opaque cursor for fetching the next page. During a cursor walk, results are ordered by the cursor field ascending and sort/order are ignored."}),e.limit=z.string().optional().meta({description:"Number of items to return (cursor pagination)"})),z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e={page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),has_next_page:z.boolean(),has_prev_page:z.boolean()};return this.isCursorPaginationActive()&&(e.next_cursor=z.string().optional()),N({request:{query:this.getQuerySchema()},responses:{200:{description:"List of resources",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(ye(this.getModelSchema(),this._meta,this.allowedIncludes)),result_info:z.object(e)})}}},400:P("Validation error")}},this.schema)}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:this.searchFields,searchParamName:this.searchParamName,sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,cursorPaginationEnabled:this.isCursorPaginationActive(),cursorField:this.cursorField,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return ae(e||{},o)}async after(e){return e}transform(e){return e}async handle(){if(this.cursorPaginationEnabled&&!this.supportsCursorPagination)throw new j("cursorPaginationEnabled is true but this adapter's List endpoint does not implement cursor pagination (supportsCursorPagination is false). Use an adapter List endpoint that supports it, or disable cursorPaginationEnabled.");this.validateTenantId();let e=this.isResponseCacheActive(),t=e?this.getTenantId():void 0;if(e){let u=await fe(this,t);if(u){let p=this.successPaginated(u.result,u.result_info);return p.headers.set("X-Cache","HIT"),p}}let o=await this.getFilters();this.applyTenantScope(o),this.applyReadPushdown(o);let r=await this.list(o),s=await Promise.all(r.result.map(u=>this.decryptOnRead(u))),i=await this.applyReadPolicyToArray(s),l=await this.after(i),d=this.fieldSelectionEnabled&&o.options.fields&&o.options.fields.length>0?{fields:o.options.fields,isActive:true}:void 0,c=await this.finalizeArray(l,d);e&&await ge(this,{result:c,result_info:r.result_info},t);let a=this.successPaginated(c,r.result_info);return e&&a.headers.set("X-Cache","MISS"),a}};var Ct=class extends O{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...A(this._meta.model),...this.excludeFromClone];return _(this.getModelSchema(),e).partial()}getSchema(){return N({request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:false}},responses:{201:{description:"Resource cloned successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:P("Source resource not found"),409:P("Unique-constraint violation (e.g. natural-key collision)")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getOverrides(){let{body:e}=await this.getValidatedData();return e||{}}async before(e){return e}async after(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getOverrides(),r={};if(e){let a=this.getMultiTenantConfig();r[a.field]=e;}let s=await this.findSource(t,r);if(!s)throw new d(this._meta.model.tableName,t);let i=nt(s,this._meta.model);for(let a of this.excludeFromClone)delete i[a];Object.assign(i,o);let l=await this.before(i),d$1=await this.createClone(l).catch(H);d$1=await this.after(d$1);let c=await this.finalizeRecord(d$1);return await this.invalidateModelCache(),this.success(c,201)}};var Et=class extends O{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:P("Soft delete not enabled or record not deleted"),404:P("Resource not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new b$3("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getAdditionalFilters();await this.before(e);let o=await this.restore(e,t);if(!o)throw new d(this._meta.model.tableName,e);this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(o))):o=await this.after(o);let r=this.getRecordId(o);if(this.isAuditEnabled()&&r!==null){let i=this.getAuditLogger();this.runAfterResponse(i.logRestore(this._meta.model.tableName,r,o,this.getAuditUserId()));}r!==null&&this.runAfterResponse(this.emitEvent("restored",{recordId:r,data:o}));let s=await this.finalizeRecord(o);return await this.invalidateModelCache(),this.success(s)}};var vt=class extends O{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=A(this._meta.model,{includePrimaryKeys:false});for(let d of this._meta.model.primaryKeys)r.includes(d)||s.push(d);let i=_(this.getModelSchema(),s),l={};for(let[d,c]of Object.entries(i.shape))r.includes(d)?l[d]=c:l[d]=c.optional();e=z.object(l);}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let i=s.schema,l=z.union([s.type==="hasMany"?z.array(i.partial()):i.partial(),z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),upsert:z.union([i.partial(),z.array(i.partial())]).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()})]).optional();o[r]=l;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return re(e,t)}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(false)})}}},201:{description:"Resource created (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(true)})}}},400:P("Validation error")}},this.schema)}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t,o){return e}async beforeCreate(e,t){return e}async beforeUpdate(e,t,o){return e}async after(e,t,o){return e}async nativeUpsert(e,t){return b$1().warn("Native upsert not implemented for this adapter. Falling back to find-then-insert/update pattern."),this.performStandardUpsert(e,t)}async performStandardUpsert(e,t){let o=await this.findExisting(e,t);if(o){let r={...e};if(this.createOnlyFields)for(let i of this.createOnlyFields)delete r[i];return r=await this.beforeUpdate(r,o,t),r=ne(r,o,this.getSoftDeleteConfig()),{data:await this.update(o,r,t),created:false}}else {let r={...e};if(this.updateOnlyFields)for(let i of this.updateOnlyFields)delete r[i];return r=await this.beforeCreate(r,t),{data:await this.create(r,t),created:true}}}async upsert(e,t){return this.useNativeUpsert?this.nativeUpsert(e,t):this.performStandardUpsert(e,t)}async processNestedWrites(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let s=await this.findExisting(r),i=!s;r=await this.before(r,i);let l=await this.upsert(r).catch(H),d=l.data,c=this.getParentId(d),a={};if(Object.keys(o).length>0&&c!==null)for(let[p,m]of Object.entries(o)){if(m==null)continue;let f=this._meta.model.relations?.[p];if(!f)continue;let h;he(m)?h={create:m}:h=m;let R=await this.processNestedWrites(c,p,f,h);a[p]=R;}if(Object.keys(a).length>0)for(let[p,m]of Object.entries(a)){let f=this._meta.model.relations?.[p];f&&(f.type==="hasMany"?d[p]=[...m.created,...m.updated]:d[p]=m.created[0]||m.updated[0]||null);}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(d,l.created))):d=await this.after(d,l.created),this.isAuditEnabled()&&c!==null){let p=this.getAuditLogger();this.runAfterResponse(p.logUpsert(this._meta.model.tableName,c,d,s,l.created,this.getAuditUserId()));}let u=await this.finalizeRecord(d);return await this.invalidateModelCache(),this.json({success:true,result:u,created:l.created},l.created?201:200)}};var At=class extends O{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:_(this.getModelSchema(),A(this._meta.model));return z.object({items:z.array(e).min(1).max(this.maxBatchSize)})}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{201:{description:"Resources created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number()})})}}},207:{description:"Partial success (some items failed)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:P("Validation error")}},this.schema)}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}async before(e,t,o){return e}async after(e,t,o){return e}transform(e){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let c=0;c<e.length;c++)try{let a=await this.before(e[c],c);o.push(a);}catch(a){if(this.stopOnError)throw a;t.push({index:c,error:a instanceof Error?a.message:String(a)});}let r=await this.batchCreate(o).catch(H),s=[];for(let c=0;c<r.length;c++)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(r[c],c))),s.push(r[c])):s.push(await this.after(r[c],c));}catch(a){if(this.stopOnError)throw a;t.push({index:c,error:a instanceof Error?a.message:String(a)}),s.push(r[c]);}if(this.isAuditEnabled()){let c=this.getAuditLogger(),a=s.map(u=>{let p=this.getRecordId(u);return p===null?null:{recordId:p,record:u}}).filter(u=>u!==null);a.length>0&&this.runAfterResponse(c.logBatch("batch_create",this._meta.model.tableName,a,this.getAuditUserId()));}let i=await this.finalizeArray(s),l={success:true,result:{created:i,count:i.length,...t.length>0&&{errors:t}}},d=t.length>0?207:201;return await this.invalidateModelCache(),this.json(l,d)}};var _t=class extends O{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:_(this.getModelSchema(),A(this._meta.model));return z.object({items:z.array(z.object({id:z.string(),data:e.partial()})).min(1).max(this.maxBatchSize)})}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("updated",this.getModelSchema(),"Resources updated successfully"),400:P("Validation error")}},this.schema)}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}filterUpdateData(e){let t={...e};if(this.allowedUpdateFields){let o=new Set(this.allowedUpdateFields);t=Object.fromEntries(Object.entries(t).filter(([r])=>o.has(r)));}if(this.blockedUpdateFields)for(let o of this.blockedUpdateFields)delete t[o];for(let o of this._meta.model.primaryKeys)delete t[o];return t}async before(e,t,o){return t}async after(e,t){return e}async handle(){this.validateTenantId();let e=await this.getItems(),t=[],o=[];for(let a of e)try{let u=this.filterUpdateData(a.data),p=await this.before(a.id,u);o.push({id:a.id,data:p});}catch(u){if(this.stopOnError)throw u;t.push({id:a.id,error:u instanceof Error?u.message:String(u)});}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(u){let p=String(a[this.lookupField]);if(this.stopOnError)throw u;t.push({id:p,error:u instanceof Error?u.message:String(u)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),u=i.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,record:p}}).filter(p=>p!==null);u.length>0&&this.runAfterResponse(a.logBatch("batch_update",this._meta.model.tableName,u,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{updated:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return await this.invalidateModelCache(),this.json(d,c)}};var Tt=class extends O{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return R(this.maxBatchSize)}getSchema(){let e=this.isSoftDeleteEnabled();return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("deleted",this.getModelSchema(),e?"Resources soft-deleted successfully":"Resources deleted successfully"),400:P("Validation error")}},this.schema)}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){this.validateTenantId();let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(u){if(this.stopOnError)throw u;t.push({id:a,error:u instanceof Error?u.message:String(u)});}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(u){let p=String(a[this.lookupField]);if(this.stopOnError)throw u;t.push({id:p,error:u instanceof Error?u.message:String(u)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),u=i.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,previousRecord:p}}).filter(p=>p!==null);u.length>0&&this.runAfterResponse(a.logBatch("batch_delete",this._meta.model.tableName,u,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{deleted:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return await this.invalidateModelCache(),this.json(d,c)}};var Nt=class extends O{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return R(this.maxBatchSize)}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("restored",this.getModelSchema(),"Resources restored successfully"),400:P("Soft delete not enabled or validation error")}},this.schema)}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new b$3("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");this.validateTenantId();let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(u){if(this.stopOnError)throw u;t.push({id:a,error:u instanceof Error?u.message:String(u)});}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(u){let p=String(a[this.lookupField]);if(this.stopOnError)throw u;t.push({id:p,error:u instanceof Error?u.message:String(u)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),u=i.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,record:p}}).filter(p=>p!==null);u.length>0&&this.runAfterResponse(a.logBatch("batch_restore",this._meta.model.tableName,u,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{restored:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return await this.invalidateModelCache(),this.json(d,c)}};var Dt=class extends O{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=A(this._meta.model,{includePrimaryKeys:false});for(let s of this._meta.model.primaryKeys)e.includes(s)||t.push(s);let o=_(this.getModelSchema(),t),r={};for(let[s,i]of Object.entries(o.shape))e.includes(s)?r[s]=i:r[s]=i.optional();return z.object(r)}getBodySchema(){return z.array(this.getItemSchema()).max(this.maxBatchSize)}getSchema(){let e=z.object({data:this.getModelSchema(),created:z.boolean(),index:z.number()});return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Batch upsert completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({items:z.array(e),createdCount:z.number(),updatedCount:z.number(),totalCount:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:P("Validation error")}},this.schema)}async getItems(){let{body:e}=await this.getValidatedData();return e}async beforeItem(e,t,o,r){return e}async afterItem(e,t,o,r){return e}async beforeBatch(e,t){return e}async afterBatch(e,t){return e}async upsertOne(e,t,o){let r=await this.findExisting(e,o),s=!r,i=await this.beforeItem(e,t,s,o),l;if(r){if(this.createOnlyFields)for(let c of this.createOnlyFields)delete i[c];let d=ne(i,r,this.getSoftDeleteConfig());l=await this.update(r,d,o);}else {if(this.updateOnlyFields)for(let d of this.updateOnlyFields)delete i[d];l=await this.create(i,o);}return l=await this.afterItem(l,t,s,o),{data:l,created:s,index:t}}async nativeBatchUpsert(e,t){return b$1().warn("Native batch upsert not implemented for this adapter. Falling back to item-by-item pattern."),this.performStandardBatchUpsert(e,t)}async performStandardBatchUpsert(e,t){let o=[],r=[],s=0,i=0;for(let d=0;d<e.length;d++)try{let c=await this.upsertOne(e[d],d,t);o.push(c),c.created?s++:i++;}catch(c){if(this.continueOnError)r.push({index:d,error:c instanceof Error?c.message:String(c)});else throw c}let l={items:o,createdCount:s,updatedCount:i,totalCount:o.length};return r.length>0&&(l.errors=r),l}async batchUpsert(e,t){return this.useNativeUpsert?this.nativeBatchUpsert(e,t):this.performStandardBatchUpsert(e,t)}async handle(){let e=await this.getItems();e=await this.beforeBatch(e);let t=await this.batchUpsert(e).catch(H);if(t=await this.afterBatch(t),this._meta.model.computedFields&&(t.items=await Promise.all(t.items.map(async o=>({...o,data:await ce(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)}}),await this.invalidateModelCache(),this.success(t)}};var Vt=class extends O{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getUpdateSchema(){let e=A(this._meta.model);return _(this.getModelSchema(),e).partial()}getSchema(){let e=this.getUpdateSchema();return N({request:{body:{content:{"application/json":{schema:e.partial()}}},query:z.object({dryRun:z.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z.object({success:z.boolean(),matched:z.number(),updated:z.number(),dryRun:z.boolean()})}}},400:P("Bulk patch rejected (empty body, size limit, or missing confirmation)")}},this.schema)}async handle(){let e=this.getContext(),o=(await this.getValidatedData()).body;if(!o||Object.keys(o).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let r=e.req.query("dryRun"),s=r==="true"||r==="1",i=ae(e.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize});this.applyTenantScope(i);let l=await this.countMatching(i);if(l===0)return this.json({success:true,matched:0,updated:0,dryRun:s});if(l>this.maxBulkSize)return this.error(`Bulk patch affects ${l} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(l>=this.confirmThreshold&&e.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${l} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(s)return this.json({success:true,matched:l,updated:0,dryRun:true});let d=o;this.beforeBulkPatch&&(d=await this.beforeBulkPatch(d,i,l));let c=await this.applyPatch(d,i),a={matched:l,updated:c.updated,dryRun:false,records:this.returnRecords?c.records:void 0};return this.afterBulkPatch&&await this.afterBulkPatch(a),await this.invalidateModelCache(),this.json({success:true,matched:a.matched,updated:a.updated,dryRun:false,...this.returnRecords&&a.records?{records:a.records}:{}})}};var zt=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()}),Zt=class extends O{lookupField="id";defaultLimit=20;maxLimit=100;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({limit:z.coerce.number().min(1).max(this.maxLimit).optional(),offset:z.coerce.number().min(0).optional()})}getSchema(){return N({request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version history retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({versions:z.array(zt),totalVersions:z.number()})})}}},400:P("Versioning not enabled"),404:P("Record not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getPaginationOptions(){let{query:e}=await this.getValidatedData();return {limit:e?.limit?Number(e.limit):this.defaultLimit,offset:e?.offset?Number(e.offset):0}}async recordExists(e){return true}async handle(){if(!this.isVersioningEnabled())throw new b$3("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{limit:t,offset:o}=await this.getPaginationOptions();if(!await this.recordExists(e))throw new d(this._meta.model.tableName,e);let s=this.getVersionManager(),i=await s.getVersions(e,{limit:t,offset:o}),l=await s.getLatestVersion(e);return this.success({versions:i,totalVersions:l})}},Lt=class extends O{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:zt})}}},400:P("Versioning not enabled"),404:P("Version not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new b$3("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),r=await this.getVersionManager().getVersion(e,t);if(!r)throw new d(`version ${t}`,e);return this.success(r)}},Ut=class extends O{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({from:z.coerce.number().min(1),to:z.coerce.number().min(1)})}getSchema(){return N({request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version comparison completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({from:z.number(),to:z.number(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()}))})})}}},400:P("Versioning not enabled or invalid parameters"),404:P("Version not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumbers(){let{query:e}=await this.getValidatedData();return {from:e?.from?Number(e.from):0,to:e?.to?Number(e.to):0}}async handle(){if(!this.isVersioningEnabled())throw new b$3("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})}},qt=class extends O{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Record rolled back successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:P("Versioning not enabled"),404:P("Version not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new b$3("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),o=this.getVersionManager(),r=await o.getVersion(e,t);if(!r)throw new d(`version ${t}`,e);let i=await o.getLatestVersion(e)+1,l=await this.rollback(e,r.data,i),d$1=this._meta.model.serializer?this._meta.model.serializer(l):l;return this.success(d$1)}};var po={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},Bt=class extends O{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {...po,...this.aggregateConfig}}getQuerySchema(){return z.object({count:z.union([z.string(),z.array(z.string())]).optional(),sum:z.union([z.string(),z.array(z.string())]).optional(),avg:z.union([z.string(),z.array(z.string())]).optional(),min:z.union([z.string(),z.array(z.string())]).optional(),max:z.union([z.string(),z.array(z.string())]).optional(),countDistinct:z.union([z.string(),z.array(z.string())]).optional(),groupBy:z.string().optional(),orderBy:z.string().optional(),orderDirection:z.enum(d$1).optional(),limit:z.coerce.number().optional(),offset:z.coerce.number().optional(),withDeleted:z.coerce.boolean().optional()}).passthrough()}getSchema(){let e=z.object({key:z.record(z.string(),z.unknown()),values:z.record(z.string(),z.number().nullable())});return N({request:{query:this.getQuerySchema()},responses:{200:{description:"Aggregation result",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({values:z.record(z.string(),z.number().nullable()).optional(),groups:z.array(e).optional(),totalGroups:z.number().optional()})})}}},400:P("Invalid aggregation request")}},this.schema)}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return it(e||{})}validateAggregations(e){let t=this.getAggregateConfig();for(let o of e.aggregations)if(!(o.operation==="count"&&o.field==="*"))switch(o.operation){case "count":break;case "sum":if(t.sumFields.length>0&&!t.sumFields.includes(o.field))throw new h(`Field '${o.field}' is not allowed for SUM aggregation`);break;case "avg":if(t.avgFields.length>0&&!t.avgFields.includes(o.field))throw new h(`Field '${o.field}' is not allowed for AVG aggregation`);break;case "min":case "max":if(t.minMaxFields.length>0&&!t.minMaxFields.includes(o.field))throw new h(`Field '${o.field}' is not allowed for MIN/MAX aggregation`);break;case "countDistinct":if(t.countDistinctFields.length>0&&!t.countDistinctFields.includes(o.field))throw new h(`Field '${o.field}' is not allowed for COUNT DISTINCT aggregation`);break;default:c(o.operation);}if(e.groupBy){if(e.groupBy.length>this.maxGroupByFields)throw new h(`Maximum ${this.maxGroupByFields} GROUP BY fields allowed`);for(let o of e.groupBy)if(t.groupByFields.length>0&&!t.groupByFields.includes(o))throw new h(`Field '${o}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>t.maxLimit)throw new h(`Limit cannot exceed ${t.maxLimit}`)}getAggregateAlias(e){return e.alias?e.alias:e.field==="*"?e.operation:`${e.operation}${e.field.charAt(0).toUpperCase()}${e.field.slice(1)}`}async after(e){return e}async handle(){let e=await this.getAggregateOptions();e.filters=this.applyTenantScopeToAggregateFilters(e.filters),e.aggregations.length===0&&e.aggregations.push({operation:"count",field:"*"}),this.validateAggregations(e);let t=this.getAggregateConfig();e.groupBy&&e.groupBy.length>0&&e.limit===void 0&&(e.limit=t.defaultLimit);let o=await this.after(await this.aggregate(e));return this.success(o)}},mo={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 ho(n,e){let t=n.get(e);if(t)return t;let o=[];return n.set(e,o),o}function fs(n,e){let{aggregations:t,groupBy:o,having:r,orderBy:s,orderDirection:i,limit:l,offset:d}=e;if(!o||o.length===0){let p={};for(let m of t){let f=$t(m);p[f]=Ht(n,m);}return {values:p}}let c=new Map;for(let p of n){let f=o.map(h=>String(p[h]??"null")).join("|");ho(c,f).push(p);}let a=[];for(let[p,m]of c){let f=p.split("|"),h={};o.forEach((g,S)=>{h[g]=f[S]==="null"?null:f[S];});let R={};for(let g of t){let S=$t(g);R[S]=Ht(m,g);}a.push({key:h,values:R});}r&&(a=a.filter(p=>{for(let[m,f]of Object.entries(r)){let h=p.values[m];if(h!==null)for(let[R,g]of Object.entries(f)){let S=mo[R];if(S&&!S(h,Number(g)))return false}}return true}));let u=a.length;if(s){let p=i==="desc"?-1:1;a.sort((m,f)=>{if(s in m.values){let h=m.values[s]??0,R=f.values[s]??0;return (h-R)*p}if(s in m.key){let h=String(m.key[s]??""),R=String(f.key[s]??"");return h.localeCompare(R)*p}return 0});}if(d!==void 0||l!==void 0){let p=d||0,m=l?p+l:void 0;a=a.slice(p,m);}return {groups:a,totalGroups:u}}function Ae(n,e){return n.map(t=>t[e]).filter(t=>typeof t=="number")}var fo={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=Ae(n,e);return t.length===0?null:t.reduce((r,s)=>r+s,0)/t.length},min:(n,e)=>{let t=Ae(n,e);return t.length===0?null:Math.min(...t)},max:(n,e)=>{let t=Ae(n,e);return t.length===0?null:Math.max(...t)}};function Ht(n,e){if(n.length===0)return e.operation==="count"?0:null;let t=fo[e.operation];return t?t(n,e.field):null}function $t(n){return n.alias?n.alias:n.field==="*"?n.operation:`${n.operation}${n.field.charAt(0).toUpperCase()}${n.field.slice(1)}`}function go(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 Kt=class extends O{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 ht(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,t={};for(let[o,r]of Object.entries(e))go(r)&&(t[o]={weight:1});return t}getQuerySchema(){let t={[this.searchParamName||"q"]:z.string().min(this.minQueryLength).max(this.maxQueryLength).meta({description:"Search query"}),fields:z.string().optional().meta({description:`Comma-separated fields to search. Available: ${Object.keys(this.getSearchableFields()).join(", ")}`}),mode:z.enum(e$1).optional().meta({description:"Search mode: any (OR), all (AND), phrase (exact)"}),highlight:z.enum(["true","false"]).optional().meta({description:"Include highlighted snippets"}),minScore:z.string().optional().meta({description:"Minimum relevance score threshold (0-1)"}),page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(t.sort=z.enum(this.sortFields).optional().meta({description:"Field to sort by"}),t.order=z.enum(d$1).optional().meta({description:"Sort direction (asc or desc)"}));for(let r of this.filterFields)t[r]=z.string().optional();if(this.filterConfig)for(let[r,s]of Object.entries(this.filterConfig)){for(let i of s)t[`${r}[${i}]`]=z.string().optional();t[r]=z.string().optional();}let o=this.getSoftDeleteConfig();if(o.enabled&&o.allowQueryDeleted&&(t[o.queryParam]=z.enum(["true","false"]).optional(),t.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(t.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let r=this.getAvailableSelectFields();t.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${r.join(", ")}`});}return z.object(t)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=z.object({item:this.getModelSchema(),score:z.number().min(0).max(1),highlights:z.record(z.string(),z.array(z.string())).optional(),matchedFields:z.array(z.string())});return N({request:{query:this.getQuerySchema()},responses:{200:{description:"Search results",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(e),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),query:z.string(),searchedFields:z.array(z.string())})})}}},400:P("Invalid search request")}},this.schema)}async getSearchOptions(){let{query:e}=await this.getValidatedData(),t=this.searchParamName||"q",o=e?.[t],r=e?.fields,s=ft(e?.mode),i=e?.highlight==="true",l=e?.minScore?Math.max(0,Math.min(1,Number.parseFloat(e.minScore)||0)):this.defaultMinScore,d=this.getSearchableFields(),c=mt(r,d);return {query:o,fields:c.length>0?c:Object.keys(d),mode:s??this.defaultMode,highlight:i,minScore:l}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchParamName:"q",sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return ae(e||{},o)}async beforeSearch(e){return e}async afterSearch(e){return e}async handle(){let e=await this.getSearchOptions(),t=await this.getFilters();if(this.applyTenantScope(t),!e.query||e.query.length<this.minQueryLength)throw new b$3(`Search query must be at least ${this.minQueryLength} characters`,400,"INVALID_QUERY");e=await this.beforeSearch(e);let o=await this.search(e,t),r=await this.afterSearch(o.items),s=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?{fields:t.options.fields,isActive:true}:void 0,i=await this.finalizeArray(r.map(p=>p.item),s),l=r.map((p,m)=>({...p,item:i[m]})),d=o.postFilteredCount??o.totalCount,c=t.options.page||1,a=t.options.per_page||this.defaultPerPage,u=Math.ceil(d/a);return this.successPaginated(l,{page:c,per_page:a,total_count:d,total_pages:u,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function Os(n,e,t){let o=ct(e.query,e.mode),r={},s=e.fields||Object.keys(t);for(let l of s)t[l]&&(r[l]=t[l]);let i=[];for(let l of n){let{score:d,matchedFields:c}=ut(l,o,r,e.mode);if(d<e.minScore||c.length===0)continue;let a;if(e.highlight){a={};for(let u of c){let p=pt(l[u],o,e.mode);p.length>0&&(a[u]=p);}}i.push({item:l,score:d,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:c});}return i.sort((l,d)=>d.score-l.score),i}function $(n,e={}){let{delimiter:t=",",nullValue:o="",dateFormat:r="iso"}=e;if(n==null)return o;if(n instanceof Date)switch(r){case "timestamp":return String(n.getTime());case "locale":return n.toLocaleString();default:return n.toISOString()}if(typeof n=="object")return $(JSON.stringify(n),e);if(typeof n=="boolean")return n?"true":"false";let s=String(n),i=s.charAt(0);return i==="="||i==="+"||i==="-"||i==="@"||i===" "||i==="\r"?`" ${s.replace(/"/g,'""')}"`:s.includes(t)||s.includes('"')||s.includes(`
|
|
2
|
+
`)||s.includes("\r")?`"${s.replace(/"/g,'""')}"`:s}function _e(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
|
|
3
|
+
`,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:l={},nullValue:d="",dateFormat:c="iso"}=e;if(n.length===0)return "";let a=e.headers;a?a=a.filter(p=>!i.includes(p)):a=Object.keys(n[0]).filter(p=>!i.includes(p));let u=[];if(r){let p=a.map(m=>{let f=l[m]||m;return $(f,{delimiter:t,nullValue:d,dateFormat:c})});u.push(p.join(t));}for(let p of n){let m=a.map(f=>{let h=p[f];return s[f]&&(h=s[f](h)),$(h,{delimiter:t,nullValue:d,dateFormat:c})});u.push(m.join(t));}return u.join(o)}function js(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
|
|
4
|
+
`,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:l={},nullValue:d="",dateFormat:c="iso"}=e,a=new TextEncoder,u=0,p=false,m=e.headers;return !m&&n.length>0?m=Object.keys(n[0]).filter(f=>!i.includes(f)):m?m=m.filter(f=>!i.includes(f)):m=[],new ReadableStream({pull(f){if(r&&!p&&m.length>0){let g=m.map(S=>{let j=l[S]||S;return $(j,{delimiter:t,nullValue:d,dateFormat:c})});f.enqueue(a.encode(g.join(t)+o)),p=true;return}let h=100,R=[];for(;u<n.length&&R.length<h;){let g=n[u],S=m.map(j=>{let D=g[j];return s[j]&&(D=s[j](D)),$(D,{delimiter:t,nullValue:d,dateFormat:c})});R.push(S.join(t)),u++;}R.length>0&&f.enqueue(a.encode(R.join(o)+o)),u>=n.length&&f.close();}})}function Qt(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 bo(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 Te(n,e={}){let{delimiter:t=",",hasHeader:o=true,trimValues:r=true,skipEmptyRows:s=true,parsers:i={},emptyValue:l="empty"}=e,d={data:[],headers:[],errors:[]},c=bo(n);if(c.length===0)return d;let a=0;if(o){let p=c[0];d.headers=Qt(p,t).map(m=>r?m.trim():m),a=1;}else e.headers&&(d.headers=e.headers);let u=e.headers||d.headers;for(let p=a;p<c.length;p++){let m=c[p],f=p+1;if(!(s&&m.trim()===""))try{let h=Qt(m,t),R={};for(let g=0;g<u.length;g++){let S=u[g],j=g<h.length?h[g]:"";if(r&&typeof j=="string"&&(j=j.trim()),j==="")switch(l){case "null":j=null;break;case "undefined":j=void 0;break}if(i[S]&&typeof j=="string")try{j=i[S](j);}catch(D){d.errors.push({row:f,message:`Failed to parse field "${S}": ${D instanceof Error?D.message:String(D)}`,content:m});}R[S]=j;}d.data.push(R);}catch(h){d.errors.push({row:f,message:`Failed to parse row: ${h instanceof Error?h.message:String(h)}`,content:m});}}return d}function Wt(n,e,t={}){let{allowUnknownFields:o=false,optionalFields:r=[]}=t,s=e.shape,i=Object.keys(s),d=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:d.length===0&&(o||c.length===0),missingFields:d,unknownFields:c,validFields:a}}function Ps(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 Fs(n,e={}){return _e(n,e)}function Is(n,e={}){return Te(n,e).data}var Gt=class extends we{maxExportRecords=1e4;enableStreaming=true;streamPageSize=500;excludedExportFields=[];defaultFormat="json";csvOptions={};exportFilename;getExportQuerySchema(){return this.getQuerySchema().extend({format:z.enum(["json","csv"]).optional().meta({description:"Export format"}),stream:z.enum(["true","false"]).optional().meta({description:"Enable streaming for large exports"})})}getSchema(){return N({request:{query:this.getExportQuerySchema()},responses:{200:{description:"Export successful",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({data:z.array(this.getModelSchema()),count:z.number(),format:z.enum(["json","csv"]),exportedAt:z.string()})})},"text/csv":{schema:z.string()}}},400:P("Validation error")}},this.schema)}async getExportOptions(){let{query:e}=await this.getValidatedData(),t=e?.format||this.defaultFormat,o=e?.stream==="true"&&this.enableStreaming;return {format:t,stream:o,fields:e?.fields?String(e.fields).split(","):void 0}}getExportFilename(e){let o=(this.exportFilename||this._meta.model.tableName).replace(/[^a-zA-Z0-9_-]/g,"_"),r=new Date().toISOString().replace(/[:.]/g,"-");return `${o}-export-${r}.${e}`}prepareRecordsForExport(e){return this.excludedExportFields.length===0?e:e.map(t=>{let o={};for(let[r,s]of Object.entries(t))this.excludedExportFields.includes(r)||(o[r]=s);return o})}exportAsJson(e,t){let o={data:e,count:e.length,format:t,exportedAt:new Date().toISOString()};return new Response(JSON.stringify({success:true,result:o},null,2),{status:200,headers:{"Content-Type":"application/json","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsv(e,t){let o=_e(e,{...this.csvOptions,excludeFields:this.excludedExportFields});return new Response(o,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsvStream(e,t){let o=this.getContext(),r=this.getExportFilename(t),s=this.csvOptions,i=this.excludedExportFields;return stream(o,async l=>{if(o.header("Content-Type","text/csv; charset=utf-8"),o.header("Content-Disposition",`attachment; filename="${r}"`),e.length===0)return;let d=Object.keys(e[0]).filter(u=>!i.includes(u)),c=d.map(u=>$(u,s)).join(",")+`
|
|
8
|
+
`;await l.write(c);let a=100;for(let u=0;u<e.length;u+=a)for(let p of e.slice(u,u+a)){let m=d.map(f=>$(p[f],s)).join(",")+`
|
|
9
|
+
`;await l.write(m);}})}exportAsCsvStreamPaginated(e,t){let o=this.getExportFilename(t),r=this.streamPageSize,s=Math.min(this.maxExportRecords,1e5),i=this.excludedExportFields,l=this.csvOptions,d=null,c=new ReadableStream({start:async a=>{let u=new TextEncoder,p=1,m=0;try{for(;m<s;){let f={...e,options:{...e.options,page:p,per_page:r}},R=(await this.list(f)).result;if(R.length===0)break;R.length>s-m&&(R=R.slice(0,s-m)),R=await this.after(R),R=await this.beforeExport(R);let g=this.prepareRecordsForExport(R);if(!d&&g.length>0){d=Object.keys(g[0]).filter(j=>!i.includes(j));let S=d.map(j=>$(j,l)).join(",")+`
|
|
10
|
+
`;a.enqueue(u.encode(S));}if(d)for(let S of g){let j=d.map(D=>$(S[D],l)).join(",")+`
|
|
11
|
+
`;a.enqueue(u.encode(j));}if(m+=R.length,p++,R.length<r)break}}catch(f){a.error(f);return}a.close();}});return new Response(c,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${o}"`}})}async beforeExport(e){return e}async fetchAllForExport(e){let t=Math.min(this.maxExportRecords,1e5),o={...e,options:{...e.options,page:1,per_page:t}};return (await this.list(o)).result}async handle(){let e=await this.getExportOptions(),t=await this.getFilters();if(this.applyTenantScope(t),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 Yt=class extends O{maxBatchSize=1e3;importBatchSize=100;stopOnError=false;skipInvalidRows=true;defaultMode="create";upsertKeys;immutableFields=[];csvOptions={};maxBodySize=10*1024*1024;optionalImportFields=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getImportSchema(){let e=this._meta.fields?this._meta.fields:_(this.getModelSchema(),A(this._meta.model));return z.object({items:z.array(e.partial()).min(1).max(this.maxBatchSize)})}getSchema(){return N({request:{query:z.object({mode:z.enum(["create","upsert"]).optional().meta({description:"Import mode"}),skipInvalid:z.enum(["true","false"]).optional().meta({description:"Skip invalid rows"}),stopOnError:z.enum(["true","false"]).optional().meta({description:"Stop on first error"})})},responses:{200:{description:"Import completed successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},207:{description:"Import completed with partial failures",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},400:P("Validation error")}},this.schema)}async getImportOptions(){let{query:e}=await this.getValidatedData(),t=e?.skipInvalid==="true"?true:e?.skipInvalid==="false"?false:this.skipInvalidRows,o=e?.stopOnError==="true"?true:e?.stopOnError==="false"?false:this.stopOnError;return {mode:e?.mode||this.defaultMode,skipInvalidRows:t,stopOnError:o}}async parseImportData(){let e=this.context;if(!e)throw new c$1("No request available");let t=e.req.header("content-type")||"";if(t.includes("application/json")){let o=await e.req.json();if(!o)throw new c$1("Request body is empty");if(!o.items||!Array.isArray(o.items))throw new c$1('Request body must contain an "items" array');if(o.items.length>this.maxBatchSize)throw new c$1(`Maximum ${this.maxBatchSize} items allowed per import`);return o.items}if(t.includes("text/csv")){let o=await e.req.text();if(o.length>this.maxBodySize)throw new c$1(`Request body exceeds maximum size of ${this.maxBodySize} bytes`);return this.parseCsvData(o)}if(t.includes("multipart/form-data")){let r=(await e.req.formData()).get("file");if(!r)throw new c$1("No file provided in form data");let s=await r.text();if(s.length>this.maxBodySize)throw new c$1(`Uploaded file exceeds maximum size of ${this.maxBodySize} bytes`);let i=r.name.toLowerCase();if(i.endsWith(".json")){let d;try{d=JSON.parse(s);}catch{throw new c$1("Invalid JSON content in uploaded file")}let c=Array.isArray(d)?d:d.items;if(!c||!Array.isArray(c))throw new c$1('JSON file must contain an array or an object with "items" array');if(c.length>this.maxBatchSize)throw new c$1(`Maximum ${this.maxBatchSize} items allowed per import`);return c}if(i.endsWith(".csv"))return this.parseCsvData(s);let l=s.trim();if(l.startsWith("[")||l.startsWith("{")){let d;try{d=JSON.parse(s);}catch{throw new c$1("Invalid JSON content in uploaded file")}let c=Array.isArray(d)?d:d.items;if(!c||!Array.isArray(c))throw new c$1('JSON file must contain an array or an object with "items" array');return c}return this.parseCsvData(s)}throw new c$1("Unsupported content type. Use application/json, text/csv, or multipart/form-data")}parseCsvData(e){let t=Te(e,this.csvOptions);if(t.errors.length>0)throw new c$1(`CSV parsing errors: ${t.errors.map(s=>`Row ${s.row}: ${s.message}`).join("; ")}`);if(t.data.length===0)throw new c$1("CSV file is empty");if(t.data.length>this.maxBatchSize)throw new c$1(`Maximum ${this.maxBatchSize} items allowed per import`);let o=this._meta.fields||this.getModelSchema(),r=Wt(t.headers,o,{allowUnknownFields:true,optionalFields:this.optionalImportFields});if(!r.valid&&r.missingFields.length>0)throw new c$1(`Missing required fields in CSV: ${r.missingFields.join(", ")}`);return t.data}validateRow(e,t){let o=this._meta.fields||this.getModelSchema(),r={};for(let i of A(this._meta.model))r[i]=true;for(let i of this.optionalImportFields)r[i]=true;let s=o.partial(r);try{return s.parse(e),{valid:!0}}catch(i){return i instanceof z.ZodError?{valid:false,errors:i.issues.map(d=>({path:d.path.join("."),message:d.message}))}:{valid:false,errors:[{path:"",message:i instanceof Error?i.message:String(i)}]}}}removeImmutableFields(e){if(this.immutableFields.length===0)return e;let t={};for(let[o,r]of Object.entries(e))this.immutableFields.includes(o)||(t[o]=r);return t}async before(e,t,o,r){return e}async after(e,t,o,r){return e}async processRow(e,t,o,r){let s=this.validateRow(e,t);if(!s.valid)return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Validation failed",validationErrors:s.errors}:{rowNumber:t,status:"failed",error:"Validation failed",validationErrors:s.errors};try{let i=await this.before(e,t,o.mode,r);if(o.mode==="upsert"){let d=await this.findExisting(i,r);if(d){let c=ne(this.removeImmutableFields(i),d,this.getSoftDeleteConfig()),a=await this.update(d,c,r);return {rowNumber:t,status:"updated",data:a}}}else if(await this.findExisting(i,r))return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Record already exists"}:{rowNumber:t,status:"failed",error:"Record already exists (duplicate key)"};let l=await this.create(i,r);return {rowNumber:t,status:"created",data:l}}catch(i){let l=Fe(i);return l?{rowNumber:t,status:"failed",code:"CONFLICT",error:l.message}:{rowNumber:t,status:"failed",error:i instanceof Error?i.message:String(i)}}}async handle(){let e=await this.getImportOptions(),t=await this.parseImportData();if(!Number.isInteger(this.importBatchSize)||this.importBatchSize<1)throw new j("importBatchSize must be a positive integer");let o={total:t.length,created:0,updated:0,skipped:0,failed:0},r=[],s=false,i=e.stopOnError?1:this.importBatchSize;for(let c=0;c<t.length&&!s;c+=i){let a=t.slice(c,c+i),u=await Promise.all(a.map(async(p,m)=>{let f=c+m+1,h=await this.processRow(p,f,e);return h=await this.after(h,f,e.mode),h}));for(let p of u){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(u=>u.status==="created"||u.status==="updated");if(a.length>0){let u=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);u.length>0&&this.runAfterResponse(c.logBatch(e.mode==="upsert"?"batch_upsert":"batch_create",this._meta.model.tableName,u,this.getAuditUserId()));}}let l={summary:o,results:r},d=o.failed>0&&o.failed<o.total?207:200;return await this.invalidateModelCache(),this.json({success:true,result:l},d)}};var xe=Symbol.for("hono-crud.resource-registry");function $s(n,e,t){let o=n;o[xe]||(o[xe]=[]),o[xe].push({path:e,endpoints:t});}function Ks(n){return n[xe]??[]}export{Pt as $,mt as A,Fs as Aa,ht as B,Is as Ba,ft as C,Gt as Ca,se as D,Yt as Da,Ce as E,$s as Ea,gt as F,Ks as Fa,ao as G,Y as H,lo as I,Do as J,Vo as K,Zo as L,Lo as M,Uo as N,qo as O,Ee as P,fe as Q,ge as R,Rt as S,Ho as T,ae as U,_ as V,$o as W,ve as X,Ot as Y,jt as Z,ye as _,wo as a,Ft as aa,le as b,It as ba,A as c,we as ca,tt as d,Ct as da,ot as e,Et as ea,rt as f,vt as fa,nt as g,At as ga,oo as h,_t as ha,Fe as i,Tt as ia,H as j,Nt as ja,ro as k,Dt as ka,xo as l,Vt as la,Oo as m,Zt as ma,ce as n,Lt as na,st as o,Ut as oa,re as p,qt as pa,he as q,Bt as qa,Io as r,fs as ra,it as s,Kt as sa,at as t,Os as ta,ne as u,$ as ua,lt as v,_e as va,ct as w,js as wa,so as x,Te as xa,ut as y,Wt as ya,pt as z,Ps as za};
|
package/dist/config/index.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import 'hono';
|
|
2
2
|
import 'zod';
|
|
3
|
-
export { a4 as AdapterBundle,
|
|
3
|
+
export { a4 as AdapterBundle, as as AggregateEndpointConfig, at as BatchCreateEndpointConfig, au as BatchDeleteEndpointConfig, av as BatchRestoreEndpointConfig, aw as BatchUpdateEndpointConfig, ax as BatchUpsertEndpointConfig, ay as BulkPatchEndpointConfig, az as CloneEndpointConfig, aA as CreateEndpointConfig, aB as DeleteEndpointConfig, aC as EndpointCacheConfig, aD as EndpointsConfig, aE as ExportEndpointConfig, G as GeneratedEndpoints, aF as ImportEndpointConfig, aG as ListEndpointConfig, aH as MutationCacheConfig, aI as ReadEndpointConfig, aJ as RestoreEndpointConfig, aK as SearchEndpointConfig, aL as UpdateEndpointConfig, aM as UpsertEndpointConfig, aN as VersionCompareEndpointConfig, aO as VersionHistoryEndpointConfig, aP as VersionReadEndpointConfig, aQ as VersionRollbackEndpointConfig, Q as defineEndpoints } from '../index-C7O-Gh59.js';
|
|
4
4
|
import '../route-CVsl4dg3.js';
|
|
5
5
|
import '../types-D72szrPV.js';
|
|
6
6
|
import '../types-BTRpRT28.js';
|
|
7
|
+
import '../registry-DYXgzGt0.js';
|
|
8
|
+
import '../contracts-C3YJpWrM.js';
|
|
7
9
|
import '@hono/zod-openapi';
|
|
8
10
|
import '../audit/index.js';
|
|
9
|
-
import '../registry-DYXgzGt0.js';
|
|
10
11
|
import '../path-match-DGLu6wld.js';
|
|
11
12
|
import '../types-B5wq2iKZ.js';
|
|
12
13
|
import '../types-lAPVBoYa.js';
|
package/dist/config/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as defineEndpoints}from'../chunk-
|
|
1
|
+
export{a as defineEndpoints}from'../chunk-AQXRF6RJ.js';import'../chunk-5DTBFOC3.js';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a1 as PaginatedResult, $ as NormalizedSoftDeleteConfig, ai as SoftDeleteConfig, M as MetaInput, y as HookMode, O as OpenAPIRouteSchema, w as HookContext, a5 as RelationConfig, z as IncludeOptions, V as NestedUpdateInput, X as NestedWriteResult, o as CascadeAction, t as FilterConfig, ak as SortSpec, L as ListFilters, h as AggregateConfig, a as AggregateOptions, A as AggregateField, j as AggregateResult, b as SearchFieldConfig, c as SearchMode, af as SearchOptions, ah as SearchResultItem, ag as SearchResult } from './types-D72szrPV.js';
|
|
2
2
|
import { Env } from 'hono';
|
|
3
3
|
import { ZodObject, ZodRawShape, z } from 'zod';
|
|
4
|
-
import {
|
|
4
|
+
import { ar as CrudEndpoint, i as CsvGenerateOptions } from './index-C7O-Gh59.js';
|
|
5
5
|
import { M as ModelObject, F as FieldSelection } from './types-BTRpRT28.js';
|
|
6
6
|
|
|
7
7
|
/**
|
package/dist/functional/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'../chunk-
|
|
1
|
+
import {a}from'../chunk-5DTBFOC3.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,bodySchema:e.bodySchema})}function n(e,d){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,searchParamName:e.searchParamName,sortFields:e.sortFields,defaultSort:e.defaultSort,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 r(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,bodySchema:e.bodySchema})}function s(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 createCreate,s as createDelete,n as createList,o as createRead,r as createUpdate};
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { Env, Context, MiddlewareHandler, Hono } from 'hono';
|
|
2
2
|
import { ZodError, z, ZodObject, ZodRawShape } from 'zod';
|
|
3
|
+
import { S as StorageRegistry } from './registry-DYXgzGt0.js';
|
|
4
|
+
import { c as CacheStorage } from './contracts-C3YJpWrM.js';
|
|
3
5
|
import { OpenAPIHono } from '@hono/zod-openapi';
|
|
4
6
|
import { O as OpenAPIRoute } from './route-CVsl4dg3.js';
|
|
5
7
|
import { O as OpenAPIRouteSchema, R as ResponseEnvelope, E as ErrorResponse, K as Model, M as MetaInput, Z as NormalizedAuditConfig, a0 as NormalizedVersioningConfig, $ as NormalizedSoftDeleteConfig, _ as NormalizedMultiTenantConfig, aA as RelationRequestScope, L as ListFilters, N as ModelPolicies, a3 as PolicyContext, s as FilterCondition, w as HookContext, ao as ValidatedData, y as HookMode, t as FilterConfig, aj as SortDirection, g as AfterUpdateHook, f as AfterDeleteHook, ah as SearchResultItem, j as AggregateResult } from './types-D72szrPV.js';
|
|
@@ -158,6 +160,135 @@ declare class HonoOpenAPIHandler<E extends Env = Env> {
|
|
|
158
160
|
*/
|
|
159
161
|
declare function fromHono<E extends Env = Env>(router?: Hono<E> | OpenAPIHono<E>, options?: RouterOptions): HonoOpenAPIApp<E>;
|
|
160
162
|
|
|
163
|
+
/** Per-endpoint cache configuration (list/read). */
|
|
164
|
+
interface CacheConfig {
|
|
165
|
+
/** Whether caching is enabled. @default true */
|
|
166
|
+
enabled?: boolean;
|
|
167
|
+
/** Time-to-live in seconds. @default 300 (5 min) */
|
|
168
|
+
ttlSeconds?: number;
|
|
169
|
+
/** Key prefix for cache entries. */
|
|
170
|
+
prefix?: string;
|
|
171
|
+
/** Query parameters to include in the cache key. */
|
|
172
|
+
keyFields?: string[];
|
|
173
|
+
/** Include the request `userId` var in the cache key (per-user caching). */
|
|
174
|
+
perUser?: boolean;
|
|
175
|
+
/** Tags for group invalidation. */
|
|
176
|
+
tags?: string[];
|
|
177
|
+
}
|
|
178
|
+
/** Invalidation strategy for mutation endpoints. */
|
|
179
|
+
type InvalidationStrategy = 'single' | 'list' | 'all' | 'pattern' | 'tags';
|
|
180
|
+
/** Cache invalidation configuration for mutation endpoints. */
|
|
181
|
+
interface CacheInvalidationConfig {
|
|
182
|
+
/** Invalidation strategy. @default 'all' */
|
|
183
|
+
strategy?: InvalidationStrategy;
|
|
184
|
+
/** Custom pattern for the 'pattern' strategy. */
|
|
185
|
+
pattern?: string;
|
|
186
|
+
/** Tags to invalidate for the 'tags' strategy. */
|
|
187
|
+
tags?: string[];
|
|
188
|
+
/** Related model table names to also invalidate. */
|
|
189
|
+
relatedModels?: string[];
|
|
190
|
+
}
|
|
191
|
+
/** Options for {@link generateCacheKey}. */
|
|
192
|
+
interface CacheKeyOptions {
|
|
193
|
+
tableName: string;
|
|
194
|
+
method: 'GET' | 'LIST';
|
|
195
|
+
params?: Record<string, string>;
|
|
196
|
+
query?: Record<string, unknown>;
|
|
197
|
+
keyFields?: string[];
|
|
198
|
+
userId?: string;
|
|
199
|
+
prefix?: string;
|
|
200
|
+
}
|
|
201
|
+
/** Options for {@link createInvalidationPattern}. */
|
|
202
|
+
interface InvalidationPatternOptions {
|
|
203
|
+
method?: 'GET' | 'LIST';
|
|
204
|
+
id?: string | number;
|
|
205
|
+
userId?: string;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Build a cache key.
|
|
209
|
+
* Format: `{prefix?}:{tableName}:{method}:{pathParams?}:{queryParams?}:{user=id?}`
|
|
210
|
+
*/
|
|
211
|
+
declare function generateCacheKey(options: CacheKeyOptions): string;
|
|
212
|
+
/**
|
|
213
|
+
* Build a glob pattern for invalidating cache entries for a table.
|
|
214
|
+
*
|
|
215
|
+
* @example createInvalidationPattern('users') // 'users:*'
|
|
216
|
+
* @example createInvalidationPattern('users', { method: 'LIST' }) // 'users:LIST*'
|
|
217
|
+
* @example createInvalidationPattern('users', { id: '123' }) // 'users:*:id=123*'
|
|
218
|
+
*/
|
|
219
|
+
declare function createInvalidationPattern(tableName: string, options?: InvalidationPatternOptions, prefix?: string): string;
|
|
220
|
+
/** Patterns for invalidating related models. */
|
|
221
|
+
declare function createRelatedPatterns(_tableName: string, relatedModels: string[], prefix?: string): string[];
|
|
222
|
+
/** Glob match (`*` wildcard) used by in-memory `deletePattern` backends. */
|
|
223
|
+
declare function matchesPattern(key: string, pattern: string): boolean;
|
|
224
|
+
/** Backing registry (exported for advanced use / tests). */
|
|
225
|
+
declare const cacheStorageRegistry: StorageRegistry<CacheStorage>;
|
|
226
|
+
/** Set the global cache storage instance. */
|
|
227
|
+
declare const setCacheStorage: (storage: CacheStorage) => void;
|
|
228
|
+
/** Get the explicitly-configured global cache storage, or `null`. Never throws. */
|
|
229
|
+
declare const getCacheStorage: () => CacheStorage | null;
|
|
230
|
+
/** Get the global cache storage, throwing if unset. */
|
|
231
|
+
declare const getCacheStorageRequired: () => CacheStorage;
|
|
232
|
+
/** Resolve cache storage: explicit > context > global. `null` when none. */
|
|
233
|
+
declare const resolveCacheStorage: <E extends Env>(ctx?: Context<E, any, {}> | undefined, explicit?: CacheStorage | undefined) => CacheStorage | null;
|
|
234
|
+
/**
|
|
235
|
+
* Resolve cache storage for the request path, warning once per isolate when
|
|
236
|
+
* nothing resolves. Caching then degrades to a no-op — correct for an
|
|
237
|
+
* optimization-only feature, but loud enough that a mis-wired app (forgotten
|
|
238
|
+
* `createStorageMiddleware` / `setCacheStorage`) is observable.
|
|
239
|
+
*/
|
|
240
|
+
declare function resolveCacheStorageOrWarn(ctx?: Context<Env>): CacheStorage | null;
|
|
241
|
+
/** What an endpoint exposes for the cache helpers to read its config + request. */
|
|
242
|
+
interface CacheableEndpoint {
|
|
243
|
+
getContext(): Context<Env>;
|
|
244
|
+
getValidatedData(): Promise<{
|
|
245
|
+
params?: Record<string, string>;
|
|
246
|
+
query?: Record<string, unknown>;
|
|
247
|
+
}>;
|
|
248
|
+
_meta?: {
|
|
249
|
+
model?: {
|
|
250
|
+
tableName?: string;
|
|
251
|
+
};
|
|
252
|
+
};
|
|
253
|
+
cacheEnabled: boolean;
|
|
254
|
+
cacheTtlSeconds?: number;
|
|
255
|
+
cacheKeyFields?: string[];
|
|
256
|
+
cachePerUser?: boolean;
|
|
257
|
+
cachePrefix?: string;
|
|
258
|
+
cacheTags?: string[];
|
|
259
|
+
}
|
|
260
|
+
/** What to invalidate after a mutation. */
|
|
261
|
+
type CacheInvalidateInput = boolean | Array<'list' | 'read' | 'all'> | CacheInvalidationConfig;
|
|
262
|
+
/** Mutation endpoint surface for invalidation. */
|
|
263
|
+
interface InvalidatingEndpoint {
|
|
264
|
+
getContext(): Context<Env>;
|
|
265
|
+
_meta?: {
|
|
266
|
+
model?: {
|
|
267
|
+
tableName?: string;
|
|
268
|
+
};
|
|
269
|
+
};
|
|
270
|
+
cacheInvalidate?: CacheInvalidateInput;
|
|
271
|
+
cachePrefix?: string;
|
|
272
|
+
}
|
|
273
|
+
/** Read the cached payload for this request, or `null` on miss / no storage. */
|
|
274
|
+
declare function readEndpointCache<T>(ep: CacheableEndpoint, tenantId?: string): Promise<T | null>;
|
|
275
|
+
/** Store the payload for this request under its cache key (best-effort). */
|
|
276
|
+
declare function writeEndpointCache<T>(ep: CacheableEndpoint, data: T, tenantId?: string): Promise<void>;
|
|
277
|
+
/**
|
|
278
|
+
* Invalidate caches after a successful mutation, per the endpoint's
|
|
279
|
+
* `cacheInvalidate` config. Best-effort: no storage → no-op.
|
|
280
|
+
*
|
|
281
|
+
* - `true` / `['all']` → delete every cache entry for the model's table
|
|
282
|
+
* - `['list']` / `['read']` → delete only LIST / GET caches for the table
|
|
283
|
+
* - `CacheInvalidationConfig` → tags (`deleteByTag`), custom `pattern`,
|
|
284
|
+
* `relatedModels`, or `strategy` ('all' | 'list' | 'single')
|
|
285
|
+
*
|
|
286
|
+
* `single` (record-scoped) collapses to the table-wide pattern here because the
|
|
287
|
+
* mutation's record id is not threaded into this helper; table-wide is the
|
|
288
|
+
* safe superset (never serves stale data).
|
|
289
|
+
*/
|
|
290
|
+
declare function invalidateEndpointCache(ep: InvalidatingEndpoint, tenantId?: string): Promise<void>;
|
|
291
|
+
|
|
161
292
|
/**
|
|
162
293
|
* Canonical CRUD route table — the single source of truth for every endpoint
|
|
163
294
|
* slot `registerCrud(...)` can register: `[name, HTTP verb, sub-path]`.
|
|
@@ -758,6 +889,43 @@ declare abstract class CrudEndpoint<E extends Env = Env, M extends MetaInput = M
|
|
|
758
889
|
* from pre-0.7.0).
|
|
759
890
|
*/
|
|
760
891
|
protected getPolicies(): ModelPolicies<RowOf<M>> | undefined;
|
|
892
|
+
/** Enable response caching (list/read). */
|
|
893
|
+
protected cacheEnabled: boolean;
|
|
894
|
+
/** TTL in seconds. @default 300 */
|
|
895
|
+
protected cacheTtlSeconds?: number;
|
|
896
|
+
/** Query params included in the cache key (default: all present query params). */
|
|
897
|
+
protected cacheKeyFields?: string[];
|
|
898
|
+
/** Add the request `userId` var to the cache key (per-user caching). */
|
|
899
|
+
protected cachePerUser?: boolean;
|
|
900
|
+
/** Tags attached to cache entries (for tag-based invalidation). */
|
|
901
|
+
protected cacheTags?: string[];
|
|
902
|
+
/** Invalidation config for mutation verbs (set by the config bridge). */
|
|
903
|
+
protected cacheInvalidate?: CacheInvalidateInput;
|
|
904
|
+
/** Cache key prefix (must match the read/list cache prefix). */
|
|
905
|
+
protected cachePrefix?: string;
|
|
906
|
+
/**
|
|
907
|
+
* Whether config response-caching is active for THIS request. False when
|
|
908
|
+
* disabled, or when user-scoped read policies are present and `cachePerUser`
|
|
909
|
+
* is not set — caching a tenant-only key would serve one user's policy-shaped
|
|
910
|
+
* view to another, so it is disabled (with a once-per-isolate warning) rather
|
|
911
|
+
* than risk a leak. Used by list/read.
|
|
912
|
+
*/
|
|
913
|
+
protected isResponseCacheActive(): boolean;
|
|
914
|
+
/**
|
|
915
|
+
* Whether per-user read policies are configured. When true a response can
|
|
916
|
+
* vary by caller identity (row filtering, field masking, existence-hiding),
|
|
917
|
+
* so a tenant-only cache key would leak one user's view to another. List/Read
|
|
918
|
+
* therefore SKIP config-caching when this is true unless `cachePerUser` folds
|
|
919
|
+
* the userId into the key.
|
|
920
|
+
*/
|
|
921
|
+
protected hasUserScopedReadPolicy(): boolean;
|
|
922
|
+
/**
|
|
923
|
+
* Invalidate this tenant's cached list/read entries after a successful
|
|
924
|
+
* mutation. Best-effort + a no-op when no cache store is configured, so every
|
|
925
|
+
* mutation verb can call it unconditionally. Defaults to busting all of the
|
|
926
|
+
* model's cache for the tenant; `cacheInvalidate` narrows it.
|
|
927
|
+
*/
|
|
928
|
+
protected invalidateModelCache(): Promise<void>;
|
|
761
929
|
/**
|
|
762
930
|
* Build the `PolicyContext` passed to `ModelPolicies` callbacks. Sourced
|
|
763
931
|
* from `c.var.user`, `c.var.tenantId`, etc.
|
|
@@ -1527,6 +1695,8 @@ interface CreateEndpointConfig<M extends MetaInput, E extends Env = Env> {
|
|
|
1527
1695
|
middlewares?: MiddlewareHandler<E>[];
|
|
1528
1696
|
hooks?: CreateHooks<M>;
|
|
1529
1697
|
nestedCreate?: string[];
|
|
1698
|
+
/** Invalidate cached list/read entries after a successful create. */
|
|
1699
|
+
cache?: MutationCacheConfig;
|
|
1530
1700
|
/**
|
|
1531
1701
|
* Override the request body validation schema for this endpoint.
|
|
1532
1702
|
*
|
|
@@ -1608,6 +1778,49 @@ interface ListHooks<M extends MetaInput> {
|
|
|
1608
1778
|
after?: (items: ModelObject<M['model']>[]) => Promise<ModelObject<M['model']>[]> | ModelObject<M['model']>[];
|
|
1609
1779
|
transform?: (item: ModelObject<M['model']>) => unknown;
|
|
1610
1780
|
}
|
|
1781
|
+
/**
|
|
1782
|
+
* Response cache configuration for list/read endpoints. Caching is opt-in;
|
|
1783
|
+
* `cacheStorage` is wired separately via `createCacheStorageMiddleware()`
|
|
1784
|
+
* (recommended on Workers) or `setCacheStorage()`.
|
|
1785
|
+
*
|
|
1786
|
+
* Cache keys are **tenant-scoped automatically** on multiTenant resources, so a
|
|
1787
|
+
* cached page is never served across tenants. They are NOT per-user by default:
|
|
1788
|
+
* if the resource uses user-scoped read **policies** (`read` / `fields` /
|
|
1789
|
+
* `readPushdown`), caching is automatically disabled (with a once-per-isolate
|
|
1790
|
+
* warning) unless you set `perUser: true` to fold the userId into the key —
|
|
1791
|
+
* otherwise one user's policy-shaped view could be served to another.
|
|
1792
|
+
*/
|
|
1793
|
+
interface EndpointCacheConfig {
|
|
1794
|
+
/**
|
|
1795
|
+
* Enable response caching. When the `cache` block is present, this defaults
|
|
1796
|
+
* to `true`; set `false` to keep the block (e.g. `keyFields`) but disable.
|
|
1797
|
+
*/
|
|
1798
|
+
enabled?: boolean;
|
|
1799
|
+
/** TTL in seconds. @default 300 */
|
|
1800
|
+
ttl?: number;
|
|
1801
|
+
/** Query params included in the cache key (default: all present query params). */
|
|
1802
|
+
keyFields?: string[];
|
|
1803
|
+
/** Add the request `userId` var to the cache key (per-user caching). */
|
|
1804
|
+
perUser?: boolean;
|
|
1805
|
+
/** Cache key prefix. */
|
|
1806
|
+
prefix?: string;
|
|
1807
|
+
/** Tags attached to cache entries (for tag-based invalidation). */
|
|
1808
|
+
tags?: string[];
|
|
1809
|
+
}
|
|
1810
|
+
/**
|
|
1811
|
+
* Cache invalidation configuration for mutation endpoints (create/update/delete).
|
|
1812
|
+
*/
|
|
1813
|
+
interface MutationCacheConfig {
|
|
1814
|
+
/**
|
|
1815
|
+
* What to invalidate after a successful mutation:
|
|
1816
|
+
* - `true` → all cached entries for the model (current tenant)
|
|
1817
|
+
* - `Array<'list' | 'read' | 'all'>` → only those operation caches
|
|
1818
|
+
* - a `CacheInvalidationConfig` for tags / custom pattern / related models
|
|
1819
|
+
*/
|
|
1820
|
+
invalidate?: CacheInvalidateInput;
|
|
1821
|
+
/** Prefix of the cache keys to invalidate (must match the read/list cache prefix). */
|
|
1822
|
+
prefix?: string;
|
|
1823
|
+
}
|
|
1611
1824
|
/**
|
|
1612
1825
|
* List endpoint configuration.
|
|
1613
1826
|
*/
|
|
@@ -1621,6 +1834,7 @@ interface ListEndpointConfig<M extends MetaInput, E extends Env = Env> {
|
|
|
1621
1834
|
pagination?: PaginationConfig;
|
|
1622
1835
|
includes?: string[];
|
|
1623
1836
|
fieldSelection?: FieldSelectionConfig;
|
|
1837
|
+
cache?: EndpointCacheConfig;
|
|
1624
1838
|
hooks?: ListHooks<M>;
|
|
1625
1839
|
}
|
|
1626
1840
|
/**
|
|
@@ -1641,6 +1855,7 @@ interface ReadEndpointConfig<M extends MetaInput, E extends Env = Env> {
|
|
|
1641
1855
|
additionalFilters?: string[];
|
|
1642
1856
|
includes?: string[];
|
|
1643
1857
|
fieldSelection?: FieldSelectionConfig;
|
|
1858
|
+
cache?: EndpointCacheConfig;
|
|
1644
1859
|
hooks?: ReadHooks<M>;
|
|
1645
1860
|
}
|
|
1646
1861
|
/**
|
|
@@ -1675,6 +1890,8 @@ interface UpdateEndpointConfig<M extends MetaInput, E extends Env = Env> {
|
|
|
1675
1890
|
additionalFilters?: string[];
|
|
1676
1891
|
fields?: UpdateFieldConfig;
|
|
1677
1892
|
nestedWrites?: string[];
|
|
1893
|
+
/** Invalidate cached list/read entries after a successful update. */
|
|
1894
|
+
cache?: MutationCacheConfig;
|
|
1678
1895
|
hooks?: UpdateHooks<M>;
|
|
1679
1896
|
/**
|
|
1680
1897
|
* Override the request body validation schema for this endpoint.
|
|
@@ -1711,6 +1928,8 @@ interface DeleteEndpointConfig<M extends MetaInput, E extends Env = Env> {
|
|
|
1711
1928
|
lookupField?: string;
|
|
1712
1929
|
additionalFilters?: string[];
|
|
1713
1930
|
includeCascadeResults?: boolean;
|
|
1931
|
+
/** Invalidate cached list/read entries after a successful delete. */
|
|
1932
|
+
cache?: MutationCacheConfig;
|
|
1714
1933
|
hooks?: DeleteHooks<M>;
|
|
1715
1934
|
}
|
|
1716
1935
|
/**
|
|
@@ -2128,4 +2347,4 @@ type GeneratedEndpoints<E extends Env = Env> = Pick<CrudEndpoints<E>, Exclude<ke
|
|
|
2128
2347
|
*/
|
|
2129
2348
|
declare function defineEndpoints<M extends MetaInput, E extends Env = Env>(config: EndpointsConfig<M, E>, adapters: AdapterBundle<E>): GeneratedEndpoints<E>;
|
|
2130
2349
|
|
|
2131
|
-
export { parseCsv as $, ApiException as A, BatchUpsertEndpoint as B, CacheException as C, applyManagedUpdateFields as D, type EndpointClass as E, ForbiddenException as F, type GeneratedEndpoints as G, type HonoOpenAPIApp as H, ImportEndpoint as I, assertIdStrategySupported as J, causeChain as K, contentJson as L, createCsvStream as M, type NormalizedTimestampsConfig as N, type OpenAPIConfig$1 as O, csvToJson as P, defineEndpoints as Q, type RegisterCrudOptions as R, escapeCsvValue as S, fromHono as T, UnauthorizedException as U, generateCsv as V, getManagedInputExclusions as W, getTimestampsConfig as X, inferCsvContentType as Y, jsonToCsv as Z, mapUniqueViolation as _, type AdapterKind as a, registerCrud as a0, rethrowAsConstraintError as a1, stripManagedInsertFields as a2, validateCsvHeaders as a3, type AdapterBundle as a4, CRUD_ROUTES as a5,
|
|
2350
|
+
export { parseCsv as $, ApiException as A, BatchUpsertEndpoint as B, CacheException as C, applyManagedUpdateFields as D, type EndpointClass as E, ForbiddenException as F, type GeneratedEndpoints as G, type HonoOpenAPIApp as H, ImportEndpoint as I, assertIdStrategySupported as J, causeChain as K, contentJson as L, createCsvStream as M, type NormalizedTimestampsConfig as N, type OpenAPIConfig$1 as O, csvToJson as P, defineEndpoints as Q, type RegisterCrudOptions as R, escapeCsvValue as S, fromHono as T, UnauthorizedException as U, generateCsv as V, getManagedInputExclusions as W, getTimestampsConfig as X, inferCsvContentType as Y, jsonToCsv as Z, mapUniqueViolation as _, type AdapterKind as a, registerCrud as a0, rethrowAsConstraintError as a1, stripManagedInsertFields as a2, validateCsvHeaders as a3, type AdapterBundle as a4, CRUD_ROUTES as a5, type CacheConfig as a6, type CacheInvalidateInput as a7, type CacheInvalidationConfig as a8, type CacheKeyOptions as a9, type CreateEndpointConfig as aA, type DeleteEndpointConfig as aB, type EndpointCacheConfig as aC, type EndpointsConfig as aD, type ExportEndpointConfig as aE, type ImportEndpointConfig as aF, type ListEndpointConfig as aG, type MutationCacheConfig as aH, type ReadEndpointConfig as aI, type RestoreEndpointConfig as aJ, type SearchEndpointConfig as aK, type UpdateEndpointConfig as aL, type UpsertEndpointConfig as aM, type VersionCompareEndpointConfig as aN, type VersionHistoryEndpointConfig as aO, type VersionReadEndpointConfig as aP, type VersionRollbackEndpointConfig as aQ, type CacheableEndpoint as aa, type InvalidatingEndpoint as ab, type InvalidationPatternOptions as ac, type InvalidationStrategy as ad, cacheStorageRegistry as ae, createInvalidationPattern as af, createRelatedPatterns as ag, generateCacheKey as ah, getCacheStorage as ai, getCacheStorageRequired as aj, invalidateEndpointCache as ak, matchesPattern as al, readEndpointCache as am, resolveCacheStorage as an, resolveCacheStorageOrWarn as ao, setCacheStorage as ap, writeEndpointCache as aq, CrudEndpoint as ar, type AggregateEndpointConfig as as, type BatchCreateEndpointConfig as at, type BatchDeleteEndpointConfig as au, type BatchRestoreEndpointConfig as av, type BatchUpdateEndpointConfig as aw, type BatchUpsertEndpointConfig as ax, type BulkPatchEndpointConfig as ay, type CloneEndpointConfig as az, AggregationException as b, type BatchUpsertItemResult as c, type BatchUpsertResult as d, ConfigurationException as e, ConflictException as f, type CrudEndpointName as g, type CrudEndpoints as h, type CsvGenerateOptions as i, type CsvParseError as j, type CsvParseOptions as k, type CsvParseResult as l, type CsvValidationResult as m, type EndpointMiddlewares as n, HonoOpenAPIHandler as o, type ImportMode as p, type ImportOptions as q, type ImportResult as r, type ImportRowResult as s, type ImportRowStatus as t, type ImportSummary as u, InputValidationException as v, NotFoundException as w, type RegisteredRoute as x, type RouterOptions as y, applyManagedInsertFields as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -5,10 +5,10 @@ import { L as LoggingEnv } from './types-B3XBv6XB.js';
|
|
|
5
5
|
import { TenantEnv } from './multi-tenant/index.js';
|
|
6
6
|
import { S as StorageEnv } from './types-xNoq2dk9.js';
|
|
7
7
|
export { O as OpenAPIRoute, i as isRouteClass } from './route-CVsl4dg3.js';
|
|
8
|
-
import { O as OpenAPIConfig, H as HonoOpenAPIApp, G as GeneratedEndpoints, A as ApiException } from './index-
|
|
9
|
-
export { a as AdapterKind, b as AggregationException, B as BatchUpsertEndpoint, c as BatchUpsertItemResult, d as BatchUpsertResult, C as CacheException, e as ConfigurationException, f as ConflictException, g as CrudEndpointName, h as CrudEndpoints, i as CsvGenerateOptions, j as CsvParseError, k as CsvParseOptions, l as CsvParseResult, m as CsvValidationResult, E as EndpointClass, n as EndpointMiddlewares, F as ForbiddenException, o as HonoOpenAPIHandler, I as ImportEndpoint, p as ImportMode, q as ImportOptions, r as ImportResult, s as ImportRowResult, t as ImportRowStatus, u as ImportSummary, v as InputValidationException, N as NormalizedTimestampsConfig, w as NotFoundException, R as RegisterCrudOptions, x as RegisteredRoute, y as RouterOptions, U as UnauthorizedException, z as applyManagedInsertFields, D as applyManagedUpdateFields, J as assertIdStrategySupported, K as causeChain, L as contentJson, M as createCsvStream, P as csvToJson, Q as defineEndpoints, S as escapeCsvValue, T as fromHono, V as generateCsv, W as getManagedInputExclusions, X as getTimestampsConfig, Y as inferCsvContentType, Z as jsonToCsv, _ as mapUniqueViolation, $ as parseCsv, a0 as registerCrud, a1 as rethrowAsConstraintError, a2 as stripManagedInsertFields, a3 as validateCsvHeaders } from './index-
|
|
8
|
+
import { O as OpenAPIConfig, H as HonoOpenAPIApp, G as GeneratedEndpoints, A as ApiException } from './index-C7O-Gh59.js';
|
|
9
|
+
export { a as AdapterKind, b as AggregationException, B as BatchUpsertEndpoint, c as BatchUpsertItemResult, d as BatchUpsertResult, C as CacheException, e as ConfigurationException, f as ConflictException, g as CrudEndpointName, h as CrudEndpoints, i as CsvGenerateOptions, j as CsvParseError, k as CsvParseOptions, l as CsvParseResult, m as CsvValidationResult, E as EndpointClass, n as EndpointMiddlewares, F as ForbiddenException, o as HonoOpenAPIHandler, I as ImportEndpoint, p as ImportMode, q as ImportOptions, r as ImportResult, s as ImportRowResult, t as ImportRowStatus, u as ImportSummary, v as InputValidationException, N as NormalizedTimestampsConfig, w as NotFoundException, R as RegisterCrudOptions, x as RegisteredRoute, y as RouterOptions, U as UnauthorizedException, z as applyManagedInsertFields, D as applyManagedUpdateFields, J as assertIdStrategySupported, K as causeChain, L as contentJson, M as createCsvStream, P as csvToJson, Q as defineEndpoints, S as escapeCsvValue, T as fromHono, V as generateCsv, W as getManagedInputExclusions, X as getTimestampsConfig, Y as inferCsvContentType, Z as jsonToCsv, _ as mapUniqueViolation, $ as parseCsv, a0 as registerCrud, a1 as rethrowAsConstraintError, a2 as stripManagedInsertFields, a3 as validateCsvHeaders } from './index-C7O-Gh59.js';
|
|
10
10
|
import { Env, Context, ErrorHandler } from 'hono';
|
|
11
|
-
export { A as AggregateEndpoint, B as BatchCreateEndpoint, a as BatchDeleteEndpoint, b as BatchDeleteResult, c as BatchRestoreEndpoint, d as BatchRestoreResult, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpdateResult, h as BulkPatchEndpoint, i as BulkPatchResult, C as CONTEXT_KEYS, j as CascadeResult, k as CloneEndpoint, l as ContextKey, m as CreateEndpoint, D as DeleteEndpoint, E as ExportEndpoint, n as ExportFormat, o as ExportOptions, p as ExportResult, L as ListEndpoint, q as Logger, R as ReadEndpoint, r as RestoreEndpoint, S as SearchEndpoint, U as UpdateEndpoint, s as UpsertEndpoint, t as UpsertResult, V as VersionCompareEndpoint, u as VersionHistoryEndpoint, v as VersionReadEndpoint, w as VersionRollbackEndpoint, x as applyUpsertRestore, y as computeAggregations, z as decodeCursor, F as encodeCursor, G as getLogger, H as getSoftDeleteConfig, I as searchInMemory, J as setLogger } from './context-keys-
|
|
11
|
+
export { A as AggregateEndpoint, B as BatchCreateEndpoint, a as BatchDeleteEndpoint, b as BatchDeleteResult, c as BatchRestoreEndpoint, d as BatchRestoreResult, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpdateResult, h as BulkPatchEndpoint, i as BulkPatchResult, C as CONTEXT_KEYS, j as CascadeResult, k as CloneEndpoint, l as ContextKey, m as CreateEndpoint, D as DeleteEndpoint, E as ExportEndpoint, n as ExportFormat, o as ExportOptions, p as ExportResult, L as ListEndpoint, q as Logger, R as ReadEndpoint, r as RestoreEndpoint, S as SearchEndpoint, U as UpdateEndpoint, s as UpsertEndpoint, t as UpsertResult, V as VersionCompareEndpoint, u as VersionHistoryEndpoint, v as VersionReadEndpoint, w as VersionRollbackEndpoint, x as applyUpsertRestore, y as computeAggregations, z as decodeCursor, F as encodeCursor, G as getLogger, H as getSoftDeleteConfig, I as searchInMemory, J as setLogger } from './context-keys-C7y4-168.js';
|
|
12
12
|
import { C as CrudEventEmitter } from './emitter-B8EL76d3.js';
|
|
13
13
|
import { C as CrudEventType, a as CrudEventPayload } from './types-ChLYHg52.js';
|
|
14
14
|
export { F as FieldSelection, a as FieldSelectionConfig, L as ListFilterParseOptions, M as ModelObject, S as SingleEndpointConfig, U as UpdateEndpointConfig, b as applyFieldSelection, c as applyFieldSelectionToArray, g as getSchemaFields, p as parseFieldSelection, d as parseFilterValue, e as parseListFilters } from './types-BTRpRT28.js';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {q as q$2}from'./chunk-O62WFEW2.js';export{c as getErrorMessage,a as toError,b as wrapError}from'./chunk-O62WFEW2.js';import {a,ra}from'./chunk-O6VQTREM.js';export{da as AggregateEndpoint,V as BatchCreateEndpoint,X as BatchDeleteEndpoint,Y as BatchRestoreEndpoint,W as BatchUpdateEndpoint,Z as BatchUpsertEndpoint,_ as BulkPatchEndpoint,S as CloneEndpoint,M as CreateEndpoint,Q as DeleteEndpoint,pa as ExportEndpoint,qa as ImportEndpoint,R as ListEndpoint,O as ReadEndpoint,T as RestoreEndpoint,fa as SearchEndpoint,P as UpdateEndpoint,U as UpsertEndpoint,ba as VersionCompareEndpoint,$ as VersionHistoryEndpoint,aa as VersionReadEndpoint,ca as VersionRollbackEndpoint,n as applyComputedFields,o as applyComputedFieldsToArray,K as applyFieldSelection,L as applyFieldSelectionToArray,d as applyManagedInsertFields,e as applyManagedUpdateFields,u as applyUpsertRestore,f as assertIdStrategySupported,B as buildSearchConfig,y as calculateScore,h as causeChain,ea as computeAggregations,ja as createCsvStream,oa as csvToJson,l as decodeCursor,k as encodeCursor,ha as escapeCsvValue,p as extractNestedData,ia as generateCsv,D as generateETag,z as generateHighlights,c as getManagedInputExclusions,I as getSchemaFields,t as getSoftDeleteConfig,b as getTimestampsConfig,ma as inferCsvContentType,q as isDirectNestedData,na as jsonToCsv,i as mapUniqueViolation,F as matchesIfMatch,E as matchesIfNoneMatch,r as parseAggregateField,s as parseAggregateQuery,ka as parseCsv,J as parseFieldSelection,G as parseFilterValue,H as parseListFilters,A as parseSearchFields,C as parseSearchMode,j as rethrowAsConstraintError,ga as searchInMemory,g as stripManagedInsertFields,x as termFrequency,v as tokenize,w as tokenizeQuery,la as validateCsvHeaders}from'./chunk-O6VQTREM.js';import'./chunk-P7HU2KIE.js';import {e}from'./chunk-H3VBYIDA.js';import'./chunk-CWQSQUV4.js';import'./chunk-SDNXN7M5.js';import'./chunk-HYXDMJ4K.js';import'./chunk-WBHWKOTP.js';import'./chunk-L5CVVJQH.js';import {n,o,q as q$1,m}from'./chunk-A27HDYSF.js';export{f as AGGREGATE_OPERATIONS,a as FILTER_OPERATORS,p as OpenAPIRoute,m as RESPONSE_ENVELOPE_CONTEXT_KEY,e as SEARCH_MODES,d as SORT_DIRECTIONS,c as assertNever,h as defineMeta,g as defineModel,k as errorEnvelopeSchema,P as errorResponseSchema,O as errorResponseZodSchema,Q as errorResponses,b as isFilterOperator,q as isRouteClass,N as mergeRouteSchema,j as structuredErrorSchema,l as successEnvelopeSchema,i as validationIssueSchema}from'./chunk-A27HDYSF.js';import'./chunk-V7ABUFW5.js';import {b as b$1}from'./chunk-DMGP7QDL.js';export{b as getLogger,a as setLogger}from'./chunk-DMGP7QDL.js';import'./chunk-5P4RVSHT.js';import {b as b$2}from'./chunk-TLI3TRUA.js';export{e as generateRequestId,a as getContextVar,c as getRequestId,d as getTenantId,b as setContextVar}from'./chunk-TLI3TRUA.js';import {c,b}from'./chunk-XR6JRDGX.js';export{h as AggregationException,b as ApiException,a as CONTEXT_KEYS,i as CacheException,j as ConfigurationException,e as ConflictException,g as ForbiddenException,c as InputValidationException,d as NotFoundException,f as UnauthorizedException}from'./chunk-XR6JRDGX.js';import {a as a$1}from'./chunk-NWOJZP4P.js';export{a as defineEndpoints}from'./chunk-W62PHP4A.js';import'./chunk-EMXKCEPB.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE}from'hono/streaming';function I(t){return t.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function Vt(t,e){return {content:{"application/json":{schema:t}},description:e}}function jt(t,e){return {content:{"application/json":{schema:t}},description:e,required:true}}var N=t=>{if(!t.success)throw c.fromZodError(t.error)};function Lt(t,e=400){return (o,r)=>{if(!o.success)return r.json(t(o.error),e)}}var V=new WeakMap;function j(t){return V.get(t)}var S=class{app;options;routes=new Map;constructor(e,o={}){this.app=e,this.options={openapi_url:"/openapi.json",...o};}registerRoute(e,o$1,r,p=[]){let f=`${e.toUpperCase()} ${o$1}`,l=r,d=new l().getSchema();this.routes.set(f,{method:e,path:o$1,schema:d,routeClass:r});let i=createRoute({method:e,path:I(o$1),...d,responses:d.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(p.length>0)for(let c of p)this.app.use(o$1,async(s,n)=>{if(s.req.method.toLowerCase()===e)return c(s,n);await n();});this.app.openapi(i,async c=>{let s=new l;s.setContext(c);try{return await s.handle()}catch(n$1){if(n$1 instanceof b){let a=n$1.toJSON(),E=n(c);return E?o(c,E.error(a.error),n$1.status):o(c,a,n$1.status)}throw n$1}});}setupDocs(e,o){let r=e??this.options.openapi_url??"/openapi.json";this.app.doc(r,{openapi:o.openapi||"3.1.0",info:o.info,servers:o.servers,security:o.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return I(e)}};function Bt(t=new OpenAPIHono,e={}){let o="openAPIRegistry"in t?t:new OpenAPIHono;o.defaultHook??=N;let r=new S(o,e),p=["get","post","put","patch","delete","options","head"],f=new Proxy(o,{get(l,m){if(p.includes(m))return (i,...c)=>{let s=c[c.length-1];if(q$1(s)){let n=c.slice(0,-1);return r.registerRoute(m,i,s,n),f}return l[m](i,...c)};if(m==="doc")return (i,c)=>{r.setupDocs(i,c);};if(m==="use")return (...i)=>(l[m](...i),f);let d=l[m];return typeof d=="function"?d.bind(l):d}});return V.set(f,r),f}var Kt=6e4,Wt={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Jt(t,e,o={}){let r=j(t);if(!r)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let p=o.config??Wt,f=`openapi:${e.tenantId??"global"}:${p.info.version}`;if(o.cache){let i=await o.cache.get(f);if(i!=null)return i}let l=new OpenAPIHono;for(let i of r.getRegisteredRoutes().values()){let c=i.routeClass,s=new c,n=Yt(e);s.setContext(n),typeof s.resolveModelSchema=="function"&&await s.resolveModelSchema();let a=s.getSchema(),E=createRoute({...a,method:i.method,path:r.toOpenApiPath(i.path),responses:a.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});l.openapi(E,()=>new Response);}let m={openapi:p.openapi??"3.1.0",info:p.info,servers:p.servers,security:p.security},d=o.spec==="3.0"?l.getOpenAPIDocument(m):l.getOpenAPI31Document(m);return o.cache&&await o.cache.set(f,d,o.cacheTtlMs??Kt),d}function Yt(t){let e={};t.tenantId!==void 0&&(e.tenantId=t.tenantId),t.organizationId!==void 0&&(e.organizationId=t.organizationId);let o=t.request??new Request("http://localhost/");return {var:e,env:t.env,req:{raw:o,header:()=>{},query:()=>{},param:()=>{}},set(r,p){e[r]=p;},get(r){return e[r]},executionCtx:void 0}}function Xt(t){return {async get(e){let o=await t.get(e);return o?o.data:void 0},async set(e,o,r){await t.set(e,o,r!=null?{ttlMs:r}:void 0);}}}function oo(t,e){let r=`/${t}/${e}`.replace(/\/{2,}/g,"/");return r.length>1&&r.endsWith("/")?r.slice(0,-1):r}function no(t,e={}){let o=e.basePath??"",r=e.tag,p=new OpenAPIHono,f=0,l=t;for(let[i,c,s]of a){let n=l[i];if(!n)continue;let E=new n().getSchema(),g=r!==void 0?{...E,tags:[r]}:E,h=oo(o,I(s)),C=createRoute({...g,method:c,path:h,responses:g.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});p.openapi(C,()=>new Response),f+=1;}return f===0?{}:p.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var L=t=>{if(t instanceof ZodError)return c.fromZodError(t)};function po(t={}){let{mappers:e=[],hooks:o$1=[],includeRequestId:r=true,includeStackTrace:p=false,defaultErrorCode:f="INTERNAL_ERROR",defaultErrorMessage:l="An internal error occurred",logUnmappedErrors:m=true,onHookError:d,responseEnvelope:i}=t,c=[...e,L];return async(s,n)=>{let a;if(s instanceof b)a=s;else if(s instanceof HTTPException)a=new b(s.message,s.status,"HTTP_ERROR");else {for(let y of c)try{let R=await y(s,n);if(R){a=R;break}}catch{}!a&&m&&b$1().error("Unmapped error",{error:s instanceof Error?s.message:String(s)});}let E=a??new b(l,500,f),g=a$1(n);for(let y of o$1)try{let R=y(s,n,E);if(R instanceof Promise){let B=R.catch(Z=>{d&&d(Z,s,n);});g?.(B);}}catch(R){d&&d(R,s,n);}let h=E.toJSON();if(r){let y=q$2(n);y&&(h.error.requestId=y);}p&&s.stack&&(h.error.stack=s.stack);let C=q(n,i),u=C?C.error(h.error):h;return o(n,u,E.status)}}function q(t,e){return n(t)??e}var v=new Map,ao=["password","token","secret","apiKey","creditCard","ssn"];function H(t,e){if(t==null||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>H(r,e));let o={};for(let[r,p]of Object.entries(t))e.includes(r)||(o[r]=typeof p=="object"&&p!==null?H(p,e):p);return o}function co(t){let{table:e$1,events:o,emitter:r,filter:p,heartbeatIntervalMs:f=3e4,maxConnections:l=1e3,connectionTimeoutMs:m=3e5,excludeFields:d=ao}=t;return i=>{let c=e(i,r);if(!c)throw new b("Event emitter not configured",500,"EVENT_EMITTER_NOT_CONFIGURED");let s=v.get(e$1)||0;if(s>=l)throw new b("Too many SSE connections",503,"TOO_MANY_CONNECTIONS");return v.set(e$1,s+1),streamSSE(i,async n=>{let a,E=async u=>{if(o&&o.length>0&&!o.includes(u.type)||p&&!p(u,i))return;let y=d.length>0?H(u.data,d):u.data,R=u.previousData&&d.length>0?H(u.previousData,d):u.previousData;try{await n.writeSSE({event:`${u.table}.${u.type}`,data:JSON.stringify({type:u.type,table:u.table,recordId:u.recordId,data:y,previousData:R,timestamp:u.timestamp}),id:`${u.table}-${u.recordId}-${Date.now()}`});}catch{}};a=c.onTable(e$1,E);let g=()=>{a.unsubscribe();let u=v.get(e$1)||1;u<=1?v.delete(e$1):v.set(e$1,u-1);};n.onAbort(()=>{g();});let h=Date.now(),C=h;for(;!n.closed;){await n.sleep(1e3);let u=Date.now();if(u-h>=m){n.abort();break}if(u-C>=f){C=u;try{await n.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}})}}function uo(t,e,o,r={}){let p=e.endsWith("/")?e.slice(0,-1):e,f=t,{middlewares:l=[],endpointMiddlewares:m$1={},responseEnvelope:d}=r,i=d?async(n,a)=>{b$2(n,m,d),await a();}:void 0,c=n=>{let a=o[n],E=a&&"_middlewares"in a?a._middlewares||[]:[];return [...i?[i]:[],...l,...m$1[n]||[],...E]},s=(n,a,E,g)=>{let h=c(E),C=f[n];h.length>0?C(a,...h,g):C(a,g);};for(let[n,a$1,E]of a){let g=o[n];g&&s(a$1,`${p}${E}`,n,g);}ra(t,p,o);}function lo(t){return {content:{"application/json":{schema:t}}}}
|
|
1
|
+
import {q as q$2}from'./chunk-O62WFEW2.js';export{c as getErrorMessage,a as toError,b as wrapError}from'./chunk-O62WFEW2.js';import {a,Ea}from'./chunk-VOKEDJQ7.js';export{qa as AggregateEndpoint,ga as BatchCreateEndpoint,ia as BatchDeleteEndpoint,ja as BatchRestoreEndpoint,ha as BatchUpdateEndpoint,ka as BatchUpsertEndpoint,la as BulkPatchEndpoint,da as CloneEndpoint,Z as CreateEndpoint,ba as DeleteEndpoint,Ca as ExportEndpoint,Da as ImportEndpoint,ca as ListEndpoint,$ as ReadEndpoint,ea as RestoreEndpoint,sa as SearchEndpoint,aa as UpdateEndpoint,fa as UpsertEndpoint,oa as VersionCompareEndpoint,ma as VersionHistoryEndpoint,na as VersionReadEndpoint,pa as VersionRollbackEndpoint,n as applyComputedFields,o as applyComputedFieldsToArray,X as applyFieldSelection,Y as applyFieldSelectionToArray,d as applyManagedInsertFields,e as applyManagedUpdateFields,u as applyUpsertRestore,f as assertIdStrategySupported,B as buildSearchConfig,y as calculateScore,h as causeChain,ra as computeAggregations,wa as createCsvStream,Ba as csvToJson,l as decodeCursor,k as encodeCursor,ua as escapeCsvValue,p as extractNestedData,va as generateCsv,D as generateETag,z as generateHighlights,c as getManagedInputExclusions,V as getSchemaFields,t as getSoftDeleteConfig,b as getTimestampsConfig,za as inferCsvContentType,q as isDirectNestedData,Aa as jsonToCsv,i as mapUniqueViolation,F as matchesIfMatch,E as matchesIfNoneMatch,r as parseAggregateField,s as parseAggregateQuery,xa as parseCsv,W as parseFieldSelection,T as parseFilterValue,U as parseListFilters,A as parseSearchFields,C as parseSearchMode,j as rethrowAsConstraintError,ta as searchInMemory,g as stripManagedInsertFields,x as termFrequency,v as tokenize,w as tokenizeQuery,ya as validateCsvHeaders}from'./chunk-VOKEDJQ7.js';import'./chunk-P7HU2KIE.js';import {e}from'./chunk-H3VBYIDA.js';import'./chunk-CWQSQUV4.js';import'./chunk-SDNXN7M5.js';import'./chunk-HYXDMJ4K.js';import'./chunk-WBHWKOTP.js';import'./chunk-L5CVVJQH.js';import {n,o,q as q$1,m}from'./chunk-A27HDYSF.js';export{f as AGGREGATE_OPERATIONS,a as FILTER_OPERATORS,p as OpenAPIRoute,m as RESPONSE_ENVELOPE_CONTEXT_KEY,e as SEARCH_MODES,d as SORT_DIRECTIONS,c as assertNever,h as defineMeta,g as defineModel,k as errorEnvelopeSchema,P as errorResponseSchema,O as errorResponseZodSchema,Q as errorResponses,b as isFilterOperator,q as isRouteClass,N as mergeRouteSchema,j as structuredErrorSchema,l as successEnvelopeSchema,i as validationIssueSchema}from'./chunk-A27HDYSF.js';import'./chunk-V7ABUFW5.js';import {b as b$1}from'./chunk-DMGP7QDL.js';export{b as getLogger,a as setLogger}from'./chunk-DMGP7QDL.js';import'./chunk-5P4RVSHT.js';import {b as b$2}from'./chunk-TLI3TRUA.js';export{e as generateRequestId,a as getContextVar,c as getRequestId,d as getTenantId,b as setContextVar}from'./chunk-TLI3TRUA.js';import {c,b}from'./chunk-XR6JRDGX.js';export{h as AggregationException,b as ApiException,a as CONTEXT_KEYS,i as CacheException,j as ConfigurationException,e as ConflictException,g as ForbiddenException,c as InputValidationException,d as NotFoundException,f as UnauthorizedException}from'./chunk-XR6JRDGX.js';import {a as a$1}from'./chunk-NWOJZP4P.js';export{a as defineEndpoints}from'./chunk-AQXRF6RJ.js';import'./chunk-5DTBFOC3.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE}from'hono/streaming';function I(t){return t.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function Vt(t,e){return {content:{"application/json":{schema:t}},description:e}}function jt(t,e){return {content:{"application/json":{schema:t}},description:e,required:true}}var N=t=>{if(!t.success)throw c.fromZodError(t.error)};function Lt(t,e=400){return (o,r)=>{if(!o.success)return r.json(t(o.error),e)}}var V=new WeakMap;function j(t){return V.get(t)}var S=class{app;options;routes=new Map;constructor(e,o={}){this.app=e,this.options={openapi_url:"/openapi.json",...o};}registerRoute(e,o$1,r,p=[]){let f=`${e.toUpperCase()} ${o$1}`,l=r,d=new l().getSchema();this.routes.set(f,{method:e,path:o$1,schema:d,routeClass:r});let i=createRoute({method:e,path:I(o$1),...d,responses:d.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(p.length>0)for(let c of p)this.app.use(o$1,async(s,n)=>{if(s.req.method.toLowerCase()===e)return c(s,n);await n();});this.app.openapi(i,async c=>{let s=new l;s.setContext(c);try{return await s.handle()}catch(n$1){if(n$1 instanceof b){let a=n$1.toJSON(),E=n(c);return E?o(c,E.error(a.error),n$1.status):o(c,a,n$1.status)}throw n$1}});}setupDocs(e,o){let r=e??this.options.openapi_url??"/openapi.json";this.app.doc(r,{openapi:o.openapi||"3.1.0",info:o.info,servers:o.servers,security:o.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return I(e)}};function Bt(t=new OpenAPIHono,e={}){let o="openAPIRegistry"in t?t:new OpenAPIHono;o.defaultHook??=N;let r=new S(o,e),p=["get","post","put","patch","delete","options","head"],f=new Proxy(o,{get(l,m){if(p.includes(m))return (i,...c)=>{let s=c[c.length-1];if(q$1(s)){let n=c.slice(0,-1);return r.registerRoute(m,i,s,n),f}return l[m](i,...c)};if(m==="doc")return (i,c)=>{r.setupDocs(i,c);};if(m==="use")return (...i)=>(l[m](...i),f);let d=l[m];return typeof d=="function"?d.bind(l):d}});return V.set(f,r),f}var Kt=6e4,Wt={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Jt(t,e,o={}){let r=j(t);if(!r)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let p=o.config??Wt,f=`openapi:${e.tenantId??"global"}:${p.info.version}`;if(o.cache){let i=await o.cache.get(f);if(i!=null)return i}let l=new OpenAPIHono;for(let i of r.getRegisteredRoutes().values()){let c=i.routeClass,s=new c,n=Yt(e);s.setContext(n),typeof s.resolveModelSchema=="function"&&await s.resolveModelSchema();let a=s.getSchema(),E=createRoute({...a,method:i.method,path:r.toOpenApiPath(i.path),responses:a.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});l.openapi(E,()=>new Response);}let m={openapi:p.openapi??"3.1.0",info:p.info,servers:p.servers,security:p.security},d=o.spec==="3.0"?l.getOpenAPIDocument(m):l.getOpenAPI31Document(m);return o.cache&&await o.cache.set(f,d,o.cacheTtlMs??Kt),d}function Yt(t){let e={};t.tenantId!==void 0&&(e.tenantId=t.tenantId),t.organizationId!==void 0&&(e.organizationId=t.organizationId);let o=t.request??new Request("http://localhost/");return {var:e,env:t.env,req:{raw:o,header:()=>{},query:()=>{},param:()=>{}},set(r,p){e[r]=p;},get(r){return e[r]},executionCtx:void 0}}function Xt(t){return {async get(e){let o=await t.get(e);return o?o.data:void 0},async set(e,o,r){await t.set(e,o,r!=null?{ttlMs:r}:void 0);}}}function oo(t,e){let r=`/${t}/${e}`.replace(/\/{2,}/g,"/");return r.length>1&&r.endsWith("/")?r.slice(0,-1):r}function no(t,e={}){let o=e.basePath??"",r=e.tag,p=new OpenAPIHono,f=0,l=t;for(let[i,c,s]of a){let n=l[i];if(!n)continue;let E=new n().getSchema(),g=r!==void 0?{...E,tags:[r]}:E,h=oo(o,I(s)),C=createRoute({...g,method:c,path:h,responses:g.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});p.openapi(C,()=>new Response),f+=1;}return f===0?{}:p.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var L=t=>{if(t instanceof ZodError)return c.fromZodError(t)};function po(t={}){let{mappers:e=[],hooks:o$1=[],includeRequestId:r=true,includeStackTrace:p=false,defaultErrorCode:f="INTERNAL_ERROR",defaultErrorMessage:l="An internal error occurred",logUnmappedErrors:m=true,onHookError:d,responseEnvelope:i}=t,c=[...e,L];return async(s,n)=>{let a;if(s instanceof b)a=s;else if(s instanceof HTTPException)a=new b(s.message,s.status,"HTTP_ERROR");else {for(let y of c)try{let R=await y(s,n);if(R){a=R;break}}catch{}!a&&m&&b$1().error("Unmapped error",{error:s instanceof Error?s.message:String(s)});}let E=a??new b(l,500,f),g=a$1(n);for(let y of o$1)try{let R=y(s,n,E);if(R instanceof Promise){let B=R.catch(Z=>{d&&d(Z,s,n);});g?.(B);}}catch(R){d&&d(R,s,n);}let h=E.toJSON();if(r){let y=q$2(n);y&&(h.error.requestId=y);}p&&s.stack&&(h.error.stack=s.stack);let C=q(n,i),u=C?C.error(h.error):h;return o(n,u,E.status)}}function q(t,e){return n(t)??e}var v=new Map,ao=["password","token","secret","apiKey","creditCard","ssn"];function H(t,e){if(t==null||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>H(r,e));let o={};for(let[r,p]of Object.entries(t))e.includes(r)||(o[r]=typeof p=="object"&&p!==null?H(p,e):p);return o}function co(t){let{table:e$1,events:o,emitter:r,filter:p,heartbeatIntervalMs:f=3e4,maxConnections:l=1e3,connectionTimeoutMs:m=3e5,excludeFields:d=ao}=t;return i=>{let c=e(i,r);if(!c)throw new b("Event emitter not configured",500,"EVENT_EMITTER_NOT_CONFIGURED");let s=v.get(e$1)||0;if(s>=l)throw new b("Too many SSE connections",503,"TOO_MANY_CONNECTIONS");return v.set(e$1,s+1),streamSSE(i,async n=>{let a,E=async u=>{if(o&&o.length>0&&!o.includes(u.type)||p&&!p(u,i))return;let y=d.length>0?H(u.data,d):u.data,R=u.previousData&&d.length>0?H(u.previousData,d):u.previousData;try{await n.writeSSE({event:`${u.table}.${u.type}`,data:JSON.stringify({type:u.type,table:u.table,recordId:u.recordId,data:y,previousData:R,timestamp:u.timestamp}),id:`${u.table}-${u.recordId}-${Date.now()}`});}catch{}};a=c.onTable(e$1,E);let g=()=>{a.unsubscribe();let u=v.get(e$1)||1;u<=1?v.delete(e$1):v.set(e$1,u-1);};n.onAbort(()=>{g();});let h=Date.now(),C=h;for(;!n.closed;){await n.sleep(1e3);let u=Date.now();if(u-h>=m){n.abort();break}if(u-C>=f){C=u;try{await n.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}})}}function uo(t,e,o,r={}){let p=e.endsWith("/")?e.slice(0,-1):e,f=t,{middlewares:l=[],endpointMiddlewares:m$1={},responseEnvelope:d}=r,i=d?async(n,a)=>{b$2(n,m,d),await a();}:void 0,c=n=>{let a=o[n],E=a&&"_middlewares"in a?a._middlewares||[]:[];return [...i?[i]:[],...l,...m$1[n]||[],...E]},s=(n,a,E,g)=>{let h=c(E),C=f[n];h.length>0?C(a,...h,g):C(a,g);};for(let[n,a$1,E]of a){let g=o[n];g&&s(a$1,`${p}${E}`,n,g);}Ea(t,p,o);}function lo(t){return {content:{"application/json":{schema:t}}}}
|
|
2
2
|
export{S as HonoOpenAPIHandler,Jt as buildPerTenantOpenApi,lo as contentJson,po as createErrorHandler,co as createSubscribeHandler,Lt as createValidationHook,Bt as fromHono,Vt as jsonContent,jt as jsonContentRequired,N as openApiValidationHook,uo as registerCrud,q as resolveErrorEnvelope,no as toOpenApiPaths,Xt as wrapCacheStorageForOpenApi,L as zodErrorMapper};
|
package/dist/internal.d.ts
CHANGED
|
@@ -2,10 +2,10 @@ import { a5 as RelationConfig, M as MetaInput, z as IncludeOptions, aA as Relati
|
|
|
2
2
|
export { aB as AbstractConstructor, A as AggregateField, a as AggregateOptions, j as AggregateResult, aC as Constructor, E as ErrorResponse, s as FilterCondition, u as FilterOperator, L as ListFilters, V as NestedUpdateInput, X as NestedWriteResult, O as OpenAPIRouteSchema, a1 as PaginatedResult, a7 as RelationsConfig, a9 as ResponseEnvelopeInfo, af as SearchOptions, ag as SearchResult, ah as SearchResultItem, as as assertNever, aw as isFilterOperator } from './types-D72szrPV.js';
|
|
3
3
|
export { M as ModelObject } from './types-BTRpRT28.js';
|
|
4
4
|
export { O as OpenAPIRoute } from './route-CVsl4dg3.js';
|
|
5
|
-
import { h as CrudEndpoints } from './index-
|
|
6
|
-
export { a4 as AdapterBundle, A as ApiException, B as BatchUpsertEndpoint, c as BatchUpsertItemResult, d as BatchUpsertResult, a5 as CRUD_ROUTES, e as ConfigurationException, g as CrudEndpointName, G as GeneratedEndpoints, I as ImportEndpoint, p as ImportMode, q as ImportOptions, r as ImportResult, s as ImportRowResult, t as ImportRowStatus, u as ImportSummary, w as NotFoundException, U as UnauthorizedException } from './index-
|
|
5
|
+
import { h as CrudEndpoints } from './index-C7O-Gh59.js';
|
|
6
|
+
export { a4 as AdapterBundle, A as ApiException, B as BatchUpsertEndpoint, c as BatchUpsertItemResult, d as BatchUpsertResult, a5 as CRUD_ROUTES, a6 as CacheConfig, a7 as CacheInvalidateInput, a8 as CacheInvalidationConfig, a9 as CacheKeyOptions, aa as CacheableEndpoint, e as ConfigurationException, g as CrudEndpointName, G as GeneratedEndpoints, I as ImportEndpoint, p as ImportMode, q as ImportOptions, r as ImportResult, s as ImportRowResult, t as ImportRowStatus, u as ImportSummary, ab as InvalidatingEndpoint, ac as InvalidationPatternOptions, ad as InvalidationStrategy, w as NotFoundException, U as UnauthorizedException, ae as cacheStorageRegistry, af as createInvalidationPattern, ag as createRelatedPatterns, ah as generateCacheKey, ai as getCacheStorage, aj as getCacheStorageRequired, ak as invalidateEndpointCache, al as matchesPattern, am as readEndpointCache, an as resolveCacheStorage, ao as resolveCacheStorageOrWarn, ap as setCacheStorage, aq as writeEndpointCache } from './index-C7O-Gh59.js';
|
|
7
7
|
import { Env } from 'hono';
|
|
8
|
-
export { A as AggregateEndpoint, B as BatchCreateEndpoint, a as BatchDeleteEndpoint, b as BatchDeleteResult, c as BatchRestoreEndpoint, d as BatchRestoreResult, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpdateResult, h as BulkPatchEndpoint, i as BulkPatchResult, C as CONTEXT_KEYS, j as CascadeResult, k as CloneEndpoint, l as ContextKey, m as CreateEndpoint, K as CursorPage, M as CursorPageInput, D as DeleteEndpoint, E as ExportEndpoint, n as ExportFormat, o as ExportOptions, p as ExportResult, L as ListEndpoint, q as Logger, R as ReadEndpoint, r as RestoreEndpoint, S as SearchEndpoint, U as UpdateEndpoint, s as UpsertEndpoint, t as UpsertResult, V as VersionCompareEndpoint, u as VersionHistoryEndpoint, v as VersionReadEndpoint, w as VersionRollbackEndpoint, x as applyUpsertRestore, N as buildCursorPage, y as computeAggregations, z as decodeCursor, F as encodeCursor, G as getLogger, I as searchInMemory } from './context-keys-
|
|
8
|
+
export { A as AggregateEndpoint, B as BatchCreateEndpoint, a as BatchDeleteEndpoint, b as BatchDeleteResult, c as BatchRestoreEndpoint, d as BatchRestoreResult, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpdateResult, h as BulkPatchEndpoint, i as BulkPatchResult, C as CONTEXT_KEYS, j as CascadeResult, k as CloneEndpoint, l as ContextKey, m as CreateEndpoint, K as CursorPage, M as CursorPageInput, D as DeleteEndpoint, E as ExportEndpoint, n as ExportFormat, o as ExportOptions, p as ExportResult, L as ListEndpoint, q as Logger, R as ReadEndpoint, r as RestoreEndpoint, S as SearchEndpoint, U as UpdateEndpoint, s as UpsertEndpoint, t as UpsertResult, V as VersionCompareEndpoint, u as VersionHistoryEndpoint, v as VersionReadEndpoint, w as VersionRollbackEndpoint, x as applyUpsertRestore, N as buildCursorPage, y as computeAggregations, z as decodeCursor, F as encodeCursor, G as getLogger, I as searchInMemory } from './context-keys-C7y4-168.js';
|
|
9
9
|
import { ZodObject, ZodRawShape } from 'zod';
|
|
10
10
|
export { a as getContextVar, s as setContextVar } from './context-m0qIRK5d.js';
|
|
11
11
|
export { C as ClientIpOptions, g as getClientIp, a as getUserId } from './request-info-OQ40JnWp.js';
|
package/dist/internal.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as MemoryTtlStore}from'./chunk-YB6AVUPQ.js';export{
|
|
1
|
+
export{a as MemoryTtlStore}from'./chunk-YB6AVUPQ.js';export{qa as AggregateEndpoint,ga as BatchCreateEndpoint,ia as BatchDeleteEndpoint,ja as BatchRestoreEndpoint,ha as BatchUpdateEndpoint,ka as BatchUpsertEndpoint,la as BulkPatchEndpoint,a as CRUD_ROUTES,da as CloneEndpoint,Z as CreateEndpoint,ba as DeleteEndpoint,Ca as ExportEndpoint,Da as ImportEndpoint,ca as ListEndpoint,$ as ReadEndpoint,ea as RestoreEndpoint,sa as SearchEndpoint,aa as UpdateEndpoint,fa as UpsertEndpoint,oa as VersionCompareEndpoint,ma as VersionHistoryEndpoint,na as VersionReadEndpoint,pa as VersionRollbackEndpoint,u as applyUpsertRestore,m as buildCursorPage,K as cacheStorageRegistry,ra as computeAggregations,H as createInvalidationPattern,I as createRelatedPatterns,l as decodeCursor,k as encodeCursor,G as generateCacheKey,M as getCacheStorage,N as getCacheStorageRequired,Fa as getRegisteredCrudResources,S as invalidateEndpointCache,J as matchesPattern,Q as readEndpointCache,Ea as recordCrudResource,O as resolveCacheStorage,P as resolveCacheStorageOrWarn,ta as searchInMemory,L as setCacheStorage,_ as withIncludableRelations,R as writeEndpointCache}from'./chunk-VOKEDJQ7.js';import'./chunk-P7HU2KIE.js';import'./chunk-H3VBYIDA.js';import'./chunk-CWQSQUV4.js';import'./chunk-SDNXN7M5.js';import'./chunk-HYXDMJ4K.js';import'./chunk-WBHWKOTP.js';import'./chunk-L5CVVJQH.js';export{p as extractBearerToken}from'./chunk-CTOFQ5RC.js';export{p as OpenAPIRoute,c as assertNever,b as isFilterOperator}from'./chunk-A27HDYSF.js';export{a as getClientIp,b as getUserId,e as isPathIncluded,d as matchAny,c as matchPath}from'./chunk-V7ABUFW5.js';export{b as getLogger}from'./chunk-DMGP7QDL.js';export{a as StorageRegistry,b as createStorageFeature}from'./chunk-5P4RVSHT.js';export{a as getContextVar,b as setContextVar}from'./chunk-TLI3TRUA.js';export{b as ApiException,a as CONTEXT_KEYS,j as ConfigurationException,d as NotFoundException,f as UnauthorizedException}from'./chunk-XR6JRDGX.js';import'./chunk-NWOJZP4P.js';function m(e,t,n){let o=t.scope;if(!o||!n)return e;let{tenantField:r,softDeleteField:l}=o,{tenantId:a,includeDeleted:i}=n,p=r!=null&&a!=null,c=l!=null&&!i;return !p&&!c?e:e.filter(u=>!(p&&u[r]!==a||c&&u[l]!=null))}function y(e,t){let n=e.scope;if(!n||!t)return;let o=n.tenantField!=null&&t.tenantId!=null?n.tenantField:void 0,r=n.softDeleteField!=null&&!t.includeDeleted?n.softDeleteField:void 0;if(!(o==null&&r==null))return {tenantField:o,tenantValue:t.tenantId,excludeDeletedField:r}}async function Be(e,t,n,o){if(!e.length||!o?.relations?.length||!t.model.relations)return e;let r=e.map(l=>({...l}));for(let l of o.relations){let a=t.model.relations[l];if(!a)continue;let i=await n.resolveRelation(a);i!=null&&(r=await Me[a.type](r,l,a,i,n,o.scope));}return r}function x(e){return async(t,n,o,r,l,a)=>{let i=o.localKey||"id",p=[...new Set(t.map(s=>s[i]).filter(s=>s!=null))];if(p.length===0)return t.map(s=>({...s,[n]:e?null:[]}));let c=y(o,a),u=await l.fetchRelated(r,o.foreignKey,p,c),f=m(u,o,a),d=new Map;for(let s of f){let R=s[o.foreignKey],g=d.get(R);g?g.push(s):d.set(R,[s]);}return t.map(s=>{let R=d.get(s[i])||[];return {...s,[n]:e?R[0]||null:R}})}}function Oe(){return async(e,t,n,o,r,l)=>{let a=n.localKey||"id",i=[...new Set(e.map(d=>d[n.foreignKey]).filter(d=>d!=null))];if(i.length===0)return e.map(d=>({...d,[t]:null}));let p=y(n,l),c=await r.fetchRelated(o,a,i,p),u=m(c,n,l),f=new Map;for(let d of u)f.set(d[a],d);return e.map(d=>({...d,[t]:f.get(d[n.foreignKey])||null}))}}var Me={hasOne:x(true),hasMany:x(false),belongsTo:Oe()},h={hasOne:e=>e[0]??null,hasMany:e=>e,belongsTo:e=>e[0]??null};function C(e,t){let n=e.localKey||"id";if(e.type==="belongsTo"){let r=t[e.foreignKey];return r==null?null:{gateValue:r,keyField:n}}let o=t[n];return o==null?null:{gateValue:o,keyField:e.foreignKey}}async function S(e,t,n,o,r){let l=h[t.type],a=C(t,e);if(!a)return l([]);let i=m(await o(n,a.keyField,[a.gateValue],y(t,r)),t,r);return l(i)}function E(e,t,n,o,r){let l=h[t.type],a=C(t,e);if(!a)return l([]);let i=m(o(n,a.keyField,[a.gateValue],y(t,r)),t,r);return l(i)}async function Ve(e,t,n,o){if(!o?.relations?.length||!t.model.relations)return e;let r={...e};for(let l of o.relations){let a=t.model.relations[l];if(!a)continue;let i=await n.resolveRelation(a);i!=null&&(r[l]=await S(r,a,i,n.fetchRelated,o.scope));}return r}function Ke(e,t,n,o){if(!o?.relations?.length||!t.model.relations)return e;let r={...e};for(let l of o.relations){let a=t.model.relations[l];if(!a)continue;let i=n.resolveRelation(a);i!=null&&(r[l]=E(r,a,i,n.fetchRelated,o.scope));}return r}export{Be as batchLoadRelations,Ve as loadRelationsForItem,Ke as loadRelationsForItemSync,S as resolveRelationValueAsync,E as resolveRelationValueSync};
|
package/package.json
CHANGED
package/dist/chunk-O6VQTREM.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import {e as e$3,f as f$1}from'./chunk-P7HU2KIE.js';import {e as e$2}from'./chunk-H3VBYIDA.js';import {a as a$4,b as b$3}from'./chunk-CWQSQUV4.js';import {a as a$5,b as b$4}from'./chunk-SDNXN7M5.js';import {i,a as a$3}from'./chunk-HYXDMJ4K.js';import {h as h$1}from'./chunk-WBHWKOTP.js';import {a}from'./chunk-L5CVVJQH.js';import {f,b,N,P,d as d$1,S,R,c,e as e$1,p,y}from'./chunk-A27HDYSF.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {a as a$1,b as b$5}from'./chunk-TLI3TRUA.js';import {j,e,d,b as b$2,h,c as c$1,a as a$2,g}from'./chunk-XR6JRDGX.js';import {z}from'zod';import {stream}from'hono/streaming';var no=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["bulkPatch","patch","/bulk"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"],["versionHistory","get","/:id/versions"],["versionCompare","get","/:id/versions/compare"],["versionRead","get","/:id/versions/:version"],["versionRollback","post","/:id/versions/:version/rollback"]];var Se="createdAt",Oe="updatedAt";function ie(n){return n?n===true?{enabled:true,createdAt:Se,updatedAt:Oe}:{enabled:true,createdAt:n.createdAt??Se,updatedAt:n.updatedAt??Oe}:{enabled:false,createdAt:Se,updatedAt:Oe}}function A(n,e={}){let{includePrimaryKeys:t=true}=e,o=new Set;if(t)for(let s of n.primaryKeys)o.add(s);let r=ie(n.timestamps);return r.enabled&&(o.add(r.createdAt),o.add(r.updatedAt)),[...o]}function Lt(n){return n!=null&&n!==""}function Qe(n,e,t,o){let r={...n},s=e.primaryKeys[0];if(!Lt(r[s])){let l=e.id;if(typeof l=="function")r[s]=l();else if(l==="database"){if(t==="memory")throw new j("MemoryAdapter does not support id:'database' (no database to generate the key)");delete r[s];}else r[s]=o?o():crypto.randomUUID();}let i=ie(e.timestamps);if(i.enabled){let l=Date.now();i.createdAt in n||(r[i.createdAt]=l),i.updatedAt in n||(r[i.updatedAt]=l);}return r}function We(n,e){let t=ie(e.timestamps);return t.enabled?{...n,[t.updatedAt]:Date.now()}:{...n}}function Ge(n,e){if(e==="memory"&&n.id==="database")throw new j("MemoryAdapter does not support id:'database' (no database to generate the key)")}function Ye(n,e){let t={...n};for(let o of A(e))delete t[o];return t}var Ut=new Set(["P2002","SQLITE_CONSTRAINT_UNIQUE","SQLITE_CONSTRAINT","23505","ER_DUP_ENTRY",1062,"1062"]),zt=/UNIQUE constraint failed|duplicate key value violates unique constraint|Duplicate entry/i;function Bt(n){if(!n||typeof n!="object")return false;let{code:e,message:t}=n;return (typeof e=="string"||typeof e=="number")&&Ut.has(e)?true:typeof t=="string"&&zt.test(t)}function*qt(n,e=8){for(let t=n,o=0;o<e&&t!=null&&typeof t=="object";o++)yield t,t=t.cause;}function ke(n){for(let e$1 of qt(n))if(Bt(e$1))return new e("Unique constraint violation");return null}function H(n){throw ke(n)??n}function Ht(n){return btoa(String(n))}function lo(n){try{return atob(n)}catch{return null}}function co(n){let{rows:e,limit:t,totalCount:o,cursorField:r,cursorApplied:s}=n,i=e.length>t,l=i?e.slice(0,t):e,d=l[l.length-1];return {items:l,result_info:{page:0,per_page:t,total_count:o,has_next_page:i,has_prev_page:s,next_cursor:i&&d!==void 0?Ht(d[r]):void 0}}}async function ae(n,e){if(!e||Object.keys(e).length===0)return n;let t={...n};for(let[o,r]of Object.entries(e))try{let s=await r.compute(n);t[o]=s;}catch{t[o]=void 0;}return t}async function Je(n,e){return !e||Object.keys(e).length===0?n:Promise.all(n.map(t=>ae(t,e)))}function oe(n,e){let t={},o={};for(let[r,s]of Object.entries(n))e.includes(r)&&s!==void 0?o[r]=s:t[r]=s;return {mainData:t,nestedData:o}}function pe(n){if(Array.isArray(n))return true;if(typeof n=="object"&&n!==null){let e=Object.keys(n),t=["create","update","delete","connect","disconnect","set"];return !e.some(o=>t.includes(o))}return false}function fo(n){let e=n.split(":");if(e.length<2)return null;let t=e[0].toLowerCase();return f.map(s=>s.toLowerCase()).includes(t)?{operation:t==="countdistinct"?"countDistinct":t,field:e[1],alias:e[2]}:null}function Xe(n){let e=[],t={};for(let a of f){let p=n[a];if(p){let u=Array.isArray(p)?p:[p];for(let m of u)typeof m=="string"&&e.push({operation:a,field:m==="true"||m===""?"*":m});}}let o;if(n.groupBy){let a=n.groupBy;typeof a=="string"?o=a.split(",").map(p=>p.trim()):Array.isArray(a)&&(o=a.filter(p=>typeof p=="string"));}let r;for(let[a,p]of Object.entries(n)){let u=a.match(/^having\[(\w+)\]\[(\w+)\]$/);if(u){let[,m,f]=u;r||(r={}),r[m]||(r[m]={}),r[m][f]=p;}}let s=typeof n.orderBy=="string"?n.orderBy:void 0,i=n.orderDirection==="desc"?"desc":"asc",l=typeof n.limit=="string"?Number.parseInt(n.limit,10):void 0,d=typeof n.offset=="string"?Number.parseInt(n.offset,10):void 0,c=[...f,"groupBy","orderBy","orderDirection","limit","offset"];for(let[a,p]of Object.entries(n))!c.includes(a)&&!a.startsWith("having[")&&(t[a]=p);return {aggregations:e,groupBy:o,filters:Object.keys(t).length>0?t:void 0,having:r,orderBy:s,orderDirection:i,limit:l,offset:d}}function et(n){return n?n===true?{enabled:true,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}:{enabled:true,field:n.field??"deletedAt",allowQueryDeleted:n.allowQueryDeleted??true,queryParam:n.queryParam??"withDeleted"}:{enabled:false,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}}function re(n,e,t){return t.enabled&&e[t.field]!=null?{...n,[t.field]:null}:n}var $t=new Set(["a","an","and","are","as","at","be","by","for","from","has","he","in","is","it","its","of","on","or","that","the","to","was","were","will","with"]);function ot(n,e=true){if(!n||typeof n!="string")return [];let t=n.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(Boolean);return e?t.filter(o=>!$t.has(o)&&o.length>1):t}function rt(n,e){return e==="phrase"?[n.toLowerCase().trim()]:ot(n)}function Kt(n,e){return e.length===0?0:e.filter(o=>o===n||o.includes(n)).length/e.length}function nt(n,e,t,o){if(e.length===0)return {score:0,matchedFields:[]};let r=0,s=0,i=[];for(let[d,c]of Object.entries(t)){let a=n[d];if(a==null)continue;let p=c.weight??1;s+=p;let u;c.type==="array"&&Array.isArray(a)?u=a.join(" "):u=String(a);let m=ot(u,false),f=u.toLowerCase(),h=0,S=0;if(o==="phrase"){let g=e[0];f.includes(g)&&(h=1,S=1);}else {for(let g of e){let R=Kt(g,m);R>0?(S++,h+=R):f.includes(g)&&(S++,h+=.5/e.length);}e.length>0&&(h=h/e.length);}o==="all"&&S<e.length&&(h=0),h>0&&(i.push(d),r+=h*p);}return {score:s>0?Math.min(1,r/s):0,matchedFields:i}}function st(n,e,t,o="mark",r=150){if(n==null)return [];let s;if(Array.isArray(n)?s=n.join(" "):s=String(n),!s||e.length===0)return [];let i=[],l=s.toLowerCase();if(t==="phrase"){let d=e[0],c=l.indexOf(d);if(c!==-1){let a=tt(s,c,d.length,r,o);a&&i.push(a);}}else {let d=[];for(let a of e){let p=0;for(;p<l.length;){let u=l.indexOf(a,p);if(u===-1)break;d.push({start:u,length:a.length}),p=u+1;}}d.sort((a,p)=>a.start-p.start);let c=new Set;for(let a of d){if(Array.from(c).some(m=>Math.abs(m-a.start)<r))continue;let u=tt(s,a.start,a.length,r,o);if(u&&(i.push(u),c.add(a.start)),i.length>=3)break}}return i}function tt(n,e,t,o,r){let s=Math.floor(o/2),i=Math.max(0,e-s),l=Math.min(n.length,e+t+s);if(i>0){let a=n.indexOf(" ",i);a!==-1&&a<e&&(i=a+1);}if(l<n.length){let a=n.lastIndexOf(" ",l);a!==-1&&a>e+t&&(l=a);}let d=n.slice(i,l);return i>0&&(d="..."+d),l<n.length&&(d=d+"..."),Qt(d,[n.slice(e,e+t)],r)}function Qt(n,e,t){let o=n,r=n.toLowerCase(),s=[...e].sort((i,l)=>l.length-i.length);for(let i of s){let l=i.toLowerCase(),d=0,c="",a=0;for(;a<r.length;){let p=r.indexOf(l,a);if(p===-1)break;c+=o.slice(d,p),c+=`<${t}>${o.slice(p,p+i.length)}</${t}>`,d=p+i.length,a=d;}c&&(c+=o.slice(d),o=c);}return o}function it(n,e){if(!n)return Object.keys(e);let t=n.split(",").map(r=>r.trim()).filter(Boolean),o=Object.keys(e);return t.filter(r=>o.includes(r))}function at(n,e){let t={};for(let o of n)t[o]={weight:e?.[o]??1};return t}function dt(n){return n==="all"||n==="phrase"?n:"any"}function xe(n){if(n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(xe);let e={};for(let t of Object.keys(n).sort())e[t]=xe(n[t]);return e}async function de(n){let e=JSON.stringify(xe(n)),t=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",t);return `"${Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("").substring(0,32)}"`}function lt(n,e){return n?n==="*"?true:n.split(",").map(t=>t.trim()).includes(e):false}function ct(n,e){return !n||n==="*"?true:n.split(",").map(t=>t.trim()).includes(e)}function ut(n,e){return n==="in"||n==="nin"||n==="between"?e.split(",").map(t=>t.trim()):n==="null"?e.toLowerCase()==="true":e}function Ro(n){let e=n.match(/^\[([a-z]+)\](.*)$/);if(e&&b(e[1])){let t=e[1];return {operator:t,value:ut(t,e[2])}}return {operator:"eq",value:n}}function ne(n,e){let t=[],o={},{filterFields:r=[],filterConfig:s={},searchFields:i=[],searchParamName:l="search",sortFields:d=[],defaultSort:c,defaultPerPage:a=20,maxPerPage:p=100,cursorPaginationEnabled:u=false,cursorField:m,softDeleteQueryParam:f="withDeleted",allowedIncludes:h=[],fieldSelectionEnabled:S=false,allowedSelectFields:g=[],blockedSelectFields:R=[],alwaysIncludeFields:j=[],defaultSelectFields:N=[]}=e,J={};for(let C of r)J[C]=["eq"];Object.assign(J,s);for(let[C,Me]of Object.entries(n)){if(Me==null)continue;let D=String(Me);if(u&&C==="cursor"){o.cursor=D;continue}if(u&&C==="limit"){o.limit=Math.min(p,Math.max(1,Number.parseInt(D,10)||a));continue}if(C==="page"){o.page=Math.max(1,Number.parseInt(D,10)||1);continue}if(C==="per_page"){o.per_page=Math.min(p,Math.max(1,Number.parseInt(D,10)||a));continue}if(C==="sort"){(d.length===0||d.includes(D))&&(o.order_by=D);continue}if(C==="order"){(D==="asc"||D==="desc")&&(o.order_by_direction=D);continue}if(C===l&&i.length>0){o.search=D;continue}if(C===f){o.withDeleted=D.toLowerCase()==="true";continue}if(C==="onlyDeleted"){o.onlyDeleted=D.toLowerCase()==="true";continue}if(C==="include"){let X=D.split(",").map(U=>U.trim()).filter(Boolean);h&&h.length>0?o.include=X.filter(U=>h.includes(U)):o.include=X;continue}if(C==="fields"&&S){let U=D.split(",").map(se=>se.trim()).filter(Boolean);g.length>0&&(U=U.filter(se=>g.includes(se))),R.length>0&&(U=U.filter(se=>!R.includes(se))),j.length>0&&(U=[...new Set([...j,...U])]),o.fields=U;continue}let Re=C.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(Re){let X=Re[1],U=Re[2];J[X]?.includes(U)&&t.push({field:X,operator:U,value:ut(U,D)});continue}J[C]&&t.push({field:C,operator:"eq",value:D});}if(o.page||(o.page=1),o.per_page||(o.per_page=a),!o.order_by&&c?.field&&(o.order_by=c.field),o.order_by_direction||(o.order_by_direction=c?.order??"asc"),u&&(o.cursor!==void 0||o.limit!==void 0)&&(o.order_by=m??"id",o.order_by_direction="asc"),S&&!o.fields&&N.length>0){let C=[...N];j.length>0&&(C=[...new Set([...j,...C])]),o.fields=C;}return {filters:t,options:o}}function _(n,e=[]){if(e.length===0)return n;let t=new Set(Object.keys(n.shape)),o=e.filter(s=>t.has(s));if(o.length===0)return n;let r=Object.fromEntries(o.map(s=>[s,true]));return n.omit(r)}function So(n,e={},t=[],o=[],r=[]){let{allowedFields:s=[],blockedFields:i=[],alwaysIncludeFields:l=[],defaultFields:d=[],allowComputedFields:c=true,allowRelationFields:a=true}=e;if(!n||typeof n!="string"||n.trim()==="")return d.length>0?{fields:[...new Set([...l,...d])],isActive:false}:{fields:[],isActive:false};let p=n.split(",").map(h=>h.trim()).filter(Boolean),u=new Set;for(let h of t)(s.length===0||s.includes(h))&&(i.includes(h)||u.add(h));if(c)for(let h of o)(s.length===0||s.includes(h))&&(i.includes(h)||u.add(h));if(a)for(let h of r)(s.length===0||s.includes(h))&&(i.includes(h)||u.add(h));let m=p.filter(h=>u.has(h));return {fields:[...new Set([...l,...m])],isActive:true}}function je(n,e){if(!e.isActive||e.fields.length===0)return n;let t={};for(let o of e.fields)o in n&&(t[o]=n[o]);return t}function pt(n,e){return !e.isActive||e.fields.length===0?n:n.map(t=>je(t,e))}var mt="__honoCrudResolvedSchema:";function Wt(n){return typeof n.getBodySchema=="function"}var k=class extends p{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=h$1(this._meta.model.audit,void 0,this.context??void 0)),this._auditLogger}getAuditConfig(){return a(this._meta.model.audit)}isAuditEnabled(){return this.getAuditConfig().enabled}getAuditUserId(){let e=this.getAuditConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?a$1(this.context,a$2.userId):void 0}getVersionManager(){return this._versionManager||(this._versionManager=i(this._meta.model.versioning,this._meta.model.tableName,void 0,this.context??void 0)),this._versionManager}getVersioningConfig(){return a$3(this._meta.model.versioning,this._meta.model.tableName)}isVersioningEnabled(){return this.getVersioningConfig().enabled}getVersioningUserId(){let e=this.getVersioningConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?a$1(this.context,a$2.userId):void 0}getSoftDeleteConfig(){return et(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return a$4(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,t,o){return Qe(e,this._meta.model,t,o)}applyManagedUpdateFields(e){return We(e,this._meta.model)}assertIdStrategySupported(e){Ge(this._meta.model,e);}getTimestampsConfig(){return ie(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return b$3(this.context,e)}getRelationScope(e=false){return {tenantId:this.getTenantId(),includeDeleted:e}}getTenantScopeFilter(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();return t==null?void 0:{field:e.field,value:t}}applyTenantScope(e){let t=this.validateTenantId();t&&e.filters.push({field:this.getMultiTenantConfig().field,operator:"eq",value:t});}applyTenantScopeToAggregateFilters(e){let t=this.validateTenantId();return t?{...e??{},[this.getMultiTenantConfig().field]:t}:e}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();if(!t&&e.required)throw new b$2(e.errorMessage,400,"TENANT_REQUIRED");return t}injectTenantId(e){let t=this.getMultiTenantConfig();if(!t.enabled)return e;let o=this.getTenantId();return o?{...e,[t.field]:o}:e}async emitEvent(e,t){let o=e$2(this.context??void 0);o&&await o.emit({type:e,table:this._meta.model.tableName,recordId:t.recordId,data:t.data??null,previousData:t.previousData,userId:this.getAuditUserId(),tenantId:this.context?this.getTenantId():void 0,organizationId:this.context?a$1(this.context,a$2.organizationId):void 0,timestamp:new Date().toISOString(),metadata:t.metadata});}async encryptOnWrite(e){let t=this._meta.model.fieldEncryption;return t?await e$3(e,t.fields,t.keyProvider):e}async decryptOnRead(e){let t=this._meta.model.fieldEncryption;return t?await f$1(e,t.fields,t.keyProvider):e}applyProfile(e){let t=this._meta.model.serializationProfile;return t?a$5(e,t):e}applyProfileToArray(e){let t=this._meta.model.serializationProfile;return t?b$4(e,t):e}transform(e){return e}async finalizeRecord(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await ae(r,o.computedFields));let s=o.serializer?o.serializer(r):r,i=this.applyProfile(s),l=this.transform(i);return t?.isActive&&t.fields.length>0?je(l,t):l}async finalizeArray(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await Je(r,o.computedFields));let s=o.serializer?r.map(d=>o.serializer(d)):r,l=this.applyProfileToArray(s).map(d=>this.transform(d));return t?.isActive&&t.fields.length>0?pt(l,t):l}getRecordId(e){if(e===null||typeof e!="object")return null;let t=this._meta.model.primaryKeys[0],o=e[t];return typeof o=="string"||typeof o=="number"?o:null}getParentId(e){return this.getRecordId(e)}getPolicies(){if(this.context){let e=a$1(this.context,y);if(e)return e}return this._meta.model.policies}buildPolicyContext(){let e=this.context;return {user:e?a$1(e,a$2.user):void 0,userId:e?a$1(e,a$2.userId):void 0,tenantId:e?a$1(e,a$2.tenantId):void 0,organizationId:e?a$1(e,a$2.organizationId):void 0,request:e?.req?.raw??new Request("http://localhost/")}}async applyReadPolicy(e){let t=this.getPolicies();if(!t)return e;let o=this.buildPolicyContext();if(t.read&&!await t.read(o,e))return null;if(t.fields){let r=t.fields(o,e);return {...e,...r}}return e}async applyReadPolicyToArray(e){if(!this.getPolicies())return e;let o=[];for(let r of e){let s=await this.applyReadPolicy(r);s!==null&&o.push(s);}return o}async applyWritePolicy(e){let t=this.getPolicies();if(!t?.write)return;if(!await t.write(this.buildPolicyContext(),e))throw new g("Forbidden by policy")}applyReadPushdown(e){let t=this.getPolicies();if(!t?.readPushdown)return;let o=t.readPushdown(this.buildPolicyContext());o&&o.length>0&&e.filters.push(...o);}buildHookContext(){let e=this.context;return {db:{tx:this._tx},request:e?.req?.raw,tenantId:e?this.getTenantId():void 0,organizationId:e?a$1(e,a$2.organizationId):void 0,userId:e?a$1(e,a$2.userId):void 0,agentId:e?a$1(e,a$2.agentId):void 0,agentRunId:e?a$1(e,a$2.agentRunId):void 0}}getModelSchema(){if(this.context&&this._meta.model.resolveSchema){let e=a$1(this.context,mt+this._meta.model.tableName);if(e)return e}return this._meta.model.schema}async resolveModelSchema(){let e=this._meta.model.resolveSchema;if(!e||!this.context)return this._meta.model.schema;let t=mt+this._meta.model.tableName,o=a$1(this.context,t);if(o)return o;let r={tenantId:a$1(this.context,a$2.tenantId),organizationId:a$1(this.context,a$2.organizationId),request:this.context.req?.raw,env:this.context.env},s;try{s=await e(r);}catch(i){throw new b$2(i instanceof Error?i.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",i instanceof Error?{cause:i.message}:void 0)}return b$5(this.context,t,s),s}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&Wt(this)){let t=e.body;try{t=await this.context.req.json();}catch{}let r=this.getBodySchema().safeParse(t);if(!r.success)throw c$1.fromZodError(r.error);e.body=r.data;}return e}};var ht=class extends k{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,t=A(this._meta.model),o=this.getMultiTenantConfig();o.enabled&&t.push(o.field),this._meta.fields?e=this._meta.fields:e=_(this.getModelSchema(),t);let r=this.getNestedWritableRelations();if(r.length===0)return e;let s={...e.shape};for(let i of r){let l=this._meta.model.relations?.[i];if(!l?.schema)continue;let d=["id",l.foreignKey],c=_(l.schema,d);l.type==="hasMany"?s[i]=z.array(c).optional():s[i]=c.optional();}return z.object(s)}getNestedWritableRelations(){if(this.allowNestedCreate.length>0)return this.allowNestedCreate;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>o.nestedWrites?.allowCreate===true).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return oe(e,t)}getSchema(){let e=this.getBodySchema();return N({request:{body:{content:{"application/json":{schema:e}},required:true}},responses:{201:{description:"Resource created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:P("Validation error")}},this.schema)}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t){return e}async after(e,t){return e}transform(e){return e}async createNested(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override createNested() in your adapter.`),[]}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let s=this.buildHookContext();r=await this.before(r,s),r=await this.encryptOnWrite(r),r=await this.create(r,s.db.tx).catch(H),r=await this.decryptOnRead(r);let i=this.getParentId(r),l={};if(Object.keys(o).length>0&&i!==null)for(let[c,a]of Object.entries(o)){if(a==null)continue;let p=this._meta.model.relations?.[c];if(!p)continue;let u=await this.createNested(i,c,p,a);l[c]=u;}if(Object.keys(l).length>0){let c={};for(let[a,p]of Object.entries(l)){let u=this._meta.model.relations?.[a];u&&(u.type==="hasMany"?c[a]=p:c[a]=p[0]||null);}r={...r,...c};}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(r,s))):r=await this.after(r,s),this.isAuditEnabled()&&i!==null){let c=this.getAuditLogger();this.runAfterResponse(c.logCreate(this._meta.model.tableName,i,r,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("created",{recordId:i,data:r}));let d=await this.finalizeRecord(r);return this.success(d,201)}};function he(n,e,t){let o=e.model.relations;if(!o||t.length===0)return n;let r={};for(let s of t){let i=o[s],l=i?.schema;l&&(r[s]=i.type==="hasMany"?z.array(l).optional():l.nullable().optional());}return Object.keys(r).length>0?n.extend(r):n}var ft=class extends k{lookupField="id";lookupFields;additionalFilters;etagEnabled=false;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){let e={};if(this.additionalFilters?.length)for(let t of this.additionalFilters)e[t]=z.string().optional();if(this.allowedIncludes.length>0&&(e.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let t=this.getAvailableSelectFields();e.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${t.join(", ")}`});}if(Object.keys(e).length!==0)return z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=this.getQuerySchema();return N({request:{params:this.getParamsSchema(),...e&&{query:e}},responses:{200:{description:"Resource retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:he(this.getModelSchema(),this._meta,this.allowedIncludes)})}}},404:P("Resource not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async getIncludeOptions(){let{query:e}=await this.getValidatedData(),t=e?.include;if(!t||typeof t!="string")return {relations:[]};let o=t.split(",").map(r=>r.trim()).filter(Boolean);return this.allowedIncludes.length>0?{relations:o.filter(r=>this.allowedIncludes.includes(r))}:{relations:o}}async getFieldSelection(){if(!this.fieldSelectionEnabled)return {fields:[],isActive:false};let{query:e}=await this.getValidatedData(),t=e?.fields;if(!t||typeof t!="string"||t.trim()==="")return this.defaultSelectFields.length>0?{fields:[...new Set([...this.alwaysIncludeFields,...this.defaultSelectFields])],isActive:true}:{fields:[],isActive:false};let o=t.split(",").map(i=>i.trim()).filter(Boolean),r=new Set(this.getAvailableSelectFields()),s=o.filter(i=>r.has(i));return this.alwaysIncludeFields.length>0&&(s=[...new Set([...this.alwaysIncludeFields,...s])]),{fields:s,isActive:true}}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters(),r=await this.getIncludeOptions();r&&(r.scope=this.getRelationScope());let s=await this.getFieldSelection();if(e){let c=this.getMultiTenantConfig();o[c.field]=e;}let i=await this.read(t,o,r);if(!i)throw new d(this._meta.model.tableName,t);i=await this.decryptOnRead(i);let l=await this.applyReadPolicy(i);if(l===null)throw new d(this._meta.model.tableName,t);i=l,i=await this.after(i);let d$1=await this.finalizeRecord(i,s);if(this.etagEnabled){let c=await de(d$1),a=this.getContext(),p=a.req.header("If-None-Match");if(lt(p,c))return new Response(null,{status:304,headers:{ETag:c}});a.header("ETag",c);}return this.success(d$1)}};var gt=class extends k{lookupField="id";lookupFields;additionalFilters;allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];etagEnabled=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields.partial();else {let r=A(this._meta.model);this.blockedUpdateFields&&(r=[...r,...this.blockedUpdateFields]);let s=_(this.getModelSchema(),r);if(this.allowedUpdateFields){let i={};for(let l of this.allowedUpdateFields)i[l]=true;s=s.pick(i);}e=s.partial();}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let i=s.schema,l=z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()}).optional();o[r]=l;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return oe(e,t)}getSchema(){return N({request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:P("Validation error"),404:P("Resource not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getObject(){let{body:e}=await this.getValidatedData();return e}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){return e}async after(e,t,o){return t}transform(e){return e}async findExisting(e,t,o){return null}async processNestedWrites(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let g=this.getMultiTenantConfig();o[g.field]=e;}let r=await this.getObject(),{mainData:s,nestedData:i}=this.extractNestedData(r),l=this.getPolicies(),d$1=await this.findExisting(t,o,this._tx);if(d$1&&l?.write&&await this.applyWritePolicy(d$1),this.etagEnabled&&d$1){let g=this.getContext().req.header("If-Match");if(g){let R=await de(d$1);if(!ct(g,R))return this.error("Resource has been modified by another request","CONFLICT",409)}}let c;if(this.isVersioningEnabled()&&d$1){let g=this.getVersionManager(),R=this.getParentId(d$1);R!==null&&(c=await g.saveVersion(R,d$1,void 0,this.getVersioningUserId()));}let a=s;if(this.isVersioningEnabled()&&c!==void 0){let g=this.getVersioningConfig().field;a[g]=c;}let p=this.buildHookContext();a=await this.before(a,p),a=await this.encryptOnWrite(a);let u=await this.update(t,a,o,p.db.tx);if(!u)throw new d(this._meta.model.tableName,t);u=await this.decryptOnRead(u);let m=this.getParentId(u),f={};if(Object.keys(i).length>0&&m!==null)for(let[g,R]of Object.entries(i)){if(R==null)continue;let j=this._meta.model.relations?.[g];if(!j)continue;let N;pe(R)?N={create:R}:N=R;let J=await this.processNestedWrites(m,g,j,N);f[g]=J;}if(Object.keys(f).length>0)for(let[g,R]of Object.entries(f)){let j=this._meta.model.relations?.[g];j&&(j.type==="hasMany"?u[g]=[...R.created,...R.updated]:u[g]=R.created[0]||R.updated[0]||null);}let h=d$1??u;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(h,u,p)));else {let g=await this.after(h,u,p);g!=null&&(u=g);}if(this.isAuditEnabled()&&m!==null&&d$1){let g=this.getAuditLogger();this.runAfterResponse(g.logUpdate(this._meta.model.tableName,m,d$1,u,this.getAuditUserId()));}m!==null&&this.runAfterResponse(this.emitEvent("updated",{recordId:m,data:u,previousData:d$1??void 0}));let S=await this.finalizeRecord(u);if(this.etagEnabled){let g=await de(S);this.getContext().header("ETag",g);}return this.success(S)}};var bt=class extends k{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";includeCascadeResults=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getCascadeRelations(e){let t=this._meta.model.relations;return t?Object.entries(t).filter(([o,r])=>{let s=r.cascade?.[e];return s&&s!=="noAction"}).map(([o,r])=>({name:o,config:r,action:r.cascade[e]})):[]}getSchema(){let e=this.includeCascadeResults?z.object({deleted:z.literal(true),cascade:z.object({deleted:z.record(z.string(),z.number()),nullified:z.record(z.string(),z.number())}).optional()}):z.object({deleted:z.literal(true)});return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:P("Resource not found"),409:{description:"Cannot delete - related records exist (restrict)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.object({relation:z.string(),count:z.number()}).optional()})})}}}}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){}async countRelated(e,t,o,r){return b$1().warn(`countRelated not implemented for ${t}. Override in your adapter for restrict cascade to work.`),0}async deleteRelated(e,t,o,r){return b$1().warn(`deleteRelated not implemented for ${t}. Override in your adapter for cascade delete to work.`),0}async nullifyRelated(e,t,o,r){return b$1().warn(`nullifyRelated not implemented for ${t}. Override in your adapter for setNull cascade to work.`),0}async processCascade(e,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r),i={deleted:{},nullified:{}};for(let{name:l,config:d,action:c}of s)if(c==="cascade"){let a=await this.deleteRelated(e,l,d,o);a>0&&(i.deleted[l]=a);}else if(c==="setNull"){let a=await this.nullifyRelated(e,l,d,o);a>0&&(i.nullified[l]=a);}return i}async checkRestrictConstraints(e$1,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r);for(let{name:i,config:l,action:d}of s)if(d==="restrict"){let c=await this.countRelated(e$1,i,l,o);if(c>0)throw new e(`Cannot delete: ${c} related ${i} record(s) exist. Remove them first or change the cascade configuration.`,{relation:i,count:c})}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let p=this.getMultiTenantConfig();o[p.field]=e;}let r=this.isSoftDeleteEnabled(),s=await this.findForDelete(t,o,this._tx);if(!s)throw new d(this._meta.model.tableName,t);let i=this.getParentId(s);i!==null&&await this.checkRestrictConstraints(i,r),await this.applyWritePolicy(s);let l=this.buildHookContext();if(await this.before(t,l),!await this.delete(t,o,l.db.tx))throw new d(this._meta.model.tableName,t);let c;if(i!==null&&(c=await this.processCascade(i,r)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(s,l))):await this.after(s,l),this.isAuditEnabled()&&i!==null){let p=this.getAuditLogger();this.runAfterResponse(p.logDelete(this._meta.model.tableName,i,s,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("deleted",{recordId:i,previousData:s}));let a={deleted:true};if(this.includeCascadeResults&&c){let p=Object.keys(c.deleted).length>0,u=Object.keys(c.nullified).length>0;(p||u)&&(a.cascade=c);}return this.success(a)}};var fe=class extends k{filterFields=[];filterConfig;searchFields=[];searchParamName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;supportsCursorPagination=false;cursorField;isCursorPaginationActive(){return this.cursorPaginationEnabled&&this.supportsCursorPagination}allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getQuerySchema(){let e={page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(e.sort=z.enum(this.sortFields).optional().meta({description:"Field to sort by"}),e.order=z.enum(d$1).optional().meta({description:"Sort direction (asc or desc)"})),this.searchFields.length>0&&(e[this.searchParamName]=z.string().optional());for(let o of this.filterFields)e[o]=z.string().optional();if(this.filterConfig)for(let[o,r]of Object.entries(this.filterConfig)){for(let s of r)e[`${o}[${s}]`]=z.string().optional();e[o]=z.string().optional();}let t=this.getSoftDeleteConfig();if(t.enabled&&t.allowQueryDeleted&&(e[t.queryParam]=z.enum(["true","false"]).optional(),e.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(e.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let o=this.getAvailableSelectFields();e.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${o.join(", ")}`});}return this.isCursorPaginationActive()&&(e.cursor=z.string().optional().meta({description:"Opaque cursor for fetching the next page. During a cursor walk, results are ordered by the cursor field ascending and sort/order are ignored."}),e.limit=z.string().optional().meta({description:"Number of items to return (cursor pagination)"})),z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e={page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),has_next_page:z.boolean(),has_prev_page:z.boolean()};return this.isCursorPaginationActive()&&(e.next_cursor=z.string().optional()),N({request:{query:this.getQuerySchema()},responses:{200:{description:"List of resources",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(he(this.getModelSchema(),this._meta,this.allowedIncludes)),result_info:z.object(e)})}}},400:P("Validation error")}},this.schema)}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:this.searchFields,searchParamName:this.searchParamName,sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,cursorPaginationEnabled:this.isCursorPaginationActive(),cursorField:this.cursorField,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return ne(e||{},o)}async after(e){return e}transform(e){return e}async handle(){if(this.cursorPaginationEnabled&&!this.supportsCursorPagination)throw new j("cursorPaginationEnabled is true but this adapter's List endpoint does not implement cursor pagination (supportsCursorPagination is false). Use an adapter List endpoint that supports it, or disable cursorPaginationEnabled.");this.validateTenantId();let e=await this.getFilters();this.applyTenantScope(e),this.applyReadPushdown(e);let t=await this.list(e),o=await Promise.all(t.result.map(d=>this.decryptOnRead(d))),r=await this.applyReadPolicyToArray(o),s=await this.after(r),i=this.fieldSelectionEnabled&&e.options.fields&&e.options.fields.length>0?{fields:e.options.fields,isActive:true}:void 0,l=await this.finalizeArray(s,i);return this.successPaginated(l,t.result_info)}};var yt=class extends k{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...A(this._meta.model),...this.excludeFromClone];return _(this.getModelSchema(),e).partial()}getSchema(){return N({request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:false}},responses:{201:{description:"Resource cloned successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:P("Source resource not found"),409:P("Unique-constraint violation (e.g. natural-key collision)")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getOverrides(){let{body:e}=await this.getValidatedData();return e||{}}async before(e){return e}async after(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getOverrides(),r={};if(e){let a=this.getMultiTenantConfig();r[a.field]=e;}let s=await this.findSource(t,r);if(!s)throw new d(this._meta.model.tableName,t);let i=Ye(s,this._meta.model);for(let a of this.excludeFromClone)delete i[a];Object.assign(i,o);let l=await this.before(i),d$1=await this.createClone(l).catch(H);d$1=await this.after(d$1);let c=await this.finalizeRecord(d$1);return this.success(c,201)}};var wt=class extends k{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:P("Soft delete not enabled or record not deleted"),404:P("Resource not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new b$2("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getAdditionalFilters();await this.before(e);let o=await this.restore(e,t);if(!o)throw new d(this._meta.model.tableName,e);this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(o))):o=await this.after(o);let r=this.getRecordId(o);if(this.isAuditEnabled()&&r!==null){let i=this.getAuditLogger();this.runAfterResponse(i.logRestore(this._meta.model.tableName,r,o,this.getAuditUserId()));}r!==null&&this.runAfterResponse(this.emitEvent("restored",{recordId:r,data:o}));let s=await this.finalizeRecord(o);return this.success(s)}};var Mt=class extends k{upsertKeys;useNativeUpsert=false;createOnlyFields;updateOnlyFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields;else {let r=this.getUpsertKeys(),s=A(this._meta.model,{includePrimaryKeys:false});for(let d of this._meta.model.primaryKeys)r.includes(d)||s.push(d);let i=_(this.getModelSchema(),s),l={};for(let[d,c]of Object.entries(i.shape))r.includes(d)?l[d]=c:l[d]=c.optional();e=z.object(l);}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let i=s.schema,l=z.union([s.type==="hasMany"?z.array(i.partial()):i.partial(),z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),upsert:z.union([i.partial(),z.array(i.partial())]).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()})]).optional();o[r]=l;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return oe(e,t)}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(false)})}}},201:{description:"Resource created (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(true)})}}},400:P("Validation error")}},this.schema)}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t,o){return e}async beforeCreate(e,t){return e}async beforeUpdate(e,t,o){return e}async after(e,t,o){return e}async nativeUpsert(e,t){return b$1().warn("Native upsert not implemented for this adapter. Falling back to find-then-insert/update pattern."),this.performStandardUpsert(e,t)}async performStandardUpsert(e,t){let o=await this.findExisting(e,t);if(o){let r={...e};if(this.createOnlyFields)for(let i of this.createOnlyFields)delete r[i];return r=await this.beforeUpdate(r,o,t),r=re(r,o,this.getSoftDeleteConfig()),{data:await this.update(o,r,t),created:false}}else {let r={...e};if(this.updateOnlyFields)for(let i of this.updateOnlyFields)delete r[i];return r=await this.beforeCreate(r,t),{data:await this.create(r,t),created:true}}}async upsert(e,t){return this.useNativeUpsert?this.nativeUpsert(e,t):this.performStandardUpsert(e,t)}async processNestedWrites(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let s=await this.findExisting(r),i=!s;r=await this.before(r,i);let l=await this.upsert(r).catch(H),d=l.data,c=this.getParentId(d),a={};if(Object.keys(o).length>0&&c!==null)for(let[u,m]of Object.entries(o)){if(m==null)continue;let f=this._meta.model.relations?.[u];if(!f)continue;let h;pe(m)?h={create:m}:h=m;let S=await this.processNestedWrites(c,u,f,h);a[u]=S;}if(Object.keys(a).length>0)for(let[u,m]of Object.entries(a)){let f=this._meta.model.relations?.[u];f&&(f.type==="hasMany"?d[u]=[...m.created,...m.updated]:d[u]=m.created[0]||m.updated[0]||null);}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(d,l.created))):d=await this.after(d,l.created),this.isAuditEnabled()&&c!==null){let u=this.getAuditLogger();this.runAfterResponse(u.logUpsert(this._meta.model.tableName,c,d,s,l.created,this.getAuditUserId()));}let p=await this.finalizeRecord(d);return this.json({success:true,result:p,created:l.created},l.created?201:200)}};var Rt=class extends k{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:_(this.getModelSchema(),A(this._meta.model));return z.object({items:z.array(e).min(1).max(this.maxBatchSize)})}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{201:{description:"Resources created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number()})})}}},207:{description:"Partial success (some items failed)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:P("Validation error")}},this.schema)}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}async before(e,t,o){return e}async after(e,t,o){return e}transform(e){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let c=0;c<e.length;c++)try{let a=await this.before(e[c],c);o.push(a);}catch(a){if(this.stopOnError)throw a;t.push({index:c,error:a instanceof Error?a.message:String(a)});}let r=await this.batchCreate(o).catch(H),s=[];for(let c=0;c<r.length;c++)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(r[c],c))),s.push(r[c])):s.push(await this.after(r[c],c));}catch(a){if(this.stopOnError)throw a;t.push({index:c,error:a instanceof Error?a.message:String(a)}),s.push(r[c]);}if(this.isAuditEnabled()){let c=this.getAuditLogger(),a=s.map(p=>{let u=this.getRecordId(p);return u===null?null:{recordId:u,record:p}}).filter(p=>p!==null);a.length>0&&this.runAfterResponse(c.logBatch("batch_create",this._meta.model.tableName,a,this.getAuditUserId()));}let i=await this.finalizeArray(s),l={success:true,result:{created:i,count:i.length,...t.length>0&&{errors:t}}},d=t.length>0?207:201;return this.json(l,d)}};var St=class extends k{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:_(this.getModelSchema(),A(this._meta.model));return z.object({items:z.array(z.object({id:z.string(),data:e.partial()})).min(1).max(this.maxBatchSize)})}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("updated",this.getModelSchema(),"Resources updated successfully"),400:P("Validation error")}},this.schema)}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}filterUpdateData(e){let t={...e};if(this.allowedUpdateFields){let o=new Set(this.allowedUpdateFields);t=Object.fromEntries(Object.entries(t).filter(([r])=>o.has(r)));}if(this.blockedUpdateFields)for(let o of this.blockedUpdateFields)delete t[o];for(let o of this._meta.model.primaryKeys)delete t[o];return t}async before(e,t,o){return t}async after(e,t){return e}async handle(){this.validateTenantId();let e=await this.getItems(),t=[],o=[];for(let a of e)try{let p=this.filterUpdateData(a.data),u=await this.before(a.id,p);o.push({id:a.id,data:u});}catch(p){if(this.stopOnError)throw p;t.push({id:a.id,error:p instanceof Error?p.message:String(p)});}let{updated:r,notFound:s}=await this.batchUpdate(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(p){let u=String(a[this.lookupField]);if(this.stopOnError)throw p;t.push({id:u,error:p instanceof Error?p.message:String(p)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),p=i.map(u=>{let m=this.getRecordId(u);return m===null?null:{recordId:m,record:u}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(a.logBatch("batch_update",this._meta.model.tableName,p,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{updated:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(d,c)}};var Ot=class extends k{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return R(this.maxBatchSize)}getSchema(){let e=this.isSoftDeleteEnabled();return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("deleted",this.getModelSchema(),e?"Resources soft-deleted successfully":"Resources deleted successfully"),400:P("Validation error")}},this.schema)}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){this.validateTenantId();let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(p){if(this.stopOnError)throw p;t.push({id:a,error:p instanceof Error?p.message:String(p)});}let{deleted:r,notFound:s}=await this.batchDelete(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(p){let u=String(a[this.lookupField]);if(this.stopOnError)throw p;t.push({id:u,error:p instanceof Error?p.message:String(p)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),p=i.map(u=>{let m=this.getRecordId(u);return m===null?null:{recordId:m,previousRecord:u}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(a.logBatch("batch_delete",this._meta.model.tableName,p,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{deleted:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(d,c)}};var kt=class extends k{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return R(this.maxBatchSize)}getSchema(){return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{...S("restored",this.getModelSchema(),"Resources restored successfully"),400:P("Soft delete not enabled or validation error")}},this.schema)}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new b$2("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");this.validateTenantId();let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(p){if(this.stopOnError)throw p;t.push({id:a,error:p instanceof Error?p.message:String(p)});}let{restored:r,notFound:s}=await this.batchRestore(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(p){let u=String(a[this.lookupField]);if(this.stopOnError)throw p;t.push({id:u,error:p instanceof Error?p.message:String(p)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),p=i.map(u=>{let m=this.getRecordId(u);return m===null?null:{recordId:m,record:u}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(a.logBatch("batch_restore",this._meta.model.tableName,p,this.getAuditUserId()));}let l=await this.finalizeArray(i),d={success:true,result:{restored:l,count:l.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(d,c)}};var xt=class extends k{upsertKeys;createOnlyFields;updateOnlyFields;maxBatchSize=100;continueOnError=false;useNativeUpsert=false;beforeHookMode="sequential";afterHookMode="sequential";getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getItemSchema(){if(this._meta.fields)return this._meta.fields;let e=this.getUpsertKeys(),t=A(this._meta.model,{includePrimaryKeys:false});for(let s of this._meta.model.primaryKeys)e.includes(s)||t.push(s);let o=_(this.getModelSchema(),t),r={};for(let[s,i]of Object.entries(o.shape))e.includes(s)?r[s]=i:r[s]=i.optional();return z.object(r)}getBodySchema(){return z.array(this.getItemSchema()).max(this.maxBatchSize)}getSchema(){let e=z.object({data:this.getModelSchema(),created:z.boolean(),index:z.number()});return N({request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Batch upsert completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({items:z.array(e),createdCount:z.number(),updatedCount:z.number(),totalCount:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:P("Validation error")}},this.schema)}async getItems(){let{body:e}=await this.getValidatedData();return e}async beforeItem(e,t,o,r){return e}async afterItem(e,t,o,r){return e}async beforeBatch(e,t){return e}async afterBatch(e,t){return e}async upsertOne(e,t,o){let r=await this.findExisting(e,o),s=!r,i=await this.beforeItem(e,t,s,o),l;if(r){if(this.createOnlyFields)for(let c of this.createOnlyFields)delete i[c];let d=re(i,r,this.getSoftDeleteConfig());l=await this.update(r,d,o);}else {if(this.updateOnlyFields)for(let d of this.updateOnlyFields)delete i[d];l=await this.create(i,o);}return l=await this.afterItem(l,t,s,o),{data:l,created:s,index:t}}async nativeBatchUpsert(e,t){return b$1().warn("Native batch upsert not implemented for this adapter. Falling back to item-by-item pattern."),this.performStandardBatchUpsert(e,t)}async performStandardBatchUpsert(e,t){let o=[],r=[],s=0,i=0;for(let d=0;d<e.length;d++)try{let c=await this.upsertOne(e[d],d,t);o.push(c),c.created?s++:i++;}catch(c){if(this.continueOnError)r.push({index:d,error:c instanceof Error?c.message:String(c)});else throw c}let l={items:o,createdCount:s,updatedCount:i,totalCount:o.length};return r.length>0&&(l.errors=r),l}async batchUpsert(e,t){return this.useNativeUpsert?this.nativeBatchUpsert(e,t):this.performStandardBatchUpsert(e,t)}async handle(){let e=await this.getItems();e=await this.beforeBatch(e);let t=await this.batchUpsert(e).catch(H);if(t=await this.afterBatch(t),this._meta.model.computedFields&&(t.items=await Promise.all(t.items.map(async o=>({...o,data:await ae(o.data,this._meta.model.computedFields)})))),this.isAuditEnabled()){let o=this.getAuditLogger(),r=t.items.map(s=>{let i=this.getRecordId(s.data);return i===null?null:{recordId:i,record:s.data}}).filter(s=>s!==null);r.length>0&&this.runAfterResponse(o.logBatch("batch_upsert",this._meta.model.tableName,r,this.getAuditUserId()));}return t.items=t.items.map(o=>{let r=this._meta.model.serializer?this._meta.model.serializer(o.data):o.data,s=this.applyProfile(r);return {...o,data:this.transform(s)}}),this.success(t)}};var jt=class extends k{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getUpdateSchema(){let e=A(this._meta.model);return _(this.getModelSchema(),e).partial()}getSchema(){let e=this.getUpdateSchema();return N({request:{body:{content:{"application/json":{schema:e.partial()}}},query:z.object({dryRun:z.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z.object({success:z.boolean(),matched:z.number(),updated:z.number(),dryRun:z.boolean()})}}},400:P("Bulk patch rejected (empty body, size limit, or missing confirmation)")}},this.schema)}async handle(){let e=this.getContext(),o=(await this.getValidatedData()).body;if(!o||Object.keys(o).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let r=e.req.query("dryRun"),s=r==="true"||r==="1",i=ne(e.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize});this.applyTenantScope(i);let l=await this.countMatching(i);if(l===0)return this.json({success:true,matched:0,updated:0,dryRun:s});if(l>this.maxBulkSize)return this.error(`Bulk patch affects ${l} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(l>=this.confirmThreshold&&e.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${l} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(s)return this.json({success:true,matched:l,updated:0,dryRun:true});let d=o;this.beforeBulkPatch&&(d=await this.beforeBulkPatch(d,i,l));let c=await this.applyPatch(d,i),a={matched:l,updated:c.updated,dryRun:false,records:this.returnRecords?c.records:void 0};return this.afterBulkPatch&&await this.afterBulkPatch(a),this.json({success:true,matched:a.matched,updated:a.updated,dryRun:false,...this.returnRecords&&a.records?{records:a.records}:{}})}};var Ct=z.object({id:z.string(),recordId:z.union([z.string(),z.number()]),version:z.number(),data:z.record(z.string(),z.unknown()),createdAt:z.date(),changedBy:z.string().optional(),changeReason:z.string().optional(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()})).optional()}),Ft=class extends k{lookupField="id";defaultLimit=20;maxLimit=100;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({limit:z.coerce.number().min(1).max(this.maxLimit).optional(),offset:z.coerce.number().min(0).optional()})}getSchema(){return N({request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version history retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({versions:z.array(Ct),totalVersions:z.number()})})}}},400:P("Versioning not enabled"),404:P("Record not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getPaginationOptions(){let{query:e}=await this.getValidatedData();return {limit:e?.limit?Number(e.limit):this.defaultLimit,offset:e?.offset?Number(e.offset):0}}async recordExists(e){return true}async handle(){if(!this.isVersioningEnabled())throw new b$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{limit:t,offset:o}=await this.getPaginationOptions();if(!await this.recordExists(e))throw new d(this._meta.model.tableName,e);let s=this.getVersionManager(),i=await s.getVersions(e,{limit:t,offset:o}),l=await s.getLatestVersion(e);return this.success({versions:i,totalVersions:l})}},Pt=class extends k{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:Ct})}}},400:P("Versioning not enabled"),404:P("Version not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new b$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),r=await this.getVersionManager().getVersion(e,t);if(!r)throw new d(`version ${t}`,e);return this.success(r)}},It=class extends k{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({from:z.coerce.number().min(1),to:z.coerce.number().min(1)})}getSchema(){return N({request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version comparison completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({from:z.number(),to:z.number(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()}))})})}}},400:P("Versioning not enabled or invalid parameters"),404:P("Version not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumbers(){let{query:e}=await this.getValidatedData();return {from:e?.from?Number(e.from):0,to:e?.to?Number(e.to):0}}async handle(){if(!this.isVersioningEnabled())throw new b$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{from:t,to:o}=await this.getVersionNumbers(),s=await this.getVersionManager().compareVersions(e,t,o);return this.success({from:t,to:o,changes:s})}},Et=class extends k{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return N({request:{params:this.getParamsSchema()},responses:{200:{description:"Record rolled back successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:P("Versioning not enabled"),404:P("Version not found")}},this.schema)}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new b$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),o=this.getVersionManager(),r=await o.getVersion(e,t);if(!r)throw new d(`version ${t}`,e);let i=await o.getLatestVersion(e)+1,l=await this.rollback(e,r.data,i),d$1=this._meta.model.serializer?this._meta.model.serializer(l):l;return this.success(d$1)}};var Yt={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},vt=class extends k{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {...Yt,...this.aggregateConfig}}getQuerySchema(){return z.object({count:z.union([z.string(),z.array(z.string())]).optional(),sum:z.union([z.string(),z.array(z.string())]).optional(),avg:z.union([z.string(),z.array(z.string())]).optional(),min:z.union([z.string(),z.array(z.string())]).optional(),max:z.union([z.string(),z.array(z.string())]).optional(),countDistinct:z.union([z.string(),z.array(z.string())]).optional(),groupBy:z.string().optional(),orderBy:z.string().optional(),orderDirection:z.enum(d$1).optional(),limit:z.coerce.number().optional(),offset:z.coerce.number().optional(),withDeleted:z.coerce.boolean().optional()}).passthrough()}getSchema(){let e=z.object({key:z.record(z.string(),z.unknown()),values:z.record(z.string(),z.number().nullable())});return N({request:{query:this.getQuerySchema()},responses:{200:{description:"Aggregation result",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({values:z.record(z.string(),z.number().nullable()).optional(),groups:z.array(e).optional(),totalGroups:z.number().optional()})})}}},400:P("Invalid aggregation request")}},this.schema)}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return Xe(e||{})}validateAggregations(e){let t=this.getAggregateConfig();for(let o of e.aggregations)if(!(o.operation==="count"&&o.field==="*"))switch(o.operation){case "count":break;case "sum":if(t.sumFields.length>0&&!t.sumFields.includes(o.field))throw new h(`Field '${o.field}' is not allowed for SUM aggregation`);break;case "avg":if(t.avgFields.length>0&&!t.avgFields.includes(o.field))throw new h(`Field '${o.field}' is not allowed for AVG aggregation`);break;case "min":case "max":if(t.minMaxFields.length>0&&!t.minMaxFields.includes(o.field))throw new h(`Field '${o.field}' is not allowed for MIN/MAX aggregation`);break;case "countDistinct":if(t.countDistinctFields.length>0&&!t.countDistinctFields.includes(o.field))throw new h(`Field '${o.field}' is not allowed for COUNT DISTINCT aggregation`);break;default:c(o.operation);}if(e.groupBy){if(e.groupBy.length>this.maxGroupByFields)throw new h(`Maximum ${this.maxGroupByFields} GROUP BY fields allowed`);for(let o of e.groupBy)if(t.groupByFields.length>0&&!t.groupByFields.includes(o))throw new h(`Field '${o}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>t.maxLimit)throw new h(`Limit cannot exceed ${t.maxLimit}`)}getAggregateAlias(e){return e.alias?e.alias:e.field==="*"?e.operation:`${e.operation}${e.field.charAt(0).toUpperCase()}${e.field.slice(1)}`}async after(e){return e}async handle(){let e=await this.getAggregateOptions();e.filters=this.applyTenantScopeToAggregateFilters(e.filters),e.aggregations.length===0&&e.aggregations.push({operation:"count",field:"*"}),this.validateAggregations(e);let t=this.getAggregateConfig();e.groupBy&&e.groupBy.length>0&&e.limit===void 0&&(e.limit=t.defaultLimit);let o=await this.after(await this.aggregate(e));return this.success(o)}},Jt={eq:(n,e)=>n===e,ne:(n,e)=>n!==e,gt:(n,e)=>n>e,gte:(n,e)=>n>=e,lt:(n,e)=>n<e,lte:(n,e)=>n<=e};function Xt(n,e){let t=n.get(e);if(t)return t;let o=[];return n.set(e,o),o}function zn(n,e){let{aggregations:t,groupBy:o,having:r,orderBy:s,orderDirection:i,limit:l,offset:d}=e;if(!o||o.length===0){let u={};for(let m of t){let f=_t(m);u[f]=At(n,m);}return {values:u}}let c=new Map;for(let u of n){let f=o.map(h=>String(u[h]??"null")).join("|");Xt(c,f).push(u);}let a=[];for(let[u,m]of c){let f=u.split("|"),h={};o.forEach((g,R)=>{h[g]=f[R]==="null"?null:f[R];});let S={};for(let g of t){let R=_t(g);S[R]=At(m,g);}a.push({key:h,values:S});}r&&(a=a.filter(u=>{for(let[m,f]of Object.entries(r)){let h=u.values[m];if(h!==null)for(let[S,g]of Object.entries(f)){let R=Jt[S];if(R&&!R(h,Number(g)))return false}}return true}));let p=a.length;if(s){let u=i==="desc"?-1:1;a.sort((m,f)=>{if(s in m.values){let h=m.values[s]??0,S=f.values[s]??0;return (h-S)*u}if(s in m.key){let h=String(m.key[s]??""),S=String(f.key[s]??"");return h.localeCompare(S)*u}return 0});}if(d!==void 0||l!==void 0){let u=d||0,m=l?u+l:void 0;a=a.slice(u,m);}return {groups:a,totalGroups:p}}function Fe(n,e){return n.map(t=>t[e]).filter(t=>typeof t=="number")}var eo={count:(n,e)=>e==="*"?n.length:n.filter(t=>t[e]!==null&&t[e]!==void 0).length,countDistinct:(n,e)=>new Set(n.map(o=>o[e]).filter(o=>o!=null).map(o=>String(o))).size,sum:(n,e)=>{let t=0;for(let o of n){let r=o[e];typeof r=="number"&&(t+=r);}return t},avg:(n,e)=>{let t=Fe(n,e);return t.length===0?null:t.reduce((r,s)=>r+s,0)/t.length},min:(n,e)=>{let t=Fe(n,e);return t.length===0?null:Math.min(...t)},max:(n,e)=>{let t=Fe(n,e);return t.length===0?null:Math.max(...t)}};function At(n,e){if(n.length===0)return e.operation==="count"?0:null;let t=eo[e.operation];return t?t(n,e.field):null}function _t(n){return n.alias?n.alias:n.field==="*"?n.operation:`${n.operation}${n.field.charAt(0).toUpperCase()}${n.field.slice(1)}`}function to(n){if(n instanceof z.ZodString)return true;let e=n;return e?e._def?.type==="string"||e._def?.typeName==="ZodString"||e.def?.type==="string":false}var Tt=class extends k{searchableFields={};searchFields=[];fieldWeights={};defaultMode="any";minQueryLength=2;maxQueryLength=500;highlightTag="mark";snippetLength=150;defaultMinScore=0;searchParamName="q";filterFields=[];filterConfig;sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getSearchableFields(){if(Object.keys(this.searchableFields).length>0)return this.searchableFields;if(this.searchFields.length>0)return at(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,t={};for(let[o,r]of Object.entries(e))to(r)&&(t[o]={weight:1});return t}getQuerySchema(){let t={[this.searchParamName||"q"]:z.string().min(this.minQueryLength).max(this.maxQueryLength).meta({description:"Search query"}),fields:z.string().optional().meta({description:`Comma-separated fields to search. Available: ${Object.keys(this.getSearchableFields()).join(", ")}`}),mode:z.enum(e$1).optional().meta({description:"Search mode: any (OR), all (AND), phrase (exact)"}),highlight:z.enum(["true","false"]).optional().meta({description:"Include highlighted snippets"}),minScore:z.string().optional().meta({description:"Minimum relevance score threshold (0-1)"}),page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(t.sort=z.enum(this.sortFields).optional().meta({description:"Field to sort by"}),t.order=z.enum(d$1).optional().meta({description:"Sort direction (asc or desc)"}));for(let r of this.filterFields)t[r]=z.string().optional();if(this.filterConfig)for(let[r,s]of Object.entries(this.filterConfig)){for(let i of s)t[`${r}[${i}]`]=z.string().optional();t[r]=z.string().optional();}let o=this.getSoftDeleteConfig();if(o.enabled&&o.allowQueryDeleted&&(t[o.queryParam]=z.enum(["true","false"]).optional(),t.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(t.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let r=this.getAvailableSelectFields();t.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${r.join(", ")}`});}return z.object(t)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=z.object({item:this.getModelSchema(),score:z.number().min(0).max(1),highlights:z.record(z.string(),z.array(z.string())).optional(),matchedFields:z.array(z.string())});return N({request:{query:this.getQuerySchema()},responses:{200:{description:"Search results",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(e),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),query:z.string(),searchedFields:z.array(z.string())})})}}},400:P("Invalid search request")}},this.schema)}async getSearchOptions(){let{query:e}=await this.getValidatedData(),t=this.searchParamName||"q",o=e?.[t],r=e?.fields,s=dt(e?.mode),i=e?.highlight==="true",l=e?.minScore?Math.max(0,Math.min(1,Number.parseFloat(e.minScore)||0)):this.defaultMinScore,d=this.getSearchableFields(),c=it(r,d);return {query:o,fields:c.length>0?c:Object.keys(d),mode:s??this.defaultMode,highlight:i,minScore:l}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchParamName:"q",sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return ne(e||{},o)}async beforeSearch(e){return e}async afterSearch(e){return e}async handle(){let e=await this.getSearchOptions(),t=await this.getFilters();if(this.applyTenantScope(t),!e.query||e.query.length<this.minQueryLength)throw new b$2(`Search query must be at least ${this.minQueryLength} characters`,400,"INVALID_QUERY");e=await this.beforeSearch(e);let o=await this.search(e,t),r=await this.afterSearch(o.items),s=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?{fields:t.options.fields,isActive:true}:void 0,i=await this.finalizeArray(r.map(u=>u.item),s),l=r.map((u,m)=>({...u,item:i[m]})),d=o.postFilteredCount??o.totalCount,c=t.options.page||1,a=t.options.per_page||this.defaultPerPage,p=Math.ceil(d/a);return this.successPaginated(l,{page:c,per_page:a,total_count:d,total_pages:p,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function Yn(n,e,t){let o=rt(e.query,e.mode),r={},s=e.fields||Object.keys(t);for(let l of s)t[l]&&(r[l]=t[l]);let i=[];for(let l of n){let{score:d,matchedFields:c}=nt(l,o,r,e.mode);if(d<e.minScore||c.length===0)continue;let a;if(e.highlight){a={};for(let p of c){let u=st(l[p],o,e.mode);u.length>0&&(a[p]=u);}}i.push({item:l,score:d,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:c});}return i.sort((l,d)=>d.score-l.score),i}function $(n,e={}){let{delimiter:t=",",nullValue:o="",dateFormat:r="iso"}=e;if(n==null)return o;if(n instanceof Date)switch(r){case "timestamp":return String(n.getTime());case "locale":return n.toLocaleString();default:return n.toISOString()}if(typeof n=="object")return $(JSON.stringify(n),e);if(typeof n=="boolean")return n?"true":"false";let s=String(n),i=s.charAt(0);return i==="="||i==="+"||i==="-"||i==="@"||i===" "||i==="\r"?`" ${s.replace(/"/g,'""')}"`:s.includes(t)||s.includes('"')||s.includes(`
|
|
2
|
-
`)||s.includes("\r")?`"${s.replace(/"/g,'""')}"`:s}function Pe(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
|
|
3
|
-
`,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:l={},nullValue:d="",dateFormat:c="iso"}=e;if(n.length===0)return "";let a=e.headers;a?a=a.filter(u=>!i.includes(u)):a=Object.keys(n[0]).filter(u=>!i.includes(u));let p=[];if(r){let u=a.map(m=>{let f=l[m]||m;return $(f,{delimiter:t,nullValue:d,dateFormat:c})});p.push(u.join(t));}for(let u of n){let m=a.map(f=>{let h=u[f];return s[f]&&(h=s[f](h)),$(h,{delimiter:t,nullValue:d,dateFormat:c})});p.push(m.join(t));}return p.join(o)}function Xn(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
|
|
4
|
-
`,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:l={},nullValue:d="",dateFormat:c="iso"}=e,a=new TextEncoder,p=0,u=false,m=e.headers;return !m&&n.length>0?m=Object.keys(n[0]).filter(f=>!i.includes(f)):m?m=m.filter(f=>!i.includes(f)):m=[],new ReadableStream({pull(f){if(r&&!u&&m.length>0){let g=m.map(R=>{let j=l[R]||R;return $(j,{delimiter:t,nullValue:d,dateFormat:c})});f.enqueue(a.encode(g.join(t)+o)),u=true;return}let h=100,S=[];for(;p<n.length&&S.length<h;){let g=n[p],R=m.map(j=>{let N=g[j];return s[j]&&(N=s[j](N)),$(N,{delimiter:t,nullValue:d,dateFormat:c})});S.push(R.join(t)),p++;}S.length>0&&f.enqueue(a.encode(S.join(o)+o)),p>=n.length&&f.close();}})}function Nt(n,e){let t=[],o="",r=false,s=0;for(;s<n.length;){let i=n[s];if(r){if(i==='"'){if(s+1<n.length&&n[s+1]==='"'){o+='"',s+=2;continue}r=false,s++;continue}o+=i,s++;}else {if(i==='"'){r=true,s++;continue}if(i===e){t.push(o),o="",s++;continue}o+=i,s++;}}return t.push(o),t}function oo(n){let e=[],t="",o=false;for(let r=0;r<n.length;r++){let s=n[r];if(s==='"'){if(o&&r+1<n.length&&n[r+1]==='"'){t+='""',r++;continue}o=!o,t+=s;continue}if(!o&&(s===`
|
|
5
|
-
`||s==="\r")){s==="\r"&&r+1<n.length&&n[r+1]===`
|
|
6
|
-
`&&r++,t.length>0&&(e.push(t),t="");continue}t+=s;}return t.length>0&&e.push(t),e}function Ie(n,e={}){let{delimiter:t=",",hasHeader:o=true,trimValues:r=true,skipEmptyRows:s=true,parsers:i={},emptyValue:l="empty"}=e,d={data:[],headers:[],errors:[]},c=oo(n);if(c.length===0)return d;let a=0;if(o){let u=c[0];d.headers=Nt(u,t).map(m=>r?m.trim():m),a=1;}else e.headers&&(d.headers=e.headers);let p=e.headers||d.headers;for(let u=a;u<c.length;u++){let m=c[u],f=u+1;if(!(s&&m.trim()===""))try{let h=Nt(m,t),S={};for(let g=0;g<p.length;g++){let R=p[g],j=g<h.length?h[g]:"";if(r&&typeof j=="string"&&(j=j.trim()),j==="")switch(l){case "null":j=null;break;case "undefined":j=void 0;break}if(i[R]&&typeof j=="string")try{j=i[R](j);}catch(N){d.errors.push({row:f,message:`Failed to parse field "${R}": ${N instanceof Error?N.message:String(N)}`,content:m});}S[R]=j;}d.data.push(S);}catch(h){d.errors.push({row:f,message:`Failed to parse row: ${h instanceof Error?h.message:String(h)}`,content:m});}}return d}function Dt(n,e,t={}){let{allowUnknownFields:o=false,optionalFields:r=[]}=t,s=e.shape,i=Object.keys(s),d=i.filter(u=>r.includes(u)?false:!s[u].isOptional()).filter(u=>!n.includes(u)),c=n.filter(u=>!i.includes(u)),a=n.filter(u=>i.includes(u));return {valid:d.length===0&&(o||c.length===0),missingFields:d,unknownFields:c,validFields:a}}function es(n,e){if(n){let t=n.toLowerCase().split(".").pop();if(t==="csv")return "csv";if(t==="json")return "json"}if(e){let t=e.trim();if(t.startsWith("[")||t.startsWith("{"))return "json";if(t.includes(",")||t.includes(`
|
|
7
|
-
`))return "csv"}return "unknown"}function ts(n,e={}){return Pe(n,e)}function os(n,e={}){return Ie(n,e).data}var Vt=class extends fe{maxExportRecords=1e4;enableStreaming=true;streamPageSize=500;excludedExportFields=[];defaultFormat="json";csvOptions={};exportFilename;getExportQuerySchema(){return this.getQuerySchema().extend({format:z.enum(["json","csv"]).optional().meta({description:"Export format"}),stream:z.enum(["true","false"]).optional().meta({description:"Enable streaming for large exports"})})}getSchema(){return N({request:{query:this.getExportQuerySchema()},responses:{200:{description:"Export successful",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({data:z.array(this.getModelSchema()),count:z.number(),format:z.enum(["json","csv"]),exportedAt:z.string()})})},"text/csv":{schema:z.string()}}},400:P("Validation error")}},this.schema)}async getExportOptions(){let{query:e}=await this.getValidatedData(),t=e?.format||this.defaultFormat,o=e?.stream==="true"&&this.enableStreaming;return {format:t,stream:o,fields:e?.fields?String(e.fields).split(","):void 0}}getExportFilename(e){let o=(this.exportFilename||this._meta.model.tableName).replace(/[^a-zA-Z0-9_-]/g,"_"),r=new Date().toISOString().replace(/[:.]/g,"-");return `${o}-export-${r}.${e}`}prepareRecordsForExport(e){return this.excludedExportFields.length===0?e:e.map(t=>{let o={};for(let[r,s]of Object.entries(t))this.excludedExportFields.includes(r)||(o[r]=s);return o})}exportAsJson(e,t){let o={data:e,count:e.length,format:t,exportedAt:new Date().toISOString()};return new Response(JSON.stringify({success:true,result:o},null,2),{status:200,headers:{"Content-Type":"application/json","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsv(e,t){let o=Pe(e,{...this.csvOptions,excludeFields:this.excludedExportFields});return new Response(o,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsvStream(e,t){let o=this.getContext(),r=this.getExportFilename(t),s=this.csvOptions,i=this.excludedExportFields;return stream(o,async l=>{if(o.header("Content-Type","text/csv; charset=utf-8"),o.header("Content-Disposition",`attachment; filename="${r}"`),e.length===0)return;let d=Object.keys(e[0]).filter(p=>!i.includes(p)),c=d.map(p=>$(p,s)).join(",")+`
|
|
8
|
-
`;await l.write(c);let a=100;for(let p=0;p<e.length;p+=a)for(let u of e.slice(p,p+a)){let m=d.map(f=>$(u[f],s)).join(",")+`
|
|
9
|
-
`;await l.write(m);}})}exportAsCsvStreamPaginated(e,t){let o=this.getExportFilename(t),r=this.streamPageSize,s=Math.min(this.maxExportRecords,1e5),i=this.excludedExportFields,l=this.csvOptions,d=null,c=new ReadableStream({start:async a=>{let p=new TextEncoder,u=1,m=0;try{for(;m<s;){let f={...e,options:{...e.options,page:u,per_page:r}},S=(await this.list(f)).result;if(S.length===0)break;S.length>s-m&&(S=S.slice(0,s-m)),S=await this.after(S),S=await this.beforeExport(S);let g=this.prepareRecordsForExport(S);if(!d&&g.length>0){d=Object.keys(g[0]).filter(j=>!i.includes(j));let R=d.map(j=>$(j,l)).join(",")+`
|
|
10
|
-
`;a.enqueue(p.encode(R));}if(d)for(let R of g){let j=d.map(N=>$(R[N],l)).join(",")+`
|
|
11
|
-
`;a.enqueue(p.encode(j));}if(m+=S.length,u++,S.length<r)break}}catch(f){a.error(f);return}a.close();}});return new Response(c,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${o}"`}})}async beforeExport(e){return e}async fetchAllForExport(e){let t=Math.min(this.maxExportRecords,1e5),o={...e,options:{...e.options,page:1,per_page:t}};return (await this.list(o)).result}async handle(){let e=await this.getExportOptions(),t=await this.getFilters();if(this.applyTenantScope(t),e.format==="csv"&&e.stream)return this.exportAsCsvStreamPaginated(t,e.format);let o=await this.fetchAllForExport(t);o=await this.after(o),o=await this.beforeExport(o);let r=this.prepareRecordsForExport(o);return e.format==="csv"?this.exportAsCsv(r,e.format):this.exportAsJson(r,e.format)}};var Zt=class extends k{maxBatchSize=1e3;importBatchSize=100;stopOnError=false;skipInvalidRows=true;defaultMode="create";upsertKeys;immutableFields=[];csvOptions={};maxBodySize=10*1024*1024;optionalImportFields=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getImportSchema(){let e=this._meta.fields?this._meta.fields:_(this.getModelSchema(),A(this._meta.model));return z.object({items:z.array(e.partial()).min(1).max(this.maxBatchSize)})}getSchema(){return N({request:{query:z.object({mode:z.enum(["create","upsert"]).optional().meta({description:"Import mode"}),skipInvalid:z.enum(["true","false"]).optional().meta({description:"Skip invalid rows"}),stopOnError:z.enum(["true","false"]).optional().meta({description:"Stop on first error"})})},responses:{200:{description:"Import completed successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},207:{description:"Import completed with partial failures",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},400:P("Validation error")}},this.schema)}async getImportOptions(){let{query:e}=await this.getValidatedData(),t=e?.skipInvalid==="true"?true:e?.skipInvalid==="false"?false:this.skipInvalidRows,o=e?.stopOnError==="true"?true:e?.stopOnError==="false"?false:this.stopOnError;return {mode:e?.mode||this.defaultMode,skipInvalidRows:t,stopOnError:o}}async parseImportData(){let e=this.context;if(!e)throw new c$1("No request available");let t=e.req.header("content-type")||"";if(t.includes("application/json")){let o=await e.req.json();if(!o)throw new c$1("Request body is empty");if(!o.items||!Array.isArray(o.items))throw new c$1('Request body must contain an "items" array');if(o.items.length>this.maxBatchSize)throw new c$1(`Maximum ${this.maxBatchSize} items allowed per import`);return o.items}if(t.includes("text/csv")){let o=await e.req.text();if(o.length>this.maxBodySize)throw new c$1(`Request body exceeds maximum size of ${this.maxBodySize} bytes`);return this.parseCsvData(o)}if(t.includes("multipart/form-data")){let r=(await e.req.formData()).get("file");if(!r)throw new c$1("No file provided in form data");let s=await r.text();if(s.length>this.maxBodySize)throw new c$1(`Uploaded file exceeds maximum size of ${this.maxBodySize} bytes`);let i=r.name.toLowerCase();if(i.endsWith(".json")){let d;try{d=JSON.parse(s);}catch{throw new c$1("Invalid JSON content in uploaded file")}let c=Array.isArray(d)?d:d.items;if(!c||!Array.isArray(c))throw new c$1('JSON file must contain an array or an object with "items" array');if(c.length>this.maxBatchSize)throw new c$1(`Maximum ${this.maxBatchSize} items allowed per import`);return c}if(i.endsWith(".csv"))return this.parseCsvData(s);let l=s.trim();if(l.startsWith("[")||l.startsWith("{")){let d;try{d=JSON.parse(s);}catch{throw new c$1("Invalid JSON content in uploaded file")}let c=Array.isArray(d)?d:d.items;if(!c||!Array.isArray(c))throw new c$1('JSON file must contain an array or an object with "items" array');return c}return this.parseCsvData(s)}throw new c$1("Unsupported content type. Use application/json, text/csv, or multipart/form-data")}parseCsvData(e){let t=Ie(e,this.csvOptions);if(t.errors.length>0)throw new c$1(`CSV parsing errors: ${t.errors.map(s=>`Row ${s.row}: ${s.message}`).join("; ")}`);if(t.data.length===0)throw new c$1("CSV file is empty");if(t.data.length>this.maxBatchSize)throw new c$1(`Maximum ${this.maxBatchSize} items allowed per import`);let o=this._meta.fields||this.getModelSchema(),r=Dt(t.headers,o,{allowUnknownFields:true,optionalFields:this.optionalImportFields});if(!r.valid&&r.missingFields.length>0)throw new c$1(`Missing required fields in CSV: ${r.missingFields.join(", ")}`);return t.data}validateRow(e,t){let o=this._meta.fields||this.getModelSchema(),r={};for(let i of A(this._meta.model))r[i]=true;for(let i of this.optionalImportFields)r[i]=true;let s=o.partial(r);try{return s.parse(e),{valid:!0}}catch(i){return i instanceof z.ZodError?{valid:false,errors:i.issues.map(d=>({path:d.path.join("."),message:d.message}))}:{valid:false,errors:[{path:"",message:i instanceof Error?i.message:String(i)}]}}}removeImmutableFields(e){if(this.immutableFields.length===0)return e;let t={};for(let[o,r]of Object.entries(e))this.immutableFields.includes(o)||(t[o]=r);return t}async before(e,t,o,r){return e}async after(e,t,o,r){return e}async processRow(e,t,o,r){let s=this.validateRow(e,t);if(!s.valid)return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Validation failed",validationErrors:s.errors}:{rowNumber:t,status:"failed",error:"Validation failed",validationErrors:s.errors};try{let i=await this.before(e,t,o.mode,r);if(o.mode==="upsert"){let d=await this.findExisting(i,r);if(d){let c=re(this.removeImmutableFields(i),d,this.getSoftDeleteConfig()),a=await this.update(d,c,r);return {rowNumber:t,status:"updated",data:a}}}else if(await this.findExisting(i,r))return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Record already exists"}:{rowNumber:t,status:"failed",error:"Record already exists (duplicate key)"};let l=await this.create(i,r);return {rowNumber:t,status:"created",data:l}}catch(i){let l=ke(i);return l?{rowNumber:t,status:"failed",code:"CONFLICT",error:l.message}:{rowNumber:t,status:"failed",error:i instanceof Error?i.message:String(i)}}}async handle(){let e=await this.getImportOptions(),t=await this.parseImportData();if(!Number.isInteger(this.importBatchSize)||this.importBatchSize<1)throw new j("importBatchSize must be a positive integer");let o={total:t.length,created:0,updated:0,skipped:0,failed:0},r=[],s=false,i=e.stopOnError?1:this.importBatchSize;for(let c=0;c<t.length&&!s;c+=i){let a=t.slice(c,c+i),p=await Promise.all(a.map(async(u,m)=>{let f=c+m+1,h=await this.processRow(u,f,e);return h=await this.after(h,f,e.mode),h}));for(let u of p){switch(r.push(u),u.status){case "created":o.created++;break;case "updated":o.updated++;break;case "skipped":o.skipped++;break;case "failed":o.failed++;break}if(e.stopOnError&&u.status==="failed"){s=true;break}}}if(this.isAuditEnabled()){let c=this.getAuditLogger(),a=r.filter(p=>p.status==="created"||p.status==="updated");if(a.length>0){let p=a.map(u=>{if(!u.data)return null;let m=this.getRecordId(u.data);return m===null?null:{recordId:m,record:u.data}}).filter(u=>u!==null);p.length>0&&this.runAfterResponse(c.logBatch(e.mode==="upsert"?"batch_upsert":"batch_create",this._meta.model.tableName,p,this.getAuditUserId()));}}let l={summary:o,results:r},d=o.failed>0&&o.failed<o.total?207:200;return this.json({success:true,result:l},d)}};var we=Symbol.for("hono-crud.resource-registry");function ws(n,e,t){let o=n;o[we]||(o[we]=[]),o[we].push({path:e,endpoints:t});}function Ms(n){return n[we]??[]}export{Ft as $,it as A,at as B,dt as C,de as D,lt as E,ct as F,Ro as G,ne as H,_ as I,So as J,je as K,pt as L,ht as M,he as N,ft as O,gt as P,bt as Q,fe as R,yt as S,wt as T,Mt as U,Rt as V,St as W,Ot as X,kt as Y,xt as Z,jt as _,no as a,Pt as aa,ie as b,It as ba,A as c,Et as ca,Qe as d,vt as da,We as e,zn as ea,Ge as f,Tt as fa,Ye as g,Yn as ga,qt as h,$ as ha,ke as i,Pe as ia,H as j,Xn as ja,Ht as k,Ie as ka,lo as l,Dt as la,co as m,es as ma,ae as n,ts as na,Je as o,os as oa,oe as p,Vt as pa,pe as q,Zt as qa,fo as r,ws as ra,Xe as s,Ms as sa,et as t,re as u,ot as v,rt as w,Kt as x,nt as y,st as z};
|
package/dist/chunk-W62PHP4A.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-EMXKCEPB.js';var s={search:"SearchEndpoint",aggregate:"AggregateEndpoint",restore:"RestoreEndpoint",batchCreate:"BatchCreateEndpoint",batchUpdate:"BatchUpdateEndpoint",batchDelete:"BatchDeleteEndpoint",batchRestore:"BatchRestoreEndpoint",batchUpsert:"BatchUpsertEndpoint",export:"ExportEndpoint",import:"ImportEndpoint",upsert:"UpsertEndpoint",clone:"CloneEndpoint",bulkPatch:"BulkPatchEndpoint",versionHistory:"VersionHistoryEndpoint",versionRead:"VersionReadEndpoint",versionCompare:"VersionCompareEndpoint",versionRollback:"VersionRollbackEndpoint"};function r(t,a){let n=s[a],e=t[n];if(!e)throw new Error(`defineEndpoints: "${a}" is configured but the adapter bundle has no ${n}. Use an adapter bundle that ships ${n}, or remove the "${a}" config.`);return e}function f(t,a$1){let n={};if(t.create!==void 0){let e=t.create;n.create=a(a$1.CreateEndpoint,{meta:t.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(t.list!==void 0){let e=t.list;n.list=a(a$1.ListEndpoint,{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,filterFields:e.filtering?.fields,filterConfig:e.filtering?.config,searchFields:e.search?.fields,searchParamName:e.search?.paramName,sortFields:e.sorting?.fields,defaultSort:e.sorting?.default?{field:e.sorting.default,order:e.sorting.defaultOrder??"asc"}:void 0,defaultPerPage:e.pagination?.defaultPerPage,maxPerPage:e.pagination?.maxPerPage,cursorPaginationEnabled:e.pagination?.cursor?.enabled,cursorField:e.pagination?.cursor?.field,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(t.read!==void 0){let e=t.read;n.read=a(a$1.ReadEndpoint,{meta:t.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(t.update!==void 0){let e=t.update;n.update=a(a$1.UpdateEndpoint,{meta:t.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(t.delete!==void 0){let e=t.delete;n.delete=a(a$1.DeleteEndpoint,{meta:t.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(t.search!==void 0){let e=t.search,o={};e.fields!==void 0&&(o.searchFields=e.fields),e.mode!==void 0&&(o.defaultMode=e.mode),e.paramName!==void 0&&(o.searchParamName=e.paramName),e.hooks?.after!==void 0&&(o.afterSearch=e.hooks.after),n.search=a(r(a$1,"search"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,extras:o});}if(t.aggregate!==void 0){let e=t.aggregate,o={};e.fields!==void 0&&(o.filterFields=e.fields),n.aggregate=a(r(a$1,"aggregate"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,after:e.hooks?.after,extras:o});}if(t.restore!==void 0){let e=t.restore;n.restore=a(r(a$1,"restore"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after});}if(t.batchCreate!==void 0){let e=t.batchCreate,o={};e.maxBatchSize!==void 0&&(o.maxBatchSize=e.maxBatchSize),n.batchCreate=a(r(a$1,"batchCreate"),{meta:t.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:o});}if(t.batchUpdate!==void 0){let e=t.batchUpdate,o={};e.maxBatchSize!==void 0&&(o.maxBatchSize=e.maxBatchSize),n.batchUpdate=a(r(a$1,"batchUpdate"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:o});}if(t.batchDelete!==void 0){let e=t.batchDelete,o={};e.maxBatchSize!==void 0&&(o.maxBatchSize=e.maxBatchSize),n.batchDelete=a(r(a$1,"batchDelete"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:o});}if(t.batchRestore!==void 0){let e=t.batchRestore,o={};e.maxBatchSize!==void 0&&(o.maxBatchSize=e.maxBatchSize),n.batchRestore=a(r(a$1,"batchRestore"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:o});}if(t.batchUpsert!==void 0){let e=t.batchUpsert,o=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,i={};e.maxBatchSize!==void 0&&(i.maxBatchSize=e.maxBatchSize),o!==void 0&&(i.upsertKeys=o),e.hooks?.before!==void 0&&(i.beforeBatch=e.hooks.before),e.hooks?.after!==void 0&&(i.afterBatch=e.hooks.after),n.batchUpsert=a(r(a$1,"batchUpsert"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,extras:i});}if(t.export!==void 0){let e=t.export,o={};e.maxRows!==void 0&&(o.maxExportRecords=e.maxRows),e.formats!==void 0&&e.formats.length>0&&(o.defaultFormat=e.formats[0]),n.export=a(r(a$1,"export"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,extras:o});}if(t.import!==void 0){let e=t.import,o={};e.maxRows!==void 0&&(o.maxBatchSize=e.maxRows),n.import=a(r(a$1,"import"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:o});}if(t.upsert!==void 0){let e=t.upsert,o=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,i={};o!==void 0&&(i.upsertKeys=o),n.upsert=a(r(a$1,"upsert"),{meta:t.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:i});}if(t.clone!==void 0){let e=t.clone,o={};e.fieldsToReset!==void 0&&(o.excludeFromClone=e.fieldsToReset),n.clone=a(r(a$1,"clone"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:o});}if(t.bulkPatch!==void 0){let e=t.bulkPatch,o={};e.fields!==void 0&&(o.filterFields=e.fields),e.maxBulkSize!==void 0&&(o.maxBulkSize=e.maxBulkSize),e.confirmThreshold!==void 0&&(o.confirmThreshold=e.confirmThreshold),e.returnRecords!==void 0&&(o.returnRecords=e.returnRecords),n.bulkPatch=a(r(a$1,"bulkPatch"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,extras:o});}if(t.versionHistory!==void 0){let e=t.versionHistory,o={};e.defaultLimit!==void 0&&(o.defaultLimit=e.defaultLimit),e.maxLimit!==void 0&&(o.maxLimit=e.maxLimit),n.versionHistory=a(r(a$1,"versionHistory"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares,extras:o});}if(t.versionRead!==void 0){let e=t.versionRead;n.versionRead=a(r(a$1,"versionRead"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares});}if(t.versionCompare!==void 0){let e=t.versionCompare;n.versionCompare=a(r(a$1,"versionCompare"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares});}if(t.versionRollback!==void 0){let e=t.versionRollback;n.versionRollback=a(r(a$1,"versionRollback"),{meta:t.meta,schema:e.openapi,middlewares:e.middlewares});}return n}export{f as a};
|