/** * @db4/core - Plugin System * * Provides plugin discovery, registration, and lifecycle management for db4. * * ## Features * * - **Plugin Registration**: Register custom plugins at runtime * - **Lazy Loading**: Load plugins on-demand for better startup performance * - **Lifecycle Hooks**: Full lifecycle support (init, query, mutation, dispose) * - **Dependency Management**: Declare and resolve plugin dependencies with version checking * - **Middleware Pattern**: Intercept and transform query/mutation operations * - **Storage Adapters**: Pluggable storage backends * - **Type Safety**: Use TypedPlugin for full generic type support * * ## Quick Start * * ```typescript * import { createPluginManager, type TypedPlugin } from '@db4/core'; * * // Create a plugin manager * const manager = createPluginManager(); * * // Register a type-safe plugin * interface MyContext { appName: string } * interface MyOutput { success: boolean } * * const myPlugin: TypedPlugin = { * name: 'my-plugin', * version: '1.0.0', * hooks: { * init: async (context) => { * console.log(`Initializing for ${context.appName}`); * }, * mutation: async (data) => ({ success: true }), * }, * }; * * manager.register(myPlugin); * await manager.initialize('my-plugin', { appName: 'MyApp' }); * const result = await manager.execute('my-plugin', 'mutation', data); * ``` * * ## Plugin Lifecycle * * 1. **Registration**: Plugin is registered with `register()` or `registerLazy()` * 2. **Loading**: For lazy plugins, loaded on first use with `load()` * 3. **Initialization**: `init` hook called with context via `initialize()` * 4. **Execution**: Hooks called via `execute()` - query, mutation * 5. **Disposal**: `dispose` hook called via `dispose()` or `shutdown()` * * @packageDocumentation */ import { DB4Error } from './errors.js'; /** * Base error for plugin system errors. */ export declare class PluginError extends DB4Error { readonly pluginName?: string; constructor(message: string, options?: { code?: string; pluginName?: string; cause?: Error; }); /** Returns the plugin-specific error code from details */ get pluginCode(): string; get cause(): Error | undefined; } /** * Error thrown when plugin loading fails. */ export declare class PluginLoadError extends PluginError { constructor(message: string, options?: { pluginName?: string; cause?: Error; }); } /** * Error thrown when plugin dependency resolution fails. */ export declare class PluginDependencyError extends PluginError { readonly dependencyName?: string; readonly requiredVersion?: string; readonly availableVersion?: string; constructor(message: string, options?: { pluginName?: string; dependencyName?: string; requiredVersion?: string; availableVersion?: string; cause?: Error; }); } /** * Error thrown when plugin lifecycle hook fails. */ export declare class PluginLifecycleError extends PluginError { readonly hook?: string; readonly phase?: string; constructor(message: string, options?: { pluginName?: string; hook?: string; phase?: string; cause?: Error; }); } /** * Plugin dependency specification. */ export interface PluginDependency { /** Name of the dependency plugin */ name: string; /** Required version using semver range syntax (^x.y.z, ~x.y.z, or exact x.y.z) */ version: string; /** If true, missing dependency won't throw an error */ optional?: boolean; } /** * Valid hook names for plugins. */ export type HookName = 'init' | 'query' | 'mutation' | 'dispose'; /** * Array of valid hook names for runtime validation. */ export declare const VALID_HOOK_NAMES: readonly HookName[]; /** * Plugin context passed to init hook. */ export interface PluginContext { /** Database instance or connection */ db?: unknown; /** Configuration object */ config?: Record; /** Additional context data */ [key: string]: unknown; } /** * Plugin lifecycle hooks (non-generic version). */ export interface PluginHooks { /** Called when plugin is initialized with context */ init?: (context: PluginContext) => Promise | void; /** Called for query operations */ query?: (args: unknown, deps?: Map) => Promise; /** Called for mutation operations */ mutation?: (args: unknown, deps?: Map) => Promise; /** Called when plugin is disposed */ dispose?: () => Promise | void; } /** * Type-safe plugin lifecycle hooks with generic parameters. */ export interface TypedPluginHooks { /** Called when plugin is initialized with typed context */ init?: (context: TContext) => Promise | void; /** Called for query operations */ query?: (args: TInput, deps?: Map) => Promise; /** Called for mutation operations */ mutation?: (args: TInput, deps?: Map) => Promise; /** Called when plugin is disposed */ dispose?: () => Promise | void; } /** * Plugin interface. */ export interface Plugin { /** Plugin name (must be unique) */ name: string; /** Plugin version (semver) */ version: string; /** Plugin dependencies */ dependencies?: PluginDependency[]; /** Plugin lifecycle hooks */ hooks: PluginHooks; } /** * Type-safe plugin interface with generic parameters. */ export interface TypedPlugin { /** Plugin name */ name: string; /** Plugin version */ version: string; /** Plugin dependencies */ dependencies?: PluginDependency[]; /** Plugin lifecycle hooks */ hooks: TypedPluginHooks; } /** * Middleware context for intercepting operations. */ export interface MiddlewareContext { /** Type of operation */ operation: 'query' | 'mutation'; /** Collection name (if applicable) */ collection?: string; /** Operation arguments */ args: Record; /** Metadata for passing data between middlewares */ metadata?: Record; /** If true, skip remaining middlewares and use result */ shortCircuit?: boolean; /** Result for short-circuit case */ result?: unknown; } /** * Middleware hooks for intercepting operations. */ export interface MiddlewareHooks { /** Called before query execution */ beforeQuery?: (ctx: MiddlewareContext) => Promise; /** Called after query execution */ afterQuery?: (ctx: MiddlewareContext, result: unknown) => Promise; /** Called before mutation execution */ beforeMutation?: (ctx: MiddlewareContext) => Promise; /** Called after mutation execution */ afterMutation?: (ctx: MiddlewareContext, result: unknown) => Promise; } /** * Plugin middleware for intercepting operations. */ export interface PluginMiddleware { /** Middleware name */ name: string; /** Middleware version */ version: string; /** Priority (higher = runs first for before hooks, last for after hooks) */ priority?: number; /** Middleware hooks */ hooks: MiddlewareHooks; } /** * Storage adapter hooks for data operations. */ export interface StorageAdapterHooks { /** Initialize the storage adapter */ init?: (config: Record) => Promise; /** Read data by key */ read: (key: string) => Promise; /** Write data with key */ write: (key: string, value: unknown) => Promise; /** Delete data by key */ delete: (key: string) => Promise; /** List keys with optional prefix */ list: (prefix?: string) => Promise; /** Batch write operation */ batchWrite?: (operations: Array<{ key: string; value: unknown; }>) => Promise<{ success: number; failed: number; }>; /** Dispose the storage adapter */ dispose?: () => Promise; } /** * Storage adapter plugin. */ export interface StorageAdapterPlugin { /** Adapter name */ name: string; /** Adapter version */ version: string; /** Plugin type identifier */ type: 'storage'; /** Storage hooks */ hooks: StorageAdapterHooks; } /** * Plugin manager configuration. */ export interface PluginManagerConfig { /** Strict mode - throw on validation errors */ strictMode?: boolean; /** Enable caching of loaded plugins */ enableCaching?: boolean; /** Maximum number of plugins allowed */ maxPlugins?: number; } /** * Plugin registration options. */ export interface RegisterOptions { /** Force registration even if plugin exists */ force?: boolean; } /** * Plugin manager interface. */ export interface PluginManager { /** Plugin manager configuration */ config: Required; /** Register a plugin */ register(plugin: Plugin, options?: RegisterOptions): void; /** Register a lazy-loaded plugin */ registerLazy(name: string, loader: () => Promise): void; /** Unregister a plugin by name */ unregister(name: string): Promise; /** Get a plugin by name */ get(name: string): Plugin | undefined; /** Check if a plugin is registered */ has(name: string): boolean; /** List all registered plugin names */ list(): string[]; /** Clear all registered plugins */ clear(): Promise; /** Check if a plugin is loaded (not just registered) */ isLoaded(name: string): boolean; /** Load a lazy-registered plugin */ load(name: string): Promise; /** Preload multiple plugins */ preload(names: string[]): Promise; /** Initialize a plugin with context */ initialize(name: string, context: PluginContext): Promise; /** Check if a plugin is initialized */ isInitialized(name: string): boolean; /** Execute a plugin hook */ execute(name: string, hook: HookName, ...args: unknown[]): Promise; /** Dispose a plugin */ dispose(name: string): Promise; /** Shutdown the plugin manager */ shutdown(): Promise; /** Resolve plugin dependencies */ resolveDependencies(name: string): Promise; /** Initialize plugin with its dependencies */ initializeWithDependencies(name: string, context: PluginContext): Promise; /** Execute hook with dependencies available */ executeWithDependencies(name: string, hook: HookName, ...args: unknown[]): Promise; /** Register a middleware */ registerMiddleware(middleware: PluginMiddleware): void; /** Run middleware chain for a hook */ runMiddleware(hook: keyof MiddlewareHooks, ctx: MiddlewareContext, result?: unknown): Promise; /** Register a storage adapter */ registerStorageAdapter(adapter: StorageAdapterPlugin): void; /** Check if a storage adapter exists */ hasStorageAdapter(name: string): boolean; /** Get a storage adapter */ getStorageAdapter(name: string): StorageAdapterPlugin | undefined; /** Execute a storage operation */ executeStorageOp(name: string, operation: keyof StorageAdapterHooks, ...args: unknown[]): Promise; /** Initialize a storage adapter */ initializeStorageAdapter(name: string, config: Record): Promise; /** Dispose a storage adapter */ disposeStorageAdapter(name: string): Promise; } /** * Type guard to check if a string is a valid hook name. */ export declare function isValidHookName(name: string): name is HookName; /** * Type guard to check if a plugin has a specific hook defined. */ export declare function hasHook(plugin: Plugin, hookName: K): plugin is Plugin & { hooks: PluginHooks & Required>; }; /** * Type guard for PluginError. */ export declare function isPluginError(error: unknown): error is PluginError; /** * Type guard for PluginLoadError. */ export declare function isPluginLoadError(error: unknown): error is PluginLoadError; /** * Type guard for PluginDependencyError. */ export declare function isPluginDependencyError(error: unknown): error is PluginDependencyError; /** * Type guard for PluginLifecycleError. */ export declare function isPluginLifecycleError(error: unknown): error is PluginLifecycleError; /** * Create a plugin manager instance. */ export declare function createPluginManager(options?: PluginManagerConfig): PluginManager; //# sourceMappingURL=plugin.d.ts.map