import type { OperationNode, QueryId, QueryResult, RootOperationNode, Selectable, UnknownRow } from 'kysely'; import type { ZodType } from 'zod'; import type { ClientContract, ZModelFunction } from '.'; import type { GetModelFields, GetModels, NonRelationFields, SchemaDef } from '@zenstackhq/schema'; import type { MaybePromise } from '../utils/type-utils'; import type { MapModelFieldType } from './crud-types'; import type { AllCrudOperations, CoreCrudOperations } from './crud/operations/base'; import type { ToKyselySchema } from './query-builder'; type AllowedExtQueryArgKeys = CoreCrudOperations | '$create' | '$read' | '$update' | '$delete' | '$all'; /** * Base shape of plugin-extended query args. */ export type ExtQueryArgsBase = { [K in AllowedExtQueryArgKeys]?: object; }; /** * Base type for plugin-extended client members (methods and properties). * Member names should start with '$' to avoid model name conflicts. */ export type ExtClientMembersBase = Record; /** * Base shape of plugin-extended result fields. * Keyed by model name, each value maps field names to their definitions. * `needs` keys are constrained to non-relation fields of the corresponding model. */ export type ExtResultBase = { [M in GetModels as Uncapitalize]?: Record< string, { needs: Partial, true>>; compute: (...args: any[]) => any; } >; }; /** * Mapped type that provides per-field contextual typing for `compute` callbacks * based on the `needs` declaration. Uses a separate type parameter `R_` that captures * the needs shape (model → field → { neededField: true }), then links each field's * `compute` parameter to exactly the keys declared in its `needs`. */ export type ExtResultInferenceArgs = { [K in keyof R_ & string]: { [P in keyof R_[K]]?: { needs?: { // constraint for `needs` keys [F in keyof R_[K][P]]: F extends NonRelationFields> ? true : never; } & Partial>, true>>; // further intersects with all possible keys for intellisense // refine `computes`'s parameter type based on the inferred type of `needs` compute: (data: ExtResultComputeData, R_[K][P]>) => unknown; }; }; }; /** * Reverse-maps an uncapitalized key back to the original model name in the schema. * E.g., for a schema with model `myModel`, the key `myModel` maps back to `myModel` * (not `MyModel` as `Capitalize` would produce). */ type ModelNameFromKey = { [M in GetModels]: Uncapitalize extends K ? M : never; }[GetModels]; /** * Maps the needs shape `S` to an object with actual schema field types. * For each key in `S` that is a valid non-relation field of model `M`, * resolves the TypeScript type from the schema field definition. */ type ExtResultComputeData, S> = { [F in keyof S & GetModelFields]: MapModelFieldType; }; /** * ZenStack runtime plugin. */ export interface RuntimePlugin< Schema extends SchemaDef, ExtQueryArgs extends ExtQueryArgsBase, ExtClientMembers extends Record, ExtResult extends ExtResultBase, > { /** * Plugin ID. */ id: string; /** * Plugin display name. */ name?: string; /** * Plugin description. */ description?: string; // TODO: revisit /** * Custom function implementations. * @private */ functions?: Record>; /** * Intercepts an ORM query. */ onQuery?: OnQueryCallback; /** * Intercepts a procedure invocation. */ onProcedure?: OnProcedureCallback; /** * Intercepts an entity mutation. */ onEntityMutation?: EntityMutationHooksDef; /** * Intercepts a Kysely query. */ onKyselyQuery?: OnKyselyQueryCallback; /** * Extended query args configuration. */ queryArgs?: { [K in keyof ExtQueryArgs]: ZodType; }; /** * Extended client members (methods and properties). */ client?: ExtClientMembers; /** * Extended result fields on query results. * Keyed by model name, each value defines computed fields with `needs` and `compute`. */ result?: ExtResult; } export type AnyPlugin = RuntimePlugin; /** * Defines a ZenStack runtime plugin based on type of the given schema. * * @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation} * * @example * ```typescript * definePlugin(schema, { * id: 'my-plugin', * result: { * user: { * fullName: { * needs: { firstName: true, lastName: true }, * compute: (user) => `${user.firstName} ${user.lastName}`, * }, * }, * }, * }); * ``` */ export function definePlugin< Schema extends SchemaDef, const ExtQueryArgs extends ExtQueryArgsBase = {}, const ExtClientMembers extends Record = {}, const ExtResult extends ExtResultBase = {}, R_ = {}, >( schema: Schema, plugin: RuntimePlugin & { result?: ExtResultInferenceArgs; }, ): RuntimePlugin; /** * Defines a ZenStack runtime plugin. * * @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation} * * @example * ```typescript * definePlugin(schema, { * id: 'my-plugin', * result: { * user: { * fullName: { * needs: { firstName: true, lastName: true }, * compute: (user) => `${user.firstName} ${user.lastName}`, * }, * }, * }, * }); * ``` * */ export function definePlugin< Schema extends SchemaDef, const ExtQueryArgs extends ExtQueryArgsBase = {}, const ExtClientMembers extends Record = {}, const ExtResult extends ExtResultBase = {}, >( plugin: RuntimePlugin, ): RuntimePlugin; export function definePlugin(...args: unknown[]) { return args.length === 2 ? args[1] : args[0]; } // #region OnProcedure hooks type OnProcedureCallback = (ctx: OnProcedureHookContext) => Promise; export type OnProcedureHookContext = { /** * The procedure name. */ name: string; /** * Whether the procedure is a mutation. */ mutation: boolean; /** * Procedure invocation input (envelope). * * The canonical shape is `{ args?: Record }`. * When a procedure has required params, `args` is required. */ input: unknown; /** * Continues the invocation. The input passed here is forwarded to the next handler. */ proceed: (input: unknown) => Promise; /** * The ZenStack client that is invoking the procedure. */ client: ClientContract; }; // #endregion // #region OnQuery hooks type OnQueryCallback = (ctx: OnQueryHookContext) => Promise; type OnQueryHookContext = { /** * The model that is being queried. */ model: GetModels; /** * The operation that is being performed. */ operation: AllCrudOperations; /** * The query arguments. */ args: Record | undefined; /** * The function to proceed with the original query. * It takes the same arguments as the operation method. * * @param args The query arguments. */ proceed: (args: Record | undefined) => Promise; /** * The ZenStack client that is performing the operation. */ client: ClientContract; }; // #endregion // #region OnEntityMutation hooks export type EntityMutationHooksDef = { [M in '$all' | GetModels]?: M extends '$all' ? AllEntityMutationHooksDef : ModelEntityMutationHooksDef>; }; export type AllEntityMutationHooksDef = { /** * Called before entities are mutated. */ beforeEntityMutation?: BeforeEntityMutationCallback; /** * Called after entities are mutated. */ afterEntityMutation?: AfterEntityMutationCallback; /** * Whether to run after-mutation hooks within the transaction that performs the mutation. * * If set to `true`, if the mutation already runs inside a transaction, the callbacks are * executed immediately after the mutation within the transaction boundary. If the mutation * is not running inside a transaction, a new transaction is created to run both the mutation * and the callbacks. * * If set to `false`, the callbacks are executed after the mutation transaction is committed. * * Defaults to `false`. */ runAfterMutationWithinTransaction?: boolean; }; type MutationHooksArgs = { /** * The model that is being mutated. */ model: GetModels; /** * The mutation action that is being performed. */ action: 'create' | 'update' | 'delete'; /** * The mutation data. Only available for create and update actions. */ queryNode: OperationNode; /** * A query ID that uniquely identifies the mutation operation. You can use it to correlate * data between the before and after mutation hooks. */ queryId: QueryId; }; export type BeforeEntityMutationCallback = ( args: PluginBeforeEntityMutationArgs, ) => MaybePromise; export type AfterEntityMutationCallback = ( args: PluginAfterEntityMutationArgs, ) => MaybePromise; export type PluginBeforeEntityMutationArgs = MutationHooksArgs & { /** * Loads the entities that are about to be mutated. The db operation that loads the entities is executed * within the same transaction context as the mutation. */ loadBeforeMutationEntities(): Promise[] | undefined>; /** * The ZenStack client you can use to perform additional operations. The database operations initiated * from this client are executed within the same transaction as the mutation if the mutation is running * inside a transaction. * * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops. */ client: ClientContract; }; export type PluginAfterEntityMutationArgs = MutationHooksArgs & { /** * Loads the entities that have been mutated. */ loadAfterMutationEntities(): Promise[] | undefined>; /** * The entities before mutation. Only available if `beforeEntityMutation` hook is provided and * the `loadBeforeMutationEntities` function is called in that hook. */ beforeMutationEntities?: Record[]; /** * The ZenStack client you can use to perform additional operations. * See {@link AllEntityMutationHooksDef.runAfterMutationWithinTransaction} for detailed transaction behavior. * * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops. */ client: ClientContract; }; /** * The shape of an entity passed to per-model entity mutation hooks. Entities are * loaded directly from the database table (the same way as `$qb` query results), * so they contain only physical columns (no relations, no computed fields, and no * fields inherited from a delegate base model), and values are in the form returned * by the database driver, not post-processed by the ORM. * * For models using delegate inheritance (`@@delegate`), a mutation fires one event * per physical table written, keyed by that table's model. E.g., creating a sub-model * entity fires a base-model event followed by a sub-model event; updating only * inherited fields fires only a base-model event; deleting a sub-model entity fires * only a base-model event (the sub-model row is removed by cascade). Base-model * entities carry the discriminator field, which can be used to identify the concrete * sub-model. To observe all mutations of a sub-model, register hooks on its base model * (or use `$all`). */ export type MutationHookEntity> = Selectable< ToKyselySchema[Model] >; export type PluginModelBeforeEntityMutationArgs> = Omit< MutationHooksArgs, 'model' > & { model: Model; loadBeforeMutationEntities(): Promise[] | undefined>; client: ClientContract; }; export type PluginModelAfterEntityMutationArgs> = Omit< MutationHooksArgs, 'model' > & { model: Model; loadAfterMutationEntities(): Promise[] | undefined>; beforeMutationEntities?: MutationHookEntity[]; client: ClientContract; }; export type ModelEntityMutationHooksDef> = { beforeEntityMutation?: (args: PluginModelBeforeEntityMutationArgs) => MaybePromise; afterEntityMutation?: (args: PluginModelAfterEntityMutationArgs) => MaybePromise; runAfterMutationWithinTransaction?: boolean; }; // #endregion // #region OnKyselyQuery hooks export type OnKyselyQueryArgs = { schema: SchemaDef; client: ClientContract; query: RootOperationNode; proceed: ProceedKyselyQueryFunction; }; export type ProceedKyselyQueryFunction = (query: RootOperationNode) => Promise>; export type OnKyselyQueryCallback = ( args: OnKyselyQueryArgs, ) => Promise>; // #endregion