@zenstackhq/runtime 3.0.0-beta.7 → 3.0.0-beta.9

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/dist/index.d.ts CHANGED
@@ -1,36 +1,1191 @@
1
- import { C as ClientConstructor } from './contract-BJce14-p.js';
2
- export { K as AggregateArgs, L as AggregateResult, B as BatchResult, i as BooleanFilter, h as BytesFilter, c as ClientContract, d as ClientOptions, G as CountArgs, H as CountResult, u as CreateArgs, w as CreateManyAndReturnArgs, v as CreateManyArgs, D as DateTimeFilter, A as DeleteArgs, E as DeleteManyArgs, F as FindArgs, s as FindFirstArgs, r as FindManyArgs, t as FindUniqueArgs, P as GroupByArgs, Q as GroupByResult, I as IncludeInput, J as JsonArray, a as JsonObject, b as JsonValue, M as ModelResult, k as NullsOrder, N as NumberFilter, m as OmitInput, O as OrderBy, n as SelectIncludeOmit, o as SelectInput, q as SelectSubset, S as SimplifiedModelResult, j as SortOrder, g as StringFilter, p as Subset, T as ToKysely, f as TypeDefResult, U as UpdateArgs, y as UpdateManyAndReturnArgs, x as UpdateManyArgs, z as UpsertArgs, W as WhereInput, l as WhereUniqueInput, Z as ZenStackPromise, e as definePlugin } from './contract-BJce14-p.js';
3
- export { sql } from 'kysely';
4
- import 'decimal.js';
5
- import '@zenstackhq/sdk/schema';
1
+ import Decimal from 'decimal.js';
2
+ import * as _zenstackhq_sdk_schema from '@zenstackhq/sdk/schema';
3
+ import { SchemaDef, BuiltinType, GetModels, FieldDef, ModelDef, DataSourceProviderType, GetModel, ProcedureDef, IsDelegateModel } from '@zenstackhq/sdk/schema';
4
+ import { F as FindArgs, O as OrArray, a as OrderBy, M as MaybePromise, T as ToKyselySchema, P as PrependParameter, A as AuthType, b as ToKysely, U as UnwrapTuplePromises, S as SelectSubset, c as Simplify, d as ModelResult, e as FindUniqueArgs, C as CreateArgs, f as CreateManyArgs, B as BatchResult, g as CreateManyAndReturnArgs, h as UpdateArgs, i as UpdateManyArgs, j as Subset, k as UpdateManyAndReturnArgs, l as UpsertArgs, D as DeleteArgs, m as DeleteManyArgs, n as CountArgs, o as CountResult, p as AggregateArgs, q as AggregateResult, G as GroupByArgs, r as GroupByResult, s as OrUndefinedIf } from './auth-CzM6GLw6.js';
5
+ export { E as BooleanFilter, z as BytesFilter, y as DateTimeFilter, Y as FindFirstArgs, X as FindManyArgs, V as IncludeInput, J as JsonArray, t as JsonObject, u as JsonValue, I as NullsOrder, N as NumberFilter, L as OmitInput, Q as SelectIncludeOmit, R as SelectInput, v as SimplifiedModelResult, H as SortOrder, x as StringFilter, w as TypeDefResult, W as WhereInput, K as WhereUniqueInput } from './auth-CzM6GLw6.js';
6
+ import * as kysely from 'kysely';
7
+ import { ExpressionBuilder, SelectQueryBuilder, Expression, SqlBool, ExpressionWrapper, OperationNode, RootOperationNode, QueryResult, UnknownRow, Dialect, KyselyConfig } from 'kysely';
8
+
9
+ /**
10
+ * Client API methods that are not supported in transactions.
11
+ */
12
+ declare const TRANSACTION_UNSUPPORTED_METHODS: readonly ["$transaction", "$disconnect", "$use"];
13
+ /**
14
+ * Logical combinators used in filters.
15
+ */
16
+ declare const LOGICAL_COMBINATORS: readonly ["AND", "OR", "NOT"];
17
+ /**
18
+ * Aggregation operators.
19
+ */
20
+ declare const AGGREGATE_OPERATORS: readonly ["_count", "_sum", "_avg", "_min", "_max"];
21
+ type AGGREGATE_OPERATORS = (typeof AGGREGATE_OPERATORS)[number];
22
+
23
+ declare abstract class BaseCrudDialect<Schema extends SchemaDef> {
24
+ protected readonly schema: Schema;
25
+ protected readonly options: ClientOptions<Schema>;
26
+ protected eb: ExpressionBuilder<any, any>;
27
+ constructor(schema: Schema, options: ClientOptions<Schema>);
28
+ transformPrimitive(value: unknown, _type: BuiltinType, _forArrayField: boolean): unknown;
29
+ transformOutput(value: unknown, _type: BuiltinType): unknown;
30
+ buildSelectModel(model: string, modelAlias: string): SelectQueryBuilder<any, any, {}>;
31
+ buildFilterSortTake(model: GetModels<Schema>, args: FindArgs<Schema, GetModels<Schema>, true>, query: SelectQueryBuilder<any, any, {}>, modelAlias: string): SelectQueryBuilder<any, any, {}>;
32
+ buildFilter(model: string, modelAlias: string, where: boolean | object | undefined): Expression<SqlBool>;
33
+ private buildCursorFilter;
34
+ private isLogicalCombinator;
35
+ protected buildCompositeFilter(model: string, modelAlias: string, key: (typeof LOGICAL_COMBINATORS)[number], payload: any): Expression<SqlBool>;
36
+ private buildRelationFilter;
37
+ private buildToOneRelationFilter;
38
+ private buildToManyRelationFilter;
39
+ private buildArrayFilter;
40
+ buildPrimitiveFilter(fieldRef: Expression<any>, fieldDef: FieldDef, payload: any): Expression<SqlBool>;
41
+ private buildLiteralFilter;
42
+ private buildStandardFilter;
43
+ private buildStringFilter;
44
+ private prepStringCasing;
45
+ private buildNumberFilter;
46
+ private buildBooleanFilter;
47
+ private buildDateTimeFilter;
48
+ private buildBytesFilter;
49
+ private buildEnumFilter;
50
+ buildOrderBy(query: SelectQueryBuilder<any, any, any>, model: string, modelAlias: string, orderBy: OrArray<OrderBy<Schema, GetModels<Schema>, boolean, boolean>> | undefined, useDefaultIfEmpty: boolean, negated: boolean): SelectQueryBuilder<any, any, any>;
51
+ buildSelectAllFields(model: string, query: SelectQueryBuilder<any, any, any>, omit: Record<string, boolean | undefined> | undefined, modelAlias: string): SelectQueryBuilder<any, any, any>;
52
+ protected buildModelSelect(model: GetModels<Schema>, subQueryAlias: string, payload: true | FindArgs<Schema, GetModels<Schema>, true>, selectAllFields: boolean): SelectQueryBuilder<any, any, {}>;
53
+ buildSelectField(query: SelectQueryBuilder<any, any, any>, model: string, modelAlias: string, field: string): SelectQueryBuilder<any, any, any>;
54
+ buildDelegateJoin(thisModel: string, thisModelAlias: string, otherModelAlias: string, query: SelectQueryBuilder<any, any, any>): SelectQueryBuilder<any, any, any>;
55
+ buildCountJson(model: string, eb: ExpressionBuilder<any, any>, parentAlias: string, payload: any): ExpressionWrapper<any, any, unknown>;
56
+ private negateSort;
57
+ true(): Expression<SqlBool>;
58
+ false(): Expression<SqlBool>;
59
+ isTrue(expression: Expression<SqlBool>): boolean;
60
+ isFalse(expression: Expression<SqlBool>): boolean;
61
+ and(...args: Expression<SqlBool>[]): Expression<SqlBool>;
62
+ or(...args: Expression<SqlBool>[]): Expression<SqlBool>;
63
+ not(...args: Expression<SqlBool>[]): ExpressionWrapper<any, any, SqlBool>;
64
+ fieldRef(model: string, field: string, modelAlias?: string, inlineComputedField?: boolean): ExpressionWrapper<any, any, unknown>;
65
+ protected canJoinWithoutNestedSelect(modelDef: ModelDef, payload: boolean | FindArgs<Schema, GetModels<Schema>, true>): boolean;
66
+ abstract get provider(): DataSourceProviderType;
67
+ /**
68
+ * Builds selection for a relation field.
69
+ */
70
+ abstract buildRelationSelection(query: SelectQueryBuilder<any, any, any>, model: string, relationField: string, parentAlias: string, payload: true | FindArgs<Schema, GetModels<Schema>, true>): SelectQueryBuilder<any, any, any>;
71
+ /**
72
+ * Builds skip and take clauses.
73
+ */
74
+ abstract buildSkipTake(query: SelectQueryBuilder<any, any, any>, skip: number | undefined, take: number | undefined): SelectQueryBuilder<any, any, any>;
75
+ /**
76
+ * Builds an Kysely expression that returns a JSON object for the given key-value pairs.
77
+ */
78
+ abstract buildJsonObject(value: Record<string, Expression<unknown>>): ExpressionWrapper<any, any, unknown>;
79
+ /**
80
+ * Builds an Kysely expression that returns the length of an array.
81
+ */
82
+ abstract buildArrayLength(array: Expression<unknown>): ExpressionWrapper<any, any, number>;
83
+ /**
84
+ * Builds an array literal SQL string for the given values.
85
+ */
86
+ abstract buildArrayLiteralSQL(values: unknown[]): string;
87
+ /**
88
+ * Whether the dialect supports updating with a limit on the number of updated rows.
89
+ */
90
+ abstract get supportsUpdateWithLimit(): boolean;
91
+ /**
92
+ * Whether the dialect supports deleting with a limit on the number of deleted rows.
93
+ */
94
+ abstract get supportsDeleteWithLimit(): boolean;
95
+ /**
96
+ * Whether the dialect supports DISTINCT ON.
97
+ */
98
+ abstract get supportsDistinctOn(): boolean;
99
+ /**
100
+ * Whether the dialect support inserting with `DEFAULT` as field value.
101
+ */
102
+ abstract get supportInsertWithDefault(): boolean;
103
+ /**
104
+ * Gets the SQL column type for the given field definition.
105
+ */
106
+ abstract getFieldSqlType(fieldDef: FieldDef): string;
107
+ abstract getStringCasingBehavior(): {
108
+ supportsILike: boolean;
109
+ likeCaseSensitive: boolean;
110
+ };
111
+ }
112
+
113
+ type CoreCrudOperation = 'findMany' | 'findUnique' | 'findFirst' | 'create' | 'createMany' | 'createManyAndReturn' | 'update' | 'updateMany' | 'updateManyAndReturn' | 'upsert' | 'delete' | 'deleteMany' | 'count' | 'aggregate' | 'groupBy';
114
+ type AllCrudOperation = CoreCrudOperation | 'findUniqueOrThrow' | 'findFirstOrThrow';
115
+
116
+ /**
117
+ * ZenStack runtime plugin.
118
+ */
119
+ interface RuntimePlugin<Schema extends SchemaDef = SchemaDef> {
120
+ /**
121
+ * Plugin ID.
122
+ */
123
+ id: string;
124
+ /**
125
+ * Plugin display name.
126
+ */
127
+ name?: string;
128
+ /**
129
+ * Plugin description.
130
+ */
131
+ description?: string;
132
+ /**
133
+ * Custom function implementations.
134
+ */
135
+ functions?: Record<string, ZModelFunction<Schema>>;
136
+ /**
137
+ * Intercepts an ORM query.
138
+ */
139
+ onQuery?: OnQueryCallback<Schema>;
140
+ /**
141
+ * Intercepts an entity mutation.
142
+ */
143
+ onEntityMutation?: EntityMutationHooksDef<Schema>;
144
+ /**
145
+ * Intercepts a Kysely query.
146
+ */
147
+ onKyselyQuery?: OnKyselyQueryCallback<Schema>;
148
+ }
149
+ /**
150
+ * Defines a ZenStack runtime plugin.
151
+ */
152
+ declare function definePlugin<Schema extends SchemaDef>(plugin: RuntimePlugin<Schema>): RuntimePlugin<Schema>;
153
+
154
+ type OnQueryCallback<Schema extends SchemaDef> = (ctx: OnQueryHookContext<Schema>) => Promise<unknown>;
155
+ type OnQueryHookContext<Schema extends SchemaDef> = {
156
+ /**
157
+ * The model that is being queried.
158
+ */
159
+ model: GetModels<Schema>;
160
+ /**
161
+ * The operation that is being performed.
162
+ */
163
+ operation: AllCrudOperation;
164
+ /**
165
+ * The query arguments.
166
+ */
167
+ args: unknown;
168
+ /**
169
+ * The function to proceed with the original query.
170
+ * It takes the same arguments as the operation method.
171
+ *
172
+ * @param args The query arguments.
173
+ */
174
+ proceed: (args: unknown) => Promise<unknown>;
175
+ /**
176
+ * The ZenStack client that is performing the operation.
177
+ */
178
+ client: ClientContract<Schema>;
179
+ };
180
+ type EntityMutationHooksDef<Schema extends SchemaDef> = {
181
+ /**
182
+ * Called before entities are mutated.
183
+ */
184
+ beforeEntityMutation?: BeforeEntityMutationCallback<Schema>;
185
+ /**
186
+ * Called after entities are mutated.
187
+ */
188
+ afterEntityMutation?: AfterEntityMutationCallback<Schema>;
189
+ /**
190
+ * Whether to run after-mutation hooks within the transaction that performs the mutation.
191
+ *
192
+ * If set to `true`, if the mutation already runs inside a transaction, the callbacks are
193
+ * executed immediately after the mutation within the transaction boundary. If the mutation
194
+ * is not running inside a transaction, a new transaction is created to run both the mutation
195
+ * and the callbacks.
196
+ *
197
+ * If set to `false`, the callbacks are executed after the mutation transaction is committed.
198
+ *
199
+ * Defaults to `false`.
200
+ */
201
+ runAfterMutationWithinTransaction?: boolean;
202
+ };
203
+ type MutationHooksArgs<Schema extends SchemaDef> = {
204
+ /**
205
+ * The model that is being mutated.
206
+ */
207
+ model: GetModels<Schema>;
208
+ /**
209
+ * The mutation action that is being performed.
210
+ */
211
+ action: 'create' | 'update' | 'delete';
212
+ /**
213
+ * The mutation data. Only available for create and update actions.
214
+ */
215
+ queryNode: OperationNode;
216
+ /**
217
+ * A query ID that uniquely identifies the mutation operation. You can use it to correlate
218
+ * data between the before and after mutation hooks.
219
+ */
220
+ queryId: string;
221
+ };
222
+ type BeforeEntityMutationCallback<Schema extends SchemaDef> = (args: PluginBeforeEntityMutationArgs<Schema>) => MaybePromise<void>;
223
+ type AfterEntityMutationCallback<Schema extends SchemaDef> = (args: PluginAfterEntityMutationArgs<Schema>) => MaybePromise<void>;
224
+ type PluginBeforeEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
225
+ /**
226
+ * Loads the entities that are about to be mutated. The db operation that loads the entities is executed
227
+ * within the same transaction context as the mutation.
228
+ */
229
+ loadBeforeMutationEntities(): Promise<Record<string, unknown>[] | undefined>;
230
+ /**
231
+ * The ZenStack client you can use to perform additional operations. The database operations initiated
232
+ * from this client are executed within the same transaction as the mutation if the mutation is running
233
+ * inside a transaction.
234
+ *
235
+ * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops.
236
+ */
237
+ client: ClientContract<Schema>;
238
+ };
239
+ type PluginAfterEntityMutationArgs<Schema extends SchemaDef> = MutationHooksArgs<Schema> & {
240
+ /**
241
+ * Loads the entities that have been mutated.
242
+ */
243
+ loadAfterMutationEntities(): Promise<Record<string, unknown>[] | undefined>;
244
+ /**
245
+ * The ZenStack client you can use to perform additional operations.
246
+ * See {@link EntityMutationHooksDef.runAfterMutationWithinTransaction} for detailed transaction behavior.
247
+ *
248
+ * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops.
249
+ */
250
+ client: ClientContract<Schema>;
251
+ };
252
+ type OnKyselyQueryArgs<Schema extends SchemaDef> = {
253
+ schema: SchemaDef;
254
+ client: ClientContract<Schema>;
255
+ query: RootOperationNode;
256
+ proceed: ProceedKyselyQueryFunction;
257
+ };
258
+ type ProceedKyselyQueryFunction = (query: RootOperationNode) => Promise<QueryResult<any>>;
259
+ type OnKyselyQueryCallback<Schema extends SchemaDef> = (args: OnKyselyQueryArgs<Schema>) => Promise<QueryResult<UnknownRow>>;
260
+
261
+ type ZModelFunctionContext<Schema extends SchemaDef> = {
262
+ /**
263
+ * ZenStack client instance
264
+ */
265
+ client: ClientContract<Schema>;
266
+ /**
267
+ * Database dialect
268
+ */
269
+ dialect: BaseCrudDialect<Schema>;
270
+ /**
271
+ * The containing model name
272
+ */
273
+ model: GetModels<Schema>;
274
+ /**
275
+ * The alias name that can be used to refer to the containing model
276
+ */
277
+ modelAlias: string;
278
+ /**
279
+ * The CRUD operation being performed
280
+ */
281
+ operation: CRUD_EXT;
282
+ };
283
+ type ZModelFunction<Schema extends SchemaDef> = (eb: ExpressionBuilder<ToKyselySchema<Schema>, keyof ToKyselySchema<Schema>>, args: Expression<any>[], context: ZModelFunctionContext<Schema>) => Expression<unknown>;
284
+ /**
285
+ * ZenStack client options.
286
+ */
287
+ type ClientOptions<Schema extends SchemaDef> = {
288
+ /**
289
+ * Kysely dialect.
290
+ */
291
+ dialect: Dialect;
292
+ /**
293
+ * Custom function definitions.
294
+ */
295
+ functions?: Record<string, ZModelFunction<Schema>>;
296
+ /**
297
+ * Plugins.
298
+ */
299
+ plugins?: RuntimePlugin<Schema>[];
300
+ /**
301
+ * Logging configuration.
302
+ */
303
+ log?: KyselyConfig['log'];
304
+ /**
305
+ * Whether to automatically fix timezone for `DateTime` fields returned by node-pg. Defaults
306
+ * to `true`.
307
+ *
308
+ * Node-pg has a terrible quirk that it interprets the date value as local timezone (as a
309
+ * `Date` object) although for `DateTime` field the data in DB is stored in UTC.
310
+ * @see https://github.com/brianc/node-postgres/issues/429
311
+ */
312
+ fixPostgresTimezone?: boolean;
313
+ /**
314
+ * Whether to enable input validations expressed with attributes like `@email`, `@regex`,
315
+ * `@@validate`, etc. Defaults to `true`.
316
+ */
317
+ validateInput?: boolean;
318
+ } & (HasComputedFields<Schema> extends true ? {
319
+ /**
320
+ * Computed field definitions.
321
+ */
322
+ computedFields: ComputedFieldsOptions<Schema>;
323
+ } : {}) & (HasProcedures<Schema> extends true ? {
324
+ /**
325
+ * Custom procedure definitions.
326
+ */
327
+ procedures: ProceduresOptions<Schema>;
328
+ } : {});
329
+ type ComputedFieldsOptions<Schema extends SchemaDef> = {
330
+ [Model in GetModels<Schema> as 'computedFields' extends keyof GetModel<Schema, Model> ? Model : never]: {
331
+ [Field in keyof Schema['models'][Model]['computedFields']]: PrependParameter<ExpressionBuilder<ToKyselySchema<Schema>, Model>, Schema['models'][Model]['computedFields'][Field]>;
332
+ };
333
+ };
334
+ type HasComputedFields<Schema extends SchemaDef> = string extends GetModels<Schema> ? false : keyof ComputedFieldsOptions<Schema> extends never ? false : true;
335
+ type ProceduresOptions<Schema extends SchemaDef> = Schema extends {
336
+ procedures: Record<string, ProcedureDef>;
337
+ } ? {
338
+ [Key in keyof Schema['procedures']]: PrependParameter<ClientContract<Schema>, ProcedureFunc<Schema, Schema['procedures'][Key]>>;
339
+ } : {};
340
+ type HasProcedures<Schema extends SchemaDef> = Schema extends {
341
+ procedures: Record<string, ProcedureDef>;
342
+ } ? true : false;
343
+
344
+ /**
345
+ * A promise that only executes when it's awaited or .then() is called.
346
+ */
347
+ type ZenStackPromise<Schema extends SchemaDef, T> = Promise<T> & {
348
+ /**
349
+ * @private
350
+ * Callable to get a plain promise.
351
+ */
352
+ cb: (txClient?: ClientContract<Schema>) => Promise<T>;
353
+ };
354
+
355
+ type TransactionUnsupportedMethods = (typeof TRANSACTION_UNSUPPORTED_METHODS)[number];
356
+ /**
357
+ * Transaction isolation levels.
358
+ */
359
+ declare enum TransactionIsolationLevel {
360
+ ReadUncommitted = "read uncommitted",
361
+ ReadCommitted = "read committed",
362
+ RepeatableRead = "repeatable read",
363
+ Serializable = "serializable",
364
+ Snapshot = "snapshot"
365
+ }
366
+ /**
367
+ * ZenStack client interface.
368
+ */
369
+ type ClientContract<Schema extends SchemaDef> = {
370
+ readonly $schema: Schema;
371
+ /**
372
+ * The client options.
373
+ */
374
+ readonly $options: ClientOptions<Schema>;
375
+ /**
376
+ * Executes a prepared raw query and returns the number of affected rows.
377
+ * @example
378
+ * ```
379
+ * const result = await db.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};`
380
+ * ```
381
+ */
382
+ $executeRaw(query: TemplateStringsArray, ...values: any[]): ZenStackPromise<Schema, number>;
383
+ /**
384
+ * Executes a raw query and returns the number of affected rows.
385
+ * This method is susceptible to SQL injections.
386
+ * @example
387
+ * ```
388
+ * const result = await db.$executeRawUnsafe('UPDATE User SET cool = $1 WHERE email = $2 ;', true, 'user@email.com')
389
+ * ```
390
+ */
391
+ $executeRawUnsafe(query: string, ...values: any[]): ZenStackPromise<Schema, number>;
392
+ /**
393
+ * Performs a prepared raw query and returns the `SELECT` data.
394
+ * @example
395
+ * ```
396
+ * const result = await db.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};`
397
+ * ```
398
+ */
399
+ $queryRaw<T = unknown>(query: TemplateStringsArray, ...values: any[]): ZenStackPromise<Schema, T>;
400
+ /**
401
+ * Performs a raw query and returns the `SELECT` data.
402
+ * This method is susceptible to SQL injections.
403
+ * @example
404
+ * ```
405
+ * const result = await db.$queryRawUnsafe('SELECT * FROM User WHERE id = $1 OR email = $2;', 1, 'user@email.com')
406
+ * ```
407
+ */
408
+ $queryRawUnsafe<T = unknown>(query: string, ...values: any[]): ZenStackPromise<Schema, T>;
409
+ /**
410
+ * The current user identity.
411
+ */
412
+ get $auth(): AuthType<Schema> | undefined;
413
+ /**
414
+ * Sets the current user identity.
415
+ */
416
+ $setAuth(auth: AuthType<Schema> | undefined): ClientContract<Schema>;
417
+ /**
418
+ * Returns a new client enabling/disabling input validations expressed with attributes like
419
+ * `@email`, `@regex`, `@@validate`, etc.
420
+ */
421
+ $setInputValidation(enable: boolean): ClientContract<Schema>;
422
+ /**
423
+ * The Kysely query builder instance.
424
+ */
425
+ readonly $qb: ToKysely<Schema>;
426
+ /**
427
+ * The raw Kysely query builder without any ZenStack enhancements.
428
+ */
429
+ readonly $qbRaw: ToKysely<any>;
430
+ /**
431
+ * Starts an interactive transaction.
432
+ */
433
+ $transaction<T>(callback: (tx: Omit<ClientContract<Schema>, TransactionUnsupportedMethods>) => Promise<T>, options?: {
434
+ isolationLevel?: TransactionIsolationLevel;
435
+ }): Promise<T>;
436
+ /**
437
+ * Starts a sequential transaction.
438
+ */
439
+ $transaction<P extends ZenStackPromise<Schema, any>[]>(arg: [...P], options?: {
440
+ isolationLevel?: TransactionIsolationLevel;
441
+ }): Promise<UnwrapTuplePromises<P>>;
442
+ /**
443
+ * Returns a new client with the specified plugin installed.
444
+ */
445
+ $use(plugin: RuntimePlugin<Schema>): ClientContract<Schema>;
446
+ /**
447
+ * Returns a new client with the specified plugin removed.
448
+ */
449
+ $unuse(pluginId: string): ClientContract<Schema>;
450
+ /**
451
+ * Returns a new client with all plugins removed.
452
+ */
453
+ $unuseAll(): ClientContract<Schema>;
454
+ /**
455
+ * Disconnects the underlying Kysely instance from the database.
456
+ */
457
+ $disconnect(): Promise<void>;
458
+ /**
459
+ * Pushes the schema to the database. For testing purposes only.
460
+ * @private
461
+ */
462
+ $pushSchema(): Promise<void>;
463
+ } & {
464
+ [Key in GetModels<Schema> as Uncapitalize<Key>]: ModelOperations<Schema, Key>;
465
+ } & Procedures<Schema>;
466
+ /**
467
+ * The contract for a client in a transaction.
468
+ */
469
+ type TransactionClientContract<Schema extends SchemaDef> = Omit<ClientContract<Schema>, TransactionUnsupportedMethods>;
470
+ type _TypeMap = {
471
+ String: string;
472
+ Int: number;
473
+ Float: number;
474
+ BigInt: bigint;
475
+ Decimal: Decimal;
476
+ Boolean: boolean;
477
+ DateTime: Date;
478
+ };
479
+ type MapType<Schema extends SchemaDef, T extends string> = T extends keyof _TypeMap ? _TypeMap[T] : T extends GetModels<Schema> ? ModelResult<Schema, T> : unknown;
480
+ type Procedures<Schema extends SchemaDef> = Schema['procedures'] extends Record<string, ProcedureDef> ? {
481
+ $procedures: {
482
+ [Key in keyof Schema['procedures']]: ProcedureFunc<Schema, Schema['procedures'][Key]>;
483
+ };
484
+ } : {};
485
+ type ProcedureFunc<Schema extends SchemaDef, Proc extends ProcedureDef> = (...args: MapProcedureParams<Schema, Proc['params']>) => Promise<MapType<Schema, Proc['returnType']>>;
486
+ type MapProcedureParams<Schema extends SchemaDef, Params> = {
487
+ [P in keyof Params]: Params[P] extends {
488
+ type: infer U;
489
+ } ? OrUndefinedIf<MapType<Schema, U & string>, Params[P] extends {
490
+ optional: true;
491
+ } ? true : false> : never;
492
+ };
493
+ /**
494
+ * Creates a new ZenStack client instance.
495
+ */
496
+ interface ClientConstructor {
497
+ new <Schema extends SchemaDef>(schema: Schema, options: ClientOptions<Schema>): ClientContract<Schema>;
498
+ }
499
+ /**
500
+ * CRUD operations.
501
+ */
502
+ type CRUD = 'create' | 'read' | 'update' | 'delete';
503
+ /**
504
+ * CRUD operations.
505
+ */
506
+ declare const CRUD: readonly ["create", "read", "update", "delete"];
507
+ /**
508
+ * Extended CRUD operations including 'post-update'.
509
+ */
510
+ type CRUD_EXT = CRUD | 'post-update';
511
+ /**
512
+ * Extended CRUD operations including 'post-update'.
513
+ */
514
+ declare const CRUD_EXT: readonly ["create", "read", "update", "delete", "post-update"];
515
+ type AllModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
516
+ /**
517
+ * Returns a list of entities.
518
+ * @param args - query args
519
+ * @returns a list of entities
520
+ *
521
+ * @example
522
+ * ```ts
523
+ * // find all users and return all scalar fields
524
+ * await db.user.findMany();
525
+ *
526
+ * // find all users with name 'Alex'
527
+ * await db.user.findMany({
528
+ * where: {
529
+ * name: 'Alex'
530
+ * }
531
+ * });
532
+ *
533
+ * // select fields
534
+ * await db.user.findMany({
535
+ * select: {
536
+ * name: true,
537
+ * email: true,
538
+ * }
539
+ * }); // result: `Array<{ name: string, email: string }>`
540
+ *
541
+ * // omit fields
542
+ * await db.user.findMany({
543
+ * omit: {
544
+ * name: true,
545
+ * }
546
+ * }); // result: `Array<{ id: number; email: string; ... }>`
547
+ *
548
+ * // include relations (and all scalar fields)
549
+ * await db.user.findMany({
550
+ * include: {
551
+ * posts: true,
552
+ * }
553
+ * }); // result: `Array<{ ...; posts: Post[] }>`
554
+ *
555
+ * // include relations with filter
556
+ * await db.user.findMany({
557
+ * include: {
558
+ * posts: {
559
+ * where: {
560
+ * published: true
561
+ * }
562
+ * }
563
+ * }
564
+ * });
565
+ *
566
+ * // pagination and sorting
567
+ * await db.user.findMany({
568
+ * skip: 10,
569
+ * take: 10,
570
+ * orderBy: [{ name: 'asc' }, { email: 'desc' }],
571
+ * });
572
+ *
573
+ * // pagination with cursor (https://www.prisma.io/docs/orm/prisma-client/queries/pagination#cursor-based-pagination)
574
+ * await db.user.findMany({
575
+ * cursor: { id: 10 },
576
+ * skip: 1,
577
+ * take: 10,
578
+ * orderBy: { id: 'asc' },
579
+ * });
580
+ *
581
+ * // distinct
582
+ * await db.user.findMany({
583
+ * distinct: ['name']
584
+ * });
585
+ *
586
+ * // count all relations
587
+ * await db.user.findMany({
588
+ * _count: true,
589
+ * }); // result: `{ _count: { posts: number; ... } }`
590
+ *
591
+ * // count selected relations
592
+ * await db.user.findMany({
593
+ * _count: { select: { posts: true } },
594
+ * }); // result: `{ _count: { posts: number } }`
595
+ * ```
596
+ */
597
+ findMany<T extends FindArgs<Schema, Model, true>>(args?: SelectSubset<T, FindArgs<Schema, Model, true>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>[]>;
598
+ /**
599
+ * Returns a uniquely identified entity.
600
+ * @param args - query args
601
+ * @returns a single entity or null if not found
602
+ * @see {@link findMany}
603
+ */
604
+ findUnique<T extends FindUniqueArgs<Schema, Model>>(args: SelectSubset<T, FindUniqueArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>> | null>;
605
+ /**
606
+ * Returns a uniquely identified entity or throws `NotFoundError` if not found.
607
+ * @param args - query args
608
+ * @returns a single entity
609
+ * @see {@link findMany}
610
+ */
611
+ findUniqueOrThrow<T extends FindUniqueArgs<Schema, Model>>(args: SelectSubset<T, FindUniqueArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
612
+ /**
613
+ * Returns the first entity.
614
+ * @param args - query args
615
+ * @returns a single entity or null if not found
616
+ * @see {@link findMany}
617
+ */
618
+ findFirst<T extends FindArgs<Schema, Model, true>>(args?: SelectSubset<T, FindArgs<Schema, Model, true>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>> | null>;
619
+ /**
620
+ * Returns the first entity or throws `NotFoundError` if not found.
621
+ * @param args - query args
622
+ * @returns a single entity
623
+ * @see {@link findMany}
624
+ */
625
+ findFirstOrThrow<T extends FindArgs<Schema, Model, true>>(args?: SelectSubset<T, FindArgs<Schema, Model, true>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
626
+ /**
627
+ * Creates a new entity.
628
+ * @param args - create args
629
+ * @returns the created entity
630
+ *
631
+ * @example
632
+ * ```ts
633
+ * // simple create
634
+ * await db.user.create({
635
+ * data: { name: 'Alex', email: 'alex@zenstack.dev' }
636
+ * });
637
+ *
638
+ * // nested create with relation
639
+ * await db.user.create({
640
+ * data: {
641
+ * email: 'alex@zenstack.dev',
642
+ * posts: { create: { title: 'Hello World' } }
643
+ * }
644
+ * });
645
+ *
646
+ * // you can use `select`, `omit`, and `include` to control
647
+ * // the fields returned by the query, as with `findMany`
648
+ * await db.user.create({
649
+ * data: {
650
+ * email: 'alex@zenstack.dev',
651
+ * posts: { create: { title: 'Hello World' } }
652
+ * },
653
+ * include: { posts: true }
654
+ * }); // result: `{ id: number; posts: Post[] }`
655
+ *
656
+ * // connect relations
657
+ * await db.user.create({
658
+ * data: {
659
+ * email: 'alex@zenstack.dev',
660
+ * posts: { connect: { id: 1 } }
661
+ * }
662
+ * });
663
+ *
664
+ * // connect relations, and create if not found
665
+ * await db.user.create({
666
+ * data: {
667
+ * email: 'alex@zenstack.dev',
668
+ * posts: {
669
+ * connectOrCreate: {
670
+ * where: { id: 1 },
671
+ * create: { title: 'Hello World' }
672
+ * }
673
+ * }
674
+ * }
675
+ * });
676
+ * ```
677
+ */
678
+ create<T extends CreateArgs<Schema, Model>>(args: SelectSubset<T, CreateArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
679
+ /**
680
+ * Creates multiple entities. Only scalar fields are allowed.
681
+ * @param args - create args
682
+ * @returns count of created entities: `{ count: number }`
683
+ *
684
+ * @example
685
+ * ```ts
686
+ * // create multiple entities
687
+ * await db.user.createMany({
688
+ * data: [
689
+ * { name: 'Alex', email: 'alex@zenstack.dev' },
690
+ * { name: 'John', email: 'john@zenstack.dev' }
691
+ * ]
692
+ * });
693
+ *
694
+ * // skip items that cause unique constraint violation
695
+ * await db.user.createMany({
696
+ * data: [
697
+ * { name: 'Alex', email: 'alex@zenstack.dev' },
698
+ * { name: 'John', email: 'john@zenstack.dev' }
699
+ * ],
700
+ * skipDuplicates: true
701
+ * });
702
+ * ```
703
+ */
704
+ createMany<T extends CreateManyArgs<Schema, Model>>(args?: SelectSubset<T, CreateManyArgs<Schema, Model>>): ZenStackPromise<Schema, BatchResult>;
705
+ /**
706
+ * Creates multiple entities and returns them.
707
+ * @param args - create args. See {@link createMany} for input. Use
708
+ * `select` and `omit` to control the fields returned.
709
+ * @returns the created entities
710
+ *
711
+ * @example
712
+ * ```ts
713
+ * // create multiple entities and return selected fields
714
+ * await db.user.createManyAndReturn({
715
+ * data: [
716
+ * { name: 'Alex', email: 'alex@zenstack.dev' },
717
+ * { name: 'John', email: 'john@zenstack.dev' }
718
+ * ],
719
+ * select: { id: true, email: true }
720
+ * });
721
+ * ```
722
+ */
723
+ createManyAndReturn<T extends CreateManyAndReturnArgs<Schema, Model>>(args?: SelectSubset<T, CreateManyAndReturnArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>[]>;
724
+ /**
725
+ * Updates a uniquely identified entity.
726
+ * @param args - update args. See {@link findMany} for how to control
727
+ * fields and relations returned.
728
+ * @returns the updated entity. Throws `NotFoundError` if the entity is not found.
729
+ *
730
+ * @example
731
+ * ```ts
732
+ * // update fields
733
+ * await db.user.update({
734
+ * where: { id: 1 },
735
+ * data: { name: 'Alex' }
736
+ * });
737
+ *
738
+ * // connect a relation
739
+ * await db.user.update({
740
+ * where: { id: 1 },
741
+ * data: { posts: { connect: { id: 1 } } }
742
+ * });
743
+ *
744
+ * // connect relation, and create if not found
745
+ * await db.user.update({
746
+ * where: { id: 1 },
747
+ * data: {
748
+ * posts: {
749
+ * connectOrCreate: {
750
+ * where: { id: 1 },
751
+ * create: { title: 'Hello World' }
752
+ * }
753
+ * }
754
+ * }
755
+ * });
756
+ *
757
+ * // create many related entities (only available for one-to-many relations)
758
+ * await db.user.update({
759
+ * where: { id: 1 },
760
+ * data: {
761
+ * posts: {
762
+ * createMany: {
763
+ * data: [{ title: 'Hello World' }, { title: 'Hello World 2' }],
764
+ * }
765
+ * }
766
+ * }
767
+ * });
768
+ *
769
+ * // disconnect a one-to-many relation
770
+ * await db.user.update({
771
+ * where: { id: 1 },
772
+ * data: { posts: { disconnect: { id: 1 } } }
773
+ * });
774
+ *
775
+ * // disconnect a one-to-one relation
776
+ * await db.user.update({
777
+ * where: { id: 1 },
778
+ * data: { profile: { disconnect: true } }
779
+ * });
780
+ *
781
+ * // replace a relation (only available for one-to-many relations)
782
+ * await db.user.update({
783
+ * where: { id: 1 },
784
+ * data: {
785
+ * posts: {
786
+ * set: [{ id: 1 }, { id: 2 }]
787
+ * }
788
+ * }
789
+ * });
790
+ *
791
+ * // update a relation
792
+ * await db.user.update({
793
+ * where: { id: 1 },
794
+ * data: {
795
+ * posts: {
796
+ * update: { where: { id: 1 }, data: { title: 'Hello World' } }
797
+ * }
798
+ * }
799
+ * });
800
+ *
801
+ * // upsert a relation
802
+ * await db.user.update({
803
+ * where: { id: 1 },
804
+ * data: {
805
+ * posts: {
806
+ * upsert: {
807
+ * where: { id: 1 },
808
+ * create: { title: 'Hello World' },
809
+ * update: { title: 'Hello World' }
810
+ * }
811
+ * }
812
+ * }
813
+ * });
814
+ *
815
+ * // update many related entities (only available for one-to-many relations)
816
+ * await db.user.update({
817
+ * where: { id: 1 },
818
+ * data: {
819
+ * posts: {
820
+ * updateMany: {
821
+ * where: { published: true },
822
+ * data: { title: 'Hello World' }
823
+ * }
824
+ * }
825
+ * }
826
+ * });
827
+ *
828
+ * // delete a one-to-many relation
829
+ * await db.user.update({
830
+ * where: { id: 1 },
831
+ * data: { posts: { delete: { id: 1 } } }
832
+ * });
833
+ *
834
+ * // delete a one-to-one relation
835
+ * await db.user.update({
836
+ * where: { id: 1 },
837
+ * data: { profile: { delete: true } }
838
+ * });
839
+ * ```
840
+ */
841
+ update<T extends UpdateArgs<Schema, Model>>(args: SelectSubset<T, UpdateArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
842
+ /**
843
+ * Updates multiple entities.
844
+ * @param args - update args. Only scalar fields are allowed for data.
845
+ * @returns count of updated entities: `{ count: number }`
846
+ *
847
+ * @example
848
+ * ```ts
849
+ * // update many entities
850
+ * await db.user.updateMany({
851
+ * where: { email: { endsWith: '@zenstack.dev' } },
852
+ * data: { role: 'ADMIN' }
853
+ * });
854
+ *
855
+ * // limit the number of updated entities
856
+ * await db.user.updateMany({
857
+ * where: { email: { endsWith: '@zenstack.dev' } },
858
+ * data: { role: 'ADMIN' },
859
+ * limit: 10
860
+ * });
861
+ */
862
+ updateMany<T extends UpdateManyArgs<Schema, Model>>(args: Subset<T, UpdateManyArgs<Schema, Model>>): ZenStackPromise<Schema, BatchResult>;
863
+ /**
864
+ * Updates multiple entities and returns them.
865
+ * @param args - update args. Only scalar fields are allowed for data.
866
+ * @returns the updated entities
867
+ *
868
+ * @example
869
+ * ```ts
870
+ * // update many entities and return selected fields
871
+ * await db.user.updateManyAndReturn({
872
+ * where: { email: { endsWith: '@zenstack.dev' } },
873
+ * data: { role: 'ADMIN' },
874
+ * select: { id: true, email: true }
875
+ * }); // result: `Array<{ id: string; email: string }>`
876
+ *
877
+ * // limit the number of updated entities
878
+ * await db.user.updateManyAndReturn({
879
+ * where: { email: { endsWith: '@zenstack.dev' } },
880
+ * data: { role: 'ADMIN' },
881
+ * limit: 10
882
+ * });
883
+ * ```
884
+ */
885
+ updateManyAndReturn<T extends UpdateManyAndReturnArgs<Schema, Model>>(args: Subset<T, UpdateManyAndReturnArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>[]>;
886
+ /**
887
+ * Creates or updates an entity.
888
+ * @param args - upsert args
889
+ * @returns the upserted entity
890
+ *
891
+ * @example
892
+ * ```ts
893
+ * // upsert an entity
894
+ * await db.user.upsert({
895
+ * // `where` clause is used to find the entity
896
+ * where: { id: 1 },
897
+ * // `create` clause is used if the entity is not found
898
+ * create: { email: 'alex@zenstack.dev', name: 'Alex' },
899
+ * // `update` clause is used if the entity is found
900
+ * update: { name: 'Alex-new' },
901
+ * // `select` and `omit` can be used to control the returned fields
902
+ * ...
903
+ * });
904
+ * ```
905
+ */
906
+ upsert<T extends UpsertArgs<Schema, Model>>(args: SelectSubset<T, UpsertArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
907
+ /**
908
+ * Deletes a uniquely identifiable entity.
909
+ * @param args - delete args
910
+ * @returns the deleted entity. Throws `NotFoundError` if the entity is not found.
911
+ *
912
+ * @example
913
+ * ```ts
914
+ * // delete an entity
915
+ * await db.user.delete({
916
+ * where: { id: 1 }
917
+ * });
918
+ *
919
+ * // delete an entity and return selected fields
920
+ * await db.user.delete({
921
+ * where: { id: 1 },
922
+ * select: { id: true, email: true }
923
+ * }); // result: `{ id: string; email: string }`
924
+ * ```
925
+ */
926
+ delete<T extends DeleteArgs<Schema, Model>>(args: SelectSubset<T, DeleteArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<ModelResult<Schema, Model, T>>>;
927
+ /**
928
+ * Deletes multiple entities.
929
+ * @param args - delete args
930
+ * @returns count of deleted entities: `{ count: number }`
931
+ *
932
+ * @example
933
+ * ```ts
934
+ * // delete many entities
935
+ * await db.user.deleteMany({
936
+ * where: { email: { endsWith: '@zenstack.dev' } }
937
+ * });
938
+ *
939
+ * // limit the number of deleted entities
940
+ * await db.user.deleteMany({
941
+ * where: { email: { endsWith: '@zenstack.dev' } },
942
+ * limit: 10
943
+ * });
944
+ * ```
945
+ */
946
+ deleteMany<T extends DeleteManyArgs<Schema, Model>>(args?: Subset<T, DeleteManyArgs<Schema, Model>>): ZenStackPromise<Schema, BatchResult>;
947
+ /**
948
+ * Counts rows or field values.
949
+ * @param args - count args
950
+ * @returns `number`, or an object containing count of selected relations
951
+ *
952
+ * @example
953
+ * ```ts
954
+ * // count all
955
+ * await db.user.count();
956
+ *
957
+ * // count with a filter
958
+ * await db.user.count({ where: { email: { endsWith: '@zenstack.dev' } } });
959
+ *
960
+ * // count rows and field values
961
+ * await db.user.count({
962
+ * select: { _all: true, email: true }
963
+ * }); // result: `{ _all: number, email: number }`
964
+ */
965
+ count<T extends CountArgs<Schema, Model>>(args?: Subset<T, CountArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<CountResult<Schema, Model, T>>>;
966
+ /**
967
+ * Aggregates rows.
968
+ * @param args - aggregation args
969
+ * @returns an object containing aggregated values
970
+ *
971
+ * @example
972
+ * ```ts
973
+ * // aggregate rows
974
+ * await db.profile.aggregate({
975
+ * where: { email: { endsWith: '@zenstack.dev' } },
976
+ * _count: true,
977
+ * _avg: { age: true },
978
+ * _sum: { age: true },
979
+ * _min: { age: true },
980
+ * _max: { age: true }
981
+ * }); // result: `{ _count: number, _avg: { age: number }, ... }`
982
+ */
983
+ aggregate<T extends AggregateArgs<Schema, Model>>(args: Subset<T, AggregateArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<AggregateResult<Schema, Model, T>>>;
984
+ /**
985
+ * Groups rows by columns.
986
+ * @param args - groupBy args
987
+ * @returns an object containing grouped values
988
+ *
989
+ * @example
990
+ * ```ts
991
+ * // group by a field
992
+ * await db.profile.groupBy({
993
+ * by: 'country',
994
+ * _count: true
995
+ * }); // result: `Array<{ country: string, _count: number }>`
996
+ *
997
+ * // group by multiple fields
998
+ * await db.profile.groupBy({
999
+ * by: ['country', 'city'],
1000
+ * _count: true
1001
+ * }); // result: `Array<{ country: string, city: string, _count: number }>`
1002
+ *
1003
+ * // group by with sorting, the `orderBy` fields must be either an aggregation
1004
+ * // or a field used in the `by` list
1005
+ * await db.profile.groupBy({
1006
+ * by: 'country',
1007
+ * orderBy: { country: 'desc' }
1008
+ * });
1009
+ *
1010
+ * // group by with having (post-aggregation filter), the fields used in `having` must
1011
+ * // be either an aggregation, or a field used in the `by` list
1012
+ * await db.profile.groupBy({
1013
+ * by: 'country',
1014
+ * having: { country: 'US', age: { _avg: { gte: 18 } } }
1015
+ * });
1016
+ */
1017
+ groupBy<T extends GroupByArgs<Schema, Model>>(args: Subset<T, GroupByArgs<Schema, Model>>): ZenStackPromise<Schema, Simplify<GroupByResult<Schema, Model, T>>>;
1018
+ };
1019
+ type ModelOperations<Schema extends SchemaDef, Model extends GetModels<Schema>> = Omit<AllModelOperations<Schema, Model>, IsDelegateModel<Schema, Model> extends true ? 'create' | 'createMany' | 'createManyAndReturn' | 'upsert' : never>;
6
1020
 
7
1021
  /**
8
1022
  * ZenStack ORM client.
9
1023
  */
10
1024
  declare const ZenStackClient: ClientConstructor;
11
1025
 
1026
+ declare function getCrudDialect<Schema extends SchemaDef>(schema: Schema, options: ClientOptions<Schema>): BaseCrudDialect<Schema>;
1027
+
1028
+ /**
1029
+ * Base for all ZenStack runtime errors.
1030
+ */
1031
+ declare class ZenStackError extends Error {
1032
+ }
12
1033
  /**
13
1034
  * Error thrown when input validation fails.
14
1035
  */
15
- declare class InputValidationError extends Error {
1036
+ declare class InputValidationError extends ZenStackError {
16
1037
  constructor(message: string, cause?: unknown);
17
1038
  }
18
1039
  /**
19
1040
  * Error thrown when a query fails.
20
1041
  */
21
- declare class QueryError extends Error {
1042
+ declare class QueryError extends ZenStackError {
22
1043
  constructor(message: string, cause?: unknown);
23
1044
  }
24
1045
  /**
25
1046
  * Error thrown when an internal error occurs.
26
1047
  */
27
- declare class InternalError extends Error {
1048
+ declare class InternalError extends ZenStackError {
28
1049
  }
29
1050
  /**
30
1051
  * Error thrown when an entity is not found.
31
1052
  */
32
- declare class NotFoundError extends Error {
1053
+ declare class NotFoundError extends ZenStackError {
33
1054
  constructor(model: string, details?: string);
34
1055
  }
1056
+ /**
1057
+ * Reason code for policy rejection.
1058
+ */
1059
+ declare enum RejectedByPolicyReason {
1060
+ /**
1061
+ * Rejected because the operation is not allowed by policy.
1062
+ */
1063
+ NO_ACCESS = "no-access",
1064
+ /**
1065
+ * Rejected because the result cannot be read back after mutation due to policy.
1066
+ */
1067
+ CANNOT_READ_BACK = "cannot-read-back",
1068
+ /**
1069
+ * Other reasons.
1070
+ */
1071
+ OTHER = "other"
1072
+ }
1073
+ /**
1074
+ * Error thrown when an operation is rejected by access policy.
1075
+ */
1076
+ declare class RejectedByPolicyError extends ZenStackError {
1077
+ readonly model: string | undefined;
1078
+ readonly reason: RejectedByPolicyReason;
1079
+ constructor(model: string | undefined, reason?: RejectedByPolicyReason, message?: string);
1080
+ }
1081
+
1082
+ declare function hasModel(schema: SchemaDef, model: string): boolean;
1083
+ declare function getModel(schema: SchemaDef, model: string): ModelDef | undefined;
1084
+ declare function getTypeDef(schema: SchemaDef, type: string): _zenstackhq_sdk_schema.TypeDefDef | undefined;
1085
+ declare function requireModel(schema: SchemaDef, model: string): ModelDef;
1086
+ declare function getField(schema: SchemaDef, model: string, field: string): FieldDef | undefined;
1087
+ declare function requireField(schema: SchemaDef, modelOrType: string, field: string): FieldDef;
1088
+ declare function getIdFields<Schema extends SchemaDef>(schema: SchemaDef, model: GetModels<Schema>): string[] | undefined;
1089
+ declare function requireIdFields(schema: SchemaDef, model: string): string[];
1090
+ declare function getRelationForeignKeyFieldPairs(schema: SchemaDef, model: string, relationField: string): {
1091
+ keyPairs: {
1092
+ fk: string;
1093
+ pk: string;
1094
+ }[];
1095
+ ownedByModel: boolean;
1096
+ };
1097
+ declare function isScalarField(schema: SchemaDef, model: string, field: string): boolean;
1098
+ declare function isForeignKeyField(schema: SchemaDef, model: string, field: string): boolean;
1099
+ declare function isRelationField(schema: SchemaDef, model: string, field: string): boolean;
1100
+ declare function isInheritedField(schema: SchemaDef, model: string, field: string): boolean;
1101
+ declare function getUniqueFields(schema: SchemaDef, model: string): ({
1102
+ name: string;
1103
+ def: FieldDef;
1104
+ } | {
1105
+ name: string;
1106
+ defs: Record<string, FieldDef>;
1107
+ })[];
1108
+ declare function getIdValues(schema: SchemaDef, model: string, data: any): Record<string, any>;
1109
+ declare function buildFieldRef<Schema extends SchemaDef>(schema: Schema, model: string, field: string, options: ClientOptions<Schema>, eb: ExpressionBuilder<any, any>, modelAlias?: string, inlineComputedField?: boolean): ExpressionWrapper<any, any, unknown>;
1110
+ declare function fieldHasDefaultValue(fieldDef: FieldDef): boolean | undefined;
1111
+ declare function isEnum(schema: SchemaDef, type: string): boolean;
1112
+ declare function getEnum(schema: SchemaDef, type: string): _zenstackhq_sdk_schema.EnumDef | undefined;
1113
+ declare function buildJoinPairs(schema: SchemaDef, model: string, modelAlias: string, relationField: string, relationModelAlias: string): [string, string][];
1114
+ declare function makeDefaultOrderBy<Schema extends SchemaDef>(schema: SchemaDef, model: string): OrderBy<Schema, Extract<keyof Schema["models"], string>, true, false>[];
1115
+ declare function getManyToManyRelation(schema: SchemaDef, model: string, field: string): {
1116
+ parentFkName: string;
1117
+ parentPKName: string;
1118
+ otherModel: string;
1119
+ otherField: string;
1120
+ otherFkName: string;
1121
+ otherPKName: string;
1122
+ joinTable: string;
1123
+ } | undefined;
1124
+ /**
1125
+ * Convert filter like `{ id1_id2: { id1: 1, id2: 1 } }` to `{ id1: 1, id2: 1 }`
1126
+ */
1127
+ declare function flattenCompoundUniqueFilters(schema: SchemaDef, model: string, filter: unknown): any;
1128
+ declare function ensureArray<T>(value: T | T[]): T[];
1129
+ declare function safeJSONStringify(value: unknown): string;
1130
+ declare function extractIdFields(entity: any, schema: SchemaDef, model: string): {
1131
+ [k: string]: unknown;
1132
+ };
1133
+ declare function getDiscriminatorField(schema: SchemaDef, model: string): string | undefined;
1134
+ declare function getDelegateDescendantModels(schema: SchemaDef, model: string, collected?: Set<ModelDef>): ModelDef[];
1135
+ declare function aggregate(eb: ExpressionBuilder<any, any>, expr: Expression<any>, op: AGGREGATE_OPERATORS): kysely.AggregateFunctionBuilder<any, any, string | number | bigint>;
1136
+ /**
1137
+ * Strips alias from the node if it exists.
1138
+ */
1139
+ declare function stripAlias(node: OperationNode): {
1140
+ alias: OperationNode;
1141
+ node: OperationNode;
1142
+ } | {
1143
+ alias: undefined;
1144
+ node: OperationNode;
1145
+ };
1146
+ /**
1147
+ * Extracts model name from an OperationNode.
1148
+ */
1149
+ declare function extractModelName(node: OperationNode): string | undefined;
1150
+ /**
1151
+ * Extracts field name from an OperationNode.
1152
+ */
1153
+ declare function extractFieldName(node: OperationNode): string | undefined;
1154
+
1155
+ declare const queryUtils_aggregate: typeof aggregate;
1156
+ declare const queryUtils_buildFieldRef: typeof buildFieldRef;
1157
+ declare const queryUtils_buildJoinPairs: typeof buildJoinPairs;
1158
+ declare const queryUtils_ensureArray: typeof ensureArray;
1159
+ declare const queryUtils_extractFieldName: typeof extractFieldName;
1160
+ declare const queryUtils_extractIdFields: typeof extractIdFields;
1161
+ declare const queryUtils_extractModelName: typeof extractModelName;
1162
+ declare const queryUtils_fieldHasDefaultValue: typeof fieldHasDefaultValue;
1163
+ declare const queryUtils_flattenCompoundUniqueFilters: typeof flattenCompoundUniqueFilters;
1164
+ declare const queryUtils_getDelegateDescendantModels: typeof getDelegateDescendantModels;
1165
+ declare const queryUtils_getDiscriminatorField: typeof getDiscriminatorField;
1166
+ declare const queryUtils_getEnum: typeof getEnum;
1167
+ declare const queryUtils_getField: typeof getField;
1168
+ declare const queryUtils_getIdFields: typeof getIdFields;
1169
+ declare const queryUtils_getIdValues: typeof getIdValues;
1170
+ declare const queryUtils_getManyToManyRelation: typeof getManyToManyRelation;
1171
+ declare const queryUtils_getModel: typeof getModel;
1172
+ declare const queryUtils_getRelationForeignKeyFieldPairs: typeof getRelationForeignKeyFieldPairs;
1173
+ declare const queryUtils_getTypeDef: typeof getTypeDef;
1174
+ declare const queryUtils_getUniqueFields: typeof getUniqueFields;
1175
+ declare const queryUtils_hasModel: typeof hasModel;
1176
+ declare const queryUtils_isEnum: typeof isEnum;
1177
+ declare const queryUtils_isForeignKeyField: typeof isForeignKeyField;
1178
+ declare const queryUtils_isInheritedField: typeof isInheritedField;
1179
+ declare const queryUtils_isRelationField: typeof isRelationField;
1180
+ declare const queryUtils_isScalarField: typeof isScalarField;
1181
+ declare const queryUtils_makeDefaultOrderBy: typeof makeDefaultOrderBy;
1182
+ declare const queryUtils_requireField: typeof requireField;
1183
+ declare const queryUtils_requireIdFields: typeof requireIdFields;
1184
+ declare const queryUtils_requireModel: typeof requireModel;
1185
+ declare const queryUtils_safeJSONStringify: typeof safeJSONStringify;
1186
+ declare const queryUtils_stripAlias: typeof stripAlias;
1187
+ declare namespace queryUtils {
1188
+ export { queryUtils_aggregate as aggregate, queryUtils_buildFieldRef as buildFieldRef, queryUtils_buildJoinPairs as buildJoinPairs, queryUtils_ensureArray as ensureArray, queryUtils_extractFieldName as extractFieldName, queryUtils_extractIdFields as extractIdFields, queryUtils_extractModelName as extractModelName, queryUtils_fieldHasDefaultValue as fieldHasDefaultValue, queryUtils_flattenCompoundUniqueFilters as flattenCompoundUniqueFilters, queryUtils_getDelegateDescendantModels as getDelegateDescendantModels, queryUtils_getDiscriminatorField as getDiscriminatorField, queryUtils_getEnum as getEnum, queryUtils_getField as getField, queryUtils_getIdFields as getIdFields, queryUtils_getIdValues as getIdValues, queryUtils_getManyToManyRelation as getManyToManyRelation, queryUtils_getModel as getModel, queryUtils_getRelationForeignKeyFieldPairs as getRelationForeignKeyFieldPairs, queryUtils_getTypeDef as getTypeDef, queryUtils_getUniqueFields as getUniqueFields, queryUtils_hasModel as hasModel, queryUtils_isEnum as isEnum, queryUtils_isForeignKeyField as isForeignKeyField, queryUtils_isInheritedField as isInheritedField, queryUtils_isRelationField as isRelationField, queryUtils_isScalarField as isScalarField, queryUtils_makeDefaultOrderBy as makeDefaultOrderBy, queryUtils_requireField as requireField, queryUtils_requireIdFields as requireIdFields, queryUtils_requireModel as requireModel, queryUtils_safeJSONStringify as safeJSONStringify, queryUtils_stripAlias as stripAlias };
1189
+ }
35
1190
 
36
- export { ClientConstructor, InputValidationError, InternalError, NotFoundError, QueryError, ZenStackClient };
1191
+ export { type AfterEntityMutationCallback, AggregateArgs, AggregateResult, type AllModelOperations, BaseCrudDialect, BatchResult, type BeforeEntityMutationCallback, CRUD, CRUD_EXT, type ClientConstructor, type ClientContract, type ClientOptions, type ComputedFieldsOptions, CountArgs, CountResult, CreateArgs, CreateManyAndReturnArgs, CreateManyArgs, type CoreCrudOperation as CrudOperation, DeleteArgs, DeleteManyArgs, type EntityMutationHooksDef, FindArgs, FindUniqueArgs, GroupByArgs, GroupByResult, type HasComputedFields, type HasProcedures, InputValidationError, InternalError, type ModelOperations, ModelResult, NotFoundError, type OnKyselyQueryArgs, type OnKyselyQueryCallback, OrderBy, type PluginAfterEntityMutationArgs, type PluginBeforeEntityMutationArgs, type ProcedureFunc, type Procedures, type ProceduresOptions, type ProceedKyselyQueryFunction, QueryError, queryUtils as QueryUtils, RejectedByPolicyError, RejectedByPolicyReason, type RuntimePlugin, SelectSubset, Subset, ToKysely, type TransactionClientContract, TransactionIsolationLevel, UpdateArgs, UpdateManyAndReturnArgs, UpdateManyArgs, UpsertArgs, type ZModelFunction, type ZModelFunctionContext, ZenStackClient, ZenStackError, type ZenStackPromise, definePlugin, getCrudDialect };