viborm 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +529 -0
  2. package/dist/adapters.d.mts +2 -0
  3. package/dist/adapters.mjs +1 -0
  4. package/dist/bun-sql.d.mts +3 -0
  5. package/dist/bun-sql.mjs +2 -0
  6. package/dist/bun-sql.mjs.map +1 -0
  7. package/dist/bun-sqlite.d.mts +3 -0
  8. package/dist/bun-sqlite.mjs +2 -0
  9. package/dist/bun-sqlite.mjs.map +1 -0
  10. package/dist/cache/cloudflare-kv.d.mts +3 -0
  11. package/dist/cache/cloudflare-kv.mjs +2 -0
  12. package/dist/cache/cloudflare-kv.mjs.map +1 -0
  13. package/dist/cache/memory.d.mts +3 -0
  14. package/dist/cache/memory.mjs +2 -0
  15. package/dist/cache/memory.mjs.map +1 -0
  16. package/dist/cache.d.mts +4 -0
  17. package/dist/cache.mjs +1 -0
  18. package/dist/cli.d.mts +1 -0
  19. package/dist/cli.mjs +41 -0
  20. package/dist/cli.mjs.map +1 -0
  21. package/dist/client-CgdtiDGV.mjs +2 -0
  22. package/dist/client-CgdtiDGV.mjs.map +1 -0
  23. package/dist/client.d.mts +3 -0
  24. package/dist/client.mjs +1 -0
  25. package/dist/cloudflare-kv-DauXhtnT.d.mts +1110 -0
  26. package/dist/d1-http.d.mts +3 -0
  27. package/dist/d1-http.mjs +2 -0
  28. package/dist/d1-http.mjs.map +1 -0
  29. package/dist/d1.d.mts +3 -0
  30. package/dist/d1.mjs +2 -0
  31. package/dist/d1.mjs.map +1 -0
  32. package/dist/driver-B_vBzQ6A.mjs +2 -0
  33. package/dist/driver-B_vBzQ6A.mjs.map +1 -0
  34. package/dist/driver-Cj1EbciY.mjs +2 -0
  35. package/dist/driver-Cj1EbciY.mjs.map +1 -0
  36. package/dist/driver.d.mts +2 -0
  37. package/dist/driver.mjs +1 -0
  38. package/dist/errors-DvcqIdEo.mjs +2 -0
  39. package/dist/errors-DvcqIdEo.mjs.map +1 -0
  40. package/dist/helper-cDCDjRAD.d.mts +3020 -0
  41. package/dist/helpers-WNr9B-2U.mjs +2 -0
  42. package/dist/helpers-WNr9B-2U.mjs.map +1 -0
  43. package/dist/hydration-CFnwc7j6.mjs +2 -0
  44. package/dist/hydration-CFnwc7j6.mjs.map +1 -0
  45. package/dist/index-3sdVKfeG.d.mts +1447 -0
  46. package/dist/index-BGmpst1h.d.mts +2158 -0
  47. package/dist/index.d.mts +46 -0
  48. package/dist/index.mjs +2 -0
  49. package/dist/index.mjs.map +1 -0
  50. package/dist/instrumentation.d.mts +2 -0
  51. package/dist/instrumentation.mjs +1 -0
  52. package/dist/libsql.d.mts +3 -0
  53. package/dist/libsql.mjs +2 -0
  54. package/dist/libsql.mjs.map +1 -0
  55. package/dist/migrations.d.mts +1588 -0
  56. package/dist/migrations.mjs +11 -0
  57. package/dist/migrations.mjs.map +1 -0
  58. package/dist/mysql-adapter-0catKeCI.mjs +6 -0
  59. package/dist/mysql-adapter-0catKeCI.mjs.map +1 -0
  60. package/dist/mysql-utils-BPw9qhac.mjs +2 -0
  61. package/dist/mysql-utils-BPw9qhac.mjs.map +1 -0
  62. package/dist/mysql2.d.mts +3 -0
  63. package/dist/mysql2.mjs +2 -0
  64. package/dist/mysql2.mjs.map +1 -0
  65. package/dist/native-types-BwICkVjz.mjs +2 -0
  66. package/dist/native-types-BwICkVjz.mjs.map +1 -0
  67. package/dist/neon-http.d.mts +3 -0
  68. package/dist/neon-http.mjs +2 -0
  69. package/dist/neon-http.mjs.map +1 -0
  70. package/dist/pending-operation-CkzYTpi4.mjs +2 -0
  71. package/dist/pending-operation-CkzYTpi4.mjs.map +1 -0
  72. package/dist/pg.d.mts +3 -0
  73. package/dist/pg.mjs +2 -0
  74. package/dist/pg.mjs.map +1 -0
  75. package/dist/pglite.d.mts +3 -0
  76. package/dist/pglite.mjs +2 -0
  77. package/dist/pglite.mjs.map +1 -0
  78. package/dist/planetscale.d.mts +3 -0
  79. package/dist/planetscale.mjs +2 -0
  80. package/dist/planetscale.mjs.map +1 -0
  81. package/dist/postgres-adapter-Blzqj1bl.mjs +6 -0
  82. package/dist/postgres-adapter-Blzqj1bl.mjs.map +1 -0
  83. package/dist/postgres.d.mts +3 -0
  84. package/dist/postgres.mjs +2 -0
  85. package/dist/postgres.mjs.map +1 -0
  86. package/dist/push-qZreXYkb.mjs +252 -0
  87. package/dist/push-qZreXYkb.mjs.map +1 -0
  88. package/dist/result-parsing-FNQbuHvC.mjs +2 -0
  89. package/dist/result-parsing-FNQbuHvC.mjs.map +1 -0
  90. package/dist/schema-DeAJZocc.mjs +2 -0
  91. package/dist/schema-DeAJZocc.mjs.map +1 -0
  92. package/dist/schema.d.mts +293 -0
  93. package/dist/schema.mjs +2 -0
  94. package/dist/schema.mjs.map +1 -0
  95. package/dist/spans-CJt5UgbJ.mjs +2 -0
  96. package/dist/spans-CJt5UgbJ.mjs.map +1 -0
  97. package/dist/sqlite-adapter-5Em_-oGU.mjs +6 -0
  98. package/dist/sqlite-adapter-5Em_-oGU.mjs.map +1 -0
  99. package/dist/sqlite-utils-BW7elKTz.mjs +2 -0
  100. package/dist/sqlite-utils-BW7elKTz.mjs.map +1 -0
  101. package/dist/sqlite3.d.mts +3 -0
  102. package/dist/sqlite3.mjs +2 -0
  103. package/dist/sqlite3.mjs.map +1 -0
  104. package/dist/tracer-CGzIAsj8.mjs +2 -0
  105. package/dist/tracer-CGzIAsj8.mjs.map +1 -0
  106. package/dist/validation-RtU-wu4N.mjs +2 -0
  107. package/dist/validation-RtU-wu4N.mjs.map +1 -0
  108. package/dist/validation.d.mts +2 -0
  109. package/dist/validation.mjs +1 -0
  110. package/dist/validator-DpJsJcd7.mjs +3 -0
  111. package/dist/validator-DpJsJcd7.mjs.map +1 -0
  112. package/package.json +278 -0
  113. package/readme/README.md +69 -0
