hono-crud 0.12.5 → 0.13.1
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 +4 -0
- package/dist/adapters/drizzle/index.d.ts +93 -9
- package/dist/adapters/drizzle/index.js +1 -1
- package/dist/chunk-DJOJGLOT.js +4 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-GZSO6UUO.js +0 -4
package/CHANGELOG.md
CHANGED
|
@@ -14,6 +14,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
14
14
|
%b
|
|
15
15
|
%b
|
|
16
16
|
%b
|
|
17
|
+
%b
|
|
18
|
+
%b
|
|
17
19
|
## [0.8.0] — 2026-05-03
|
|
18
20
|
|
|
19
21
|
### Added
|
|
@@ -93,3 +95,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
93
95
|
[0.12.3]: https://github.com/kshdotdev/hono-crud/compare/v0.12.2...v0.12.3
|
|
94
96
|
[0.12.4]: https://github.com/kshdotdev/hono-crud/compare/v0.12.3...v0.12.4
|
|
95
97
|
[0.12.5]: https://github.com/kshdotdev/hono-crud/compare/v0.12.4...v0.12.5
|
|
98
|
+
[0.13.0]: https://github.com/kshdotdev/hono-crud/compare/v0.12.5...v0.13.0
|
|
99
|
+
[0.13.1]: https://github.com/kshdotdev/hono-crud/compare/v0.13.0...v0.13.1
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Table, SQL, Column } from 'drizzle-orm';
|
|
2
2
|
import { M as MetaInput, I as IncludeOptions, n as FilterCondition, h as RelationConfig, N as NestedUpdateInput, i as NestedWriteResult, L as ListFilters, P as PaginatedResult, j as AggregateOptions, k as AggregateResult, S as SearchOptions, l as SearchResult } from '../../types-Dfi9RdjS.js';
|
|
3
3
|
import { Env } from 'hono';
|
|
4
|
-
import { a as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, b as RestoreEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, A as AggregateEndpoint, g as BatchUpsertEndpoint, h as CloneEndpoint, i as UpsertEndpoint,
|
|
4
|
+
import { a as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, b as RestoreEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, A as AggregateEndpoint, g as BatchUpsertEndpoint, h as CloneEndpoint, i as UpsertEndpoint, S as SearchEndpoint, E as ExportEndpoint, I as ImportEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-Gx0ZUJjI.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { A as AdapterBundle } from '../../index-B1QEfh5v.js';
|
|
7
7
|
import '../../types-B5wq2iKZ.js';
|
|
@@ -90,6 +90,16 @@ type DrizzleDatabase = DrizzleDatabaseConstraint;
|
|
|
90
90
|
* @deprecated Pass your database type as a generic parameter instead
|
|
91
91
|
*/
|
|
92
92
|
type DrizzleDB = DrizzleDatabaseConstraint;
|
|
93
|
+
/**
|
|
94
|
+
* Drizzle SQL dialect identifier used to branch dialect-specific behavior
|
|
95
|
+
* (e.g. native upsert syntax: `ON CONFLICT DO UPDATE` for sqlite/pg vs
|
|
96
|
+
* `ON DUPLICATE KEY UPDATE` for mysql).
|
|
97
|
+
*
|
|
98
|
+
* The default for {@link createDrizzleCrud} is `'sqlite'` (preserves
|
|
99
|
+
* pre-existing portable behavior). Set explicitly when targeting PostgreSQL
|
|
100
|
+
* or MySQL to enable the appropriate code paths.
|
|
101
|
+
*/
|
|
102
|
+
type DrizzleDialect = 'sqlite' | 'pg' | 'mysql';
|
|
93
103
|
/**
|
|
94
104
|
* Type helper for defining Hono Env with database in Variables.
|
|
95
105
|
* Use this when injecting the database via middleware.
|
|
@@ -438,6 +448,26 @@ declare abstract class DrizzleBatchRestoreEndpoint<E extends Env = Env, M extend
|
|
|
438
448
|
}>;
|
|
439
449
|
}
|
|
440
450
|
|
|
451
|
+
/**
|
|
452
|
+
* Emit a dialect-correct case-insensitive substring-match SQL expression.
|
|
453
|
+
*
|
|
454
|
+
* Replaces the previous `LOWER(col) LIKE LOWER('%needle%') ESCAPE '\\'`
|
|
455
|
+
* approach: by using the native substring-position function for each
|
|
456
|
+
* dialect, the needle is never injected into a pattern, so LIKE
|
|
457
|
+
* wildcards (`%`, `_`) and the LIKE escape character lose their
|
|
458
|
+
* special meaning entirely — no wildcard surface means no escape
|
|
459
|
+
* needed.
|
|
460
|
+
*
|
|
461
|
+
* Dialect mapping:
|
|
462
|
+
* - `'sqlite'` → `INSTR(LOWER(col), LOWER(needle)) > 0`
|
|
463
|
+
* - `'pg'` → `POSITION(LOWER(needle) IN LOWER(col)) > 0`
|
|
464
|
+
* - `'mysql'` → `LOCATE(LOWER(needle), LOWER(col)) > 0`
|
|
465
|
+
*
|
|
466
|
+
* All three return a 1-based position (or 0 for "not found"), so
|
|
467
|
+
* `> 0` is the dialect-agnostic predicate that means "needle is a
|
|
468
|
+
* substring of col".
|
|
469
|
+
*/
|
|
470
|
+
declare function substringMatch(col: Column | SQL, needle: string, dialect: DrizzleDialect): SQL;
|
|
441
471
|
/**
|
|
442
472
|
* Drizzle Upsert endpoint.
|
|
443
473
|
* Creates a record if it doesn't exist, updates it if it does.
|
|
@@ -445,6 +475,16 @@ declare abstract class DrizzleBatchRestoreEndpoint<E extends Env = Env, M extend
|
|
|
445
475
|
declare abstract class DrizzleUpsertEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends UpsertEndpoint<E, M> {
|
|
446
476
|
/** Drizzle database instance. Can be undefined if using context injection. */
|
|
447
477
|
db?: DrizzleDatabase;
|
|
478
|
+
/**
|
|
479
|
+
* SQL dialect of the underlying Drizzle database.
|
|
480
|
+
*
|
|
481
|
+
* Used to branch dialect-specific behavior — currently the native upsert
|
|
482
|
+
* path (`ON CONFLICT DO UPDATE` for sqlite/pg vs `ON DUPLICATE KEY UPDATE`
|
|
483
|
+
* for mysql). Set via {@link createDrizzleCrud}'s `options.dialect`, or
|
|
484
|
+
* override in your subclass. Defaults to `'sqlite'` for backward
|
|
485
|
+
* compatibility with pre-existing portable behavior.
|
|
486
|
+
*/
|
|
487
|
+
protected dialect: DrizzleDialect;
|
|
448
488
|
/** Gets the database instance from property or context. */
|
|
449
489
|
protected getDb(): DrizzleDatabase;
|
|
450
490
|
protected getTable(): Table;
|
|
@@ -460,7 +500,7 @@ declare abstract class DrizzleUpsertEndpoint<E extends Env = Env, M extends Meta
|
|
|
460
500
|
* The `created` flag is set to `false` by default. If you need accurate create/update
|
|
461
501
|
* tracking, use the standard upsert pattern (useNativeUpsert = false).
|
|
462
502
|
*/
|
|
463
|
-
protected nativeUpsert(data: Partial<ModelObject<M['model']>>,
|
|
503
|
+
protected nativeUpsert(data: Partial<ModelObject<M['model']>>, _tx?: unknown): Promise<{
|
|
464
504
|
data: ModelObject<M['model']>;
|
|
465
505
|
created: boolean;
|
|
466
506
|
}>;
|
|
@@ -471,6 +511,11 @@ declare abstract class DrizzleUpsertEndpoint<E extends Env = Env, M extends Meta
|
|
|
471
511
|
declare abstract class DrizzleBatchUpsertEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends BatchUpsertEndpoint<E, M> {
|
|
472
512
|
/** Drizzle database instance. Can be undefined if using context injection. */
|
|
473
513
|
db?: DrizzleDatabase;
|
|
514
|
+
/**
|
|
515
|
+
* SQL dialect of the underlying Drizzle database. See
|
|
516
|
+
* {@link DrizzleUpsertEndpoint.dialect} for full semantics.
|
|
517
|
+
*/
|
|
518
|
+
protected dialect: DrizzleDialect;
|
|
474
519
|
/** Gets the database instance from property or context. */
|
|
475
520
|
protected getDb(): DrizzleDatabase;
|
|
476
521
|
protected getTable(): Table;
|
|
@@ -486,7 +531,7 @@ declare abstract class DrizzleBatchUpsertEndpoint<E extends Env = Env, M extends
|
|
|
486
531
|
* All records are marked as `created: false`. If you need accurate tracking,
|
|
487
532
|
* use the standard batch upsert pattern (useNativeUpsert = false).
|
|
488
533
|
*/
|
|
489
|
-
protected nativeBatchUpsert(items: Partial<ModelObject<M['model']>>[],
|
|
534
|
+
protected nativeBatchUpsert(items: Partial<ModelObject<M['model']>>[], _tx?: unknown): Promise<{
|
|
490
535
|
items: Array<{
|
|
491
536
|
data: ModelObject<M['model']>;
|
|
492
537
|
created: boolean;
|
|
@@ -557,11 +602,12 @@ declare abstract class DrizzleAggregateEndpoint<E extends Env = Env, M extends M
|
|
|
557
602
|
* Provides full-text search with relevance scoring and highlighting.
|
|
558
603
|
*
|
|
559
604
|
* For PostgreSQL, this can leverage native tsvector/tsquery for better performance.
|
|
560
|
-
* For SQLite/MySQL, it falls back to
|
|
605
|
+
* For SQLite/MySQL/PostgreSQL non-vector mode, it falls back to dialect-native
|
|
606
|
+
* substring-position search (INSTR/POSITION/LOCATE) with in-memory scoring.
|
|
561
607
|
*
|
|
562
608
|
* Features:
|
|
563
609
|
* - PostgreSQL: Uses to_tsvector() and plainto_tsquery() for native full-text search
|
|
564
|
-
* -
|
|
610
|
+
* - Fallback: dialect-native substring match with in-memory scoring
|
|
565
611
|
* - Configurable field weights
|
|
566
612
|
* - Search modes: 'any' (OR), 'all' (AND), 'phrase' (exact)
|
|
567
613
|
* - Highlighted snippets
|
|
@@ -583,12 +629,24 @@ declare abstract class DrizzleAggregateEndpoint<E extends Env = Env, M extends M
|
|
|
583
629
|
declare abstract class DrizzleSearchEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends SearchEndpoint<E, M> {
|
|
584
630
|
/** Drizzle database instance. Can be undefined if using context injection. */
|
|
585
631
|
db?: DrizzleDatabase;
|
|
632
|
+
/**
|
|
633
|
+
* SQL dialect of the underlying Drizzle database.
|
|
634
|
+
*
|
|
635
|
+
* Drives the substring-match function emitted on the fallback search path:
|
|
636
|
+
* `INSTR` for sqlite, `POSITION` for pg, `LOCATE` for mysql. Set via
|
|
637
|
+
* {@link createDrizzleCrud}'s `options.dialect`, or override in your
|
|
638
|
+
* subclass. Defaults to `'sqlite'` for backward compatibility with
|
|
639
|
+
* pre-existing portable behavior.
|
|
640
|
+
*
|
|
641
|
+
* See {@link DrizzleUpsertEndpoint.dialect} for full semantics.
|
|
642
|
+
*/
|
|
643
|
+
protected dialect: DrizzleDialect;
|
|
586
644
|
/** Gets the database instance from property or context. */
|
|
587
645
|
protected getDb(): DrizzleDatabase;
|
|
588
646
|
/**
|
|
589
647
|
* Enable PostgreSQL native full-text search.
|
|
590
648
|
* When true and vectorColumn is set, uses tsvector/tsquery.
|
|
591
|
-
* When false, uses
|
|
649
|
+
* When false, uses substring-position-based search with in-memory scoring.
|
|
592
650
|
*/
|
|
593
651
|
protected useNativeSearch: boolean;
|
|
594
652
|
/**
|
|
@@ -614,6 +672,12 @@ declare abstract class DrizzleSearchEndpoint<E extends Env = Env, M extends Meta
|
|
|
614
672
|
declare abstract class DrizzleExportEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ExportEndpoint<E, M> {
|
|
615
673
|
/** Drizzle database instance. Can be undefined if using context injection. */
|
|
616
674
|
db?: DrizzleDatabase;
|
|
675
|
+
/**
|
|
676
|
+
* SQL dialect of the underlying Drizzle database. Drives the
|
|
677
|
+
* substring-match function emitted on the `?search=` path. See
|
|
678
|
+
* {@link DrizzleUpsertEndpoint.dialect} for full semantics.
|
|
679
|
+
*/
|
|
680
|
+
protected dialect: DrizzleDialect;
|
|
617
681
|
/** Gets the database instance from property or context. */
|
|
618
682
|
protected getDb(): DrizzleDatabase;
|
|
619
683
|
protected getTable(): Table;
|
|
@@ -691,18 +755,38 @@ interface DrizzleCrudClasses<M extends MetaInput, E extends Env = Env> {
|
|
|
691
755
|
List: ConfiguredDrizzleEndpoint<DrizzleListEndpoint<E, M>, M>;
|
|
692
756
|
Restore: ConfiguredDrizzleEndpoint<DrizzleRestoreEndpoint<E, M>, M>;
|
|
693
757
|
Upsert: ConfiguredDrizzleEndpoint<DrizzleUpsertEndpoint<E, M>, M>;
|
|
758
|
+
Search: ConfiguredDrizzleEndpoint<DrizzleSearchEndpoint<E, M>, M>;
|
|
694
759
|
BatchCreate: ConfiguredDrizzleEndpoint<DrizzleBatchCreateEndpoint<E, M>, M>;
|
|
695
760
|
BatchUpdate: ConfiguredDrizzleEndpoint<DrizzleBatchUpdateEndpoint<E, M>, M>;
|
|
696
761
|
BatchDelete: ConfiguredDrizzleEndpoint<DrizzleBatchDeleteEndpoint<E, M>, M>;
|
|
697
762
|
BatchRestore: ConfiguredDrizzleEndpoint<DrizzleBatchRestoreEndpoint<E, M>, M>;
|
|
698
763
|
BatchUpsert: ConfiguredDrizzleEndpoint<DrizzleBatchUpsertEndpoint<E, M>, M>;
|
|
699
764
|
}
|
|
765
|
+
/**
|
|
766
|
+
* Options accepted by {@link createDrizzleCrud}.
|
|
767
|
+
*/
|
|
768
|
+
interface CreateDrizzleCrudOptions {
|
|
769
|
+
/**
|
|
770
|
+
* SQL dialect of the Drizzle database. Used to branch dialect-specific
|
|
771
|
+
* behavior such as native upsert syntax (`ON CONFLICT DO UPDATE` for
|
|
772
|
+
* `'sqlite'`/`'pg'` vs `ON DUPLICATE KEY UPDATE` for `'mysql'`).
|
|
773
|
+
*
|
|
774
|
+
* Defaults to `'sqlite'`, which preserves the pre-existing portable
|
|
775
|
+
* behavior for callers that don't specify a dialect.
|
|
776
|
+
*
|
|
777
|
+
* @default 'sqlite'
|
|
778
|
+
*/
|
|
779
|
+
dialect?: DrizzleDialect;
|
|
780
|
+
}
|
|
700
781
|
/**
|
|
701
782
|
* Creates a set of Drizzle CRUD endpoint base classes with db and meta pre-configured.
|
|
702
783
|
* This is the cleanest pattern - no need to set `_meta` or `db` in your classes.
|
|
703
784
|
*
|
|
704
785
|
* @param db - Your Drizzle database instance
|
|
705
786
|
* @param meta - The meta object (from defineMeta)
|
|
787
|
+
* @param options - Optional factory options. Pass `{ dialect: 'pg' | 'mysql' | 'sqlite' }`
|
|
788
|
+
* to enable dialect-specific code paths (e.g. native upsert syntax).
|
|
789
|
+
* Defaults to `{ dialect: 'sqlite' }`.
|
|
706
790
|
* @returns Object with Create, Read, Update, Delete, List base classes
|
|
707
791
|
*
|
|
708
792
|
* @example
|
|
@@ -710,7 +794,7 @@ interface DrizzleCrudClasses<M extends MetaInput, E extends Env = Env> {
|
|
|
710
794
|
* import { createDrizzleCrud } from 'hono-crud/adapters/drizzle';
|
|
711
795
|
*
|
|
712
796
|
* const projectMeta = defineMeta({ model: ProjectModel, fields: projectSchemas.insert });
|
|
713
|
-
* const Project = createDrizzleCrud(db, projectMeta);
|
|
797
|
+
* const Project = createDrizzleCrud(db, projectMeta, { dialect: 'pg' });
|
|
714
798
|
*
|
|
715
799
|
* // Now define endpoints with minimal boilerplate:
|
|
716
800
|
* class ProjectCreate extends Project.Create {
|
|
@@ -724,7 +808,7 @@ interface DrizzleCrudClasses<M extends MetaInput, E extends Env = Env> {
|
|
|
724
808
|
* }
|
|
725
809
|
* ```
|
|
726
810
|
*/
|
|
727
|
-
declare function createDrizzleCrud<M extends MetaInput, E extends Env = Env>(db: DrizzleDatabaseConstraint, meta: M): DrizzleCrudClasses<M, E>;
|
|
811
|
+
declare function createDrizzleCrud<M extends MetaInput, E extends Env = Env>(db: DrizzleDatabaseConstraint, meta: M, options?: CreateDrizzleCrudOptions): DrizzleCrudClasses<M, E>;
|
|
728
812
|
|
|
729
813
|
/**
|
|
730
814
|
* Drizzle-Zod schema utilities.
|
|
@@ -903,4 +987,4 @@ declare function isDrizzleZodAvailable(): boolean;
|
|
|
903
987
|
*/
|
|
904
988
|
declare const DrizzleAdapters: AdapterBundle;
|
|
905
989
|
|
|
906
|
-
export { type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleCloneEndpoint, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDB, type DrizzleDatabase, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, type QueryBuilder, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations };
|
|
990
|
+
export { type CreateDrizzleCrudOptions, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleCloneEndpoint, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDB, type DrizzleDatabase, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleDialect, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, type QueryBuilder, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations, substringMatch };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{J as DrizzleAdapters,y as DrizzleAggregateEndpoint,n as DrizzleBatchCreateEndpoint,p as DrizzleBatchDeleteEndpoint,q as DrizzleBatchRestoreEndpoint,o as DrizzleBatchUpdateEndpoint,t as DrizzleBatchUpsertEndpoint,C as DrizzleCloneEndpoint,h as DrizzleCreateEndpoint,k as DrizzleDeleteEndpoint,A as DrizzleExportEndpoint,B as DrizzleImportEndpoint,l as DrizzleListEndpoint,i as DrizzleReadEndpoint,m as DrizzleRestoreEndpoint,z as DrizzleSearchEndpoint,j as DrizzleUpdateEndpoint,s as DrizzleUpsertEndpoint,w as DrizzleVersionCompareEndpoint,u as DrizzleVersionHistoryEndpoint,v as DrizzleVersionReadEndpoint,x as DrizzleVersionRollbackEndpoint,f as batchLoadDrizzleRelations,g as buildWhereCondition,a as cast,D as createDrizzleCrud,H as createDrizzleSchemas,F as createInsertSchema,E as createSelectSchema,G as createUpdateSchema,c as getColumn,b as getTable,I as isDrizzleZodAvailable,d as loadDrizzleRelation,e as loadDrizzleRelations,r as substringMatch}from'../../chunk-DJOJGLOT.js';import'../../chunk-ZBCVLQ3W.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FC56WWPB.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {t,u,v,w,x,z as z$1,B as B$1,C,D as D$1,E,A as A$1,F as F$1,G,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,T,U as U$1,ba,ca,y}from'./chunk-ZBCVLQ3W.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt,gte,gt as gt$1,ne as ne$1,and,sql,or,desc,asc}from'drizzle-orm';import {z}from'zod';function X(a){return a}function f(a){if(!a.model.table)throw new Error(`Model ${a.model.tableName} does not have a table reference`);return a.model.table}function b(a,e){let t=getTableColumns(a),o=t[e];if(!o)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return o}async function Pe(a,e,t,o){if(!o.table)return e;let n=o.table;switch(o.type){case "hasOne":{let r=o.localKey||"id",s=e[r];if(s==null)return e;let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s)).limit(1);return {...e,[t]:l[0]||null}}case "hasMany":{let r=o.localKey||"id",s=e[r];if(s==null)return {...e,[t]:[]};let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s));return {...e,[t]:l}}case "belongsTo":{let r=e[o.foreignKey];if(r==null)return {...e,[t]:null};let s=b(n,o.localKey||"id"),i=await a.select().from(n).where(eq(s,r)).limit(1);return {...e,[t]:i[0]||null}}default:return e}}async function le(a,e,t,o){if(!o?.relations?.length||!t.model.relations)return e;let n={...e};for(let r of o.relations){let s=t.model.relations[r];s&&(n=await Pe(a,n,r,s));}return n}async function S(a,e,t,o){if(!e.length||!o?.relations?.length||!t.model.relations)return e;let n=e.map(r=>({...r}));for(let r of o.relations){let s=t.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[l]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=b(i,s.foreignKey),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[s.foreignKey];m.has(g)||m.set(g,[]),m.get(g).push(p);}n=n.map(p=>{let g=p[l],h=m.get(g)||[];return {...p,[r]:s.type==="hasMany"?h:h[0]||null}});break}case "belongsTo":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:null}));continue}let u=b(i,l),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[l];m.set(g,p);}n=n.map(p=>{let g=p[s.foreignKey];return {...p,[r]:m.get(g)||null}});break}}}return n}function O(a,e){let t=b(a,e.field);switch(e.operator){case "eq":return eq(t,e.value);case "ne":return ne$1(t,e.value);case "gt":return gt$1(t,e.value);case "gte":return gte(t,e.value);case "lt":return lt(t,e.value);case "lte":return lte(t,e.value);case "in":return inArray(t,e.value);case "nin":return notInArray(t,e.value);case "like":return like(t,e.value);case "ilike":return ilike(t,e.value);case "null":return e.value?isNull(t):isNotNull(t);case "between":{let[o,n]=e.value;return between(t,o,n)}default:return}}function D(a){let e=a;if(e._tx)return e._tx;if(e.db)return e.db;let t=e.context?.get?.("db");if(t)return t;throw new Error(`Database not configured. Either:
|
|
2
|
+
1. Set db property: db = myDb;
|
|
3
|
+
2. Use middleware: c.set("db", myDb);
|
|
4
|
+
3. Use factory: createDrizzleCrud(db, meta)`)}var _=class extends t{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,t){let o=t??this.getDb(),n=this.getTable(),r=this.applyManagedInsertFields(e,"drizzle");return (await o.insert(n).values(r).returning())[0]}async createNested(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(n)?n:[n],d=[];for(let u of l){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[o.foreignKey]:e},m=await s.insert(i).values(c).returning();m[0]&&d.push(m[0]);}return d}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},I=class extends u{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async read(e,t,o){let n=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),i=[eq(r,e)];if(t)for(let[u,c]of Object.entries(t))i.push(eq(this.getColumn(u),c));s.enabled&&i.push(isNull(this.getColumn(s.field)));let l=await this.getDb().select().from(n).where(and(...i)).limit(1);return l[0]?await le(this.getDb(),l[0],this._meta,o):null}},P=class extends v{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async update(e,t,o,n){let r=n??this.getDb(),s=this.getTable(),i=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),d=[eq(i,e)];if(o)for(let[c,m]of Object.entries(o))d.push(eq(this.getColumn(c),m));return l.enabled&&d.push(isNull(this.getColumn(l.field))),(await r.update(s).set(this.applyManagedUpdateFields(t)).where(and(...d)).returning())[0]||null}async processNestedWrites(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let l={created:[],updated:[],deleted:[],connected:[],disconnected:[]},d=b(i,o.foreignKey),u=b(i,"id");if(n.create){let c=Array.isArray(n.create)?n.create:[n.create];for(let m of c){if(typeof m!="object"||m===null)continue;let p={...m,id:crypto.randomUUID(),[o.foreignKey]:e},g=await s.insert(i).values(p).returning();g[0]&&l.created.push(g[0]);}}if(n.update)for(let c of n.update){if(!c.id||!(await s.select().from(i).where(and(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:p,...g}=c,h=await s.update(i).set(g).where(eq(u,p)).returning();h[0]&&l.updated.push(h[0]);}if(n.delete)for(let c of n.delete)(await s.delete(i).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.deleted.push(c);if(n.connect)for(let c of n.connect)(await s.update(i).set({[o.foreignKey]:e}).where(eq(u,c)).returning())[0]&&l.connected.push(c);if(n.disconnect)for(let c of n.disconnect)(await s.update(i).set({[o.foreignKey]:null}).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.disconnected.push(c);return l}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},U=class extends w{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async delete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[d,u]of Object.entries(t))l.push(eq(this.getColumn(d),u));return i.enabled&&l.push(isNull(this.getColumn(i.field))),i.enabled?(await n.update(r).set({[i.field]:new Date}).where(and(...l)).returning())[0]||null:(await n.delete(r).where(and(...l)).returning())[0]||null}async countRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey),l=await r.select({count:sql`count(*)`}).from(s).where(eq(i,e));return Number(l[0]?.count)||0}async deleteRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.delete(s).where(eq(i,e)).returning()).length}async nullifyRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.update(s).set({[o.foreignKey]:null}).where(eq(i,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},B=class extends x{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let y=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(y)):e.options.withDeleted||o.push(isNull(y));}for(let y of e.filters){let R=O(t,y);R&&o.push(R);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(R=>{let $=this.getColumn(R);return sql`LOWER(${$}) LIKE LOWER(${`%${e.options.search}%`})`});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=this.getDb(),i=await s.select({count:sql`count(*)`}).from(t).where(r),l=Number(i[0]?.count)||0,d=s.select().from(t).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(R(y));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;d=d.limit(c).offset((u-1)*c);let m=await d,p={relations:e.options.include||[]},g=await S(this.getDb(),m,this._meta,p),h=Math.ceil(l/c);return {result:g,result_info:{page:u,per_page:c,total_count:l,total_pages:h,has_next_page:u<h,has_prev_page:u>1}}}},L=class extends z$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async restore(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return l.push(isNotNull(this.getColumn(i.field))),(await n.update(r).set({[i.field]:null}).where(and(...l)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var A=class extends B$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}async batchCreate(e){let t=this.getTable(),o=e.map(r=>this.applyManagedInsertFields(r,"drizzle"));return await this.getDb().insert(t).values(o).returning()}},K=class extends C{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[],s=[];for(let i of e){let l=[eq(o,i.id)];n.enabled&&l.push(isNull(this.getColumn(n.field)));let d=await this.getDb().update(t).set(this.applyManagedUpdateFields(i.data)).where(and(...l)).returning();d[0]?r.push(d[0]):s.push(i.id);}return {updated:r,notFound:s}}},Z=class extends D$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e)];n.enabled&&r.push(isNull(this.getColumn(n.field)));let s;n.enabled?s=await this.getDb().update(t).set({[n.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(t).where(and(...r)).returning();let i=s,l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {deleted:i,notFound:d}}},F=class extends E{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e),isNotNull(this.getColumn(n.field))],i=await this.getDb().update(t).set({[n.field]:null}).where(and(...r)).returning(),l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {restored:i,notFound:d}}};function $e(a,e,t){switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${a})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${a})) > 0`;default:return sql`INSTR(LOWER(${a}), LOWER(${e})) > 0`}}function gt(a){return a.split(/\s+/).filter(e=>e.length>0)}var Q=class extends A$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeUpsert(e,t){let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),i=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[h,y]of Object.entries(e))!n.includes(h)&&h!==r&&(this.createOnlyFields?.includes(h)||(d[h]=y));i.enabled&&(d[i.updatedAt]=Date.now());let u=n.map(h=>this.getColumn(h)),c;s.enabled&&(c=isNull(this.getColumn(s.field)));let m=Object.keys(d).length>0?d:{[r]:sql`${this.getColumn(r)}`},p=this.getDb().insert(o).values(l);return this.dialect==="mysql"?{data:(await p.onDuplicateKeyUpdate({set:m}).returning())[0],created:false}:{data:(await p.onConflictDoUpdate({target:u,set:m,where:c}).returning())[0],created:false}}},N=class extends F$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=[];for(let s of o){let i=e[s];i!==void 0&&n.push(eq(this.getColumn(s),i));}return n.length===0?null:(await this.getDb().select().from(t).where(and(...n)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeBatchUpsert(e,t){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),i=e.map(g=>this.applyManagedInsertFields(g,"drizzle")),l={},d=e[0];for(let g of Object.keys(d))!n.includes(g)&&g!==r&&(this.createOnlyFields?.includes(g)||(l[g]=sql`excluded.${sql.identifier(g)}`));s.enabled&&(l[s.updatedAt]=Date.now());let u=n.map(g=>this.getColumn(g)),c=Object.keys(l).length>0?l:{[r]:sql`${this.getColumn(r)}`},m=this.getDb().insert(o).values(i),p=await(this.dialect==="mysql"?m.onDuplicateKeyUpdate({set:c}):m.onConflictDoUpdate({target:u,set:c})).returning();return {items:p.map((g,h)=>({data:g,created:false,index:h})),createdCount:0,updatedCount:p.length,totalCount:p.length}}},Ae=class extends G{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async recordExists(e){let t=this.getTable(),o=await this.getDb().select({count:sql`count(*)`}).from(t).where(eq(this.getColumn("id"),e));return Number(o[0]?.count)>0}},Ke=class extends H$1{},Ze=class extends I$1{},Fe=class extends J$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async rollback(e,t,o){let n=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(n).set({...t,[r]:o}).where(eq(this.getColumn("id"),e)).returning())[0]}},H=class extends K$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async aggregate(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let{query:i}=await this.getValidatedData();i?.withDeleted===true||i?.withDeleted==="true"||o.push(isNull(this.getColumn(n.field)));}if(e.filters)for(let[i,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[d,u]of Object.entries(l)){let c=O(t,{field:i,operator:d,value:u});c&&o.push(c);}else o.push(eq(this.getColumn(i),l));let r=o.length>0?and(...o):void 0,s=await this.getDb().select().from(t).where(r);return L$1(s,e)}},q=class extends T{db;dialect="sqlite";getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async search(e,t){let o=this.getTable(),n=[],r=this.getSoftDeleteConfig();r.enabled&&(t.options.onlyDeleted?n.push(isNotNull(this.getColumn(r.field))):t.options.withDeleted||n.push(isNull(this.getColumn(r.field))));for(let w of t.filters){let M=O(o,w);M&&n.push(M);}let s=this.getSearchableFields(),i=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),M=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;n.push(sql`${w} @@ ${M}`);}else {let w=(M,x)=>{try{let re=this.getColumn(M);return $e(sql`CAST(${re} AS TEXT)`,x,this.dialect)}catch{return}};if(e.mode==="all"){let M=gt(e.query);if(M.length>0){let x=[];for(let re of M){let ue=i.map(se=>w(se,re)).filter(se=>se!==void 0);ue.length>0&&x.push(or(...ue));}x.length>0&&n.push(and(...x));}}else {let M=i.map(x=>w(x,e.query)).filter(x=>x!==void 0);M.length>0&&n.push(or(...M));}}let l=n.length>0?and(...n):void 0,d=await this.getDb().select({count:sql`count(*)`}).from(o).where(l),u=Number(d[0]?.count)||0,c=this.getDb().select().from(o).where(l);if(t.options.order_by){let w=this.getColumn(t.options.order_by),M=t.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(M(w));}let m=t.options.page||1,p=t.options.per_page||this.defaultPerPage;c=c.limit(p).offset((m-1)*p);let g=await c,h=e.mode==="all"?{...e,mode:"any"}:e,y=U$1(g,h,s),R={relations:t.options.include||[]},$=y.map(w=>w.item),Xe=await S(this.getDb(),$,this._meta,R);return {items:y.map((w,M)=>({...w,item:Xe[M]})),totalCount:u}}},J=class extends ba{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let h=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(h)):e.options.withDeleted||o.push(isNull(h));}for(let h of e.filters){let y=O(t,h);y&&o.push(y);}if(e.options.search&&this.searchFields.length>0){let h=e.options.search,y=this.searchFields.map(R=>{let $=this.getColumn(R);return $e($,h,this.dialect)});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(t).where(r),i=Number(s[0]?.count)||0,l=this.getDb().select().from(t).where(r);if(e.options.order_by){let h=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;l=l.orderBy(y(h));}let d=e.options.page||1,u=e.options.per_page||this.defaultPerPage;l=l.limit(u).offset((d-1)*u);let c=await l,m={relations:e.options.include||[]},p=await S(this.getDb(),c,this._meta,m),g=Math.ceil(i/u);return {result:p,result_info:{page:d,per_page:u,total_count:i,total_pages:g,has_next_page:d<g,has_prev_page:d>1}}}},Y=class extends ca{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}},ee=class extends y{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let o=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),s=[eq(n,e)];if(t)for(let[l,d]of Object.entries(t))s.push(eq(this.getColumn(l),d));r.enabled&&s.push(isNull(this.getColumn(r.field)));let i=await this.getDb().select().from(o).where(and(...s)).limit(1);return i[0]?i[0]:null}async createClone(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(t).values(o).returning())[0]}};function an(a,e,t){let o=t?.dialect??"sqlite";return {Create:class extends _{_meta=e;db=a},Read:class extends I{_meta=e;db=a},Update:class extends P{_meta=e;db=a},Delete:class extends U{_meta=e;db=a},List:class extends B{_meta=e;db=a},Restore:class extends L{_meta=e;db=a},Upsert:class extends Q{_meta=e;db=a;dialect=o},Search:class extends q{_meta=e;db=a;dialect=o},BatchCreate:class extends A{_meta=e;db=a},BatchUpdate:class extends K{_meta=e;db=a},BatchDelete:class extends Z{_meta=e;db=a},BatchRestore:class extends F{_meta=e;db=a},BatchUpsert:class extends N{_meta=e;db=a;dialect=o}}}var ne=null,We=false,te=null;async function oe(){if(We){if(te)throw te;return ne}We=true;try{return ne=await import('drizzle-zod'),ne}catch{throw te=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),te}}async function mt(a,e){return (await oe()).createSelectSchema(a,e)}async function bt(a,e){return (await oe()).createInsertSchema(a,e)}async function ht(a,e){let t=await oe();return t.createUpdateSchema?t.createUpdateSchema(a,e):t.createInsertSchema(a,e).partial()}async function ft(a,e){let t=await oe(),o=e?.coerceDates!==false,n=o?Mt(a):new Set,r=t.createSelectSchema(a,e?.selectRefine),s=t.createInsertSchema(a,e?.insertRefine),i;return t.createUpdateSchema?i=t.createUpdateSchema(a,e?.updateRefine):i=t.createInsertSchema(a,e?.updateRefine).partial(),o&&n.size>0&&(s=Ve(s,n),i=Ve(i,n)),{select:r,insert:s,update:i}}function zt(){return ne!==null}var Dt=z.preprocess(a=>{if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date()),yt=z.preprocess(a=>{if(a==null)return null;if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date().nullable());function Mt(a){let e=new Set,t=a;for(let[o,n]of Object.entries(t)){if(o==="_"||o==="$inferInsert"||o==="$inferSelect")continue;let r=n;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),i=String(r.columnType??"").toLowerCase(),l=r.config,d=String(l?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||i.includes("pgtimestamp")||i.includes("pgdate")||i.includes("mysqltimestamp")||i.includes("mysqldate")||i.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(o);}return e}function Ve(a,e){if(e.size===0)return a;let t=a.shape,o={};for(let[n,r]of Object.entries(t))if(e.has(n)){let s=r.isOptional?.()??false,i=r.isNullable?.()??false,l=Dt;(i||s)&&(l=yt),s&&(l=l.optional()),o[n]=l;}else o[n]=r;return z.object(o)}var xn={CreateEndpoint:_,ListEndpoint:B,ReadEndpoint:I,UpdateEndpoint:P,DeleteEndpoint:U,RestoreEndpoint:L,BatchCreateEndpoint:A,BatchUpdateEndpoint:K,BatchDeleteEndpoint:Z,BatchRestoreEndpoint:F,BatchUpsertEndpoint:N,SearchEndpoint:q,AggregateEndpoint:H,ExportEndpoint:J,ImportEndpoint:Y,UpsertEndpoint:Q,CloneEndpoint:ee};export{J as A,Y as B,ee as C,an as D,mt as E,bt as F,ht as G,ft as H,zt as I,xn as J,X as a,f as b,b as c,Pe as d,le as e,S as f,O as g,_ as h,I as i,P as j,U as k,B as l,L as m,A as n,K as o,Z as p,F as q,$e as r,Q as s,N as t,Ae as u,Ke as v,Ze as w,Fe as x,H as y,q as z};
|
package/dist/index.d.ts
CHANGED
|
@@ -45,7 +45,7 @@ export { a as SerializationConfig, S as SerializationProfile } from './types-B5w
|
|
|
45
45
|
export { StaticKeyProvider, decryptFields, decryptValue, encryptFields, encryptValue, isEncryptedValue } from './encryption/index.js';
|
|
46
46
|
export { E as EncryptedValue, a as EncryptionKeyProvider, F as FieldEncryptionConfig } from './types-BAcN7U0B.js';
|
|
47
47
|
export { ApiVersionConfig, ApiVersionEnv, VersionStrategy, VersionTransformer, VersioningMiddlewareConfig, apiVersion, getApiVersion, getApiVersionConfig, versionedResponse } from './api-version/index.js';
|
|
48
|
-
export { DrizzleAdapters } from './adapters/drizzle/index.js';
|
|
48
|
+
export { DrizzleAdapters, DrizzleDialect } from './adapters/drizzle/index.js';
|
|
49
49
|
export { PrismaAdapters } from './adapters/prisma/index.js';
|
|
50
50
|
import 'hono/utils/http-status';
|
|
51
51
|
import 'hono/http-exception';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{I as DrizzleAdapters}from'./chunk-GZSO6UUO.js';import {r,s,A as A$1,z as z$1,q as q$1,p,o,n,m,l,x,y as y$1,j as j$1,i,h,k,g}from'./chunk-BXWKFJXP.js';export{a as BulkPatchEndpoint}from'./chunk-BXWKFJXP.js';export{y as PrismaAdapters}from'./chunk-FOTF3T22.js';export{K as AggregateEndpoint,B as BatchCreateEndpoint,D as BatchDeleteEndpoint,E as BatchRestoreEndpoint,C as BatchUpdateEndpoint,F as BatchUpsertEndpoint,y as CloneEndpoint,t as CreateEndpoint,w as DeleteEndpoint,ba as ExportEndpoint,ca as ImportEndpoint,x as ListEndpoint,u as ReadEndpoint,z as RestoreEndpoint,T as SearchEndpoint,v as UpdateEndpoint,A as UpsertEndpoint,I as VersionCompareEndpoint,G as VersionHistoryEndpoint,H as VersionReadEndpoint,J as VersionRollbackEndpoint,r as applyFieldSelection,s as applyFieldSelectionToArray,c as applyManagedInsertFields,d as applyManagedUpdateFields,e as assertIdStrategySupported,S as buildSearchConfig,P as calculateScore,g as causeChain,L as computeAggregations,X as createCsvStream,aa as csvToJson,V as escapeCsvValue,W as generateCsv,j as generateETag,Q as generateHighlights,b as getManagedInputExclusions,p as getSchemaFields,a as getTimestampsConfig,_ as inferCsvContentType,$ as jsonToCsv,h as mapUniqueViolation,l as matchesIfMatch,k as matchesIfNoneMatch,Y as parseCsv,q as parseFieldSelection,n as parseFilterValue,o as parseListFilters,R as parseSearchFields,i as rethrowAsConstraintError,U as searchInMemory,f as stripManagedInsertFields,O as termFrequency,M as tokenize,N as tokenizeQuery,Z as validateCsvHeaders}from'./chunk-ZBCVLQ3W.js';export{a as createHealthEndpoints,b as createHealthHandler}from'./chunk-XH7DEPW2.js';export{a as MemoryIdempotencyStorage}from'./chunk-FXIMMYFV.js';export{a as MemoryLoggingStorage}from'./chunk-3UHTK7SB.js';export{a as multiTenant}from'./chunk-L4X7KFWN.js';export{c as KVRateLimitStorage,a as MemoryRateLimitStorage,b as RedisRateLimitStorage}from'./chunk-EWKQ6BPV.js';import'./chunk-BJTWQHEV.js';export{a as applyProfile,b as applyProfileToArray,e as createArraySerializer,d as createSerializer,c as resolveProfile}from'./chunk-SDNXN7M5.js';export{g as createAPIKeyStorageMiddleware,e as createAuditStorageMiddleware,d as createCacheStorageMiddleware,c as createLoggingStorageMiddleware,b as createRateLimitStorageMiddleware,a as createStorageMiddleware,f as createVersioningStorageMiddleware}from'./chunk-R3WESU6C.js';export{a as scalarUI,e as setupDocs,f as setupDocsIndex,d as setupReDoc,b as setupScalar,c as setupSwaggerUI}from'./chunk-SPICOFUM.js';export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'./chunk-KKLMXJY4.js';export{o as AuthenticatedEndpoint,a as JWTClaimsSchema,j as createAPIKeyMiddleware,l as createAuthMiddleware,e as createJWTMiddleware,g as decodeJWT,i as defaultHashAPIKey,m as optionalAuth,b as parseJWTClaims,n as requireAuthentication,c as safeParseJWTClaims,k as validateAPIKey,h as validateAPIKeyEntry,d as validateJWTClaims,f as verifyJWT,p as withAuth}from'./chunk-7ZUZICKI.js';import {a as a$1,c}from'./chunk-XI7HT5ZM.js';export{e as MemoryApprovalStorage,b as OpenAPIRoute,f as POLICIES_CONTEXT_KEY,n as allOf,q as allowAll,o as anyOf,p as denyAll,c as isRouteClass,d as parseIso8601Duration,h as requireAllRoles,j as requireAnyPermission,t as requireApproval,k as requireAuth,r as requireAuthenticated,l as requireOwnership,m as requireOwnershipOrRole,i as requirePermissions,s as requirePolicy,g as requireRoles}from'./chunk-XI7HT5ZM.js';export{b as KVCacheStorage,a as RedisCacheStorage}from'./chunk-H3H65KZF.js';import {T}from'./chunk-UANCAA7V.js';export{C as MemoryCacheStorage,m as RateLimitExceededException,y as createInvalidationPattern,V as createLoggingMiddleware,v as createRateLimitMiddleware,z as createRelatedPatterns,p as extractAPIKey,f as extractClientIp,g as extractHeaders,n as extractIP,k as extractLoggingUserId,h as extractQuery,o as extractUserId,x as generateCacheKey,s as generateKey,l as generateRequestId,E as getCacheStorage,Q as getErrorMessage,S as getLoggingStorage,u as getRateLimitStorage,T as getRequestId,U as getRequestStartTime,j as isAllowedContentType,d as matchLoggingPath,q as matchPath,A as matchesPattern,B as parseCacheKey,c as redactHeaders,b as redactObject,w as resetRateLimit,M as resolveAPIKeyStorage,K as resolveAuditStorage,J as resolveCacheStorage,N as resolveIdempotencyStorage,I as resolveLoggingStorage,H as resolveRateLimitStorage,L as resolveVersioningStorage,D as setCacheStorage,R as setLoggingStorage,t as setRateLimitStorage,e as shouldExcludePath,a as shouldRedact,r as shouldSkipPath,O as toError,i as truncateBody,F as withCache,G as withCacheInvalidation,P as wrapError}from'./chunk-UANCAA7V.js';export{a as MemoryVersioningStorage,e as VersionManager,f as createVersionManager,d as getVersioningStorage,c as setVersioningStorage}from'./chunk-NGUMNUOP.js';export{c as getIdempotencyStorage,d as idempotency,b as setIdempotencyStorage}from'./chunk-GF2EC5G4.js';export{c as MemoryAPIKeyStorage,d as generateAPIKey,h as getAPIKeyStorage,e as hashAPIKey,f as isValidAPIKeyFormat,i as setAPIKeyStorage}from'./chunk-2M5BM4VD.js';import {a,b}from'./chunk-FC56WWPB.js';export{g as AggregationException,a as ApiException,h as CacheException,i as ConfigurationException,d as ConflictException,f as ForbiddenException,b as InputValidationException,c as NotFoundException,e as UnauthorizedException}from'./chunk-FC56WWPB.js';export{e as AuditLogger,a as MemoryAuditLogStorage,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'./chunk-FJCWFB5L.js';import {q as q$2}from'./chunk-KUFOENSK.js';export{q as RESPONSE_ENVELOPE_CONTEXT_KEY,j as applyComputedFields,k as applyComputedFieldsToArray,f as calculateChanges,b as decodeCursor,m as defineMeta,l as defineModel,a as encodeCursor,c as extractNestedData,p as extractTenantId,e as getAuditConfig,o as getMultiTenantConfig,n as getSoftDeleteConfig,g as getVersioningConfig,d as isDirectNestedData,h as parseAggregateField,i as parseAggregateQuery,r as parseSearchMode}from'./chunk-KUFOENSK.js';export{a as StorageRegistry,b as createNullableRegistry,c as createRegistryWithDefault}from'./chunk-GBQQ3YQX.js';import'./chunk-CCGZ5UPB.js';export{f as StaticKeyProvider,e as decryptFields,b as decryptValue,d as encryptFields,a as encryptValue,c as isEncryptedValue}from'./chunk-QRXEQTNE.js';export{a as registerWebhooks}from'./chunk-7DDNX2F2.js';import {d as d$1}from'./chunk-QXFY6NYI.js';export{a as CrudEventEmitter,b as getEventEmitter,d as resolveEventEmitter,c as setEventEmitter}from'./chunk-QXFY6NYI.js';import {b as b$1}from'./chunk-DMGP7QDL.js';export{b as getLogger,a as setLogger}from'./chunk-DMGP7QDL.js';export{e as getAuthType,b as getUser,a as getUserId,d as getUserPermissions,c as getUserRoles,j as hasAllPermissions,h as hasAllRoles,i as hasAnyRole,g as hasPermission,f as hasRole}from'./chunk-MDHMZPXK.js';import {b as b$2}from'./chunk-VJRDAVID.js';export{c as getContextRequestId,a as getContextVar,d as getTenantId,b as setContextVar}from'./chunk-VJRDAVID.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE}from'hono/streaming';var pe=new WeakMap;function V(o){return pe.get(o)}var P=class{app;options;routes=new Map;constructor(e,n={}){this.app=e,this.options={docs_url:"/docs",redoc_url:"/redoc",openapi_url:"/openapi.json",...n};}registerRoute(e,n,t,r=[]){let m=`${e.toUpperCase()} ${n}`,f=t,c=new f().getSchema();this.routes.set(m,{method:e,path:n,schema:c,routeClass:t});let i=createRoute({method:e,path:this.convertPath(n),...c,responses:c.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(r.length>0)for(let u of r)this.app.use(n,async(a,s)=>{if(a.req.method.toLowerCase()===e)return u(a,s);await s();});this.app.openapi(i,async u=>{let a$2=new f;a$2.setContext(u);try{return await a$2.handle()}catch(s){if(s instanceof a){let p=s.toJSON(),g=u?.var?.[q$2];return g?a$1(u,g.error(p.error),s.status):a$1(u,p,s.status)}throw s}});}convertPath(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}setupDocs(e,n){let t=e??this.options.openapi_url??"/openapi.json";this.app.doc(t,{openapi:n.openapi||"3.1.0",info:n.info,servers:n.servers,security:n.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return this.convertPath(e)}};function qr(o=new OpenAPIHono,e={}){let n="openAPIRegistry"in o?o:new OpenAPIHono,t=new P(n,e),r=["get","post","put","patch","delete","options","head"],m=new Proxy(n,{get(f,h){if(r.includes(h))return (i,...u)=>{let a=u[u.length-1];if(c(a)){let s=u.slice(0,-1);return t.registerRoute(h,i,a,s),m}return f[h](i,...u)};if(h==="doc")return (i,u)=>{t.setupDocs(i,u);};if(h==="use")return (...i)=>(f[h](...i),m);let c$1=f[h];return typeof c$1=="function"?c$1.bind(f):c$1}});return pe.set(m,t),m}var $r=6e4,Gr={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Jr(o,e,n={}){let t=V(o);if(!t)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let r=n.config??Gr,m=`openapi:${e.tenantId??"global"}:${r.info.version}`;if(n.cache){let i=await n.cache.get(m);if(i!=null)return i}let f=new OpenAPIHono;for(let i of t.getRegisteredRoutes().values()){let u=i.routeClass,a=new u,s=Yr(e);a.setContext(s),typeof a.resolveModelSchema=="function"&&await a.resolveModelSchema();let p=a.getSchema(),g=createRoute({...p,method:i.method,path:t.toOpenApiPath(i.path),responses:p.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});f.openapi(g,()=>new Response);}let h={openapi:r.openapi??"3.1.0",info:r.info,servers:r.servers,security:r.security},c=n.spec==="3.0"?f.getOpenAPIDocument(h):f.getOpenAPI31Document(h);return n.cache&&await n.cache.set(m,c,n.cacheTtlMs??$r),c}function Yr(o){let e={};o.tenantId!==void 0&&(e.tenantId=o.tenantId),o.organizationId!==void 0&&(e.organizationId=o.organizationId);let n=o.request??new Request("http://localhost/");return {var:e,env:o.env,req:{raw:n,header:()=>{},query:()=>{},param:()=>{}},set(t,r){e[t]=r;},get(t){return e[t]},executionCtx:void 0}}function Xr(o){return {async get(e){let n=await o.get(e);return n?n.data:void 0},async set(e,n,t){let r=t?Math.ceil(t/1e3):void 0;await o.set(e,n,r?{ttl:r}:void 0);}}}var oa=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"]];function na(o){return o.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function ra(o,e){let t=`/${o}/${e}`.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function aa(o,e={}){let n=e.basePath??"",t=e.tag,r=new OpenAPIHono,m=0;for(let[c,i,u]of oa){let a=o[c];if(!a)continue;let p=new a().getSchema(),g=t!==void 0?{...p,tags:[t]}:p,M=ra(n,na(u)),w=createRoute({...g,method:i,path:M,responses:g.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});r.openapi(w,()=>new Response),m+=1;}return m===0?{}:r.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var ce=o=>{if(o instanceof ZodError)return b.fromZodError(o)};function da(o={}){let{mappers:e=[],hooks:n=[],includeRequestId:t=true,includeStackTrace:r=false,defaultErrorCode:m="INTERNAL_ERROR",defaultErrorMessage:f="An internal error occurred",logUnmappedErrors:h=true,onHookError:c,responseEnvelope:i}=o,u=[...e,ce];return async(a$2,s)=>{let p,g=false;if(a$2 instanceof a)p=a$2,g=true;else if(a$2 instanceof HTTPException)p=new a(a$2.message,a$2.status,"HTTP_ERROR"),g=true;else {for(let l of u)try{let k=await l(a$2,s);if(k){p=k,g=!0;break}}catch{}g||(h&&b$1().error("Unmapped error",{error:a$2 instanceof Error?a$2.message:String(a$2)}),p=new a(f,500,m));}for(let l of n)try{let k=l(a$2,s,p);k instanceof Promise&&k.catch(B=>{c&&c(B,a$2,s);});}catch(k){c&&c(k,a$2,s);}let M=p.toJSON();if(t){let l=T(s);l&&(M.error.requestId=l);}r&&a$2.stack&&(M.error.stack=a$2.stack);let w=ue(s,i),C=w?w.error(M.error):M;return a$1(s,C,p.status)}}function ue(o,e){return o?.var?.[q$2]??e}var O=new Map,pa=["password","token","secret","apiKey","creditCard","ssn"];function I(o,e){if(o==null||typeof o!="object")return o;if(Array.isArray(o))return o.map(t=>I(t,e));let n={};for(let[t,r]of Object.entries(o))e.includes(t)||(n[t]=typeof r=="object"&&r!==null?I(r,e):r);return n}function ca(o){let{table:e,events:n,emitter:t,filter:r,heartbeatInterval:m=3e4,maxConnections:f=1e3,connectionTimeout:h=3e5,excludeFields:c=pa}=o;return i=>{let u=d$1(i,t);if(!u)return i.json({success:false,error:{code:"EVENT_EMITTER_NOT_CONFIGURED",message:"Event emitter not configured"}},500);let a=O.get(e)||0;return a>=f?i.json({success:false,error:{code:"TOO_MANY_CONNECTIONS",message:"Too many SSE connections"}},503):(O.set(e,a+1),streamSSE(i,async s=>{let p,g=async l=>{if(n&&n.length>0&&!n.includes(l.type)||r&&!r(l,i))return;let k=c.length>0?I(l.data,c):l.data,B=l.previousData&&c.length>0?I(l.previousData,c):l.previousData;try{await s.writeSSE({event:`${l.table}.${l.type}`,data:JSON.stringify({type:l.type,table:l.table,recordId:l.recordId,data:k,previousData:B,timestamp:l.timestamp}),id:`${l.table}-${l.recordId}-${Date.now()}`});}catch{}};p=u.onTable(e,g);let M=()=>{p.unsubscribe();let l=O.get(e)||1;l<=1?O.delete(e):O.set(e,l-1);};s.onAbort(()=>{M();});let w=Date.now(),C=w;for(;!s.closed;){await s.sleep(1e3);let l=Date.now();if(l-w>=h){s.abort();break}if(l-C>=m){C=l;try{await s.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}}))}}function ua(o,e,n,t={}){let r=e.endsWith("/")?e.slice(0,-1):e,m=o,{middlewares:f=[],endpointMiddlewares:h={},responseEnvelope:c}=t,i=c?async(s,p)=>{b$2(s,q$2,c),await p();}:void 0,u=s=>{let p=n[s],g=p&&"_middlewares"in p?p._middlewares||[]:[];return [...i?[i]:[],...f,...h[s]||[],...g]},a=(s,p,g,M)=>{let w=u(g),C=m[s];w.length>0?C(p,...w,M):C(p,M);};n.create&&a("post",r,"create",n.create),n.list&&a("get",r,"list",n.list),n.batchCreate&&a("post",`${r}/batch`,"batchCreate",n.batchCreate),n.batchUpdate&&a("patch",`${r}/batch`,"batchUpdate",n.batchUpdate),n.batchDelete&&a("delete",`${r}/batch`,"batchDelete",n.batchDelete),n.batchRestore&&a("post",`${r}/batch/restore`,"batchRestore",n.batchRestore),n.batchUpsert&&a("post",`${r}/batch/upsert`,"batchUpsert",n.batchUpsert),n.search&&a("get",`${r}/search`,"search",n.search),n.aggregate&&a("get",`${r}/aggregate`,"aggregate",n.aggregate),n.export&&a("get",`${r}/export`,"export",n.export),n.import&&a("post",`${r}/import`,"import",n.import),n.upsert&&a("post",`${r}/upsert`,"upsert",n.upsert),n.read&&a("get",`${r}/:id`,"read",n.read),n.update&&a("patch",`${r}/:id`,"update",n.update),n.delete&&a("delete",`${r}/:id`,"delete",n.delete),n.restore&&a("post",`${r}/:id/restore`,"restore",n.restore),n.clone&&a("post",`${r}/:id/clone`,"clone",n.clone);}function q(o){return {content:{"application/json":{schema:o}}}}function ma(o){return {description:"Success",...q({type:"object",properties:{success:{type:"boolean",enum:[true]},result:o},required:["success","result"]})}}function fa(o="Error"){return {description:o,...q({type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"object",properties:{code:{type:"string"},message:{type:"string"},details:{}},required:["code","message"]}},required:["success","error"]})}}function Z(o,e){return {content:{"application/json":{schema:o}},description:e}}function ha(o,e){return {content:{"application/json":{schema:o}},description:e,required:true}}var me=z.object({code:z.string(),path:z.array(z.union([z.string(),z.number()])),message:z.string()}),v=z.object({success:z.literal(false),error:z.object({name:z.literal("ZodError"),issues:z.array(me)})});function ga(o){return v}function Ea(...o){return v}var Ma=(o,e)=>{if(!o.success)return e.json({success:false,error:{name:"ZodError",issues:o.error.issues}},422)};function wa(o,e=422){return (n,t)=>{if(!n.success)return t.json(o(n.error),e)}}var fe=z.object({success:z.literal(false),error:z.object({message:z.string(),code:z.string().optional()})});function y(o){return Z(fe,o)}var ka={badRequest:y("Bad request"),unauthorized:y("Unauthorized"),forbidden:y("Forbidden"),notFound:y("Resource not found"),conflict:y("Resource conflict"),validationError:Z(v,"Validation error"),internalError:y("Internal server error")};function Ca(o){return async(e,n)=>{o.cache&&e.set("cacheStorage",o.cache),o.rateLimit&&e.set("rateLimitStorage",o.rateLimit),o.audit&&e.set("auditStorage",o.audit),o.versioning&&e.set("versioningStorage",o.versioning),o.logging&&e.set("loggingStorage",o.logging),o.idempotency&&e.set("idempotencyStorage",o.idempotency),o.events&&e.set("eventEmitter",o.events),await n();}}function d(o,e){let n=e.middlewares??[],t=e.extras,r=e.schema??{},m=Array.isArray(r.tags)&&r.tags.length>0,f=e.meta.model.tag??e.meta.model.tableName,h=m?r:{...r,tags:[f]};return class extends o{static _middlewares=n;constructor(){super(),t&&Object.assign(this,t);}_meta=e.meta;schema=h;beforeHookMode=e.beforeHookMode??"sequential";afterHookMode=e.afterHookMode??"sequential";allowNestedCreate=e.allowNestedCreate??[];lookupField=e.lookupField??"id";additionalFilters=e.additionalFilters;allowedUpdateFields=e.allowedUpdateFields;blockedUpdateFields=e.blockedUpdateFields;allowNestedWrites=e.allowNestedWrites??[];includeCascadeResults=e.includeCascadeResults??false;filterFields=e.filterFields??[];filterConfig=e.filterConfig;searchFields=e.searchFields??[];searchFieldName=e.searchFieldName??"search";sortFields=e.sortFields??[];defaultSort=e.defaultSort;defaultPerPage=e.defaultPerPage??20;maxPerPage=e.maxPerPage??100;allowedIncludes=e.allowedIncludes??[];fieldSelectionEnabled=e.fieldSelectionEnabled??false;allowedSelectFields=e.allowedSelectFields??[];blockedSelectFields=e.blockedSelectFields??[];alwaysIncludeFields=e.alwaysIncludeFields??[];defaultSelectFields=e.defaultSelectFields??[];getBodySchema(){return e.bodySchema?e.bodySchema:super.getBodySchema()}async before(...i){return e.before?e.before(...i):super.before(...i)}async after(...i){return e.after?e.after(...i):super.after(...i)}transform(i){return e.transform?e.transform(i):super.transform(i)}}}function ba(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,allowNestedCreate:o.allowNestedCreate})}function xa(o,e){let n=o.defaultSort??(o.defaultOrderBy?{field:o.defaultOrderBy,order:o.defaultOrderDirection??"asc"}:void 0);return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,filterFields:o.filterFields,filterConfig:o.filterConfig,searchFields:o.searchFields,searchFieldName:o.searchFieldName,sortFields:o.sortFields??o.orderByFields,defaultSort:n,defaultPerPage:o.defaultPerPage,maxPerPage:o.maxPerPage,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function ya(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function Sa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,transform:o.transform,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedUpdateFields:o.allowedUpdateFields,blockedUpdateFields:o.blockedUpdateFields,allowNestedWrites:o.allowNestedWrites})}function Oa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,includeCascadeResults:o.includeCascadeResults})}var R=class{constructor(e){this.meta=e;}_schema={};_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_allowNestedCreate=[];_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}nestedCreate(...e){return this._allowNestedCreate=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,allowNestedCreate:this._allowNestedCreate,middlewares:this._middlewares})}},A=class{constructor(e){this.meta=e;}_schema={};_filterFields=[];_filterConfig;_searchFields=[];_searchFieldName="search";_sortFields=[];_defaultSort;_defaultPerPage=20;_maxPerPage=100;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}filter(...e){return this._filterFields=e,this}filterWith(e){return this._filterConfig=e,this}search(...e){return this._searchFields=e,this}searchParam(e){return this._searchFieldName=e,this}sortable(...e){return this._sortFields=e,this}orderBy(...e){return this.sortable(...e)}defaultSort(e,n="asc"){return this._defaultSort={field:e,order:n},this}defaultOrder(e,n="asc"){return this.defaultSort(e,n)}pagination(e,n){return this._defaultPerPage=e,n!==void 0&&(this._maxPerPage=n),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 d(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchFieldName:this._searchFieldName,sortFields:this._sortFields,defaultSort:this._defaultSort,defaultPerPage:this._defaultPerPage,maxPerPage:this._maxPerPage,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},H=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return d(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})}},F=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}allowedFields(...e){return this._allowedUpdateFields=e,this}blockedFields(...e){return this._blockedUpdateFields=e,this}nestedWrites(...e){return this._allowNestedWrites=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedUpdateFields:this._allowedUpdateFields,blockedUpdateFields:this._blockedUpdateFields,allowNestedWrites:this._allowNestedWrites,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,transform:this._transform,middlewares:this._middlewares})}},_=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_includeCascadeResults=false;_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}includeCascade(e=true){return this._includeCascadeResults=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}build(e){return d(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})}},j=class{constructor(e){this.meta=e;}create(){return new R(this.meta)}list(){return new A(this.meta)}read(){return new H(this.meta)}update(){return new F(this.meta)}delete(){return new _(this.meta)}};function Pa(o){return new j(o)}var Ia={CreateEndpoint:g,ListEndpoint:k,ReadEndpoint:h,UpdateEndpoint:i,DeleteEndpoint:j$1,SearchEndpoint:y$1,AggregateEndpoint:x,RestoreEndpoint:l,BatchCreateEndpoint:m,BatchUpdateEndpoint:n,BatchDeleteEndpoint:o,BatchRestoreEndpoint:p,BatchUpsertEndpoint:q$1,ExportEndpoint:z$1,ImportEndpoint:A$1,UpsertEndpoint:s,CloneEndpoint:r};function va(o,e){let n={};if(o.create!==void 0){let t=o.create;n.create=d(e.CreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,allowNestedCreate:t.nestedCreate,before:t.hooks?.before,after:t.hooks?.after});}if(o.list!==void 0){let t=o.list;n.list=d(e.ListEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,filterFields:t.filtering?.fields,filterConfig:t.filtering?.config,searchFields:t.search?.fields,searchFieldName:t.search?.paramName,sortFields:t.sorting?.fields,defaultSort:t.sorting?.default?{field:t.sorting.default,order:t.sorting.defaultOrder??t.sorting.defaultDirection??"asc"}:void 0,defaultPerPage:t.pagination?.defaultPerPage,maxPerPage:t.pagination?.maxPerPage,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.read!==void 0){let t=o.read;n.read=d(e.ReadEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.update!==void 0){let t=o.update;n.update=d(e.UpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedUpdateFields:t.fields?.allowed,blockedUpdateFields:t.fields?.blocked,allowNestedWrites:t.nestedWrites,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.delete!==void 0){let t=o.delete;n.delete=d(e.DeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,includeCascadeResults:t.includeCascadeResults,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.search!==void 0&&e.SearchEndpoint){let t=o.search;n.search=d(e.SearchEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{searchFields:t.fields}:{},...t.mode!==void 0?{defaultMode:t.mode}:{},...t.paramName!==void 0?{searchParamName:t.paramName}:{}}});}if(o.aggregate!==void 0&&e.AggregateEndpoint){let t=o.aggregate;n.aggregate=d(e.AggregateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{filterFields:t.fields}:{}}});}if(o.restore!==void 0&&e.RestoreEndpoint){let t=o.restore;n.restore=d(e.RestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.batchCreate!==void 0&&e.BatchCreateEndpoint){let t=o.batchCreate;n.batchCreate=d(e.BatchCreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpdate!==void 0&&e.BatchUpdateEndpoint){let t=o.batchUpdate;n.batchUpdate=d(e.BatchUpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchDelete!==void 0&&e.BatchDeleteEndpoint){let t=o.batchDelete;n.batchDelete=d(e.BatchDeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchRestore!==void 0&&e.BatchRestoreEndpoint){let t=o.batchRestore;n.batchRestore=d(e.BatchRestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpsert!==void 0&&e.BatchUpsertEndpoint){let t=o.batchUpsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.batchUpsert=d(e.BatchUpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{},...r!==void 0?{upsertKeys:r}:{}}});}if(o.export!==void 0&&e.ExportEndpoint){let t=o.export;n.export=d(e.ExportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,extras:{...t.maxRows!==void 0?{maxExportRecords:t.maxRows}:{},...t.formats!==void 0&&t.formats.length>0?{defaultFormat:t.formats[0]}:{}}});}if(o.import!==void 0&&e.ImportEndpoint){let t=o.import;n.import=d(e.ImportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxRows!==void 0?{maxBatchSize:t.maxRows}:{}}});}if(o.upsert!==void 0&&e.UpsertEndpoint){let t=o.upsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.upsert=d(e.UpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...r!==void 0?{upsertKeys:r}:{}}});}if(o.clone!==void 0&&e.CloneEndpoint){let t=o.clone;n.clone=d(e.CloneEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.fieldsToReset!==void 0?{excludeFromClone:t.fieldsToReset}:{}}});}return n}
|
|
1
|
+
import {r,s,A as A$1,z as z$1,q as q$1,p,o,n,m,l,x,y as y$1,j as j$1,i,h,k,g}from'./chunk-BXWKFJXP.js';export{a as BulkPatchEndpoint}from'./chunk-BXWKFJXP.js';export{J as DrizzleAdapters}from'./chunk-DJOJGLOT.js';export{y as PrismaAdapters}from'./chunk-FOTF3T22.js';export{K as AggregateEndpoint,B as BatchCreateEndpoint,D as BatchDeleteEndpoint,E as BatchRestoreEndpoint,C as BatchUpdateEndpoint,F as BatchUpsertEndpoint,y as CloneEndpoint,t as CreateEndpoint,w as DeleteEndpoint,ba as ExportEndpoint,ca as ImportEndpoint,x as ListEndpoint,u as ReadEndpoint,z as RestoreEndpoint,T as SearchEndpoint,v as UpdateEndpoint,A as UpsertEndpoint,I as VersionCompareEndpoint,G as VersionHistoryEndpoint,H as VersionReadEndpoint,J as VersionRollbackEndpoint,r as applyFieldSelection,s as applyFieldSelectionToArray,c as applyManagedInsertFields,d as applyManagedUpdateFields,e as assertIdStrategySupported,S as buildSearchConfig,P as calculateScore,g as causeChain,L as computeAggregations,X as createCsvStream,aa as csvToJson,V as escapeCsvValue,W as generateCsv,j as generateETag,Q as generateHighlights,b as getManagedInputExclusions,p as getSchemaFields,a as getTimestampsConfig,_ as inferCsvContentType,$ as jsonToCsv,h as mapUniqueViolation,l as matchesIfMatch,k as matchesIfNoneMatch,Y as parseCsv,q as parseFieldSelection,n as parseFilterValue,o as parseListFilters,R as parseSearchFields,i as rethrowAsConstraintError,U as searchInMemory,f as stripManagedInsertFields,O as termFrequency,M as tokenize,N as tokenizeQuery,Z as validateCsvHeaders}from'./chunk-ZBCVLQ3W.js';export{a as createHealthEndpoints,b as createHealthHandler}from'./chunk-XH7DEPW2.js';export{a as MemoryIdempotencyStorage}from'./chunk-FXIMMYFV.js';export{a as MemoryLoggingStorage}from'./chunk-3UHTK7SB.js';export{a as multiTenant}from'./chunk-L4X7KFWN.js';export{c as KVRateLimitStorage,a as MemoryRateLimitStorage,b as RedisRateLimitStorage}from'./chunk-EWKQ6BPV.js';import'./chunk-BJTWQHEV.js';export{a as applyProfile,b as applyProfileToArray,e as createArraySerializer,d as createSerializer,c as resolveProfile}from'./chunk-SDNXN7M5.js';export{g as createAPIKeyStorageMiddleware,e as createAuditStorageMiddleware,d as createCacheStorageMiddleware,c as createLoggingStorageMiddleware,b as createRateLimitStorageMiddleware,a as createStorageMiddleware,f as createVersioningStorageMiddleware}from'./chunk-R3WESU6C.js';export{a as scalarUI,e as setupDocs,f as setupDocsIndex,d as setupReDoc,b as setupScalar,c as setupSwaggerUI}from'./chunk-SPICOFUM.js';export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'./chunk-KKLMXJY4.js';export{o as AuthenticatedEndpoint,a as JWTClaimsSchema,j as createAPIKeyMiddleware,l as createAuthMiddleware,e as createJWTMiddleware,g as decodeJWT,i as defaultHashAPIKey,m as optionalAuth,b as parseJWTClaims,n as requireAuthentication,c as safeParseJWTClaims,k as validateAPIKey,h as validateAPIKeyEntry,d as validateJWTClaims,f as verifyJWT,p as withAuth}from'./chunk-7ZUZICKI.js';import {a as a$1,c}from'./chunk-XI7HT5ZM.js';export{e as MemoryApprovalStorage,b as OpenAPIRoute,f as POLICIES_CONTEXT_KEY,n as allOf,q as allowAll,o as anyOf,p as denyAll,c as isRouteClass,d as parseIso8601Duration,h as requireAllRoles,j as requireAnyPermission,t as requireApproval,k as requireAuth,r as requireAuthenticated,l as requireOwnership,m as requireOwnershipOrRole,i as requirePermissions,s as requirePolicy,g as requireRoles}from'./chunk-XI7HT5ZM.js';export{b as KVCacheStorage,a as RedisCacheStorage}from'./chunk-H3H65KZF.js';import {T}from'./chunk-UANCAA7V.js';export{C as MemoryCacheStorage,m as RateLimitExceededException,y as createInvalidationPattern,V as createLoggingMiddleware,v as createRateLimitMiddleware,z as createRelatedPatterns,p as extractAPIKey,f as extractClientIp,g as extractHeaders,n as extractIP,k as extractLoggingUserId,h as extractQuery,o as extractUserId,x as generateCacheKey,s as generateKey,l as generateRequestId,E as getCacheStorage,Q as getErrorMessage,S as getLoggingStorage,u as getRateLimitStorage,T as getRequestId,U as getRequestStartTime,j as isAllowedContentType,d as matchLoggingPath,q as matchPath,A as matchesPattern,B as parseCacheKey,c as redactHeaders,b as redactObject,w as resetRateLimit,M as resolveAPIKeyStorage,K as resolveAuditStorage,J as resolveCacheStorage,N as resolveIdempotencyStorage,I as resolveLoggingStorage,H as resolveRateLimitStorage,L as resolveVersioningStorage,D as setCacheStorage,R as setLoggingStorage,t as setRateLimitStorage,e as shouldExcludePath,a as shouldRedact,r as shouldSkipPath,O as toError,i as truncateBody,F as withCache,G as withCacheInvalidation,P as wrapError}from'./chunk-UANCAA7V.js';export{a as MemoryVersioningStorage,e as VersionManager,f as createVersionManager,d as getVersioningStorage,c as setVersioningStorage}from'./chunk-NGUMNUOP.js';export{c as getIdempotencyStorage,d as idempotency,b as setIdempotencyStorage}from'./chunk-GF2EC5G4.js';export{c as MemoryAPIKeyStorage,d as generateAPIKey,h as getAPIKeyStorage,e as hashAPIKey,f as isValidAPIKeyFormat,i as setAPIKeyStorage}from'./chunk-2M5BM4VD.js';import {a,b}from'./chunk-FC56WWPB.js';export{g as AggregationException,a as ApiException,h as CacheException,i as ConfigurationException,d as ConflictException,f as ForbiddenException,b as InputValidationException,c as NotFoundException,e as UnauthorizedException}from'./chunk-FC56WWPB.js';export{e as AuditLogger,a as MemoryAuditLogStorage,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'./chunk-FJCWFB5L.js';import {q as q$2}from'./chunk-KUFOENSK.js';export{q as RESPONSE_ENVELOPE_CONTEXT_KEY,j as applyComputedFields,k as applyComputedFieldsToArray,f as calculateChanges,b as decodeCursor,m as defineMeta,l as defineModel,a as encodeCursor,c as extractNestedData,p as extractTenantId,e as getAuditConfig,o as getMultiTenantConfig,n as getSoftDeleteConfig,g as getVersioningConfig,d as isDirectNestedData,h as parseAggregateField,i as parseAggregateQuery,r as parseSearchMode}from'./chunk-KUFOENSK.js';export{a as StorageRegistry,b as createNullableRegistry,c as createRegistryWithDefault}from'./chunk-GBQQ3YQX.js';import'./chunk-CCGZ5UPB.js';export{f as StaticKeyProvider,e as decryptFields,b as decryptValue,d as encryptFields,a as encryptValue,c as isEncryptedValue}from'./chunk-QRXEQTNE.js';export{a as registerWebhooks}from'./chunk-7DDNX2F2.js';import {d as d$1}from'./chunk-QXFY6NYI.js';export{a as CrudEventEmitter,b as getEventEmitter,d as resolveEventEmitter,c as setEventEmitter}from'./chunk-QXFY6NYI.js';import {b as b$1}from'./chunk-DMGP7QDL.js';export{b as getLogger,a as setLogger}from'./chunk-DMGP7QDL.js';export{e as getAuthType,b as getUser,a as getUserId,d as getUserPermissions,c as getUserRoles,j as hasAllPermissions,h as hasAllRoles,i as hasAnyRole,g as hasPermission,f as hasRole}from'./chunk-MDHMZPXK.js';import {b as b$2}from'./chunk-VJRDAVID.js';export{c as getContextRequestId,a as getContextVar,d as getTenantId,b as setContextVar}from'./chunk-VJRDAVID.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE}from'hono/streaming';var pe=new WeakMap;function V(o){return pe.get(o)}var P=class{app;options;routes=new Map;constructor(e,n={}){this.app=e,this.options={docs_url:"/docs",redoc_url:"/redoc",openapi_url:"/openapi.json",...n};}registerRoute(e,n,t,r=[]){let m=`${e.toUpperCase()} ${n}`,f=t,c=new f().getSchema();this.routes.set(m,{method:e,path:n,schema:c,routeClass:t});let i=createRoute({method:e,path:this.convertPath(n),...c,responses:c.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(r.length>0)for(let u of r)this.app.use(n,async(a,s)=>{if(a.req.method.toLowerCase()===e)return u(a,s);await s();});this.app.openapi(i,async u=>{let a$2=new f;a$2.setContext(u);try{return await a$2.handle()}catch(s){if(s instanceof a){let p=s.toJSON(),g=u?.var?.[q$2];return g?a$1(u,g.error(p.error),s.status):a$1(u,p,s.status)}throw s}});}convertPath(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}setupDocs(e,n){let t=e??this.options.openapi_url??"/openapi.json";this.app.doc(t,{openapi:n.openapi||"3.1.0",info:n.info,servers:n.servers,security:n.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return this.convertPath(e)}};function qr(o=new OpenAPIHono,e={}){let n="openAPIRegistry"in o?o:new OpenAPIHono,t=new P(n,e),r=["get","post","put","patch","delete","options","head"],m=new Proxy(n,{get(f,h){if(r.includes(h))return (i,...u)=>{let a=u[u.length-1];if(c(a)){let s=u.slice(0,-1);return t.registerRoute(h,i,a,s),m}return f[h](i,...u)};if(h==="doc")return (i,u)=>{t.setupDocs(i,u);};if(h==="use")return (...i)=>(f[h](...i),m);let c$1=f[h];return typeof c$1=="function"?c$1.bind(f):c$1}});return pe.set(m,t),m}var $r=6e4,Gr={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Jr(o,e,n={}){let t=V(o);if(!t)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let r=n.config??Gr,m=`openapi:${e.tenantId??"global"}:${r.info.version}`;if(n.cache){let i=await n.cache.get(m);if(i!=null)return i}let f=new OpenAPIHono;for(let i of t.getRegisteredRoutes().values()){let u=i.routeClass,a=new u,s=Yr(e);a.setContext(s),typeof a.resolveModelSchema=="function"&&await a.resolveModelSchema();let p=a.getSchema(),g=createRoute({...p,method:i.method,path:t.toOpenApiPath(i.path),responses:p.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});f.openapi(g,()=>new Response);}let h={openapi:r.openapi??"3.1.0",info:r.info,servers:r.servers,security:r.security},c=n.spec==="3.0"?f.getOpenAPIDocument(h):f.getOpenAPI31Document(h);return n.cache&&await n.cache.set(m,c,n.cacheTtlMs??$r),c}function Yr(o){let e={};o.tenantId!==void 0&&(e.tenantId=o.tenantId),o.organizationId!==void 0&&(e.organizationId=o.organizationId);let n=o.request??new Request("http://localhost/");return {var:e,env:o.env,req:{raw:n,header:()=>{},query:()=>{},param:()=>{}},set(t,r){e[t]=r;},get(t){return e[t]},executionCtx:void 0}}function Xr(o){return {async get(e){let n=await o.get(e);return n?n.data:void 0},async set(e,n,t){let r=t?Math.ceil(t/1e3):void 0;await o.set(e,n,r?{ttl:r}:void 0);}}}var oa=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"]];function na(o){return o.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function ra(o,e){let t=`/${o}/${e}`.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function aa(o,e={}){let n=e.basePath??"",t=e.tag,r=new OpenAPIHono,m=0;for(let[c,i,u]of oa){let a=o[c];if(!a)continue;let p=new a().getSchema(),g=t!==void 0?{...p,tags:[t]}:p,M=ra(n,na(u)),w=createRoute({...g,method:i,path:M,responses:g.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});r.openapi(w,()=>new Response),m+=1;}return m===0?{}:r.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var ce=o=>{if(o instanceof ZodError)return b.fromZodError(o)};function da(o={}){let{mappers:e=[],hooks:n=[],includeRequestId:t=true,includeStackTrace:r=false,defaultErrorCode:m="INTERNAL_ERROR",defaultErrorMessage:f="An internal error occurred",logUnmappedErrors:h=true,onHookError:c,responseEnvelope:i}=o,u=[...e,ce];return async(a$2,s)=>{let p,g=false;if(a$2 instanceof a)p=a$2,g=true;else if(a$2 instanceof HTTPException)p=new a(a$2.message,a$2.status,"HTTP_ERROR"),g=true;else {for(let l of u)try{let k=await l(a$2,s);if(k){p=k,g=!0;break}}catch{}g||(h&&b$1().error("Unmapped error",{error:a$2 instanceof Error?a$2.message:String(a$2)}),p=new a(f,500,m));}for(let l of n)try{let k=l(a$2,s,p);k instanceof Promise&&k.catch(B=>{c&&c(B,a$2,s);});}catch(k){c&&c(k,a$2,s);}let M=p.toJSON();if(t){let l=T(s);l&&(M.error.requestId=l);}r&&a$2.stack&&(M.error.stack=a$2.stack);let w=ue(s,i),C=w?w.error(M.error):M;return a$1(s,C,p.status)}}function ue(o,e){return o?.var?.[q$2]??e}var O=new Map,pa=["password","token","secret","apiKey","creditCard","ssn"];function I(o,e){if(o==null||typeof o!="object")return o;if(Array.isArray(o))return o.map(t=>I(t,e));let n={};for(let[t,r]of Object.entries(o))e.includes(t)||(n[t]=typeof r=="object"&&r!==null?I(r,e):r);return n}function ca(o){let{table:e,events:n,emitter:t,filter:r,heartbeatInterval:m=3e4,maxConnections:f=1e3,connectionTimeout:h=3e5,excludeFields:c=pa}=o;return i=>{let u=d$1(i,t);if(!u)return i.json({success:false,error:{code:"EVENT_EMITTER_NOT_CONFIGURED",message:"Event emitter not configured"}},500);let a=O.get(e)||0;return a>=f?i.json({success:false,error:{code:"TOO_MANY_CONNECTIONS",message:"Too many SSE connections"}},503):(O.set(e,a+1),streamSSE(i,async s=>{let p,g=async l=>{if(n&&n.length>0&&!n.includes(l.type)||r&&!r(l,i))return;let k=c.length>0?I(l.data,c):l.data,B=l.previousData&&c.length>0?I(l.previousData,c):l.previousData;try{await s.writeSSE({event:`${l.table}.${l.type}`,data:JSON.stringify({type:l.type,table:l.table,recordId:l.recordId,data:k,previousData:B,timestamp:l.timestamp}),id:`${l.table}-${l.recordId}-${Date.now()}`});}catch{}};p=u.onTable(e,g);let M=()=>{p.unsubscribe();let l=O.get(e)||1;l<=1?O.delete(e):O.set(e,l-1);};s.onAbort(()=>{M();});let w=Date.now(),C=w;for(;!s.closed;){await s.sleep(1e3);let l=Date.now();if(l-w>=h){s.abort();break}if(l-C>=m){C=l;try{await s.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}}))}}function ua(o,e,n,t={}){let r=e.endsWith("/")?e.slice(0,-1):e,m=o,{middlewares:f=[],endpointMiddlewares:h={},responseEnvelope:c}=t,i=c?async(s,p)=>{b$2(s,q$2,c),await p();}:void 0,u=s=>{let p=n[s],g=p&&"_middlewares"in p?p._middlewares||[]:[];return [...i?[i]:[],...f,...h[s]||[],...g]},a=(s,p,g,M)=>{let w=u(g),C=m[s];w.length>0?C(p,...w,M):C(p,M);};n.create&&a("post",r,"create",n.create),n.list&&a("get",r,"list",n.list),n.batchCreate&&a("post",`${r}/batch`,"batchCreate",n.batchCreate),n.batchUpdate&&a("patch",`${r}/batch`,"batchUpdate",n.batchUpdate),n.batchDelete&&a("delete",`${r}/batch`,"batchDelete",n.batchDelete),n.batchRestore&&a("post",`${r}/batch/restore`,"batchRestore",n.batchRestore),n.batchUpsert&&a("post",`${r}/batch/upsert`,"batchUpsert",n.batchUpsert),n.search&&a("get",`${r}/search`,"search",n.search),n.aggregate&&a("get",`${r}/aggregate`,"aggregate",n.aggregate),n.export&&a("get",`${r}/export`,"export",n.export),n.import&&a("post",`${r}/import`,"import",n.import),n.upsert&&a("post",`${r}/upsert`,"upsert",n.upsert),n.read&&a("get",`${r}/:id`,"read",n.read),n.update&&a("patch",`${r}/:id`,"update",n.update),n.delete&&a("delete",`${r}/:id`,"delete",n.delete),n.restore&&a("post",`${r}/:id/restore`,"restore",n.restore),n.clone&&a("post",`${r}/:id/clone`,"clone",n.clone);}function q(o){return {content:{"application/json":{schema:o}}}}function ma(o){return {description:"Success",...q({type:"object",properties:{success:{type:"boolean",enum:[true]},result:o},required:["success","result"]})}}function fa(o="Error"){return {description:o,...q({type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"object",properties:{code:{type:"string"},message:{type:"string"},details:{}},required:["code","message"]}},required:["success","error"]})}}function Z(o,e){return {content:{"application/json":{schema:o}},description:e}}function ha(o,e){return {content:{"application/json":{schema:o}},description:e,required:true}}var me=z.object({code:z.string(),path:z.array(z.union([z.string(),z.number()])),message:z.string()}),v=z.object({success:z.literal(false),error:z.object({name:z.literal("ZodError"),issues:z.array(me)})});function ga(o){return v}function Ea(...o){return v}var Ma=(o,e)=>{if(!o.success)return e.json({success:false,error:{name:"ZodError",issues:o.error.issues}},422)};function wa(o,e=422){return (n,t)=>{if(!n.success)return t.json(o(n.error),e)}}var fe=z.object({success:z.literal(false),error:z.object({message:z.string(),code:z.string().optional()})});function y(o){return Z(fe,o)}var ka={badRequest:y("Bad request"),unauthorized:y("Unauthorized"),forbidden:y("Forbidden"),notFound:y("Resource not found"),conflict:y("Resource conflict"),validationError:Z(v,"Validation error"),internalError:y("Internal server error")};function Ca(o){return async(e,n)=>{o.cache&&e.set("cacheStorage",o.cache),o.rateLimit&&e.set("rateLimitStorage",o.rateLimit),o.audit&&e.set("auditStorage",o.audit),o.versioning&&e.set("versioningStorage",o.versioning),o.logging&&e.set("loggingStorage",o.logging),o.idempotency&&e.set("idempotencyStorage",o.idempotency),o.events&&e.set("eventEmitter",o.events),await n();}}function d(o,e){let n=e.middlewares??[],t=e.extras,r=e.schema??{},m=Array.isArray(r.tags)&&r.tags.length>0,f=e.meta.model.tag??e.meta.model.tableName,h=m?r:{...r,tags:[f]};return class extends o{static _middlewares=n;constructor(){super(),t&&Object.assign(this,t);}_meta=e.meta;schema=h;beforeHookMode=e.beforeHookMode??"sequential";afterHookMode=e.afterHookMode??"sequential";allowNestedCreate=e.allowNestedCreate??[];lookupField=e.lookupField??"id";additionalFilters=e.additionalFilters;allowedUpdateFields=e.allowedUpdateFields;blockedUpdateFields=e.blockedUpdateFields;allowNestedWrites=e.allowNestedWrites??[];includeCascadeResults=e.includeCascadeResults??false;filterFields=e.filterFields??[];filterConfig=e.filterConfig;searchFields=e.searchFields??[];searchFieldName=e.searchFieldName??"search";sortFields=e.sortFields??[];defaultSort=e.defaultSort;defaultPerPage=e.defaultPerPage??20;maxPerPage=e.maxPerPage??100;allowedIncludes=e.allowedIncludes??[];fieldSelectionEnabled=e.fieldSelectionEnabled??false;allowedSelectFields=e.allowedSelectFields??[];blockedSelectFields=e.blockedSelectFields??[];alwaysIncludeFields=e.alwaysIncludeFields??[];defaultSelectFields=e.defaultSelectFields??[];getBodySchema(){return e.bodySchema?e.bodySchema:super.getBodySchema()}async before(...i){return e.before?e.before(...i):super.before(...i)}async after(...i){return e.after?e.after(...i):super.after(...i)}transform(i){return e.transform?e.transform(i):super.transform(i)}}}function ba(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,allowNestedCreate:o.allowNestedCreate})}function xa(o,e){let n=o.defaultSort??(o.defaultOrderBy?{field:o.defaultOrderBy,order:o.defaultOrderDirection??"asc"}:void 0);return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,filterFields:o.filterFields,filterConfig:o.filterConfig,searchFields:o.searchFields,searchFieldName:o.searchFieldName,sortFields:o.sortFields??o.orderByFields,defaultSort:n,defaultPerPage:o.defaultPerPage,maxPerPage:o.maxPerPage,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function ya(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function Sa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,transform:o.transform,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedUpdateFields:o.allowedUpdateFields,blockedUpdateFields:o.blockedUpdateFields,allowNestedWrites:o.allowNestedWrites})}function Oa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,includeCascadeResults:o.includeCascadeResults})}var R=class{constructor(e){this.meta=e;}_schema={};_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_allowNestedCreate=[];_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}nestedCreate(...e){return this._allowNestedCreate=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,allowNestedCreate:this._allowNestedCreate,middlewares:this._middlewares})}},A=class{constructor(e){this.meta=e;}_schema={};_filterFields=[];_filterConfig;_searchFields=[];_searchFieldName="search";_sortFields=[];_defaultSort;_defaultPerPage=20;_maxPerPage=100;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}filter(...e){return this._filterFields=e,this}filterWith(e){return this._filterConfig=e,this}search(...e){return this._searchFields=e,this}searchParam(e){return this._searchFieldName=e,this}sortable(...e){return this._sortFields=e,this}orderBy(...e){return this.sortable(...e)}defaultSort(e,n="asc"){return this._defaultSort={field:e,order:n},this}defaultOrder(e,n="asc"){return this.defaultSort(e,n)}pagination(e,n){return this._defaultPerPage=e,n!==void 0&&(this._maxPerPage=n),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 d(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchFieldName:this._searchFieldName,sortFields:this._sortFields,defaultSort:this._defaultSort,defaultPerPage:this._defaultPerPage,maxPerPage:this._maxPerPage,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},H=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return d(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})}},F=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}allowedFields(...e){return this._allowedUpdateFields=e,this}blockedFields(...e){return this._blockedUpdateFields=e,this}nestedWrites(...e){return this._allowNestedWrites=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedUpdateFields:this._allowedUpdateFields,blockedUpdateFields:this._blockedUpdateFields,allowNestedWrites:this._allowNestedWrites,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,transform:this._transform,middlewares:this._middlewares})}},_=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_includeCascadeResults=false;_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}includeCascade(e=true){return this._includeCascadeResults=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}build(e){return d(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})}},j=class{constructor(e){this.meta=e;}create(){return new R(this.meta)}list(){return new A(this.meta)}read(){return new H(this.meta)}update(){return new F(this.meta)}delete(){return new _(this.meta)}};function Pa(o){return new j(o)}var Ia={CreateEndpoint:g,ListEndpoint:k,ReadEndpoint:h,UpdateEndpoint:i,DeleteEndpoint:j$1,SearchEndpoint:y$1,AggregateEndpoint:x,RestoreEndpoint:l,BatchCreateEndpoint:m,BatchUpdateEndpoint:n,BatchDeleteEndpoint:o,BatchRestoreEndpoint:p,BatchUpsertEndpoint:q$1,ExportEndpoint:z$1,ImportEndpoint:A$1,UpsertEndpoint:s,CloneEndpoint:r};function va(o,e){let n={};if(o.create!==void 0){let t=o.create;n.create=d(e.CreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,allowNestedCreate:t.nestedCreate,before:t.hooks?.before,after:t.hooks?.after});}if(o.list!==void 0){let t=o.list;n.list=d(e.ListEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,filterFields:t.filtering?.fields,filterConfig:t.filtering?.config,searchFields:t.search?.fields,searchFieldName:t.search?.paramName,sortFields:t.sorting?.fields,defaultSort:t.sorting?.default?{field:t.sorting.default,order:t.sorting.defaultOrder??t.sorting.defaultDirection??"asc"}:void 0,defaultPerPage:t.pagination?.defaultPerPage,maxPerPage:t.pagination?.maxPerPage,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.read!==void 0){let t=o.read;n.read=d(e.ReadEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.update!==void 0){let t=o.update;n.update=d(e.UpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedUpdateFields:t.fields?.allowed,blockedUpdateFields:t.fields?.blocked,allowNestedWrites:t.nestedWrites,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.delete!==void 0){let t=o.delete;n.delete=d(e.DeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,includeCascadeResults:t.includeCascadeResults,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.search!==void 0&&e.SearchEndpoint){let t=o.search;n.search=d(e.SearchEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{searchFields:t.fields}:{},...t.mode!==void 0?{defaultMode:t.mode}:{},...t.paramName!==void 0?{searchParamName:t.paramName}:{}}});}if(o.aggregate!==void 0&&e.AggregateEndpoint){let t=o.aggregate;n.aggregate=d(e.AggregateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{filterFields:t.fields}:{}}});}if(o.restore!==void 0&&e.RestoreEndpoint){let t=o.restore;n.restore=d(e.RestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.batchCreate!==void 0&&e.BatchCreateEndpoint){let t=o.batchCreate;n.batchCreate=d(e.BatchCreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpdate!==void 0&&e.BatchUpdateEndpoint){let t=o.batchUpdate;n.batchUpdate=d(e.BatchUpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchDelete!==void 0&&e.BatchDeleteEndpoint){let t=o.batchDelete;n.batchDelete=d(e.BatchDeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchRestore!==void 0&&e.BatchRestoreEndpoint){let t=o.batchRestore;n.batchRestore=d(e.BatchRestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpsert!==void 0&&e.BatchUpsertEndpoint){let t=o.batchUpsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.batchUpsert=d(e.BatchUpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{},...r!==void 0?{upsertKeys:r}:{}}});}if(o.export!==void 0&&e.ExportEndpoint){let t=o.export;n.export=d(e.ExportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,extras:{...t.maxRows!==void 0?{maxExportRecords:t.maxRows}:{},...t.formats!==void 0&&t.formats.length>0?{defaultFormat:t.formats[0]}:{}}});}if(o.import!==void 0&&e.ImportEndpoint){let t=o.import;n.import=d(e.ImportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxRows!==void 0?{maxBatchSize:t.maxRows}:{}}});}if(o.upsert!==void 0&&e.UpsertEndpoint){let t=o.upsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.upsert=d(e.UpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...r!==void 0?{upsertKeys:r}:{}}});}if(o.clone!==void 0&&e.CloneEndpoint){let t=o.clone;n.clone=d(e.CloneEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.fieldsToReset!==void 0?{excludeFromClone:t.fieldsToReset}:{}}});}return n}
|
|
2
2
|
export{R as CreateBuilder,j as CrudBuilder,_ as DeleteBuilder,P as HonoOpenAPIHandler,fe as HttpErrorSchema,A as ListBuilder,Ia as MemoryAdapters,H as ReadBuilder,F as UpdateBuilder,v as ZodErrorSchema,me as ZodIssueSchema,Jr as buildPerTenantOpenApi,ka as commonResponses,q as contentJson,ba as createCreate,Ca as createCrudMiddleware,Oa as createDelete,da as createErrorHandler,ga as createErrorSchema,xa as createList,Ea as createOneOfErrorSchema,ya as createRead,ca as createSubscribeHandler,Sa as createUpdate,wa as createValidationHook,Pa as crud,va as defineEndpoints,fa as errorResponse,qr as fromHono,V as getHandlerForApp,y as httpErrorContent,Z as jsonContent,ha as jsonContentRequired,Ma as openApiValidationHook,ua as registerCrud,ue as resolveErrorEnvelope,ma as successResponse,aa as toOpenApiPaths,Xr as wrapCacheStorageForOpenApi,ce as zodErrorMapper};
|
package/package.json
CHANGED
package/dist/chunk-GZSO6UUO.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import {t,u,v,w,x,z as z$1,B as B$1,C,D as D$1,E,A as A$1,F as F$1,G,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,T,U as U$1,ba,ca,y}from'./chunk-ZBCVLQ3W.js';import {b}from'./chunk-DMGP7QDL.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt,gte,gt as gt$1,ne as ne$1,and,sql,or,desc,asc}from'drizzle-orm';import {z}from'zod';function X(l){return l}function h(l){if(!l.model.table)throw new Error(`Model ${l.model.tableName} does not have a table reference`);return l.model.table}function m(l,e){let n=getTableColumns(l),o=n[e];if(!o)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(n).join(", ")}`);return o}async function Pe(l,e,n,o){if(!o.table)return e;let t=o.table;switch(o.type){case "hasOne":{let r=o.localKey||"id",s=e[r];if(s==null)return e;let i=m(t,o.foreignKey),a=await l.select().from(t).where(eq(i,s)).limit(1);return {...e,[n]:a[0]||null}}case "hasMany":{let r=o.localKey||"id",s=e[r];if(s==null)return {...e,[n]:[]};let i=m(t,o.foreignKey),a=await l.select().from(t).where(eq(i,s));return {...e,[n]:a}}case "belongsTo":{let r=e[o.foreignKey];if(r==null)return {...e,[n]:null};let s=m(t,o.localKey||"id"),i=await l.select().from(t).where(eq(s,r)).limit(1);return {...e,[n]:i[0]||null}}default:return e}}async function de(l,e,n,o){if(!o?.relations?.length||!n.model.relations)return e;let t={...e};for(let r of o.relations){let s=n.model.relations[r];s&&(t=await Pe(l,t,r,s));}return t}async function j(l,e,n,o){if(!e.length||!o?.relations?.length||!n.model.relations)return e;let t=e.map(r=>({...r}));for(let r of o.relations){let s=n.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let a=s.localKey||"id",c=[...new Set(t.map(p=>p[a]).filter(p=>p!=null))];if(c.length===0){t=t.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=m(i,s.foreignKey),d=await l.select().from(i).where(inArray(u,c)),g=new Map;for(let p of d){let b=p[s.foreignKey];g.has(b)||g.set(b,[]),g.get(b).push(p);}t=t.map(p=>{let b=p[a],z=g.get(b)||[];return {...p,[r]:s.type==="hasMany"?z:z[0]||null}});break}case "belongsTo":{let a=s.localKey||"id",c=[...new Set(t.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(c.length===0){t=t.map(p=>({...p,[r]:null}));continue}let u=m(i,a),d=await l.select().from(i).where(inArray(u,c)),g=new Map;for(let p of d){let b=p[a];g.set(b,p);}t=t.map(p=>{let b=p[s.foreignKey];return {...p,[r]:g.get(b)||null}});break}}}return t}function O(l,e){let n=m(l,e.field);switch(e.operator){case "eq":return eq(n,e.value);case "ne":return ne$1(n,e.value);case "gt":return gt$1(n,e.value);case "gte":return gte(n,e.value);case "lt":return lt(n,e.value);case "lte":return lte(n,e.value);case "in":return inArray(n,e.value);case "nin":return notInArray(n,e.value);case "like":return like(n,e.value);case "ilike":return ilike(n,e.value);case "null":return e.value?isNull(n):isNotNull(n);case "between":{let[o,t]=e.value;return between(n,o,t)}default:return}}function D(l){let e=l;if(e._tx)return e._tx;if(e.db)return e.db;let n=e.context?.get?.("db");if(n)return n;throw new Error(`Database not configured. Either:
|
|
2
|
-
1. Set db property: db = myDb;
|
|
3
|
-
2. Use middleware: c.set("db", myDb);
|
|
4
|
-
3. Use factory: createDrizzleCrud(db, meta)`)}var _=class extends t{db;useTransaction=false;getDb(){return D(this)}getTable(){return h(this._meta)}getRelatedTable(e){return e.table}async create(e,n){let o=n??this.getDb(),t=this.getTable(),r=this.applyManagedInsertFields(e,"drizzle");return (await o.insert(t).values(r).returning())[0]}async createNested(e,n,o,t,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b().warn(`Related table not found for ${n}. Add 'table' to the relation config.`),[];let a=Array.isArray(t)?t:[t],c=[];for(let u of a){if(typeof u!="object"||u===null)continue;let d={...u,id:crypto.randomUUID(),[o.foreignKey]:e},g=await s.insert(i).values(d).returning();g[0]&&c.push(g[0]);}return c}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},I=class extends u{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async read(e,n,o){let t=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),i=[eq(r,e)];if(n)for(let[u,d]of Object.entries(n))i.push(eq(this.getColumn(u),d));s.enabled&&i.push(isNull(this.getColumn(s.field)));let a=await this.getDb().select().from(t).where(and(...i)).limit(1);return a[0]?await de(this.getDb(),a[0],this._meta,o):null}},P=class extends v{db;useTransaction=false;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[u,d]of Object.entries(n))a.push(eq(this.getColumn(u),d));return i.enabled&&a.push(isNull(this.getColumn(i.field))),(await t.select().from(r).where(and(...a)).limit(1))[0]||null}async update(e,n,o,t){let r=t??this.getDb(),s=this.getTable(),i=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),c=[eq(i,e)];if(o)for(let[d,g]of Object.entries(o))c.push(eq(this.getColumn(d),g));return a.enabled&&c.push(isNull(this.getColumn(a.field))),(await r.update(s).set(this.applyManagedUpdateFields(n)).where(and(...c)).returning())[0]||null}async processNestedWrites(e,n,o,t,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b().warn(`Related table not found for ${n}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let a={created:[],updated:[],deleted:[],connected:[],disconnected:[]},c=m(i,o.foreignKey),u=m(i,"id");if(t.create){let d=Array.isArray(t.create)?t.create:[t.create];for(let g of d){if(typeof g!="object"||g===null)continue;let p={...g,id:crypto.randomUUID(),[o.foreignKey]:e},b=await s.insert(i).values(p).returning();b[0]&&a.created.push(b[0]);}}if(t.update)for(let d of t.update){if(!d.id||!(await s.select().from(i).where(and(eq(u,d.id),eq(c,e))).limit(1))[0])continue;let{id:p,...b}=d,z=await s.update(i).set(b).where(eq(u,p)).returning();z[0]&&a.updated.push(z[0]);}if(t.delete)for(let d of t.delete)(await s.delete(i).where(and(eq(u,d),eq(c,e))).returning())[0]&&a.deleted.push(d);if(t.connect)for(let d of t.connect)(await s.update(i).set({[o.foreignKey]:e}).where(eq(u,d)).returning())[0]&&a.connected.push(d);if(t.disconnect)for(let d of t.disconnect)(await s.update(i).set({[o.foreignKey]:null}).where(and(eq(u,d),eq(c,e))).returning())[0]&&a.disconnected.push(d);return a}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},U=class extends w{db;useTransaction=false;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[u,d]of Object.entries(n))a.push(eq(this.getColumn(u),d));return i.enabled&&a.push(isNull(this.getColumn(i.field))),(await t.select().from(r).where(and(...a)).limit(1))[0]||null}async delete(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[c,u]of Object.entries(n))a.push(eq(this.getColumn(c),u));return i.enabled&&a.push(isNull(this.getColumn(i.field))),i.enabled?(await t.update(r).set({[i.field]:new Date}).where(and(...a)).returning())[0]||null:(await t.delete(r).where(and(...a)).returning())[0]||null}async countRelated(e,n,o,t){let r=t??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=m(s,o.foreignKey),a=await r.select({count:sql`count(*)`}).from(s).where(eq(i,e));return Number(a[0]?.count)||0}async deleteRelated(e,n,o,t){let r=t??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=m(s,o.foreignKey);return (await r.delete(s).where(eq(i,e)).returning()).length}async nullifyRelated(e,n,o,t){let r=t??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=m(s,o.foreignKey);return (await r.update(s).set({[o.foreignKey]:null}).where(eq(i,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},B=class extends x{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let n=this.getTable(),o=[],t=this.getSoftDeleteConfig();if(t.enabled){let y=this.getColumn(t.field);e.options.onlyDeleted?o.push(isNotNull(y)):e.options.withDeleted||o.push(isNull(y));}for(let y of e.filters){let R=O(n,y);R&&o.push(R);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(R=>{let $=this.getColumn(R);return sql`LOWER(${$}) LIKE LOWER(${`%${e.options.search}%`})`});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=this.getDb(),i=await s.select({count:sql`count(*)`}).from(n).where(r),a=Number(i[0]?.count)||0,c=s.select().from(n).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(R(y));}let u=e.options.page||1,d=e.options.per_page||this.defaultPerPage;c=c.limit(d).offset((u-1)*d);let g=await c,p={relations:e.options.include||[]},b=await j(this.getDb(),g,this._meta,p),z=Math.ceil(a/d);return {result:b,result_info:{page:u,per_page:d,total_count:a,total_pages:z,has_next_page:u<z,has_prev_page:u>1}}}},A=class extends z$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async restore(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[u,d]of Object.entries(n))a.push(eq(this.getColumn(u),d));return a.push(isNotNull(this.getColumn(i.field))),(await t.update(r).set({[i.field]:null}).where(and(...a)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var L=class extends B$1{db;getDb(){return D(this)}getTable(){return h(this._meta)}async batchCreate(e){let n=this.getTable(),o=e.map(r=>this.applyManagedInsertFields(r,"drizzle"));return await this.getDb().insert(n).values(o).returning()}},K=class extends C{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchUpdate(e){let n=this.getTable(),o=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[],s=[];for(let i of e){let a=[eq(o,i.id)];t.enabled&&a.push(isNull(this.getColumn(t.field)));let c=await this.getDb().update(n).set(this.applyManagedUpdateFields(i.data)).where(and(...a)).returning();c[0]?r.push(c[0]):s.push(i.id);}return {updated:r,notFound:s}}},Q=class extends D$1{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchDelete(e){let n=this.getTable(),o=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(o,e)];t.enabled&&r.push(isNull(this.getColumn(t.field)));let s;t.enabled?s=await this.getDb().update(n).set({[t.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(n).where(and(...r)).returning();let i=s,a=new Set(i.map(u=>String(u[this.lookupField]))),c=e.filter(u=>!a.has(u));return {deleted:i,notFound:c}}},Z=class extends E{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchRestore(e){let n=this.getTable(),o=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(o,e),isNotNull(this.getColumn(t.field))],i=await this.getDb().update(n).set({[t.field]:null}).where(and(...r)).returning(),a=new Set(i.map(u=>String(u[this.lookupField]))),c=e.filter(u=>!a.has(u));return {restored:i,notFound:c}}};function qe(l){return l.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}function gt(l){return l.split(/\s+/).filter(e=>e.length>0)}var F=class extends A$1{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let n=this.getTable(),o=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let i of o){let a=e[i];a!==void 0&&r.push(eq(this.getColumn(i),a));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(n).where(and(...r)).limit(1))[0]||null}async create(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(n).values(o).returning())[0]}async update(e,n){let o=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(n)).where(eq(this.getColumn(t),r)).returning())[0]}async nativeUpsert(e,n){let o=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),i=this.getTimestampsConfig(),a=this.applyManagedInsertFields(e,"drizzle"),c={};for(let[g,p]of Object.entries(e))!t.includes(g)&&g!==r&&(this.createOnlyFields?.includes(g)||(c[g]=p));i.enabled&&(c[i.updatedAt]=Date.now());let u=t.map(g=>this.getColumn(g)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));try{return {data:(await this.getDb().insert(o).values(a).onConflictDoUpdate({target:u,set:Object.keys(c).length>0?c:{[r]:sql`${this.getColumn(r)}`},where:d}).returning())[0],created:!1}}catch(g){if(g instanceof Error&&g.message.includes("onConflictDoUpdate"))try{return {data:(await this.getDb().insert(o).values(a).onDuplicateKeyUpdate({set:Object.keys(c).length>0?c:{[r]:sql`${this.getColumn(r)}`}}).returning())[0],created:!1}}catch{return this.performStandardUpsert(e,n)}throw g}}},N=class extends F$1{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let n=this.getTable(),o=this.getUpsertKeys(),t=[];for(let s of o){let i=e[s];i!==void 0&&t.push(eq(this.getColumn(s),i));}return t.length===0?null:(await this.getDb().select().from(n).where(and(...t)).limit(1))[0]||null}async create(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(n).values(o).returning())[0]}async update(e,n){let o=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(n)).where(eq(this.getColumn(t),r)).returning())[0]}async nativeBatchUpsert(e,n){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),i=e.map(d=>this.applyManagedInsertFields(d,"drizzle")),a={},c=e[0];for(let d of Object.keys(c))!t.includes(d)&&d!==r&&(this.createOnlyFields?.includes(d)||(a[d]=sql`excluded.${sql.identifier(d)}`));s.enabled&&(a[s.updatedAt]=Date.now());let u=t.map(d=>this.getColumn(d));try{let g=await this.getDb().insert(o).values(i).onConflictDoUpdate({target:u,set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:g.map((p,b)=>({data:p,created:!1,index:b})),createdCount:0,updatedCount:g.length,totalCount:g.length}}catch(d){if(d instanceof Error&&d.message.includes("onConflictDoUpdate"))try{let p=await this.getDb().insert(o).values(i).onDuplicateKeyUpdate({set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:p.map((b,z)=>({data:b,created:!1,index:z})),createdCount:0,updatedCount:p.length,totalCount:p.length}}catch{return this.performStandardBatchUpsert(e,n)}throw d}}},Le=class extends G{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async recordExists(e){let n=this.getTable(),o=await this.getDb().select({count:sql`count(*)`}).from(n).where(eq(this.getColumn("id"),e));return Number(o[0]?.count)>0}},Ke=class extends H$1{},Qe=class extends I$1{},Ze=class extends J$1{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async rollback(e,n,o){let t=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(t).set({...n,[r]:o}).where(eq(this.getColumn("id"),e)).returning())[0]}},H=class extends K$1{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async aggregate(e){let n=this.getTable(),o=[],t=this.getSoftDeleteConfig();if(t.enabled){let{query:i}=await this.getValidatedData();i?.withDeleted===true||i?.withDeleted==="true"||o.push(isNull(this.getColumn(t.field)));}if(e.filters)for(let[i,a]of Object.entries(e.filters))if(typeof a=="object"&&a!==null)for(let[c,u]of Object.entries(a)){let d=O(n,{field:i,operator:c,value:u});d&&o.push(d);}else o.push(eq(this.getColumn(i),a));let r=o.length>0?and(...o):void 0,s=await this.getDb().select().from(n).where(r);return L$1(s,e)}},J=class extends T{db;getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async search(e,n){let o=this.getTable(),t=[],r=this.getSoftDeleteConfig();r.enabled&&(n.options.onlyDeleted?t.push(isNotNull(this.getColumn(r.field))):n.options.withDeleted||t.push(isNull(this.getColumn(r.field))));for(let w of n.filters){let M=O(o,w);M&&t.push(M);}let s=this.getSearchableFields(),i=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),M=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;t.push(sql`${w} @@ ${M}`);}else {let w=(M,x)=>{try{let se=this.getColumn(M),W=`%${qe(x)}%`;return sql`LOWER(CAST(${se} AS TEXT)) LIKE LOWER(${W}) ESCAPE '\\'`}catch{return}};if(e.mode==="all"){let M=gt(e.query);if(M.length>0){let x=[];for(let se of M){let W=i.map(ie=>w(ie,se)).filter(ie=>ie!==void 0);W.length>0&&x.push(or(...W));}x.length>0&&t.push(and(...x));}}else {let M=i.map(x=>w(x,e.query)).filter(x=>x!==void 0);M.length>0&&t.push(or(...M));}}let a=t.length>0?and(...t):void 0,c=await this.getDb().select({count:sql`count(*)`}).from(o).where(a),u=Number(c[0]?.count)||0,d=this.getDb().select().from(o).where(a);if(n.options.order_by){let w=this.getColumn(n.options.order_by),M=n.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(M(w));}let g=n.options.page||1,p=n.options.per_page||this.defaultPerPage;d=d.limit(p).offset((g-1)*p);let b=await d,z=e.mode==="all"?{...e,mode:"any"}:e,y=U$1(b,z,s),R={relations:n.options.include||[]},$=y.map(w=>w.item),Xe=await j(this.getDb(),$,this._meta,R);return {items:y.map((w,M)=>({...w,item:Xe[M]})),totalCount:u}}},Y=class extends ba{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let n=this.getTable(),o=[],t=this.getSoftDeleteConfig();if(t.enabled){let z=this.getColumn(t.field);e.options.onlyDeleted?o.push(isNotNull(z)):e.options.withDeleted||o.push(isNull(z));}for(let z of e.filters){let y=O(n,z);y&&o.push(y);}if(e.options.search&&this.searchFields.length>0){let z=`%${qe(e.options.search)}%`,y=this.searchFields.map(R=>{let $=this.getColumn(R);return sql`LOWER(${$}) LIKE LOWER(${z}) ESCAPE '\\'`});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(n).where(r),i=Number(s[0]?.count)||0,a=this.getDb().select().from(n).where(r);if(e.options.order_by){let z=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;a=a.orderBy(y(z));}let c=e.options.page||1,u=e.options.per_page||this.defaultPerPage;a=a.limit(u).offset((c-1)*u);let d=await a,g={relations:e.options.include||[]},p=await j(this.getDb(),d,this._meta,g),b=Math.ceil(i/u);return {result:p,result_info:{page:c,per_page:u,total_count:i,total_pages:b,has_next_page:c<b,has_prev_page:c>1}}}},ee=class extends ca{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let n=this.getTable(),o=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let i of o){let a=e[i];a!==void 0&&r.push(eq(this.getColumn(i),a));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(n).where(and(...r)).limit(1))[0]||null}async create(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(n).values(o).returning())[0]}async update(e,n){let o=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(n)).where(eq(this.getColumn(t),r)).returning())[0]}},te=class extends y{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,n){let o=this.getTable(),t=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),s=[eq(t,e)];if(n)for(let[a,c]of Object.entries(n))s.push(eq(this.getColumn(a),c));r.enabled&&s.push(isNull(this.getColumn(r.field)));let i=await this.getDb().select().from(o).where(and(...s)).limit(1);return i[0]?i[0]:null}async createClone(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(n).values(o).returning())[0]}};function an(l,e){return {Create:class extends _{_meta=e;db=l},Read:class extends I{_meta=e;db=l},Update:class extends P{_meta=e;db=l},Delete:class extends U{_meta=e;db=l},List:class extends B{_meta=e;db=l},Restore:class extends A{_meta=e;db=l},Upsert:class extends F{_meta=e;db=l},BatchCreate:class extends L{_meta=e;db=l},BatchUpdate:class extends K{_meta=e;db=l},BatchDelete:class extends Q{_meta=e;db=l},BatchRestore:class extends Z{_meta=e;db=l},BatchUpsert:class extends N{_meta=e;db=l}}}var oe=null,We=false,ne=null;async function re(){if(We){if(ne)throw ne;return oe}We=true;try{return oe=await import('drizzle-zod'),oe}catch{throw ne=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),ne}}async function mt(l,e){return (await re()).createSelectSchema(l,e)}async function bt(l,e){return (await re()).createInsertSchema(l,e)}async function ht(l,e){let n=await re();return n.createUpdateSchema?n.createUpdateSchema(l,e):n.createInsertSchema(l,e).partial()}async function ft(l,e){let n=await re(),o=e?.coerceDates!==false,t=o?Mt(l):new Set,r=n.createSelectSchema(l,e?.selectRefine),s=n.createInsertSchema(l,e?.insertRefine),i;return n.createUpdateSchema?i=n.createUpdateSchema(l,e?.updateRefine):i=n.createInsertSchema(l,e?.updateRefine).partial(),o&&t.size>0&&(s=Ve(s,t),i=Ve(i,t)),{select:r,insert:s,update:i}}function Dt(){return oe!==null}var zt=z.preprocess(l=>{if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date()),yt=z.preprocess(l=>{if(l==null)return null;if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date().nullable());function Mt(l){let e=new Set,n=l;for(let[o,t]of Object.entries(n)){if(o==="_"||o==="$inferInsert"||o==="$inferSelect")continue;let r=t;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),i=String(r.columnType??"").toLowerCase(),a=r.config,c=String(a?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||i.includes("pgtimestamp")||i.includes("pgdate")||i.includes("mysqltimestamp")||i.includes("mysqldate")||i.includes("sqlitetimestamp")||c.includes("timestamp")||c.includes("date"))&&e.add(o);}return e}function Ve(l,e){if(e.size===0)return l;let n=l.shape,o={};for(let[t,r]of Object.entries(n))if(e.has(t)){let s=r.isOptional?.()??false,i=r.isNullable?.()??false,a=zt;(i||s)&&(a=yt),s&&(a=a.optional()),o[t]=a;}else o[t]=r;return z.object(o)}var Rn={CreateEndpoint:_,ListEndpoint:B,ReadEndpoint:I,UpdateEndpoint:P,DeleteEndpoint:U,RestoreEndpoint:A,BatchCreateEndpoint:L,BatchUpdateEndpoint:K,BatchDeleteEndpoint:Q,BatchRestoreEndpoint:Z,BatchUpsertEndpoint:N,SearchEndpoint:J,AggregateEndpoint:H,ExportEndpoint:Y,ImportEndpoint:ee,UpsertEndpoint:F,CloneEndpoint:te};export{ee as A,te as B,an as C,mt as D,bt as E,ht as F,ft as G,Dt as H,Rn as I,X as a,h as b,m as c,Pe as d,de as e,j as f,O as g,_ as h,I as i,P as j,U as k,B as l,A as m,L as n,K as o,Q as p,Z as q,F as r,N as s,Le as t,Ke as u,Qe as v,Ze as w,H as x,J as y,Y as z};
|