harmony-plugin-manager
Version:
A comprehensive TypeScript library for generating harmonious color palettes with WCAG 2.1 accessibility compliance
335 lines • 11.5 kB
TypeScript
/**
* Harmony Plugin Manager - A comprehensive TypeScript plugin system
*
* A type-safe plugin system with lifecycle management, dependency resolution,
* and comprehensive error handling using modular architecture.
*
* ## Quick Start
*
* ```typescript
* import { createPluginManager, simplePlugin } from 'harmony-plugin-manager';
*
* // Create a simple text processing plugin
* const uppercasePlugin = simplePlugin(
* { name: 'uppercase', version: '1.0.0', description: 'Converts text to uppercase' },
* (input: string) => input.toUpperCase()
* );
*
* // Create and configure the manager
* const manager = createPluginManager<string, string>()
* .register(uppercasePlugin)
* .build();
*
* // Execute the pipeline
* const result = await manager.execute('hello world', {});
* console.log(result.results[0].output); // "HELLO WORLD"
* ```
*
* ## Advanced Usage
*
* ```typescript
* // Using the builder pattern for complex configurations
* const manager = createPluginBuilder<string, string>()
* .plugin(validationPlugin, { priority: 100 })
* .plugin(transformPlugin, { priority: 50 })
* .when(process.env.NODE_ENV === 'development', debugPlugin)
* .group({
* tag: 'formatting',
* items: [
* { plugin: trimPlugin },
* { plugin: normalizePlugin }
* ]
* })
* .build();
* ```
*
* ## Key Concepts
*
* - **Plugins**: Self-contained processing units with metadata and lifecycle hooks
* - **Manager**: Orchestrates plugin execution with dependency resolution
* - **Context**: Provides shared state, logging, and configuration access
* - **Pipeline**: Executes plugins in dependency order with error handling
*
* @packageDocumentation
*/
import type { PluginManagerBuilder } from './builder';
import type { IPlugin, PluginContext, PluginMetadata } from './core';
import { type PluginHooks } from './factories';
import type { PluginManager } from './manager';
export * from './core';
export { PluginContextImpl, ContextFactory } from './context';
export type { PluginContext } from './core/types';
export { PluginManager, PluginRegistration, DependencyResolver, } from './manager';
export { PluginManagerBuilder } from './builder';
export { PluginFactory, ManagerFactory } from './factories';
export type { PluginHooks } from './factories';
export { ValidationUtils, ErrorUtils } from './utils';
export { PluginError, PluginRegistrationError, PluginDependencyError, PluginValidationError, } from './utils';
export { BasePlugin as Plugin } from './core/base';
/**
* Creates a new plugin manager instance with type safety
*
* The plugin manager is the core orchestrator that handles plugin registration,
* dependency resolution, and execution. It provides a clean API for managing
* complex plugin workflows with error handling and performance monitoring.
*
* @template TInput - Type of data that plugins will receive as input
* @template TOutput - Type of data that plugins will produce as output
* @template TMetadata - Type of execution metadata passed to plugins
*
* @returns A new PluginManager instance ready for plugin registration
*
* @example
* ```typescript
* // Basic string processing manager
* const textManager = createPluginManager<string, string>();
*
* // Complex data transformation manager
* interface UserData { id: string; name: string; email: string; }
* interface ProcessedUser { id: string; displayName: string; domain: string; }
*
* const userManager = createPluginManager<UserData, ProcessedUser, {
* requestId: string;
* userId: string;
* }>();
* ```
*
* @example
* ```typescript
* // Complete workflow example
* const manager = createPluginManager<string, string>()
* .register(validationPlugin, { priority: 100 })
* .register(transformPlugin, { priority: 50 })
* .register(outputPlugin, { priority: 10 })
* .build();
*
* const result = await manager.execute('input data', {
* requestId: 'req-123',
* timestamp: Date.now()
* });
*
* if (result.success) {
* console.log('Processing completed:', result.results);
* } else {
* console.error('Processing failed:', result.errors);
* }
* ```
*/
export declare function createPluginManager<TInput = unknown, TOutput = unknown, TMetadata extends Record<string, unknown> = Record<string, unknown>>(): PluginManager<TInput, TOutput, TMetadata>;
/**
* Creates a new plugin manager builder for fluent configuration
*
* The builder pattern provides a more expressive way to configure complex
* plugin arrangements. It offers methods for conditional registration,
* grouping, priority setting, and validation before building the final manager.
*
* @template TInput - Type of data that plugins will receive as input
* @template TOutput - Type of data that plugins will produce as output
* @template TMetadata - Type of execution metadata passed to plugins
*
* @returns A new PluginManagerBuilder instance for fluent configuration
*
* @example
* ```typescript
* // Basic builder usage
* const manager = createPluginBuilder<string, string>()
* .plugin(trimPlugin)
* .plugin(uppercasePlugin)
* .build();
* ```
*
* @example
* ```typescript
* // Advanced builder with conditional logic and grouping
* const isDevelopment = process.env.NODE_ENV === 'development';
* const enableLogging = process.env.ENABLE_LOGGING === 'true';
*
* const manager = createPluginBuilder<ApiRequest, ApiResponse>()
* // High priority validation
* .withPriority(100, authPlugin)
* .withPriority(90, validationPlugin)
*
* // Conditional development plugins
* .when(isDevelopment, debugPlugin)
* .when(enableLogging, loggingPlugin)
*
* // Grouped processing plugins
* .group({
* tag: 'data-processing',
* items: [
* { plugin: transformPlugin, settings: { priority: 50 } },
* { plugin: enrichPlugin, settings: { priority: 40 } },
* { plugin: validateOutputPlugin, settings: { priority: 30 } }
* ]
* })
*
* // Response formatting
* .withPriority(10, formatResponsePlugin)
*
* .validate() // Optional: validate configuration before build
* .build();
* ```
*
* @example
* ```typescript
* // Builder with environment-specific configuration
* const createApiManager = (environment: 'dev' | 'staging' | 'prod') => {
* const builder = createPluginBuilder<ApiRequest, ApiResponse>()
* .plugin(corePlugin)
* .plugin(businessLogicPlugin);
*
* if (environment !== 'prod') {
* builder.plugin(testingPlugin);
* }
*
* if (environment === 'dev') {
* builder
* .plugin(debugPlugin)
* .plugin(mockDataPlugin);
* }
*
* return builder.build();
* };
* ```
*/
export declare function createPluginBuilder<TInput = unknown, TOutput = unknown, TMetadata extends Record<string, unknown> = Record<string, unknown>>(): PluginManagerBuilder<TInput, TOutput, TMetadata>;
/**
* Creates a simple plugin with minimal configuration
*
* This is the quickest way to create a plugin for basic data transformation.
* The plugin will have default lifecycle methods and error handling, while
* allowing you to focus on the core processing logic.
*
* @template TInput - Type of input data the plugin processes
* @template TOutput - Type of output data the plugin produces
* @template TContext - Type of plugin context (usually PluginContext)
*
* @param metadata - Plugin identification and dependency information
* @param execute - The main processing function that transforms input to output
* @param hooks - Optional lifecycle hooks for advanced plugin behavior
*
* @returns A fully configured plugin ready for registration
*
* @example
* ```typescript
* // Simple text transformation plugin
* const uppercasePlugin = simplePlugin(
* {
* name: 'uppercase-transformer',
* version: '1.0.0',
* description: 'Converts text to uppercase'
* },
* (input: string) => input.toUpperCase()
* );
* ```
*
* @example
* ```typescript
* // Plugin with async processing
* const apiCallPlugin = simplePlugin(
* {
* name: 'api-enricher',
* version: '1.2.0',
* description: 'Enriches data with external API calls',
* dependencies: ['validation-plugin'] // Runs after validation
* },
* async (userData: UserData, context) => {
* context.logger.info(`Processing user: ${userData.id}`);
*
* const response = await fetch(`/api/users/${userData.id}/details`);
* const enrichedData = await response.json();
*
* return {
* ...userData,
* ...enrichedData
* };
* }
* );
* ```
*
* @example
* ```typescript
* // Plugin with lifecycle hooks for resource management
* const databasePlugin = simplePlugin(
* {
* name: 'database-writer',
* version: '2.1.0',
* description: 'Persists data to database'
* },
* async (data: ProcessedData, context) => {
* const db = context.retrieve<Database>('database-connection');
* if (!db) {
* throw new Error('Database connection not available');
* }
*
* const result = await db.save(data);
* context.logger.info(`Saved record with ID: ${result.id}`);
*
* return result;
* },
* {
* // Initialize database connection
* initialize: async (context) => {
* const config = context.getSettings('database-writer')?.config;
* const db = await createDatabaseConnection(config);
* context.share('database-connection', db);
* context.logger.info('Database connection established');
* },
*
* // Clean up resources
* cleanup: async (context) => {
* const db = context.retrieve<Database>('database-connection');
* if (db) {
* await db.close();
* context.logger.info('Database connection closed');
* }
* },
*
* // Handle errors gracefully
* onError: async (error, context) => {
* context.logger.error('Database operation failed', {
* error: error.message,
* stack: error.stack
* });
*
* // Could implement retry logic, fallback storage, etc.
* }
* }
* );
* ```
*
* @example
* ```typescript
* // Plugin with context usage for shared state
* const cachePlugin = simplePlugin(
* {
* name: 'cache-manager',
* version: '1.0.0',
* description: 'Caches processed results'
* },
* async (input: string, context) => {
* const cacheKey = `processed_${input}`;
*
* // Try to get from cache first
* const cached = context.retrieve<string>(cacheKey);
* if (cached) {
* context.logger.debug(`Cache hit for key: ${cacheKey}`);
* return cached;
* }
*
* // Process the input (expensive operation)
* const processed = await expensiveProcessing(input);
*
* // Store in cache for future use
* context.share(cacheKey, processed);
* context.logger.debug(`Cached result for key: ${cacheKey}`);
*
* return processed;
* }
* );
* ```
*/
export declare function simplePlugin<TInput, TOutput, TContext extends PluginContext = PluginContext>(metadata: PluginMetadata, execute: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, hooks?: PluginHooks<TInput, TOutput, TContext>): IPlugin<TInput, TOutput, TContext>;
export type { PluginMetadata, PluginSettings, PluginResult, ManagerResult, } from './core/types';
export type { IPlugin, IPluginManager } from './core/interfaces';
//# sourceMappingURL=index.d.ts.map