@@ -0,0 +1,1110 @@
1
+ import { E as DriverResultParser, F as Sql$1, I as InstrumentationContext, N as QueryResult, P as TransactionOptions, T as Driver, b as PreparedQuery, h as DatabaseAdapter, k as BatchQuery, mt as InstrumentationConfig, w as AnyDriver, x as QueryMetadata } from "./index-BGmpst1h.mjs";
2
+ import { _ as Model, a as AnyRelation, b as Field, f as WithCacheOptions, l as CacheInvalidationOptions, t as FieldRecord, v as ModelState, z as FieldState } from "./helper-cDCDjRAD.mjs";
3
+ import { fn as Prettify, jt as EnumValues } from "./index-3sdVKfeG.mjs";
4
+ import { Pool, PoolClient, PoolConfig, PoolConfig as PgOptions } from "pg";
5
+ import postgres, { Options, Sql } from "postgres";
6
+ import { PGlite, PGliteOptions, PGliteOptions as PGliteOptions$1, Transaction } from "@electric-sql/pglite";
7
+ import Database from "better-sqlite3";
8
+ import { Client, Config, Transaction as Transaction$1 } from "@libsql/client";
9
+ import { NeonQueryFunction, NeonQueryFunctionInTransaction } from "@neondatabase/serverless";
10
+ import { Client as Client$1, Config as Config$1, Connection, Transaction as Transaction$2 } from "@planetscale/database";
11
+ import { Pool as Pool$1, PoolConnection, PoolOptions } from "mysql2/promise";
12
+ import { StandardSchemaV1 } from "@standard-schema/spec";
13
+ import { D1Database, KVNamespace } from "@cloudflare/workers-types";
14
+
15
+ //#region src/cache/drivers/memory.d.ts
16
+
17
+ /**
18
+ * In-memory cache implementation
19
+ */
20
+ declare class MemoryCache extends CacheDriver {
21
+ private readonly store;
22
+ private readonly timers;
23
+ constructor();
24
+ protected get<T>(key: string): Promise<CacheEntry<T> | null>;
25
+ protected set<T>(key: string, storageTtl: number, entry: CacheEntry<T>): Promise<void>;
26
+ protected delete(keys: string[]): Promise<void>;
27
+ protected clear(prefix: string): Promise<void>;
28
+ private clearTimer;
29
+ }
30
+ //#endregion
31
+ //#region src/cache/key.d.ts
32
+ /**
33
+ * Cache Key Generation
34
+ *
35
+ * Generates deterministic cache keys from operation parameters.
36
+ */
37
+ /**
38
+ * Prefix for all VibORM cache keys
39
+ */
40
+ declare const CACHE_PREFIX = "viborm";
41
+ /**
42
+ * Generate a deterministic cache key from operation parameters
43
+ *
44
+ * Returns a FULLY PREFIXED key for external use (manual invalidation, etc.)
45
+ *
46
+ * Key structure: viborm[:v<version>]:<model>:<operation>:<hash>
47
+ *
48
+ * @example
49
+ * generateCacheKey("user", "findMany", { where: { active: true } })
50
+ * // "viborm:user:findMany:abc123..."
51
+ *
52
+ * generateCacheKey("user", "findMany", { where: { active: true } }, 2)
53
+ * // "viborm:v2:user:findMany:abc123..."
54
+ */
55
+ declare function generateCacheKey(modelName: string, operation: string, args: unknown, version?: string | number): string;
56
+ /**
57
+ * Generate prefix for cache invalidation
58
+ * Used to clear all cached queries for a model
59
+ *
60
+ * Returns a FULLY PREFIXED prefix for external use.
61
+ */
62
+ declare function generateCachePrefix(modelName?: string, version?: string | number): string;
63
+ //#endregion
64
+ //#region src/cache/ttl.d.ts
65
+ /**
66
+ * TTL Parser
67
+ *
68
+ * Converts human-readable TTL strings to milliseconds.
69
+ */
70
+ declare function parseTTL(ttl: string | number): number;
71
+ //#endregion
72
+ //#region src/drivers/bun-sql/index.d.ts
73
+ interface BunSQL {
74
+ (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;
75
+ unsafe<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;
76
+ begin<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;
77
+ close(): void;
78
+ reserve(): Promise<BunSQLReservedConnection>;
79
+ }
80
+ interface BunSQLTransaction {
81
+ (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;
82
+ unsafe<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;
83
+ savepoint<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;
84
+ }
85
+ interface BunSQLReservedConnection {
86
+ (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;
87
+ unsafe<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;
88
+ release(): void;
89
+ }
90
+ interface BunSQLOptions {
91
+ hostname?: string;
92
+ port?: number;
93
+ username?: string;
94
+ password?: string;
95
+ database?: string;
96
+ tls?: boolean | object;
97
+ max?: number;
98
+ idleTimeout?: number;
99
+ maxLifetime?: number;
100
+ }
101
+ interface BunSQLDriverOptions {
102
+ client?: BunSQL;
103
+ databaseUrl?: string;
104
+ options?: BunSQLOptions;
105
+ pgvector?: boolean;
106
+ postgis?: boolean;
107
+ }
108
+ type BunSQLClientConfig<C extends DriverConfig> = BunSQLDriverOptions & C;
109
+ declare class BunSQLDriver extends Driver<BunSQL, BunSQLTransaction> {
110
+ readonly adapter: DatabaseAdapter;
111
+ private readonly driverOptions;
112
+ constructor(options?: BunSQLDriverOptions);
113
+ protected initClient(): Promise<BunSQL>;
114
+ protected closeClient(sql: BunSQL): Promise<void>;
115
+ protected execute<T>(client: BunSQL | BunSQLTransaction, sql: string, params: unknown[]): Promise<QueryResult<T>>;
116
+ protected executeRaw<T>(client: BunSQL | BunSQLTransaction, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
117
+ protected transaction<T>(client: BunSQL | BunSQLTransaction, fn: (tx: BunSQLTransaction) => Promise<T>, options?: TransactionOptions): Promise<T>;
118
+ }
119
+ declare function createClient$12<C extends DriverConfig>(config: BunSQLClientConfig<C>): VibORMClient<C & {
120
+ driver: BunSQLDriver;
121
+ }>;
122
+ //#endregion
123
+ //#region src/drivers/bun-sqlite/index.d.ts
124
+ interface BunSQLiteDatabase {
125
+ query<T = unknown>(sql: string): BunSQLiteStatement<T>;
126
+ prepare<T = unknown>(sql: string): BunSQLiteStatement<T>;
127
+ run(sql: string, ...params: unknown[]): void;
128
+ exec(sql: string): void;
129
+ close(): void;
130
+ transaction<T>(fn: () => T): () => T;
131
+ }
132
+ interface BunSQLiteStatement<T = unknown> {
133
+ all(...params: unknown[]): T[];
134
+ get(...params: unknown[]): T | null;
135
+ run(...params: unknown[]): {
136
+ changes: number;
137
+ lastInsertRowid: number | bigint;
138
+ };
139
+ values(...params: unknown[]): unknown[][];
140
+ }
141
+ interface BunSQLiteOptions {
142
+ readonly?: boolean;
143
+ create?: boolean;
144
+ readwrite?: boolean;
145
+ strict?: boolean;
146
+ }
147
+ interface BunSQLiteDriverOptions {
148
+ client?: BunSQLiteDatabase;
149
+ dataDir?: string;
150
+ options?: BunSQLiteOptions;
151
+ }
152
+ type BunSQLiteClientConfig<C extends DriverConfig> = BunSQLiteDriverOptions & C;
153
+ declare class BunSQLiteDriver extends Driver<BunSQLiteDatabase, BunSQLiteDatabase> {
154
+ readonly adapter: DatabaseAdapter;
155
+ readonly result: DriverResultParser;
156
+ private readonly driverOptions;
157
+ constructor(options?: BunSQLiteDriverOptions);
158
+ protected initClient(): Promise<BunSQLiteDatabase>;
159
+ protected closeClient(db: BunSQLiteDatabase): Promise<void>;
160
+ protected execute<T>(client: BunSQLiteDatabase, sql: string, params: unknown[]): Promise<QueryResult<T>>;
161
+ protected executeRaw<T>(client: BunSQLiteDatabase, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
162
+ private runStatement;
163
+ protected transaction<T>(client: BunSQLiteDatabase, fn: (tx: BunSQLiteDatabase) => Promise<T>, _options?: TransactionOptions): Promise<T>;
164
+ }
165
+ declare function createClient$11<C extends DriverConfig>(config: BunSQLiteClientConfig<C>): VibORMClient<C & {
166
+ driver: BunSQLiteDriver;
167
+ }>;
168
+ //#endregion
169
+ //#region src/drivers/d1/index.d.ts
170
+ interface D1DriverOptions {
171
+ database: D1Database;
172
+ }
173
+ type D1ClientConfig<C extends DriverConfig> = D1DriverOptions & C;
174
+ declare class D1Driver extends Driver<D1Database, D1Database> {
175
+ readonly adapter: DatabaseAdapter;
176
+ readonly result: DriverResultParser;
177
+ readonly supportsTransactions = false;
178
+ readonly supportsBatch = true;
179
+ private readonly driverOptions;
180
+ constructor(options: D1DriverOptions);
181
+ protected initClient(): Promise<D1Database>;
182
+ protected closeClient(_db: D1Database): Promise<void>;
183
+ protected execute<T>(client: D1Database, sql: string, params: unknown[]): Promise<QueryResult<T>>;
184
+ protected executeRaw<T>(client: D1Database, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
185
+ protected transaction<T>(client: D1Database, fn: (tx: D1Database) => Promise<T>, _options?: TransactionOptions): Promise<T>;
186
+ /**
187
+ * Execute multiple queries atomically using D1's native batch() API.
188
+ * All queries succeed or all fail together.
189
+ */
190
+ protected executeBatch<T>(client: D1Database, queries: BatchQuery[]): Promise<QueryResult<T>[]>;
191
+ }
192
+ declare function createClient$10<C extends DriverConfig>(config: D1ClientConfig<C>): VibORMClient<C & {
193
+ driver: D1Driver;
194
+ }>;
195
+ //#endregion
196
+ //#region src/drivers/d1-http/index.d.ts
197
+ interface D1HTTPClient {
198
+ accountId: string;
199
+ databaseId: string;
200
+ apiToken: string;
201
+ baseUrl: string;
202
+ }
203
+ interface D1HTTPDriverOptions {
204
+ accountId: string;
205
+ databaseId: string;
206
+ apiToken: string;
207
+ baseUrl?: string;
208
+ }
209
+ type D1HTTPClientConfig<C extends DriverConfig> = D1HTTPDriverOptions & C;
210
+ declare class D1HTTPDriver extends Driver<D1HTTPClient, D1HTTPClient> {
211
+ readonly adapter: DatabaseAdapter;
212
+ readonly result: DriverResultParser;
213
+ readonly supportsTransactions = false;
214
+ readonly supportsBatch = true;
215
+ private readonly driverOptions;
216
+ constructor(options: D1HTTPDriverOptions);
217
+ protected initClient(): Promise<D1HTTPClient>;
218
+ protected closeClient(_client: D1HTTPClient): Promise<void>;
219
+ private executeQuery;
220
+ protected execute<T>(client: D1HTTPClient, sql: string, params: unknown[]): Promise<QueryResult<T>>;
221
+ protected executeRaw<T>(client: D1HTTPClient, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
222
+ protected transaction<T>(client: D1HTTPClient, fn: (tx: D1HTTPClient) => Promise<T>, _options?: TransactionOptions): Promise<T>;
223
+ /**
224
+ * Execute multiple queries atomically using D1 HTTP API batch endpoint.
225
+ * The API accepts an array of queries in the request body.
226
+ */
227
+ protected executeBatch<T>(client: D1HTTPClient, queries: BatchQuery[]): Promise<QueryResult<T>[]>;
228
+ }
229
+ declare function createClient$9<C extends DriverConfig>(config: D1HTTPClientConfig<C>): VibORMClient<C & {
230
+ driver: D1HTTPDriver;
231
+ }>;
232
+ //#endregion
233
+ //#region src/drivers/libsql/index.d.ts
234
+ type LibSQLOptions = Omit<Config, "url">;
235
+ interface LibSQLDriverOptions {
236
+ client?: Client;
237
+ databaseUrl?: string;
238
+ dataDir?: string;
239
+ authToken?: string;
240
+ options?: LibSQLOptions;
241
+ }
242
+ type LibSQLClientConfig<C extends DriverConfig> = LibSQLDriverOptions & C;
243
+ declare class LibSQLDriver extends Driver<Client, Transaction$1> {
244
+ readonly adapter: DatabaseAdapter;
245
+ readonly result: DriverResultParser;
246
+ private readonly driverOptions;
247
+ constructor(options?: LibSQLDriverOptions);
248
+ protected initClient(): Promise<Client>;
249
+ protected closeClient(client: Client): Promise<void>;
250
+ protected execute<T>(client: Client | Transaction$1, sql: string, params: unknown[]): Promise<QueryResult<T>>;
251
+ protected executeRaw<T>(client: Client | Transaction$1, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
252
+ protected transaction<T>(client: Client | Transaction$1, fn: (tx: Transaction$1) => Promise<T>, _options?: TransactionOptions): Promise<T>;
253
+ }
254
+ declare function createClient$8<C extends DriverConfig>(config: LibSQLClientConfig<C>): VibORMClient<C & {
255
+ driver: LibSQLDriver;
256
+ }>;
257
+ //#endregion
258
+ //#region src/drivers/mysql2/index.d.ts
259
+ type MySQL2Options = PoolOptions;
260
+ interface MySQL2DriverOptions {
261
+ pool?: Pool$1;
262
+ options?: PoolOptions;
263
+ databaseUrl?: string;
264
+ }
265
+ type MySQL2ClientConfig<C extends DriverConfig> = MySQL2DriverOptions & C;
266
+ declare class MySQL2Driver extends Driver<Pool$1, PoolConnection> {
267
+ readonly adapter: DatabaseAdapter;
268
+ readonly result: DriverResultParser;
269
+ private readonly driverOptions;
270
+ constructor(options?: MySQL2DriverOptions);
271
+ protected initClient(): Promise<Pool$1>;
272
+ protected closeClient(pool: Pool$1): Promise<void>;
273
+ protected execute<T>(client: Pool$1 | PoolConnection, sql: string, params: unknown[]): Promise<QueryResult<T>>;
274
+ protected executeRaw<T>(client: Pool$1 | PoolConnection, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
275
+ protected transaction<T>(client: Pool$1 | PoolConnection, fn: (tx: PoolConnection) => Promise<T>, options?: TransactionOptions): Promise<T>;
276
+ }
277
+ declare function createClient$7<C extends DriverConfig>(config: MySQL2ClientConfig<C>): VibORMClient<C & {
278
+ driver: MySQL2Driver;
279
+ }>;
280
+ //#endregion
281
+ //#region src/drivers/neon-http/index.d.ts
282
+ interface NeonHTTPDriverOptions {
283
+ databaseUrl?: string;
284
+ options?: {
285
+ fetchOptions?: RequestInit;
286
+ };
287
+ pgvector?: boolean;
288
+ postgis?: boolean;
289
+ }
290
+ type NeonHTTPClientConfig<C extends DriverConfig> = NeonHTTPDriverOptions & C;
291
+ /**
292
+ * NeonQuery is the main query function returned by neon().
293
+ * Configured with arrayMode=false (object rows) and fullResults=true (includes rowCount).
294
+ */
295
+ type NeonQuery = NeonQueryFunction<false, true>;
296
+ /**
297
+ * NeonTx is the transaction-bound query function passed to transaction callbacks.
298
+ * Configured with arrayMode=false and fullResults=true to match the main client.
299
+ */
300
+ type NeonTx = NeonQueryFunctionInTransaction<false, true>;
301
+ declare class NeonHTTPDriver extends Driver<NeonQuery, NeonTx> {
302
+ readonly adapter: DatabaseAdapter;
303
+ readonly supportsTransactions = false;
304
+ readonly supportsBatch = true;
305
+ private readonly driverOptions;
306
+ constructor(options?: NeonHTTPDriverOptions);
307
+ protected initClient(): Promise<NeonQuery>;
308
+ protected closeClient(_client: NeonQuery): Promise<void>;
309
+ protected execute<T>(client: NeonQuery | NeonTx, sql: string, params: unknown[]): Promise<QueryResult<T>>;
310
+ protected executeRaw<T>(client: NeonQuery | NeonTx, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
311
+ protected transaction<T>(client: NeonQuery | NeonTx, fn: (tx: NeonTx) => Promise<T>): Promise<T>;
312
+ /**
313
+ * Execute multiple queries atomically using Neon's transaction() function.
314
+ * This provides atomic batch execution with full PostgreSQL transaction semantics.
315
+ */
316
+ protected executeBatch<T>(client: NeonQuery, queries: BatchQuery[]): Promise<QueryResult<T>[]>;
317
+ /**
318
+ * Parse Neon result into QueryResult format.
319
+ */
320
+ private parseResult;
321
+ }
322
+ declare function createClient$6<C extends DriverConfig>(config: NeonHTTPClientConfig<C>): VibORMClient<C & {
323
+ driver: NeonHTTPDriver;
324
+ }>;
325
+ //#endregion
326
+ //#region src/drivers/pg/index.d.ts
327
+ interface PgDriverOptions {
328
+ pool?: Pool;
329
+ options?: PoolConfig;
330
+ pgvector?: boolean;
331
+ postgis?: boolean;
332
+ databaseUrl?: string;
333
+ }
334
+ type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;
335
+ declare class PgDriver extends Driver<Pool, PoolClient> {
336
+ readonly adapter: DatabaseAdapter;
337
+ private readonly driverOptions;
338
+ constructor(options?: PgDriverOptions);
339
+ protected initClient(): Promise<Pool>;
340
+ protected closeClient(pool: Pool): Promise<void>;
341
+ protected execute<T>(client: Pool | PoolClient, sql: string, params: unknown[]): Promise<QueryResult<T>>;
342
+ protected executeRaw<T>(client: Pool | PoolClient, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
343
+ protected transaction<T>(client: Pool | PoolClient, fn: (tx: PoolClient) => Promise<T>, options?: TransactionOptions): Promise<T>;
344
+ }
345
+ declare function createClient$5<C extends DriverConfig>(config: PgClientConfig<C>): VibORMClient<C & {
346
+ driver: PgDriver;
347
+ }>;
348
+ //#endregion
349
+ //#region src/drivers/pglite/index.d.ts
350
+ interface PGliteDriverOptions {
351
+ client?: PGlite;
352
+ dataDir?: string;
353
+ options?: PGliteOptions;
354
+ pgvector?: boolean;
355
+ postgis?: boolean;
356
+ }
357
+ type PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;
358
+ declare class PGliteDriver extends Driver<PGlite, Transaction> {
359
+ readonly adapter: DatabaseAdapter;
360
+ private readonly driverOptions;
361
+ constructor(options?: PGliteDriverOptions);
362
+ protected initClient(): Promise<PGlite>;
363
+ protected closeClient(client: PGlite): Promise<void>;
364
+ protected execute<T>(client: PGlite | Transaction, sql: string, params: unknown[]): Promise<QueryResult<T>>;
365
+ protected executeRaw<T>(client: PGlite | Transaction, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
366
+ protected transaction<T>(client: PGlite | Transaction, fn: (tx: Transaction) => Promise<T>, _options?: TransactionOptions): Promise<T>;
367
+ }
368
+ declare function createClient$4<C extends DriverConfig>(config: PGliteConfig<C>): VibORMClient<C & {
369
+ driver: PGliteDriver;
370
+ }>;
371
+ //#endregion
372
+ //#region src/drivers/planetscale/index.d.ts
373
+ type PlanetScaleOptions = Omit<Config$1, "url">;
374
+ interface PlanetScaleDriverOptions {
375
+ client?: Client$1;
376
+ databaseUrl?: string;
377
+ options?: PlanetScaleOptions;
378
+ }
379
+ type PlanetScaleClientConfig<C extends DriverConfig> = PlanetScaleDriverOptions & C;
380
+ type PlanetScaleClient = Client$1 | Connection;
381
+ declare class PlanetScaleDriver extends Driver<PlanetScaleClient, Transaction$2> {
382
+ readonly adapter: DatabaseAdapter;
383
+ readonly result: DriverResultParser;
384
+ readonly supportsTransactions = true;
385
+ private readonly driverOptions;
386
+ constructor(options?: PlanetScaleDriverOptions);
387
+ protected initClient(): Promise<PlanetScaleClient>;
388
+ protected closeClient(_client: PlanetScaleClient): Promise<void>;
389
+ protected execute<T>(client: PlanetScaleClient | Transaction$2, sql: string, params: unknown[]): Promise<QueryResult<T>>;
390
+ protected executeRaw<T>(client: PlanetScaleClient | Transaction$2, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
391
+ protected transaction<T>(client: PlanetScaleClient | Transaction$2, fn: (tx: Transaction$2) => Promise<T>, options?: TransactionOptions): Promise<T>;
392
+ }
393
+ declare function createClient$3<C extends DriverConfig>(config: PlanetScaleClientConfig<C>): VibORMClient<C & {
394
+ driver: PlanetScaleDriver;
395
+ }>;
396
+ //#endregion
397
+ //#region src/drivers/postgres/index.d.ts
398
+ type PostgresOptions = Options<Record<string, postgres.PostgresType>>;
399
+ type PostgresTransaction = postgres.TransactionSql<Record<string, unknown>>;
400
+ interface PostgresDriverOptions {
401
+ client?: Sql<Record<string, unknown>>;
402
+ options?: PostgresOptions;
403
+ pgvector?: boolean;
404
+ postgis?: boolean;
405
+ databaseUrl?: string;
406
+ }
407
+ type PostgresClientConfig<C extends DriverConfig> = PostgresDriverOptions & C;
408
+ type PostgresClient = Sql<Record<string, unknown>>;
409
+ declare class PostgresDriver extends Driver<PostgresClient, PostgresTransaction> {
410
+ readonly adapter: DatabaseAdapter;
411
+ private readonly driverOptions;
412
+ constructor(options?: PostgresDriverOptions);
413
+ protected initClient(): Promise<PostgresClient>;
414
+ protected closeClient(sql: PostgresClient): Promise<void>;
415
+ protected execute<T>(client: PostgresClient | PostgresTransaction, sqlStr: string, params: unknown[]): Promise<QueryResult<T>>;
416
+ protected executeRaw<T>(client: PostgresClient | PostgresTransaction, sqlStr: string, params?: unknown[]): Promise<QueryResult<T>>;
417
+ protected transaction<T>(client: PostgresClient | PostgresTransaction, fn: (tx: PostgresTransaction) => Promise<T>, options?: TransactionOptions): Promise<T>;
418
+ }
419
+ declare function createClient$2<C extends DriverConfig>(config: PostgresClientConfig<C>): VibORMClient<C & {
420
+ driver: PostgresDriver;
421
+ }>;
422
+ //#endregion
423
+ //#region src/drivers/sqlite3/index.d.ts
424
+ type SQLite3Database = Database.Database;
425
+ type SQLite3Options = Database.Options;
426
+ interface SQLite3DriverOptions {
427
+ client?: SQLite3Database;
428
+ dataDir?: string;
429
+ options?: SQLite3Options;
430
+ }
431
+ type SQLite3ClientConfig<C extends DriverConfig> = SQLite3DriverOptions & C;
432
+ declare class SQLite3Driver extends Driver<SQLite3Database, SQLite3Database> {
433
+ readonly adapter: DatabaseAdapter;
434
+ readonly result: DriverResultParser;
435
+ private readonly driverOptions;
436
+ constructor(options?: SQLite3DriverOptions);
437
+ protected initClient(): Promise<SQLite3Database>;
438
+ protected closeClient(db: SQLite3Database): Promise<void>;
439
+ protected execute<T>(client: SQLite3Database, sql: string, params: unknown[]): Promise<QueryResult<T>>;
440
+ protected executeRaw<T>(client: SQLite3Database, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
441
+ private runStatement;
442
+ protected transaction<T>(client: SQLite3Database, fn: (tx: SQLite3Database) => Promise<T>, _options?: TransactionOptions): Promise<T>;
443
+ }
444
+ declare function createClient$1<C extends DriverConfig>(config: SQLite3ClientConfig<C>): VibORMClient<C & {
445
+ driver: SQLite3Driver;
446
+ }>;
447
+ //#endregion
448
+ //#region src/client/pending-operation.d.ts
449
+ /**
450
+ * Symbol to identify PendingOperation instances
451
+ */
452
+ declare const PENDING_OPERATION_SYMBOL: unique symbol;
453
+ /**
454
+ * A pending database operation that implements PromiseLike for deferred execution.
455
+ *
456
+ * @example
457
+ * // Direct await - executes immediately
458
+ * const users = await client.user.findMany();
459
+ *
460
+ * @example
461
+ * // Batch execution - deferred until $transaction is called
462
+ * const [users, posts] = await client.$transaction([
463
+ * client.user.findMany(),
464
+ * client.post.findMany(),
465
+ * ]);
466
+ */
467
+ declare class PendingOperation<T> implements PromiseLike<T> {
468
+ /**
469
+ * Symbol to identify this as a PendingOperation
470
+ */
471
+ readonly [PENDING_OPERATION_SYMBOL] = true;
472
+ /**
473
+ * Query metadata containing args, operation info, and executor
474
+ */
475
+ private readonly metadata;
476
+ /**
477
+ * Cached promise for execution.
478
+ * Ensures execute() is only called once even if multiple
479
+ * PromiseLike methods are chained on the same instance.
480
+ */
481
+ private _promise;
482
+ /**
483
+ * Tracks how this operation was executed to prevent mixing execution modes.
484
+ * - null: Not yet executed
485
+ * - "default": Executed via await/then/execute() (no driver override)
486
+ * - AnyDriver: Executed via executeWith(driver) in a transaction context
487
+ */
488
+ private _executedWith;
489
+ constructor(metadata: QueryMetadata<T>);
490
+ /**
491
+ * Get or create the cached promise for direct execution.
492
+ * This ensures the executor is only called once.
493
+ * Throws if already executed with a specific driver (transaction context).
494
+ */
495
+ private getPromise;
496
+ /**
497
+ * Check if this operation can be batched.
498
+ * Operations with nested writes cannot be batched as they require
499
+ * multiple queries with runtime-dependent values.
500
+ */
501
+ canBatch(): boolean;
502
+ /**
503
+ * Check if this is a batch operation (returns rowCount instead of rows)
504
+ */
505
+ isBatchOperation(): boolean;
506
+ /**
507
+ * Get raw args (not yet validated)
508
+ */
509
+ getArgs(): Record<string, unknown>;
510
+ /**
511
+ * Get model name for tracing
512
+ */
513
+ getModel(): string;
514
+ /**
515
+ * Get operation name for tracing
516
+ */
517
+ getOperation(): string;
518
+ /**
519
+ * Get client ID for origin validation
520
+ */
521
+ getClientId(): symbol;
522
+ /**
523
+ * Execute the operation immediately.
524
+ * Memoized - calling multiple times returns the same promise.
525
+ */
526
+ execute(): Promise<T>;
527
+ /**
528
+ * Execute the operation with a specific driver.
529
+ * Used for transaction-bound execution where we need to use the txDriver.
530
+ *
531
+ * Passes the driver to the executor so operations use the transaction
532
+ * context (savepoints) instead of new transactions.
533
+ *
534
+ * Memoized per-driver - calling with the same driver returns the cached promise.
535
+ * Throws if already executed with a different driver or via await/execute().
536
+ */
537
+ executeWith(driver: AnyDriver): Promise<T>;
538
+ /**
539
+ * Prepare the query for batch execution.
540
+ * Validates and builds SQL without executing.
541
+ *
542
+ * Returns undefined if:
543
+ * - The operation has nested writes (requires multiple queries)
544
+ * - The prepare function is not available
545
+ *
546
+ * @param driver - Optional driver to use for SQL dialect
547
+ * @returns PreparedQuery with sql and params, or undefined if not batchable
548
+ */
549
+ prepare(driver?: AnyDriver): PreparedQuery | undefined;
550
+ /**
551
+ * Parse raw query result into typed result.
552
+ * Used after batch execution to transform the raw result.
553
+ *
554
+ * @param raw - Raw query result from driver
555
+ * @returns Typed result
556
+ */
557
+ parseResult(raw: {
558
+ rows: unknown[];
559
+ rowCount: number;
560
+ }): T;
561
+ /**
562
+ * Wrap the executor with post-processing.
563
+ * Returns a new PendingOperation (immutable pattern).
564
+ *
565
+ * Used by the client to add cache invalidation after mutations.
566
+ *
567
+ * @example
568
+ * ```ts
569
+ * const wrapped = pendingOp.wrapExecutor(async (execute) => {
570
+ * const result = await execute();
571
+ * await cache.invalidate(modelName);
572
+ * return result;
573
+ * });
574
+ * ```
575
+ */
576
+ wrapExecutor(wrapper: (execute: (driver?: AnyDriver) => Promise<T>) => Promise<T>): PendingOperation<T>;
577
+ /**
578
+ * Implement PromiseLike.then() for direct await support
579
+ * When awaited directly, the operation executes immediately
580
+ */
581
+ then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
582
+ /**
583
+ * Implement catch() for error handling
584
+ */
585
+ catch<TResult = never>(onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<T | TResult>;
586
+ /**
587
+ * Implement finally() for cleanup
588
+ */
589
+ finally(onfinally?: (() => void) | null): Promise<T>;
590
+ }
591
+ /**
592
+ * Type guard to check if a value is a PendingOperation
593
+ */
594
+ declare function isPendingOperation<T = unknown>(value: unknown): value is PendingOperation<T>;
595
+ /**
596
+ * Utility type to extract the result type from a PendingOperation
597
+ */
598
+ type UnwrapPendingOperation<T> = T extends PendingOperation<infer U> ? U : T;
599
+ /**
600
+ * Utility type to unwrap an array of PendingOperations
601
+ */
602
+ type UnwrapPendingOperations<T extends readonly PendingOperation<unknown>[]> = { [K in keyof T]: UnwrapPendingOperation<T[K]> };
603
+ //#endregion
604
+ //#region src/client/client.d.ts
605
+ /**
606
+ * VibORM Configuration
607
+ */
608
+ interface VibORMConfig {
609
+ schema: Schema;
610
+ driver: AnyDriver;
611
+ cache?: CacheDriver;
612
+ /** Instrumentation config (for initial setup) or context (for internal reuse) */
613
+ instrumentation?: InstrumentationConfig | InstrumentationContext;
614
+ waitUntil?: WaitUntilFn;
615
+ /** Cache version for invalidating cache on schema changes */
616
+ cacheVersion?: number | string;
617
+ }
618
+ interface DriverConfig extends Omit<VibORMConfig, "driver"> {}
619
+ /**
620
+ * Extended client type with utility methods
621
+ */
622
+ type VibORMClient<C extends VibORMConfig> = Client$2<C> & Omit<{
623
+ /** Access the underlying driver */
624
+ $driver: AnyDriver;
625
+ /** Access the schema (models) */
626
+ $schema: C["schema"];
627
+ /** Execute a raw SQL query */
628
+ $executeRaw: <T = Record<string, unknown>>(query: Sql$1) => Promise<QueryResult<T>>;
629
+ /** Execute a raw SQL string */
630
+ $queryRaw: <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<QueryResult<T>>;
631
+ /**
632
+ * Run operations in a transaction or batch
633
+ *
634
+ * @example Dynamic transaction (callback) - operations can depend on each other
635
+ * ```ts
636
+ * await client.$transaction(async (tx) => {
637
+ * const user = await tx.user.create({ data: { name: "Alice" } });
638
+ * await tx.post.create({ data: { title: "Hello", authorId: user.id } });
639
+ * });
640
+ * ```
641
+ *
642
+ * @example Batch (array) - independent operations, atomic execution
643
+ * ```ts
644
+ * const [users, posts] = await client.$transaction([
645
+ * client.user.findMany(),
646
+ * client.post.findMany(),
647
+ * ]);
648
+ * ```
649
+ */
650
+ $transaction: {
651
+ <T>(fn: (tx: Client$2<C>) => Promise<T>, options?: TransactionOptions): Promise<T>;
652
+ <T extends PendingOperation<unknown>[]>(operations: [...T], options?: TransactionOptions): Promise<{ [K in keyof T]: Awaited<T[K]> }>;
653
+ };
654
+ /** Connect to the database */
655
+ $connect: () => Promise<void>;
656
+ /** Disconnect from the database */
657
+ $disconnect: () => Promise<void>;
658
+ /** Create a client with cache - only read operations available */
659
+ $withCache: (config?: WithCacheOptions) => CachedClient<C["schema"]>;
660
+ /** Invalidate cache entries by keys or patterns (use * suffix for prefix matching) */
661
+ $invalidate: (...keys: string[]) => Promise<void>;
662
+ }, C["cache"] extends CacheDriver ? "never" : "$withCache" | "$invalidate">;
663
+ /**
664
+ * Create a VibORM client
665
+ *
666
+ * @example
667
+ * ```ts
668
+ * import { PGlite } from "@electric-sql/pglite";
669
+ * import { PGliteDriver } from "viborm/drivers/pglite";
670
+ * import { createClient } from "viborm";
671
+ *
672
+ * const db = new PGlite();
673
+ * const driver = new PGliteDriver({ client: db });
674
+ * const client = createClient({ driver, schema: { user, post } });
675
+ *
676
+ * // Query
677
+ * const users = await client.user.findMany({ where: { name: "Alice" } });
678
+ *
679
+ * // Transaction
680
+ * await client.$transaction(async (tx) => {
681
+ * const user = await tx.user.create({ data: { name: "Bob" } });
682
+ * await tx.post.create({ data: { title: "Hello", authorId: user.id } });
683
+ * });
684
+ *
685
+ * // Raw query
686
+ * const result = await client.$executeRaw(sql`SELECT * FROM users`);
687
+ *
688
+ * // Disconnect
689
+ * await client.$disconnect();
690
+ * ```
691
+ */
692
+ declare const createClient: <Config$2 extends VibORMConfig>(config: Config$2) => VibORMClient<Config$2>;
693
+ //#endregion
694
+ //#region src/client/result-types.d.ts
695
+ /**
696
+ * Maps scalar field types to their DATABASE RESULT types.
697
+ * This is what the ORM returns after querying the database.
698
+ *
699
+ * Key difference from validation schema output:
700
+ * - datetime/date/time: returns Date (not ISO string)
701
+ * - json: inferred from custom schema if present, otherwise unknown
702
+ * - enum: inferred from schema values
703
+ */
704
+ type ScalarResultTypeMap = {
705
+ string: string;
706
+ int: number;
707
+ float: number;
708
+ decimal: number;
709
+ boolean: boolean;
710
+ datetime: Date;
711
+ date: Date;
712
+ time: string;
713
+ bigint: bigint;
714
+ json: unknown;
715
+ blob: Uint8Array;
716
+ vector: number[];
717
+ point: {
718
+ x: number;
719
+ y: number;
720
+ };
721
+ enum: string;
722
+ };
723
+ /**
724
+ * Extract the FieldState from a Field using infer to preserve literal types.
725
+ */
726
+ type ExtractFieldState<F$1> = F$1 extends {
727
+ "~": {
728
+ state: infer S;
729
+ };
730
+ } ? S extends FieldState ? S : never : never;
731
+ /**
732
+ * Get the base scalar type for a field, handling custom schemas.
733
+ * For json/enum fields with custom schemas, infer from the schema.
734
+ * For datetime fields, always return Date (regardless of validation schema output).
735
+ *
736
+ * Note: Enum types return `string` when accessed through relations due to type widening.
737
+ * See BUG_REPORT_RELATION_TYPES.md Bug 1 for details.
738
+ */
739
+ type GetScalarResultType<F$1 extends Field> = ExtractFieldState<F$1> extends infer S ? S extends FieldState ? S["type"] extends "json" ? S["schema"] extends StandardSchemaV1<any, infer O> ? O : unknown : S["type"] extends "enum" ? EnumValues<S["base"]>[number] : ScalarResultTypeMap[S["type"]] : unknown : unknown;
740
+ /**
741
+ * Apply nullable wrapper based on field state.
742
+ * Uses non-distributive check to handle boolean literals correctly.
743
+ */
744
+ type ApplyNullable<T, Nullable> = [Nullable] extends [true] ? T | null : T;
745
+ /**
746
+ * Apply array wrapper based on field state.
747
+ * Uses non-distributive check to handle boolean literals correctly.
748
+ */
749
+ type ApplyArray<T, IsArray> = [IsArray] extends [true] ? T[] : T;
750
+ /**
751
+ * Infer the DATABASE RESULT type for a scalar field.
752
+ *
753
+ * This is the canonical helper for inferring output types from fields.
754
+ * It correctly handles:
755
+ * - All scalar types with proper DB result mapping (datetime → Date)
756
+ * - Custom schemas for json/enum fields
757
+ * - Nullable fields
758
+ * - Array fields
759
+ *
760
+ * @example
761
+ * // For s.dateTime().nullable() → Date | null
762
+ * // For s.string().array() → string[]
763
+ * // For s.json().schema(z.object({...})) → { ... }
764
+ */
765
+ type InferScalarOutput<F$1 extends Field> = ExtractFieldState<F$1> extends infer S ? S extends FieldState ? ApplyNullable<ApplyArray<GetScalarResultType<F$1>, S["array"]>, S["nullable"]> : never : never;
766
+ /**
767
+ * Result for batch operations (createMany, updateMany, deleteMany)
768
+ */
769
+ interface BatchPayload {
770
+ count: number;
771
+ }
772
+ /**
773
+ * Result type for count operations
774
+ * Supports select for per-field counts like Prisma: count({ select: { _all: true, name: true } })
775
+ */
776
+ type CountResultType<Args> = Args extends {
777
+ select: infer S;
778
+ } ? Prettify<{ [K in keyof S as S[K] extends true ? K : never]: number }> : number;
779
+ /**
780
+ * Get the target model's state from a relation
781
+ */
782
+ type GetTargetModelState<R extends AnyRelation> = R["~"]["state"]["getter"] extends (() => infer T) ? T extends Model<infer S> ? S extends ModelState ? S : never : never : never;
783
+ /**
784
+ * Infer the output type for a model, respecting omit settings.
785
+ * Uses InferScalarOutput for correct DB result types (e.g., Date for datetime).
786
+ */
787
+ type InferModelOutput<S$1 extends ModelState> = S$1["omit"] extends Record<string, true> ? Omit<{ [K in keyof S$1["scalars"]]: S$1["scalars"][K] extends Field ? InferScalarOutput<S$1["scalars"][K]> : never }, keyof S$1["omit"]> : { [K in keyof S$1["scalars"]]: S$1["scalars"][K] extends Field ? InferScalarOutput<S$1["scalars"][K]> : never };
788
+ /**
789
+ * Get relation type (oneToMany, manyToMany, oneToOne, manyToOne)
790
+ */
791
+ type GetRelationType<R extends AnyRelation> = R["~"]["state"]["type"];
792
+ /**
793
+ * Check if a relation is optional
794
+ */
795
+ type GetRelationOptional<R extends AnyRelation> = R["~"]["state"]["optional"];
796
+ /**
797
+ * Result for a relation when included
798
+ * - To-many relations return arrays
799
+ * - To-one relations return single objects (nullable if optional)
800
+ */
801
+ type InferRelationResult<R extends AnyRelation> = [GetRelationType<R>] extends ["oneToMany" | "manyToMany"] ? InferModelOutput<GetTargetModelState<R>>[] : [GetRelationOptional<R>] extends [true] ? InferModelOutput<GetTargetModelState<R>> | null : InferModelOutput<GetTargetModelState<R>>;
802
+ /**
803
+ * Infer result from select/include args
804
+ * - select: ONLY returns selected fields
805
+ * - include: returns base model + included relations
806
+ * - neither: returns base model output
807
+ */
808
+ type InferSelectInclude<S$1 extends ModelState, Args> = Args extends {
809
+ select: infer Selection;
810
+ } ? InferSelectResult<S$1, Selection> : Args extends {
811
+ include: infer Include;
812
+ } ? InferIncludeResult<S$1, Include> : InferModelOutput<S$1>;
813
+ /**
814
+ * Result when select is provided - ONLY selected fields are returned
815
+ */
816
+ type InferSelectResult<S$1 extends ModelState, Selection$1> = Prettify<{ [K in keyof Selection$1 & keyof S$1["fields"] as Selection$1[K] extends true | object ? K : never]: S$1["fields"][K] extends Field ? InferScalarOutput<S$1["fields"][K]> : S$1["fields"][K] extends AnyRelation ? Selection$1[K] extends true ? InferRelationResult<S$1["fields"][K]> : Selection$1[K] extends {
817
+ select: infer NS;
818
+ } ? InferNestedSelectResult<S$1["fields"][K], NS> : Selection$1[K] extends {
819
+ include: infer NI;
820
+ } ? InferNestedIncludeResult<S$1["fields"][K], NI> : Selection$1[K] extends object ? InferRelationResult<S$1["fields"][K]> : never : never }>;
821
+ /**
822
+ * Result when include is provided - base result + included relations
823
+ */
824
+ type InferIncludeResult<S$1 extends ModelState, Include$1> = Prettify<InferModelOutput<S$1> & { [K in keyof Include$1 & keyof S$1["relations"] as Include$1[K] extends true | object ? K : never]: S$1["relations"][K] extends AnyRelation ? Include$1[K] extends true ? InferRelationResult<S$1["relations"][K]> : Include$1[K] extends {
825
+ select: infer NS;
826
+ } ? InferNestedSelectResult<S$1["relations"][K], NS> : Include$1[K] extends {
827
+ include: infer NI;
828
+ } ? InferNestedIncludeResult<S$1["relations"][K], NI> : Include$1[K] extends object ? InferRelationResult<S$1["relations"][K]> : never : never }>;
829
+ /**
830
+ * Nested select result for a relation
831
+ */
832
+ type InferNestedSelectResult<R extends AnyRelation, NS$1> = [GetRelationType<R>] extends ["oneToMany" | "manyToMany"] ? InferSelectResult<GetTargetModelState<R>, NS$1>[] : [GetRelationOptional<R>] extends [true] ? InferSelectResult<GetTargetModelState<R>, NS$1> | null : InferSelectResult<GetTargetModelState<R>, NS$1>;
833
+ /**
834
+ * Nested include result for a relation
835
+ */
836
+ type InferNestedIncludeResult<R extends AnyRelation, NI$1> = [GetRelationType<R>] extends ["oneToMany" | "manyToMany"] ? InferIncludeResult<GetTargetModelState<R>, NI$1>[] : [GetRelationOptional<R>] extends [true] ? InferIncludeResult<GetTargetModelState<R>, NI$1> | null : InferIncludeResult<GetTargetModelState<R>, NI$1>;
837
+ /**
838
+ * Extract scalar field keys from a FieldRecord
839
+ */
840
+ type ScalarFieldKeys<T extends FieldRecord> = { [K in keyof T]: T[K] extends Field ? K : never }[keyof T];
841
+ /**
842
+ * Infer base type from a field for aggregates.
843
+ * Uses InferScalarOutput for correct DB result types.
844
+ */
845
+ type InferFieldBase<F$1> = F$1 extends Field ? InferScalarOutput<F$1> : never;
846
+ /**
847
+ * Result type for aggregate operations
848
+ * Dynamically typed based on which aggregates are requested
849
+ */
850
+ type AggregateResultType<T extends FieldRecord, Args> = Prettify<{ [K in keyof Args as K extends `_${string}` ? K : never]: K extends "_count" ? Args[K] extends true ? number : Args[K] extends object ? { [F in keyof Args[K]]: number } : never : K extends "_avg" | "_sum" ? Args[K] extends object ? { [F in keyof Args[K]]: number | null } : never : K extends "_min" | "_max" ? Args[K] extends object ? { [F in keyof Args[K]]: F extends ScalarFieldKeys<T> ? InferFieldBase<T[F]> | null : never } : never : never }>;
851
+ /**
852
+ * Result type for groupBy operations
853
+ * Includes the grouped-by fields plus any requested aggregates
854
+ */
855
+ type GroupByResultType<T extends FieldRecord, Args> = Args extends {
856
+ by: infer B;
857
+ } ? Prettify<(B extends readonly (infer K)[] ? K extends ScalarFieldKeys<T> & keyof T ? { [F in K]: InferFieldBase<T[F]> } : never : B extends ScalarFieldKeys<T> & keyof T ? { [F in B]: InferFieldBase<T[F]> } : never) & AggregateResultType<T, Args>> : never;
858
+ //#endregion
859
+ //#region src/client/types.d.ts
860
+ /**
861
+ * Callback to extend the lifetime of the request until the promise resolves.
862
+ * Used in serverless environments (Cloudflare Workers, Vercel Edge) to keep
863
+ * the runtime alive for background operations like SWR revalidation.
864
+ */
865
+ type WaitUntilFn = (promise: Promise<unknown>) => void;
866
+ type Schema = Record<string, Model<any>>;
867
+ type Operations = "findFirst" | "findMany" | "findUnique" | "create" | "createMany" | "update" | "updateMany" | "delete" | "deleteMany" | "findUniqueOrThrow" | "findFirstOrThrow" | "count" | "aggregate" | "groupBy" | "upsert" | "exist";
868
+ /**
869
+ * Operations that can be cached (read-only operations)
870
+ */
871
+ type CacheableOperations = "findFirst" | "findMany" | "findUnique" | "findUniqueOrThrow" | "findFirstOrThrow" | "count" | "aggregate" | "groupBy" | "exist";
872
+ /**
873
+ * Operations that mutate data (not cacheable)
874
+ */
875
+ type MutationOperations = "create" | "createMany" | "update" | "updateMany" | "delete" | "deleteMany" | "upsert";
876
+ /**
877
+ * Extract fields from a Model - works with Model<any>
878
+ */
879
+ type ExtractFields<M> = M extends Model<infer S> ? S extends {
880
+ fields: infer F;
881
+ } ? F extends FieldRecord ? F : FieldRecord : FieldRecord : FieldRecord;
882
+ /**
883
+ * Operation payload type - passes Model directly to args types
884
+ * Each args type extracts what it needs internally from schema inference
885
+ */
886
+ type OperationPayload<O$1 extends Operations, M extends Model<any>> = O$1 extends "findMany" ? M["~"]["schemas"]["args"]["findMany"][" vibInferred"]["0"] : O$1 extends "findUnique" ? M["~"]["schemas"]["args"]["findUnique"][" vibInferred"]["0"] : O$1 extends "findFirst" ? M["~"]["schemas"]["args"]["findFirst"][" vibInferred"]["0"] : O$1 extends "create" ? M["~"]["schemas"]["args"]["create"][" vibInferred"]["0"] : O$1 extends "update" ? M["~"]["schemas"]["args"]["update"][" vibInferred"]["0"] : O$1 extends "delete" ? M["~"]["schemas"]["args"]["delete"][" vibInferred"]["0"] : O$1 extends "deleteMany" ? M["~"]["schemas"]["args"]["deleteMany"][" vibInferred"]["0"] : O$1 extends "upsert" ? M["~"]["schemas"]["args"]["upsert"][" vibInferred"]["0"] : O$1 extends "findUniqueOrThrow" ? M["~"]["schemas"]["args"]["findUnique"][" vibInferred"]["0"] : O$1 extends "findFirstOrThrow" ? M["~"]["schemas"]["args"]["findFirst"][" vibInferred"]["0"] : O$1 extends "count" ? M["~"]["schemas"]["args"]["count"][" vibInferred"]["0"] : O$1 extends "aggregate" ? M["~"]["schemas"]["args"]["aggregate"][" vibInferred"]["0"] : O$1 extends "groupBy" ? M["~"]["schemas"]["args"]["groupBy"][" vibInferred"]["0"] : O$1 extends "createMany" ? M["~"]["schemas"]["args"]["createMany"][" vibInferred"]["0"] : O$1 extends "updateMany" ? M["~"]["schemas"]["args"]["updateMany"][" vibInferred"]["0"] : O$1 extends "exist" ? {
887
+ where: M["~"]["schemas"]["where"][" vibInferred"]["0"];
888
+ } : never;
889
+ /**
890
+ * Operation result type - infers result shape based on select/include args
891
+ * This provides full type safety for ORM operation results
892
+ */
893
+ type OperationResult<O$1 extends Operations, M extends Model<any>, Args> = M extends Model<infer S> ? O$1 extends "findFirst" | "findUnique" ? Prettify<InferSelectInclude<S, Args>> | null : O$1 extends "findFirstOrThrow" | "findUniqueOrThrow" ? Prettify<InferSelectInclude<S, Args>> : O$1 extends "findMany" ? Prettify<InferSelectInclude<S, Args>>[] : O$1 extends "create" | "update" | "delete" | "upsert" ? Prettify<InferSelectInclude<S, Args>> : O$1 extends "createMany" | "updateMany" | "deleteMany" ? BatchPayload : O$1 extends "count" ? CountResultType<Args> : O$1 extends "exist" ? boolean : O$1 extends "aggregate" ? AggregateResultType<ExtractFields<M>, Args> : O$1 extends "groupBy" ? GroupByResultType<ExtractFields<M>, Args>[] : never : never;
894
+ /**
895
+ * Client type - provides fully typed access to all model operations
896
+ * Each operation returns a Promise with the properly inferred result type
897
+ */
898
+ type Client$2<C extends VibORMConfig> = { [K in keyof C["schema"]]: { [O in Operations]: Operation<O, C["schema"][K], C> } };
899
+ type RemoveCacheKey<C extends VibORMConfig, T> = C["cache"] extends CacheDriver ? T : T extends {
900
+ cache?: infer _;
901
+ } ? Omit<T, "cache"> & {} : T;
902
+ /**
903
+ * Operation type - returns PendingOperation which implements PromiseLike
904
+ * This allows operations to be:
905
+ * - Awaited directly: `await client.user.findMany()`
906
+ * - Batched in transactions: `await client.$transaction([op1, op2])`
907
+ */
908
+ type Operation<O$1 extends Operations, M extends Model<any>, C extends VibORMConfig, Payload = OperationPayload<O$1, M>> = undefined extends Payload ? <Arg extends RemoveCacheKey<C, Payload>>(args?: Exclude<Arg, undefined>) => PendingOperation<OperationResult<O$1, M, Arg>> : <Arg extends RemoveCacheKey<C, Payload>>(args: Arg) => PendingOperation<OperationResult<O$1, M, Arg>>;
909
+ /**
910
+ * Cached operation type - returns Promise directly (not batchable)
911
+ */
912
+ type CachedOperation<O$1 extends Operations, M extends Model<any>, Payload = OperationPayload<O$1, M>> = undefined extends Payload ? <Arg extends Payload>(args?: Exclude<Arg, undefined>) => Promise<OperationResult<O$1, M, Arg>> : <Arg extends Payload>(args: Arg) => Promise<OperationResult<O$1, M, Arg>>;
913
+ /**
914
+ * Cached client type - provides typed access to only cacheable (read) operations
915
+ * Returns Promises directly (not PendingOperation) - cache operations are not batchable
916
+ */
917
+ type CachedClient<S$1 extends Schema> = { [K in keyof S$1]: { [O in CacheableOperations]: CachedOperation<O, S$1[K]> } };
918
+ //#endregion
919
+ //#region src/cache/driver.d.ts
920
+ /**
921
+ * Cache entry with metadata for SWR
922
+ */
923
+ interface CacheEntry<T = unknown> {
924
+ value: T;
925
+ createdAt: number;
926
+ ttl: number;
927
+ }
928
+ /**
929
+ * Cache options for set operations
930
+ */
931
+ interface CacheSetOptions {
932
+ /** Time to live in milliseconds */
933
+ ttl: number;
934
+ /** SWR storage TTL in milliseconds (if provided, used as storage TTL instead of ttl) */
935
+ swrTtl?: number;
936
+ }
937
+ /**
938
+ * Options for cached execution (internal, after parsing)
939
+ */
940
+ interface CacheExecutionOptions {
941
+ /** Time to live in milliseconds (freshness duration) */
942
+ ttlMs: number;
943
+ /** SWR storage TTL in ms (ttl + staleWindow), or false to disable SWR */
944
+ swr: number | false;
945
+ /** Bypass cache read and force fresh fetch */
946
+ bypass: boolean;
947
+ /** Custom cache key override */
948
+ key?: string;
949
+ /** Callback for background operations in serverless environments */
950
+ waitUntil?: WaitUntilFn;
951
+ /** DB attributes for operation span (collection name, etc.) */
952
+ dbAttributes?: Record<string, string>;
953
+ }
954
+ /**
955
+ * Abstract base class for cache drivers.
956
+ *
957
+ * Follows the same pattern as the database Driver class:
958
+ * - Protected abstract methods for concrete implementations (non-underscored)
959
+ * - Public underscored methods handle key prefixing, instrumentation, and delegation
960
+ * - Instrumentation support
961
+ * - Cache orchestration (hit/miss/stale/SWR logic)
962
+ */
963
+ declare abstract class CacheDriver {
964
+ readonly driverName: string;
965
+ protected instrumentation?: InstrumentationContext;
966
+ protected version?: string | number;
967
+ constructor(driverName: string);
968
+ /**
969
+ * Set cache version for key prefixing
970
+ */
971
+ setVersion(version: string | number | undefined): void;
972
+ /**
973
+ * Get a value from cache
974
+ */
975
+ protected abstract get<T>(key: string): Promise<CacheEntry<T> | null>;
976
+ /**
977
+ * Set a value in cache
978
+ * @param key - The cache key
979
+ * @param storageTtl - TTL for the backing store (already SWR-compliant)
980
+ * @param entry - Cache entry with user's original TTL for staleness checks
981
+ */
982
+ protected abstract set<T>(key: string, storageTtl: number, entry: CacheEntry<T>): Promise<void>;
983
+ /**
984
+ * Delete keys from cache
985
+ * @param keys - Array of keys to delete
986
+ */
987
+ protected abstract delete(keys: string[]): Promise<void>;
988
+ /**
989
+ * Clear cache by prefix
990
+ * @param prefix - Always provided (at minimum CACHE_PREFIX to avoid clearing unrelated data)
991
+ */
992
+ protected abstract clear(prefix: string): Promise<void>;
993
+ /**
994
+ * Execute an operation with caching
995
+ *
996
+ * Handles the full cache flow:
997
+ * - Cache key generation
998
+ * - Hit/miss/stale detection
999
+ * - SWR (stale-while-revalidate) pattern
1000
+ * - Background revalidation with thundering herd prevention
1001
+ * - Instrumentation (operation span + cache event logging)
1002
+ *
1003
+ * @param modelName - Model name for key generation and logging
1004
+ * @param operation - Operation name (findMany, findFirst, etc.)
1005
+ * @param args - Operation arguments for key generation
1006
+ * @param executor - Function to execute when cache miss
1007
+ * @param options - Cache options (ttl, swr, bypass, key, waitUntil, dbAttributes)
1008
+ */
1009
+ _executeCached<T>(modelName: string, operation: string, args: unknown, executor: () => Promise<T>, options: CacheExecutionOptions): Promise<T>;
1010
+ /**
1011
+ * Set cache value in background (non-blocking)
1012
+ */
1013
+ private setInBackground;
1014
+ /**
1015
+ * Revalidate cache entry in background (for SWR)
1016
+ * Uses _markRevalidating to prevent thundering herd (multiple concurrent revalidations)
1017
+ */
1018
+ private revalidateInBackground;
1019
+ /**
1020
+ * Log cache events
1021
+ */
1022
+ private logCacheEvent;
1023
+ /**
1024
+ * Get base attributes for tracing
1025
+ */
1026
+ getBaseAttributes(): Record<string, string>;
1027
+ /**
1028
+ * Wrap an operation with a cache span if tracer is available
1029
+ */
1030
+ private withSpan;
1031
+ /**
1032
+ * Get a value from cache
1033
+ * @param key - Cache key (will be prefixed automatically)
1034
+ */
1035
+ _get<T>(key: string): Promise<CacheEntry<T> | null>;
1036
+ /**
1037
+ * Set a value in cache
1038
+ * @param key - Cache key (will be prefixed automatically)
1039
+ * @param value - Value to cache
1040
+ * @param options - Cache options including TTL
1041
+ */
1042
+ _set<T>(key: string, value: T, options: CacheSetOptions): Promise<void>;
1043
+ /**
1044
+ * Delete a specific key (and its revalidating key)
1045
+ * @param key - Cache key (will be prefixed automatically)
1046
+ */
1047
+ _delete(key: string): Promise<void>;
1048
+ /**
1049
+ * Clear cache by prefix or all (within the active version namespace)
1050
+ * @param prefix - Optional prefix to clear (will be prefixed automatically)
1051
+ *
1052
+ * When cacheVersion is set, clearing without a prefix clears only the active
1053
+ * version namespace (e.g., viborm:v2:*), preserving other versions.
1054
+ */
1055
+ _clear(prefix?: string): Promise<void>;
1056
+ /**
1057
+ * Mark entry as revalidating (for SWR coordination)
1058
+ * Returns true if this caller should perform revalidation
1059
+ * @param key - Cache key (will be prefixed automatically)
1060
+ */
1061
+ _markRevalidating(key: string): Promise<boolean>;
1062
+ /**
1063
+ * Clear revalidating flag
1064
+ * @param key - Cache key (will be prefixed automatically)
1065
+ */
1066
+ _clearRevalidating(key: string): Promise<void>;
1067
+ /**
1068
+ * Invalidate cache entries after a mutation
1069
+ * @param modelName - The model name for auto-invalidation
1070
+ * @param options - Cache invalidation options
1071
+ */
1072
+ _invalidate(modelName: string, options?: CacheInvalidationOptions): Promise<void>;
1073
+ /**
1074
+ * Set instrumentation context
1075
+ */
1076
+ setInstrumentation(ctx: InstrumentationContext | undefined): void;
1077
+ /**
1078
+ * Optional: connect to cache backend
1079
+ */
1080
+ connect?(): Promise<void>;
1081
+ /**
1082
+ * Optional: disconnect from cache backend
1083
+ */
1084
+ disconnect?(): Promise<void>;
1085
+ /**
1086
+ * Prefix a key with the cache prefix (including version if set)
1087
+ * Skips prefixing if the key is already prefixed (starts with CACHE_PREFIX)
1088
+ */
1089
+ private prefixKey;
1090
+ }
1091
+ /**
1092
+ * Type alias for any cache driver
1093
+ */
1094
+ type AnyCacheDriver = CacheDriver;
1095
+ //#endregion
1096
+ //#region src/cache/drivers/cloudflare-kv.d.ts
1097
+ /**
1098
+ * Cloudflare KV cache implementation
1099
+ */
1100
+ declare class CloudflareKVCache extends CacheDriver {
1101
+ private readonly kv;
1102
+ constructor(kv: KVNamespace);
1103
+ protected get<T>(key: string): Promise<CacheEntry<T> | null>;
1104
+ protected set<T>(key: string, storageTtl: number, entry: CacheEntry<T>): Promise<void>;
1105
+ protected delete(keys: string[]): Promise<void>;
1106
+ protected clear(prefix: string): Promise<void>;
1107
+ }
1108
+ //#endregion
1109
+ export { NeonHTTPClientConfig as $, SQLite3DriverOptions as A, createClient$12 as At, PlanetScaleDriverOptions as B, createClient as C, BunSQLiteDriverOptions as Ct, isPendingOperation as D, BunSQLDriver as Dt, UnwrapPendingOperations as E, BunSQLClientConfig as Et, PostgresDriverOptions as F, MemoryCache as Ft, PGliteDriverOptions as G, createClient$3 as H, PostgresOptions as I, PgClientConfig as J, PGliteOptions$1 as K, createClient$2 as L, createClient$1 as M, CACHE_PREFIX as Mt, PostgresClientConfig as N, generateCacheKey as Nt, SQLite3ClientConfig as O, BunSQLDriverOptions as Ot, PostgresDriver as P, generateCachePrefix as Pt, createClient$5 as Q, PlanetScaleClientConfig as R, VibORMConfig as S, BunSQLiteDriver as St, UnwrapPendingOperation as T, createClient$11 as Tt, PGliteConfig as U, PlanetScaleOptions as V, PGliteDriver as W, PgDriverOptions as X, PgDriver as Y, PgOptions as Z, BatchPayload as _, D1ClientConfig as _t, CacheExecutionOptions as a, MySQL2DriverOptions as at, InferSelectInclude as b, createClient$10 as bt, CachedClient as c, LibSQLClientConfig as ct, OperationPayload as d, LibSQLOptions as dt, NeonHTTPDriver as et, OperationResult as f, createClient$8 as ft, AggregateResultType as g, createClient$9 as gt, WaitUntilFn as h, D1HTTPDriverOptions as ht, CacheEntry as i, MySQL2Driver as it, SQLite3Options as j, parseTTL as jt, SQLite3Driver as k, BunSQLOptions as kt, Client$2 as l, LibSQLDriver as lt, Schema as m, D1HTTPDriver as mt, AnyCacheDriver as n, createClient$6 as nt, CacheSetOptions as o, MySQL2Options as ot, Operations as p, D1HTTPClientConfig as pt, createClient$4 as q, CacheDriver as r, MySQL2ClientConfig as rt, CacheableOperations as s, createClient$7 as st, CloudflareKVCache as t, NeonHTTPDriverOptions as tt, MutationOperations as u, LibSQLDriverOptions as ut, CountResultType as v, D1Driver as vt, PendingOperation as w, BunSQLiteOptions as wt, VibORMClient as x, BunSQLiteClientConfig as xt, GroupByResultType as y, D1DriverOptions as yt, PlanetScaleDriver as z };
1110
+ //# sourceMappingURL=cloudflare-kv-DauXhtnT.d.mts.map