@qlover/fe-corekit 2.0.0 → 2.0.1

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
@@ -82,92 +82,370 @@ declare class ExecutorError extends Error {
82
82
  }
83
83
 
84
84
  /**
85
- * Represents the context in which a task is executed.
85
+ * Execution context interface for task execution state management
86
86
  *
87
- * This interface is designed to encapsulate the necessary information
88
- * for executing a task, including parameters, potential errors, and
89
- * the return value. It allows for additional properties to be added
90
- * dynamically, making it flexible for various use cases.
87
+ * Core concept:
88
+ * Encapsulates the complete execution state of a task, including input parameters,
89
+ * execution results, error information, and runtime metadata. Provides a centralized
90
+ * way to manage and track task execution throughout the plugin pipeline.
91
91
  *
92
- * @template Params - The type of parameters that the task accepts.
92
+ * Main features:
93
+ * - State management: Centralized storage for task execution state
94
+ * - Error tracking: Captures and preserves error information during execution
95
+ * - Parameter passing: Maintains input parameters throughout the execution pipeline
96
+ * - Result storage: Stores task execution results and return values
97
+ * - Runtime monitoring: Tracks execution time and hook performance metrics
98
+ * - Extensibility: Supports dynamic property addition for custom use cases
93
99
  *
94
- * @since 1.0.14
100
+ * Design considerations:
101
+ * - Immutable runtime data: Hook runtime information is read-only and frozen
102
+ * - Type safety: Full TypeScript support with generic parameter types
103
+ * - Pipeline integration: Seamlessly integrates with executor plugin pipeline
104
+ * - Memory management: Runtime data is automatically cleared after execution
95
105
  *
96
- * @example
106
+ * @template Params - Type of parameters that the task accepts
107
+ *
108
+ * @since `1.0.14`
109
+ *
110
+ * @example Basic context creation
111
+ * ```typescript
112
+ * const context: ExecutorContext<MyParams> = {
113
+ * parameters: { id: 1, name: 'test' },
114
+ * error: undefined,
115
+ * returnValue: undefined,
116
+ * hooksRuntimes: {}
117
+ * };
118
+ * ```
119
+ *
120
+ * @example Context with error state
97
121
  * ```typescript
98
- * const context: ExecutorContextInterface<MyParams> = {
122
+ * const context: ExecutorContext<MyParams> = {
99
123
  * parameters: { id: 1 },
100
- * error: null,
101
- * returnValue: 'Success'
124
+ * error: new Error('Task failed'),
125
+ * returnValue: undefined,
126
+ * hooksRuntimes: {}
127
+ * };
128
+ * ```
129
+ *
130
+ * @example Context with successful result
131
+ * ```typescript
132
+ * const context: ExecutorContext<MyParams> = {
133
+ * parameters: { id: 1 },
134
+ * error: undefined,
135
+ * returnValue: { success: true, data: 'processed' },
136
+ * hooksRuntimes: {}
102
137
  * };
103
138
  * ```
104
139
  */
105
140
  interface ExecutorContext<Params = unknown> {
106
141
  /**
107
- * The error that occurred during the execution of the task.
142
+ * Error that occurred during task execution
143
+ *
144
+ * Core concept:
145
+ * Captures and preserves error information when task execution fails,
146
+ * enabling comprehensive error handling and debugging capabilities
108
147
  *
109
- * This property is optional and will be populated if an error
110
- * occurs during task execution.
148
+ * Main features:
149
+ * - Error preservation: Maintains original error objects with stack traces
150
+ * - Pipeline integration: Errors are propagated through the execution pipeline
151
+ * - Debugging support: Provides detailed error information for troubleshooting
152
+ * - Optional presence: Only populated when errors occur during execution
111
153
  *
112
- * @type {Error | undefined}
154
+ * Error handling flow:
155
+ * 1. Error occurs during task execution or plugin hook execution
156
+ * 2. Error is captured and assigned to this property
157
+ * 3. Error information is preserved for downstream processing
158
+ * 4. Error can be handled by error-specific plugins or hooks
159
+ *
160
+ * @optional
161
+ * @example `new Error('Database connection failed')`
162
+ * @example `new ValidationError('Invalid input parameters')`
113
163
  */
114
164
  error?: Error;
115
165
  /**
116
- * The parameters passed to the task.
166
+ * Input parameters passed to the task for execution
167
+ *
168
+ * Core concept:
169
+ * Contains all input data required for task execution, providing
170
+ * the necessary context and parameters for the task to perform its operations
117
171
  *
118
- * These parameters are used to execute the task and are of a generic
119
- * type, allowing for flexibility in the types of parameters that can
120
- * be passed.
172
+ * Main features:
173
+ * - Type safety: Generic type parameter ensures type safety for different parameter types
174
+ * - Pipeline persistence: Parameters are maintained throughout the execution pipeline
175
+ * - Plugin access: All plugins can access and potentially modify parameters
176
+ * - Validation support: Parameters can be validated by validation plugins
121
177
  *
122
- * @type {Params}
178
+ * Parameter lifecycle:
179
+ * 1. Initial parameters are set when context is created
180
+ * 2. Parameters can be modified by before hooks (validation, transformation)
181
+ * 3. Modified parameters are passed to the main task function
182
+ * 4. Parameters remain available for after hooks (logging, cleanup)
183
+ *
184
+ * @example Simple parameters
185
+ * ```typescript
186
+ * parameters: { id: 1, name: 'test' }
187
+ * ```
188
+ *
189
+ * @example Complex parameters
190
+ * ```typescript
191
+ * parameters: {
192
+ * user: { id: 1, name: 'John' },
193
+ * options: { timeout: 5000, retries: 3 },
194
+ * metadata: { source: 'api', version: 'v2' }
195
+ * }
196
+ * ```
123
197
  */
124
198
  parameters: Params;
125
199
  /**
126
- * The return value of the task.
200
+ * Return value from successful task execution
201
+ *
202
+ * Core concept:
203
+ * Stores the result of successful task execution, providing a centralized
204
+ * location for accessing task output and results
127
205
  *
128
- * This property is optional and will contain the result of the task
129
- * execution if it completes successfully.
206
+ * Main features:
207
+ * - Result storage: Captures task execution results for downstream processing
208
+ * - Pipeline integration: Results are available to after hooks and plugins
209
+ * - Type flexibility: Supports any return type from task execution
210
+ * - Optional presence: Only populated when task execution succeeds
130
211
  *
131
- * @type {unknown | undefined}
212
+ * Result lifecycle:
213
+ * 1. Task function executes and produces a result
214
+ * 2. Result is stored in this property
215
+ * 3. Result is available to after hooks for processing
216
+ * 4. Result can be transformed or enhanced by plugins
217
+ *
218
+ * @optional
219
+ * @example `{ success: true, data: 'processed result' }`
220
+ * @example `'simple string result'`
221
+ * @example `{ items: [], total: 0, page: 1 }`
132
222
  */
133
223
  returnValue?: unknown;
134
224
  /**
135
- * The runtime information of the task.
225
+ * Runtime information and metadata for hook execution
136
226
  *
137
- * The current runtime of each hook.
227
+ * Core concept:
228
+ * Provides detailed runtime information about hook execution, including
229
+ * performance metrics, execution state, and control flow information
138
230
  *
139
- * This property is optional and will contain the runtime information
140
- * of the task if it is executed.
231
+ * Main features:
232
+ * - Performance tracking: Monitors hook execution time and performance
233
+ * - State management: Tracks current hook name and execution state
234
+ * - Flow control: Provides mechanisms to control execution flow
235
+ * - Read-only access: Runtime data is frozen and cannot be modified
236
+ * - Auto-cleanup: Data is automatically cleared after execution completes
141
237
  *
142
- * property is read-only
238
+ * Runtime data structure:
239
+ * - hookName: Current hook being executed
240
+ * - returnValue: Return value from current hook execution
241
+ * - times: Number of times hook has been executed
242
+ * - breakChain: Flag to break the execution chain
243
+ * - returnBreakChain: Flag to break chain when return value exists
143
244
  *
144
- * will return a frozen object that will be cleared after the chain execution is complete.
245
+ * Security and performance:
246
+ * - Data is frozen to prevent modification during execution
247
+ * - Memory is automatically managed and cleared after execution
248
+ * - Provides audit trail for debugging and monitoring
145
249
  *
250
+ * @readonly
251
+ * @example
252
+ * ```typescript
253
+ * hooksRuntimes: {
254
+ * hookName: 'onBefore',
255
+ * returnValue: { validated: true },
256
+ * times: 1,
257
+ * breakChain: false,
258
+ * returnBreakChain: false
259
+ * }
260
+ * ```
146
261
  */
147
262
  hooksRuntimes: HookRuntimes;
148
263
  }
264
+ /**
265
+ * Runtime information interface for hook execution tracking
266
+ *
267
+ * Core concept:
268
+ * Provides detailed runtime metadata for individual hook execution,
269
+ * enabling performance monitoring, flow control, and execution state tracking
270
+ *
271
+ * Main features:
272
+ * - Execution tracking: Monitors hook execution state and performance
273
+ * - Flow control: Provides mechanisms to control execution pipeline flow
274
+ * - Performance metrics: Tracks execution times and performance data
275
+ * - State preservation: Maintains execution state throughout the pipeline
276
+ * - Extensibility: Supports additional custom properties for specific use cases
277
+ *
278
+ * Flow control mechanisms:
279
+ * - breakChain: Immediately stops execution pipeline
280
+ * - returnBreakChain: Stops pipeline when return value is present
281
+ * - times: Tracks execution frequency for optimization
282
+ *
283
+ * @example Basic runtime information
284
+ * ```typescript
285
+ * const runtime: HookRuntimes = {
286
+ * hookName: 'onBefore',
287
+ * returnValue: { validated: true },
288
+ * times: 1,
289
+ * breakChain: false,
290
+ * returnBreakChain: false
291
+ * };
292
+ * ```
293
+ *
294
+ * @example Runtime with custom properties
295
+ * ```typescript
296
+ * const runtime: HookRuntimes = {
297
+ * hookName: 'customHook',
298
+ * returnValue: { processed: true },
299
+ * times: 3,
300
+ * breakChain: false,
301
+ * returnBreakChain: true,
302
+ * customMetric: 'performance_data',
303
+ * executionTime: 150
304
+ * };
305
+ * ```
306
+ */
149
307
  interface HookRuntimes {
308
+ /**
309
+ * Name of the current hook being executed
310
+ *
311
+ * Core concept:
312
+ * Identifies the specific hook that is currently being executed,
313
+ * enabling targeted debugging and monitoring of hook performance
314
+ *
315
+ * Main features:
316
+ * - Hook identification: Clearly identifies which hook is executing
317
+ * - Debugging support: Enables targeted debugging of specific hooks
318
+ * - Performance monitoring: Allows tracking of individual hook performance
319
+ * - Pipeline visibility: Provides visibility into execution pipeline state
320
+ *
321
+ * @optional
322
+ * @example `'onBefore'`
323
+ * @example `'onExec'`
324
+ * @example `'onAfter'`
325
+ * @example `'customValidationHook'`
326
+ */
150
327
  hookName?: string;
151
328
  /**
152
- * The return value of the task.
329
+ * Return value from the current hook execution
153
330
  *
154
- * Readonly
331
+ * Core concept:
332
+ * Captures the return value from the current hook execution,
333
+ * enabling result tracking and flow control based on hook output
334
+ *
335
+ * Main features:
336
+ * - Result tracking: Monitors what each hook returns
337
+ * - Flow control: Enables conditional execution based on return values
338
+ * - Debugging support: Provides visibility into hook output
339
+ * - Pipeline integration: Results can influence downstream execution
340
+ *
341
+ * @readonly
342
+ * @optional
343
+ * @example `{ validated: true, data: 'processed' }`
344
+ * @example `'hook_result'`
345
+ * @example `{ error: 'validation_failed' }`
155
346
  */
156
347
  returnValue?: unknown;
157
348
  /**
158
- * 执行次数
349
+ * Number of times the hook has been executed
350
+ *
351
+ * Core concept:
352
+ * Tracks the execution frequency of hooks, enabling performance
353
+ * optimization and debugging of repeated executions
354
+ *
355
+ * Main features:
356
+ * - Execution counting: Monitors how many times hooks are called
357
+ * - Performance analysis: Identifies frequently executed hooks
358
+ * - Loop detection: Helps identify potential infinite loops
359
+ * - Optimization insights: Provides data for performance optimization
360
+ *
361
+ * Usage scenarios:
362
+ * - Performance monitoring: Track hook execution frequency
363
+ * - Debugging: Identify hooks that execute more than expected
364
+ * - Optimization: Focus optimization efforts on frequently called hooks
365
+ *
366
+ * @optional
367
+ * @example `1` // First execution
368
+ * @example `5` // Hook executed 5 times
369
+ * @example `0` // Hook not yet executed
159
370
  */
160
371
  times?: number;
161
372
  /**
162
- * 是否中断链
373
+ * Flag to immediately break the execution chain
374
+ *
375
+ * Core concept:
376
+ * Provides a mechanism to immediately stop the execution pipeline,
377
+ * enabling early termination when certain conditions are met
378
+ *
379
+ * Main features:
380
+ * - Immediate termination: Stops execution pipeline immediately
381
+ * - Conditional control: Enables conditional execution flow
382
+ * - Error handling: Allows early termination on critical errors
383
+ * - Performance optimization: Avoids unnecessary processing
384
+ *
385
+ * Use cases:
386
+ * - Error conditions: Stop execution when critical errors occur
387
+ * - Validation failures: Terminate when validation fails
388
+ * - Early success: Stop when desired result is achieved early
389
+ * - Resource constraints: Terminate when resources are exhausted
390
+ *
391
+ * @optional
392
+ * @example `true` // Break execution chain immediately
393
+ * @example `false` // Continue normal execution
163
394
  */
164
395
  breakChain?: boolean;
165
396
  /**
166
- * 如果有返回值,是否中断链
397
+ * Flag to break chain when return value exists
398
+ *
399
+ * Core concept:
400
+ * Enables conditional chain breaking based on the presence of a return value,
401
+ * commonly used in error handling and early termination scenarios
402
+ *
403
+ * Main features:
404
+ * - Conditional termination: Breaks chain only when return value exists
405
+ * - Error handling: Commonly used in `onError` lifecycle hooks
406
+ * - Result-based control: Enables flow control based on hook results
407
+ * - Flexible termination: Provides more nuanced control than `breakChain`
408
+ *
409
+ * Common usage:
410
+ * - Error handlers: Break chain when error is handled and result is returned
411
+ * - Validation: Stop processing when validation result is returned
412
+ * - Caching: Terminate when cached result is found
413
+ * - Early success: Stop when desired result is achieved
167
414
  *
168
- * 一般常用于需要返回一个值时中断链,比如 onError 声明周期
415
+ * @optional
416
+ * @example `true` // Break chain if returnValue exists
417
+ * @example `false` // Continue regardless of returnValue
169
418
  */
170
419
  returnBreakChain?: boolean;
420
+ /**
421
+ * Additional custom properties for extensibility
422
+ *
423
+ * Core concept:
424
+ * Provides a flexible mechanism to add custom properties to runtime
425
+ * information, enabling plugin-specific metadata and custom tracking
426
+ *
427
+ * Main features:
428
+ * - Extensibility: Allows plugins to add custom runtime data
429
+ * - Custom metrics: Enables plugin-specific performance tracking
430
+ * - Metadata storage: Provides space for custom execution metadata
431
+ * - Plugin integration: Enables rich plugin-to-plugin communication
432
+ *
433
+ * Common custom properties:
434
+ * - executionTime: Hook execution time in milliseconds
435
+ * - memoryUsage: Memory consumption during hook execution
436
+ * - customMetrics: Plugin-specific performance metrics
437
+ * - debugInfo: Additional debugging information
438
+ *
439
+ * @example
440
+ * ```typescript
441
+ * {
442
+ * executionTime: 150,
443
+ * memoryUsage: '2.5MB',
444
+ * customMetric: 'validation_score',
445
+ * debugInfo: { step: 'validation', level: 'info' }
446
+ * }
447
+ * ```
448
+ */
171
449
  [key: string]: unknown;
172
450
  }
173
451
 
@@ -333,24 +611,102 @@ interface ExecutorPlugin<T = unknown> {
333
611
  onExec?(context: ExecutorContext<unknown>, task: Task<unknown, unknown>): Promise<unknown> | unknown;
334
612
  }
335
613
 
614
+ type HookType = string;
336
615
  /**
337
- * Base executor class providing plugin management and execution pipeline
616
+ * Configuration interface for executor behavior customization
617
+ *
618
+ * Core concept:
619
+ * Provides flexible configuration options to customize executor behavior,
620
+ * including hook execution order, lifecycle management, and execution flow control
621
+ *
622
+ * Main features:
623
+ * - Hook customization: Define custom hook names for different execution phases
624
+ * - Execution flow control: Configure before/after execution hooks
625
+ * - Plugin integration: Support for custom execution logic hooks
338
626
  *
339
- * The Executor pattern implements a pluggable execution pipeline that allows:
340
- * 1. Pre-processing of input data
341
- * 2. Post-processing of results
342
- * 3. Error handling
343
- * 4. Custom execution logic
627
+ * @since 2.1.0
628
+ *
629
+ * @example Basic configuration
630
+ * ```typescript
631
+ * const config: ExecutorConfigInterface = {
632
+ * beforeHooks: ['validate', 'transform'],
633
+ * afterHooks: ['log', 'cleanup'],
634
+ * execHook: 'process'
635
+ * };
636
+ * ```
637
+ */
638
+ interface ExecutorConfigInterface {
639
+ /**
640
+ * Hook names to execute before task execution
641
+ *
642
+ * These hooks are executed in the order they appear in the array.
643
+ * Each hook can modify the input data or perform validation.
644
+ *
645
+ * @default `'onBefore'`
646
+ * @example `['validate', 'transform']`
647
+ * @example `'preProcess'`
648
+ */
649
+ beforeHooks?: HookType | HookType[];
650
+ /**
651
+ * Hook names to execute after successful task execution
652
+ *
653
+ * These hooks are executed in the order they appear in the array.
654
+ * Each hook can process the result or perform cleanup operations.
655
+ *
656
+ * @default `'onSuccess'`
657
+ * @example `['log', 'cleanup']`
658
+ * @example `'postProcess'`
659
+ */
660
+ afterHooks?: HookType | HookType[];
661
+ /**
662
+ * Hook name for the main execution logic
663
+ *
664
+ * This hook contains the core business logic for task execution.
665
+ * If not specified, the default `'onExec'` hook is used.
666
+ *
667
+ * @default `'onExec'`
668
+ * @example `'process'`
669
+ * @example `'execute'`
670
+ */
671
+ execHook?: HookType;
672
+ }
673
+ /**
674
+ * Base executor class providing plugin management and execution pipeline
344
675
  *
345
- * execNoError returns all errors as they are., and if there is a plugin onerror handler chain in which an error occurs, it will also return the error instead of throwing it.
676
+ * Core concept:
677
+ * Implements a pluggable execution pipeline that enables modular task processing
678
+ * with pre-processing, execution, and post-processing capabilities
679
+ *
680
+ * Main features:
681
+ * - Plugin management: Add, remove, and manage execution plugins
682
+ * - Hook system: Configurable lifecycle hooks for different execution phases
683
+ * - Error handling: Comprehensive error management with optional error wrapping
684
+ * - Task execution: Support for both synchronous and asynchronous task execution
685
+ * - Pipeline orchestration: Coordinate multiple plugins in a defined execution order
686
+ *
687
+ * Execution flow:
688
+ * 1. Before hooks: Validate and transform input data
689
+ * 2. Execution hook: Perform the main business logic
690
+ * 3. After hooks: Process results and perform cleanup
691
+ * 4. Error handling: Manage errors at any stage of execution
692
+ *
693
+ * Design considerations:
694
+ * - Plugin deduplication: Prevents duplicate plugins when `onlyOne` is true
695
+ * - Error propagation: `execNoError` methods return errors instead of throwing
696
+ * - Type safety: Full TypeScript support with generic type parameters
697
+ * - Extensibility: Easy to extend with custom plugins and hooks
346
698
  *
347
699
  * @abstract
348
700
  * @class Executor
349
701
  * @category Executor
350
- * @example
702
+ *
703
+ * @example Basic usage
351
704
  * ```typescript
352
705
  * // Create an executor instance
353
- * const executor = new AsyncExecutor();
706
+ * const executor = new AsyncExecutor({
707
+ * beforeHooks: ['validate'],
708
+ * afterHooks: ['log']
709
+ * });
354
710
  *
355
711
  * // Add plugins
356
712
  * executor.use(new LoggerPlugin());
@@ -361,157 +717,296 @@ interface ExecutorPlugin<T = unknown> {
361
717
  * return await someAsyncOperation(data);
362
718
  * });
363
719
  * ```
720
+ *
721
+ * @example With input data
722
+ * ```typescript
723
+ * const result = await executor.exec(inputData, async (data) => {
724
+ * return await processData(data);
725
+ * });
726
+ * ```
727
+ *
728
+ * @example Error-safe execution
729
+ * ```typescript
730
+ * const result = await executor.execNoError(async (data) => {
731
+ * return await riskyOperation(data);
732
+ * });
733
+ *
734
+ * if (result instanceof ExecutorError) {
735
+ * console.error('Task failed:', result.message);
736
+ * } else {
737
+ * console.log('Task succeeded:', result);
738
+ * }
739
+ * ```
364
740
  */
365
- declare abstract class Executor<ExecutorConfig = unknown> {
366
- protected config?: ExecutorConfig | undefined;
741
+ declare abstract class Executor<ExecutorConfig extends ExecutorConfigInterface> {
742
+ protected config: ExecutorConfig;
367
743
  /**
368
- * Array of active plugins
744
+ * Array of active plugins for this executor
745
+ *
746
+ * Core concept:
747
+ * Maintains an ordered collection of plugins that participate in the execution pipeline
748
+ *
749
+ * Main features:
750
+ * - Plugin storage: Stores all registered plugins in execution order
751
+ * - Lifecycle management: Manages plugin initialization and cleanup
752
+ * - Execution coordination: Ensures plugins execute in the correct sequence
753
+ * - Deduplication support: Prevents duplicate plugins when configured
369
754
  *
370
- * - Purpose: Stores and manages executor plugins
371
- * - Core Concept: Ordered plugin pipeline
372
- * - Main Features:
373
- * - Maintains plugin execution order
374
- * - Supports plugin lifecycle management
375
- * - Primary Use: Plugin orchestration and execution
755
+ * Plugin execution order:
756
+ * 1. Plugins are executed in the order they were added
757
+ * 2. Each plugin can modify data or control execution flow
758
+ * 3. Plugin hooks are called based on executor configuration
376
759
  *
377
760
  * @example
378
761
  * ```typescript
379
762
  * protected plugins = [
380
763
  * new LoggerPlugin(),
381
- * new RetryPlugin()
764
+ * new RetryPlugin({ maxAttempts: 3 }),
765
+ * new CachePlugin({ ttl: 300 })
382
766
  * ];
383
767
  * ```
384
768
  */
385
769
  protected plugins: ExecutorPlugin[];
386
770
  /**
387
- * Creates a new Executor instance
771
+ * Creates a new Executor instance with optional configuration
388
772
  *
389
- * - Purpose: Initialize executor with optional configuration
390
- * - Core Concept: Configurable executor setup
391
- * - Main Features: Configuration injection
392
- * - Primary Use: Executor instantiation
773
+ * Core concept:
774
+ * Initializes the executor with configuration that controls its behavior
775
+ * and execution pipeline setup
393
776
  *
394
- * @param {ExecutorConfig} config - Optional configuration object
777
+ * Main features:
778
+ * - Configuration injection: Accepts custom configuration for hook names and behavior
779
+ * - Default setup: Provides sensible defaults when no configuration is provided
780
+ * - Plugin preparation: Sets up the environment for plugin registration
395
781
  *
396
- * @example
782
+ * @param config - Optional configuration object to customize executor behavior
783
+ *
784
+ * @example Basic instantiation
785
+ * ```typescript
786
+ * const executor = new AsyncExecutor();
787
+ * ```
788
+ *
789
+ * @example With custom configuration
397
790
  * ```typescript
398
- * const executor = new Executor({
399
- * // config options
791
+ * const executor = new AsyncExecutor({
792
+ * beforeHooks: ['validate', 'transform'],
793
+ * afterHooks: ['log', 'cleanup'],
794
+ * execHook: 'process'
400
795
  * });
401
796
  * ```
402
797
  */
403
- constructor(config?: ExecutorConfig | undefined);
798
+ constructor(config?: ExecutorConfig);
404
799
  /**
405
- * Add a plugin to the executor
800
+ * Add a plugin to the executor's execution pipeline
406
801
  *
407
- * - Purpose: Extends executor functionality through plugins
408
- * - Core Concept: Plugin registration and deduplication
409
- * - Main Features:
410
- * - Prevents duplicate plugins if onlyOne is true
411
- * - Maintains plugin execution order
412
- * - Primary Use: Adding new capabilities to executor
802
+ * Core concept:
803
+ * Registers a plugin to participate in the executor's execution pipeline,
804
+ * extending the executor's functionality with additional capabilities
413
805
  *
414
- * @param plugin - Plugin instance to add
806
+ * Main features:
807
+ * - Plugin registration: Adds plugins to the execution pipeline
808
+ * - Deduplication: Prevents duplicate plugins when `onlyOne` is true
809
+ * - Order preservation: Maintains plugin execution order
810
+ * - Validation: Ensures plugin is a valid object
415
811
  *
416
- * @example
812
+ * Deduplication logic:
813
+ * - Checks for exact plugin instance match
814
+ * - Checks for plugin name match
815
+ * - Checks for constructor match
816
+ * - Only prevents duplicates when `plugin.onlyOne` is true
817
+ *
818
+ * @param plugin - Plugin instance to add to the execution pipeline
819
+ *
820
+ * @throws {Error} When plugin is not a valid object
821
+ *
822
+ * @example Add a class-based plugin
417
823
  * ```typescript
418
824
  * executor.use(new LoggerPlugin());
419
825
  * executor.use(new RetryPlugin({ maxAttempts: 3 }));
420
826
  * ```
421
827
  *
422
- * @example
423
- *
424
- * Use a plain object as a plugin
828
+ * @example Add a plain object plugin
425
829
  * ```typescript
426
830
  * executor.use({
427
- * onBefore: (data) => ({ ...data, modified: true })
831
+ * pluginName: 'CustomPlugin',
832
+ * onBefore: (data) => ({ ...data, modified: true }),
833
+ * onAfter: (result) => console.log('Result:', result)
428
834
  * });
429
835
  * ```
836
+ *
837
+ * @example Plugin with deduplication
838
+ * ```typescript
839
+ * const plugin = new LoggerPlugin();
840
+ * plugin.onlyOne = true;
841
+ *
842
+ * executor.use(plugin); // First addition - succeeds
843
+ * executor.use(plugin); // Second addition - skipped with warning
844
+ * ```
430
845
  */
431
846
  use(plugin: ExecutorPlugin): void;
432
847
  /**
433
- * Execute a plugin hook
848
+ * Execute a specific hook across all plugins
434
849
  *
435
- * - Purpose: Provides plugin hook execution mechanism
436
- * - Core Concept: Plugin lifecycle management
437
- * - Main Features:
438
- * - Dynamic hook execution
439
- * - Support for async and sync hooks
440
- * - Primary Use: Running plugin lifecycle methods
850
+ * Core concept:
851
+ * Provides the mechanism to execute plugin lifecycle hooks across all
852
+ * registered plugins in the correct order
441
853
  *
442
- * @param plugins - Plugins to execute
443
- * @param name - Hook name to execute
444
- * @param args - Arguments for the hook
854
+ * Main features:
855
+ * - Hook execution: Runs specified hook on all plugins
856
+ * - Order preservation: Executes plugins in registration order
857
+ * - Async support: Handles both synchronous and asynchronous hooks
858
+ * - Error propagation: Manages errors from hook execution
445
859
  *
446
- * @example
860
+ * Hook execution flow:
861
+ * 1. Iterate through plugins in registration order
862
+ * 2. Check if plugin has the specified hook method
863
+ * 3. Execute hook with provided arguments
864
+ * 4. Handle return values and errors appropriately
865
+ *
866
+ * @param plugins - Array of plugins to execute the hook on
867
+ * @param name - Name of the hook to execute (e.g., 'onBefore', 'onExec', 'onAfter')
868
+ * @param args - Arguments to pass to the hook method
869
+ *
870
+ * @returns Hook execution result or void
871
+ *
872
+ * @example Execute before hook
873
+ * ```typescript
874
+ * await executor.runHooks(plugins, 'onBefore', inputData);
875
+ * ```
876
+ *
877
+ * @example Execute custom hook
447
878
  * ```typescript
448
- * await executor.runHook(plugins, 'beforeExec', data);
879
+ * const result = await executor.runHooks(plugins, 'customHook', data, options);
449
880
  * ```
450
881
  */
451
- abstract runHooks(plugins: ExecutorPlugin[], name: keyof ExecutorPlugin, ...args: unknown[]): void | unknown | Promise<void | unknown>;
882
+ abstract runHooks(plugins: ExecutorPlugin[], name: unknown, ...args: unknown[]): void | unknown | Promise<void | unknown>;
452
883
  /**
453
- * Execute a task with plugin pipeline
884
+ * Execute a task through the plugin pipeline
454
885
  *
455
- * - Purpose: Core task execution with plugin support
456
- * - Core Concept: Task execution pipeline
457
- * - Main Features:
458
- * - Plugin hook integration
459
- * - Error handling
460
- * - Primary Use: Running tasks through the executor pipeline
886
+ * Core concept:
887
+ * Executes a task function through the complete plugin pipeline,
888
+ * including before hooks, execution, and after hooks
461
889
  *
462
- * @param task - Task to execute
463
- * @param data - Optional input data for task
464
- * @throws {ExecutorError} If task execution fails
890
+ * Main features:
891
+ * - Pipeline execution: Runs task through configured plugin pipeline
892
+ * - Hook integration: Executes before/after hooks as configured
893
+ * - Error handling: Comprehensive error management and propagation
894
+ * - Type safety: Full TypeScript support with generic types
465
895
  *
466
- * @example
896
+ * Execution pipeline:
897
+ * 1. Execute before hooks (if configured)
898
+ * 2. Execute main task function
899
+ * 3. Execute after hooks (if configured)
900
+ * 4. Return result or throw error
901
+ *
902
+ * @param task - Task function to execute through the pipeline
903
+ * @returns Task execution result
904
+ *
905
+ * @throws {ExecutorError} When task execution fails or plugin errors occur
906
+ *
907
+ * @example Basic task execution
467
908
  * ```typescript
468
909
  * const result = await executor.exec(async (data) => {
469
910
  * return await processData(data);
470
911
  * });
471
912
  * ```
913
+ *
914
+ * @example Synchronous task execution
915
+ * ```typescript
916
+ * const result = executor.exec((data) => {
917
+ * return transformData(data);
918
+ * });
919
+ * ```
472
920
  */
473
921
  abstract exec<Result, Params = unknown>(task: Task<Result, Params>): Promise<Result> | Result;
474
922
  /**
475
- * Execute a task with plugin pipeline and input data
923
+ * Execute a task with input data through the plugin pipeline
476
924
  *
477
- * - Purpose: Core task execution with plugin support and input data
478
- * - Core Concept: Task execution pipeline with data
479
- * - Main Features:
480
- * - Plugin hook integration
481
- * - Error handling
482
- * - Primary Use: Running tasks with input data through the executor pipeline
925
+ * Core concept:
926
+ * Executes a task function with provided input data through the complete
927
+ * plugin pipeline, enabling data transformation and processing
483
928
  *
484
- * @param data - Input data for task
485
- * @param task - Task to execute
486
- * @throws {ExecutorError} If task execution fails
929
+ * Main features:
930
+ * - Data processing: Passes input data through the execution pipeline
931
+ * - Pipeline execution: Runs task through configured plugin pipeline
932
+ * - Hook integration: Executes before/after hooks with input data
933
+ * - Error handling: Comprehensive error management and propagation
487
934
  *
488
- * @example
935
+ * Data flow:
936
+ * 1. Input data is passed to before hooks for validation/transformation
937
+ * 2. Transformed data is passed to the main task function
938
+ * 3. Task result is passed to after hooks for processing
939
+ * 4. Final result is returned or error is thrown
940
+ *
941
+ * @param data - Input data to pass through the execution pipeline
942
+ * @param task - Task function to execute with the input data
943
+ * @returns Task execution result
944
+ *
945
+ * @throws {ExecutorError} When task execution fails or plugin errors occur
946
+ *
947
+ * @example Execute task with input data
489
948
  * ```typescript
490
- * const result = await executor.exec(data, async (data) => {
949
+ * const result = await executor.exec(inputData, async (data) => {
491
950
  * return await processData(data);
492
951
  * });
493
952
  * ```
953
+ *
954
+ * @example Data transformation pipeline
955
+ * ```typescript
956
+ * const result = await executor.exec(rawData, (data) => {
957
+ * return transformAndValidate(data);
958
+ * });
959
+ * ```
494
960
  */
495
961
  abstract exec<Result, Params = unknown>(data: unknown, task: Task<Result, Params>): Promise<Result> | Result;
496
962
  /**
497
- * Execute a task without throwing errors
963
+ * Execute a task without throwing errors, returning errors as values
498
964
  *
499
- * - Purpose: Safe task execution with error wrapping
500
- * - Core Concept: Error-safe execution pipeline
501
- * - Main Features:
502
- * - Error wrapping in ExecutorError
503
- * - Non-throwing execution
504
- * - Primary Use: When error handling is preferred over exceptions
965
+ * Core concept:
966
+ * Provides error-safe task execution by wrapping errors in `ExecutorError`
967
+ * instances instead of throwing them, enabling explicit error handling
505
968
  *
506
- * @param task - Task to execute
969
+ * Main features:
970
+ * - Error wrapping: All errors are wrapped in `ExecutorError` instances
971
+ * - Non-throwing: Never throws errors, always returns a value
972
+ * - Pipeline execution: Runs through complete plugin pipeline
973
+ * - Type safety: Returns union type of result or error
507
974
  *
508
- * @example
975
+ * Error handling:
976
+ * - Task execution errors are wrapped in `ExecutorError`
977
+ * - Plugin hook errors are wrapped in `ExecutorError`
978
+ * - Network/async errors are wrapped in `ExecutorError`
979
+ * - All errors include original error information and context
980
+ *
981
+ * @param task - Task function to execute safely
982
+ * @returns Task result or `ExecutorError` instance
983
+ *
984
+ * @example Safe task execution
509
985
  * ```typescript
510
986
  * const result = await executor.execNoError(async (data) => {
511
987
  * return await riskyOperation(data);
512
988
  * });
989
+ *
513
990
  * if (result instanceof ExecutorError) {
514
- * console.error('Task failed:', result);
991
+ * console.error('Task failed:', result.message);
992
+ * console.error('Original error:', result.cause);
993
+ * } else {
994
+ * console.log('Task succeeded:', result);
995
+ * }
996
+ * ```
997
+ *
998
+ * @example Error handling with type guards
999
+ * ```typescript
1000
+ * const result = await executor.execNoError(async (data) => {
1001
+ * return await apiCall(data);
1002
+ * });
1003
+ *
1004
+ * if (result instanceof ExecutorError) {
1005
+ * // Handle error case
1006
+ * return { success: false, error: result.message };
1007
+ * } else {
1008
+ * // Handle success case
1009
+ * return { success: true, data: result };
515
1010
  * }
516
1011
  * ```
517
1012
  */
@@ -519,41 +1014,304 @@ declare abstract class Executor<ExecutorConfig = unknown> {
519
1014
  /**
520
1015
  * Execute a task with input data without throwing errors
521
1016
  *
522
- * - Purpose: Safe task execution with error wrapping and input data
523
- * - Core Concept: Error-safe execution pipeline with data
524
- * - Main Features:
525
- * - Error wrapping in ExecutorError
526
- * - Non-throwing execution
527
- * - Primary Use: When error handling is preferred over exceptions with input data
1017
+ * Core concept:
1018
+ * Provides error-safe task execution with input data by wrapping errors
1019
+ * in `ExecutorError` instances, enabling explicit error handling with data processing
528
1020
  *
529
- * @param data - Input data for task
530
- * @param task - Task to execute
1021
+ * Main features:
1022
+ * - Error wrapping: All errors are wrapped in `ExecutorError` instances
1023
+ * - Non-throwing: Never throws errors, always returns a value
1024
+ * - Data processing: Passes input data through the execution pipeline
1025
+ * - Pipeline execution: Runs through complete plugin pipeline
531
1026
  *
532
- * @example
1027
+ * Data and error flow:
1028
+ * 1. Input data is processed through before hooks
1029
+ * 2. Task function executes with processed data
1030
+ * 3. Result is processed through after hooks
1031
+ * 4. Final result or error is returned (never thrown)
1032
+ *
1033
+ * @param data - Input data to pass through the execution pipeline
1034
+ * @param task - Task function to execute with the input data
1035
+ * @returns Task result or `ExecutorError` instance
1036
+ *
1037
+ * @example Safe execution with input data
533
1038
  * ```typescript
534
- * const result = await executor.execNoError(data, async (data) => {
535
- * return await riskyOperation(data);
1039
+ * const result = await executor.execNoError(inputData, async (data) => {
1040
+ * return await processData(data);
536
1041
  * });
1042
+ *
537
1043
  * if (result instanceof ExecutorError) {
538
- * console.error('Task failed:', result);
1044
+ * console.error('Processing failed:', result.message);
1045
+ * } else {
1046
+ * console.log('Processing succeeded:', result);
539
1047
  * }
540
1048
  * ```
1049
+ *
1050
+ * @example Batch processing with error handling
1051
+ * ```typescript
1052
+ * const results = await Promise.all(
1053
+ * dataItems.map(item =>
1054
+ * executor.execNoError(item, async (data) => {
1055
+ * return await processItem(data);
1056
+ * })
1057
+ * )
1058
+ * );
1059
+ *
1060
+ * const successes = results.filter(r => !(r instanceof ExecutorError));
1061
+ * const errors = results.filter(r => r instanceof ExecutorError);
1062
+ * ```
541
1063
  */
542
1064
  abstract execNoError<Result, Params = unknown>(data: unknown, task: Task<Result, Params>): Promise<Result | ExecutorError> | Result | ExecutorError;
543
1065
  }
544
1066
 
1067
+ /**
1068
+ * Manages execution context state and plugin runtime tracking
1069
+ *
1070
+ * Core concept:
1071
+ * Centralized context management for executor plugin lifecycle tracking
1072
+ *
1073
+ * Main features:
1074
+ * - Context state management: Reset and initialize context state
1075
+ * - Plugin runtime tracking: Monitor plugin execution times and metadata
1076
+ * - Chain control: Manage execution chain breaking conditions
1077
+ * - Error handling: Context error state management
1078
+ * - Hook validation: Check plugin hook availability and enablement
1079
+ *
1080
+ * Key responsibilities:
1081
+ * - Maintain execution context consistency
1082
+ * - Track plugin execution metadata
1083
+ * - Control execution flow through chain breaking
1084
+ * - Manage error state propagation
1085
+ *
1086
+ * @example Basic usage
1087
+ * ```typescript
1088
+ * const handler = new ContextHandler();
1089
+ * const context = createContext(data);
1090
+ *
1091
+ * // Reset context for new execution
1092
+ * handler.reset(context);
1093
+ *
1094
+ * // Check if plugin should be skipped
1095
+ * const shouldSkip = handler.shouldSkipPluginHook(plugin, 'onBefore', context);
1096
+ * ```
1097
+ *
1098
+ * @category ContextHandler
1099
+ */
1100
+ declare class ContextHandler {
1101
+ /**
1102
+ * Reset hooks runtime state to initial values
1103
+ *
1104
+ * Core concept:
1105
+ * Clears all runtime tracking information for fresh execution
1106
+ *
1107
+ * Reset operations:
1108
+ * - Clears plugin name and hook name
1109
+ * - Resets return value and chain breaking flags
1110
+ * - Resets execution counter and index
1111
+ *
1112
+ * @param hooksRuntimes - The hooks runtime object to reset
1113
+ *
1114
+ * @example
1115
+ * ```typescript
1116
+ * const handler = new ContextHandler();
1117
+ * handler.resetHooksRuntimes(context.hooksRuntimes);
1118
+ * ```
1119
+ */
1120
+ resetHooksRuntimes(hooksRuntimes: HookRuntimes): void;
1121
+ /**
1122
+ * Reset entire context to initial state
1123
+ *
1124
+ * Core concept:
1125
+ * Complete context cleanup for new execution cycle
1126
+ *
1127
+ * Reset operations:
1128
+ * - Resets hooks runtime state
1129
+ * - Clears return value
1130
+ * - Clears error state
1131
+ *
1132
+ * @template Params - Type of context parameters
1133
+ * @param context - The execution context to reset
1134
+ *
1135
+ * @example
1136
+ * ```typescript
1137
+ * const handler = new ContextHandler();
1138
+ * handler.reset(context);
1139
+ * ```
1140
+ */
1141
+ reset<Params>(context: ExecutorContext<Params>): void;
1142
+ /**
1143
+ * Check if a plugin hook should be skipped
1144
+ * Returns true if the hook should be skipped (invalid or disabled)
1145
+ *
1146
+ * Core concept:
1147
+ * Plugin hook validation and enablement checking
1148
+ *
1149
+ * Validation criteria:
1150
+ * - Hook method exists and is callable
1151
+ * - Plugin is enabled for the specific hook
1152
+ * - Plugin enablement function returns true
1153
+ *
1154
+ * @template Params - Type of context parameters
1155
+ * @param plugin - The plugin to check
1156
+ * @param hookName - The name of the hook to validate
1157
+ * @param context - The execution context
1158
+ * @returns True if the hook should be skipped, false otherwise
1159
+ *
1160
+ * @example
1161
+ * ```typescript
1162
+ * const shouldSkip = handler.shouldSkipPluginHook(
1163
+ * validationPlugin,
1164
+ * 'onBefore',
1165
+ * context
1166
+ * );
1167
+ *
1168
+ * if (!shouldSkip) {
1169
+ * // Execute the hook
1170
+ * }
1171
+ * ```
1172
+ */
1173
+ shouldSkipPluginHook<Params>(plugin: ExecutorPlugin, hookName: string, context: ExecutorContext<Params>): boolean;
1174
+ /**
1175
+ * Update runtime tracking information for plugin execution
1176
+ *
1177
+ * Core concept:
1178
+ * Track plugin execution metadata for debugging and flow control
1179
+ *
1180
+ * Tracking information:
1181
+ * - Current plugin name
1182
+ * - Current hook name
1183
+ * - Execution counter (times)
1184
+ * - Plugin index in execution chain
1185
+ *
1186
+ * @template Params - Type of context parameters
1187
+ * @param context - The execution context
1188
+ * @param plugin - The plugin being executed
1189
+ * @param hookName - The hook name being executed
1190
+ * @param index - The index of the plugin in the execution chain
1191
+ *
1192
+ * @example
1193
+ * ```typescript
1194
+ * handler.runtimes(context, plugin, 'onBefore', 0);
1195
+ * ```
1196
+ */
1197
+ runtimes<Params>(context: ExecutorContext<Params>, plugin: ExecutorPlugin, hookName: string, index: number): void;
1198
+ /**
1199
+ * Set return value in context runtime tracking
1200
+ *
1201
+ * Core concept:
1202
+ * Store plugin hook return value for chain control and debugging
1203
+ *
1204
+ * Usage scenarios:
1205
+ * - Track plugin hook return values
1206
+ * - Enable chain breaking based on return values
1207
+ * - Debug plugin execution flow
1208
+ *
1209
+ * @template Params - Type of context parameters
1210
+ * @param context - The execution context
1211
+ * @param returnValue - The value to set as return value
1212
+ *
1213
+ * @example
1214
+ * ```typescript
1215
+ * const result = plugin.onBefore(context);
1216
+ * handler.runtimeReturnValue(context, result);
1217
+ * ```
1218
+ */
1219
+ runtimeReturnValue<Params>(context: ExecutorContext<Params>, returnValue: unknown): void;
1220
+ /**
1221
+ * Check if the execution chain should be broken
1222
+ *
1223
+ * Core concept:
1224
+ * Chain breaking control for plugin execution flow
1225
+ *
1226
+ * Chain breaking scenarios:
1227
+ * - Plugin explicitly sets breakChain flag
1228
+ * - Error conditions requiring immediate termination
1229
+ * - Business logic requiring early exit
1230
+ *
1231
+ * @template Params - Type of context parameters
1232
+ * @param context - The execution context
1233
+ * @returns True if the chain should be broken, false otherwise
1234
+ *
1235
+ * @example
1236
+ * ```typescript
1237
+ * if (handler.shouldBreakChain(context)) {
1238
+ * break; // Stop plugin execution
1239
+ * }
1240
+ * ```
1241
+ */
1242
+ shouldBreakChain<Params>(context: ExecutorContext<Params>): boolean;
1243
+ /**
1244
+ * Check if the execution chain should be broken due to return value
1245
+ *
1246
+ * Core concept:
1247
+ * Return value-based chain breaking control
1248
+ *
1249
+ * Usage scenarios:
1250
+ * - Plugin returns a value that should terminate execution
1251
+ * - Error handling hooks return error objects
1252
+ * - Business logic requires return value-based flow control
1253
+ *
1254
+ * @template Params - Type of context parameters
1255
+ * @param context - The execution context
1256
+ * @returns True if the chain should be broken due to return value, false otherwise
1257
+ *
1258
+ * @example
1259
+ * ```typescript
1260
+ * if (handler.shouldBreakChainOnReturn(context)) {
1261
+ * return context.hooksRuntimes.returnValue;
1262
+ * }
1263
+ * ```
1264
+ */
1265
+ shouldBreakChainOnReturn<Params>(context: ExecutorContext<Params>): boolean;
1266
+ /**
1267
+ * Set error in context
1268
+ *
1269
+ * Core concept:
1270
+ * Error state management for execution context
1271
+ *
1272
+ * Error handling:
1273
+ * - Store error for plugin error hooks
1274
+ * - Enable error-based flow control
1275
+ * - Support error propagation through plugin chain
1276
+ *
1277
+ * @template Params - Type of context parameters
1278
+ * @param context - The execution context
1279
+ * @param error - The error to set in context
1280
+ *
1281
+ * @example
1282
+ * ```typescript
1283
+ * try {
1284
+ * // Execute some operation
1285
+ * } catch (error) {
1286
+ * handler.setError(context, error as Error);
1287
+ * }
1288
+ * ```
1289
+ */
1290
+ setError<Params>(context: ExecutorContext<Params>, error: Error): void;
1291
+ }
1292
+
545
1293
  /**
546
1294
  * Asynchronous implementation of the Executor pattern
547
1295
  *
548
- * - Purpose: Provides asynchronous task execution with plugin support
549
- * - Core Concept: Async execution pipeline with plugin hooks
550
- * - Main Features:
551
- * - Asynchronous plugin hook execution
552
- * - Promise-based task handling
553
- * - Error handling with plugin support
554
- * - Primary Use: Handling async operations with extensible middleware
1296
+ * Core concept:
1297
+ * Asynchronous execution pipeline with plugin lifecycle management
555
1298
  *
556
- * @example
1299
+ * Main features:
1300
+ * - Asynchronous plugin hook execution: All operations are Promise-based
1301
+ * - Plugin lifecycle management: Support for onBefore, onExec, onSuccess, onError hooks
1302
+ * - Configurable hook execution: Customizable beforeHooks, afterHooks, and execHook
1303
+ * - Chain breaking support: Plugins can interrupt execution chain
1304
+ * - Error handling: Comprehensive error handling with plugin support
1305
+ *
1306
+ * Use this executor when:
1307
+ * - Operations involve async operations (API calls, file I/O, etc.)
1308
+ * - You need to handle Promise-based workflows
1309
+ * - Performance allows for async overhead
1310
+ * - Async operations are involved
1311
+ *
1312
+ * @extends Executor
1313
+ *
1314
+ * @example Basic usage
557
1315
  * ```typescript
558
1316
  * const executor = new AsyncExecutor();
559
1317
  * executor.use(new LogPlugin());
@@ -564,64 +1322,137 @@ declare abstract class Executor<ExecutorConfig = unknown> {
564
1322
  * });
565
1323
  * ```
566
1324
  *
1325
+ * @example With custom configuration
1326
+ * ```typescript
1327
+ * const executor = new AsyncExecutor({
1328
+ * beforeHooks: ['onBefore', 'onValidate'],
1329
+ * afterHooks: ['onSuccess', 'onLog'],
1330
+ * execHook: 'onCustomExec'
1331
+ * });
1332
+ *
1333
+ * const result = await executor.exec(data, async (input) => {
1334
+ * return await fetchUserData(input.userId);
1335
+ * });
1336
+ * ```
1337
+ *
567
1338
  * @category AsyncExecutor
568
1339
  */
569
- declare class AsyncExecutor<ExecutorConfig = unknown> extends Executor<ExecutorConfig> {
1340
+ declare class AsyncExecutor<ExecutorConfig extends ExecutorConfigInterface = ExecutorConfigInterface> extends Executor<ExecutorConfig> {
1341
+ protected contextHandler: ContextHandler;
570
1342
  /**
571
- * Execute plugin hook functions asynchronously
1343
+ * Execute a single plugin hook function asynchronously
572
1344
  *
573
- * - Purpose: Orchestrates asynchronous plugin hook execution
574
- * - Core Concept: Sequential async plugin pipeline
575
- * - Main Features:
576
- * - Plugin enablement checking
577
- * - Result chaining
578
- * - Error hook special handling
579
- * - Primary Use: Internal plugin lifecycle management
1345
+ * Core concept:
1346
+ * Sequential async plugin execution with chain breaking and return value handling
580
1347
  *
581
- * Plugin execution flow:
1348
+ * Execution flow:
582
1349
  * 1. Check if plugin is enabled for the hook
583
1350
  * 2. Execute plugin hook if available
584
1351
  * 3. Handle plugin results and chain breaking conditions
1352
+ * 4. Continue to next plugin or break chain
1353
+ *
1354
+ * Key features:
1355
+ * - Plugin enablement checking
1356
+ * - Chain breaking support
1357
+ * - Return value management
1358
+ * - Runtime tracking
1359
+ * - Async execution with await
585
1360
  *
586
1361
  * @param plugins - Array of plugins to execute
587
1362
  * @param hookName - Name of the hook function to execute
588
- * @param args - Arguments to pass to the hook function
589
- * @returns Promise resolving to the hook execution result
1363
+ * @param context - Execution context containing data and runtime information
1364
+ * @param args - Additional arguments to pass to the hook function
1365
+ * @returns Promise resolving to the result of the hook function execution
1366
+ * @since 2.1.0
590
1367
  *
591
- * @example
1368
+ * @example Internal usage
592
1369
  * ```typescript
593
1370
  * const result = await this.runHook(
594
1371
  * this.plugins,
595
- * 'beforeExec',
596
- * { userId: 123 }
1372
+ * 'onBefore',
1373
+ * context,
1374
+ * data
597
1375
  * );
598
1376
  * ```
599
1377
  */
600
- runHooks<Params>(plugins: ExecutorPlugin[],
1378
+ protected runHook<Params>(plugins: ExecutorPlugin[],
601
1379
  /**
602
- * allow any string as hook name.
603
- * if the hook name is not a function, it will be skipped
1380
+ * Hook name to execute
1381
+ *
1382
+ * Allows any string as hook name. If the hook name is not a function,
1383
+ * the plugin will be skipped for this hook execution.
604
1384
  *
605
1385
  * @since 1.1.3
606
1386
  */
607
- hookName: string, context?: ExecutorContext<Params>, ...args: unknown[]): Promise<unknown>;
1387
+ hookName: HookType, context?: ExecutorContext<Params>, ...args: unknown[]): Promise<Params>;
1388
+ /**
1389
+ * Execute multiple plugin hook functions asynchronously
1390
+ * Supports executing multiple hook names in sequence
1391
+ *
1392
+ * Core concept:
1393
+ * Sequential execution of multiple hooks with chain breaking support
1394
+ *
1395
+ * Execution flow:
1396
+ * 1. For each hook name, check if plugin is enabled
1397
+ * 2. Execute plugin hook if available
1398
+ * 3. Handle plugin results and chain breaking conditions
1399
+ * 4. Continue to next hook name if chain is not broken
1400
+ *
1401
+ * Key features:
1402
+ * - Supports multiple hook names in sequence
1403
+ * - Chain breaking support for each hook
1404
+ * - Return value management across hooks
1405
+ * - Backward compatibility with single hook execution
1406
+ * - Async execution with await
1407
+ *
1408
+ * @param plugins - Array of plugins to execute
1409
+ * @param hookNames - Single hook name or array of hook names to execute in sequence
1410
+ * @param context - Execution context containing data and runtime information
1411
+ * @param args - Additional arguments to pass to the hook functions
1412
+ * @returns Promise resolving to the result of the last executed hook function
1413
+ *
1414
+ * @example Execute multiple hooks in sequence
1415
+ * ```typescript
1416
+ * const result = await this.runHooks(
1417
+ * this.plugins,
1418
+ * ['onBefore', 'onValidate', 'onProcess'],
1419
+ * context,
1420
+ * data
1421
+ * );
1422
+ * ```
1423
+ *
1424
+ * @example Execute single hook (backward compatibility)
1425
+ * ```typescript
1426
+ * const result = await this.runHooks(
1427
+ * this.plugins,
1428
+ * 'onBefore',
1429
+ * context,
1430
+ * data
1431
+ * );
1432
+ * ```
1433
+ */
1434
+ runHooks<Params>(plugins: ExecutorPlugin[], hookNames: HookType | HookType[], context?: ExecutorContext<Params>, ...args: unknown[]): Promise<Params>;
608
1435
  /**
609
1436
  * Execute task without throwing errors
610
1437
  *
611
- * - Purpose: Safe execution of async tasks
612
- * - Core Concept: Error wrapping and handling
613
- * - Main Features:
614
- * - Catches all execution errors
615
- * - Wraps errors in ExecutorError
616
- * - Returns either result or error object
617
- * - Primary Use: When you want to handle errors without try-catch
1438
+ * Core concept:
1439
+ * Error-safe execution pipeline that returns errors instead of throwing
618
1440
  *
619
- * @template T - Type of task return value
1441
+ * Advantages over try-catch:
1442
+ * - Standardized error handling
1443
+ * - No exception propagation
1444
+ * - Consistent error types
1445
+ * - Plugin error handling support
1446
+ *
1447
+ * @template Result - Type of task return value
1448
+ * @template Params - Type of task input parameters
620
1449
  * @param dataOrTask - Task data or task function
621
- * @param task - Task function (optional)
622
- * @returns Promise resolving to either result or ExecutorError
1450
+ * @param task - Task function (optional when dataOrTask is a function)
1451
+ * @returns Promise resolving to task result or ExecutorError if execution fails
623
1452
  *
624
- * @example
1453
+ * @throws Never throws - all errors are wrapped in ExecutorError
1454
+ *
1455
+ * @example Basic usage
625
1456
  * ```typescript
626
1457
  * const result = await executor.execNoError(async () => {
627
1458
  * const response = await riskyOperation();
@@ -632,190 +1463,305 @@ declare class AsyncExecutor<ExecutorConfig = unknown> extends Executor<ExecutorC
632
1463
  * console.error('Operation failed:', result);
633
1464
  * }
634
1465
  * ```
1466
+ *
1467
+ * @example With input data
1468
+ * ```typescript
1469
+ * const result = await executor.execNoError(
1470
+ * { userId: 123 },
1471
+ * async (data) => await fetchUserData(data.userId)
1472
+ * );
1473
+ * ```
635
1474
  */
636
- execNoError<Result, Params = unknown>(dataOrTask: unknown | PromiseTask<Result, Params>, task?: PromiseTask<Result, Params>): Promise<Result | ExecutorError>;
1475
+ execNoError<Result, Params = unknown>(dataOrTask: Params | PromiseTask<Result, Params>, task?: PromiseTask<Result, Params>): Promise<Result | ExecutorError>;
637
1476
  /**
638
1477
  * Execute asynchronous task with full plugin pipeline
639
1478
  *
640
- * - Purpose: Primary method for executing async tasks
641
- * - Core Concept: Full plugin pipeline execution
642
- * - Main Features:
643
- * - Plugin hook integration
644
- * - Task validation
645
- * - Custom execution support
646
- * - Primary Use: Running async tasks with plugin support
1479
+ * Core concept:
1480
+ * Complete execution pipeline with plugin lifecycle management
647
1481
  *
648
1482
  * Execution flow:
649
1483
  * 1. Validate and prepare task
650
- * 2. Check for custom execution plugins
651
- * 3. Execute task with plugin pipeline
1484
+ * 2. Execute beforeHooks (configured or default 'onBefore')
1485
+ * 3. Execute core task logic with execHook support
1486
+ * 4. Execute afterHooks (configured or default 'onSuccess')
1487
+ * 5. Handle errors with onError hooks if needed
652
1488
  *
653
- * @template T - Type of task return value
654
- * @template D - Type of task data
1489
+ * Performance considerations:
1490
+ * - Async overhead for Promise handling
1491
+ * - Sequential execution path
1492
+ * - Plugin chain optimization
1493
+ *
1494
+ * @template Result - Type of task return value
1495
+ * @template Params - Type of task input parameters
655
1496
  * @param dataOrTask - Task data or task function
656
- * @param task - Task function (optional)
1497
+ * @param task - Task function (optional when dataOrTask is a function)
657
1498
  * @throws {Error} When task is not an async function
658
- * @returns Promise resolving to task result
1499
+ * @throws {ExecutorError} When task execution fails
1500
+ * @returns Promise resolving to task execution result
659
1501
  *
660
- * @example
1502
+ * @example Basic task execution
1503
+ * ```typescript
1504
+ * const result = await executor.exec(async (data) => {
1505
+ * const response = await fetch('https://api.example.com/data');
1506
+ * return response.json();
1507
+ * });
1508
+ * ```
1509
+ *
1510
+ * @example With input data
661
1511
  * ```typescript
662
- * // With separate data and task
663
1512
  * const data = { userId: 123 };
664
1513
  * const result = await executor.exec(data, async (input) => {
665
1514
  * return await fetchUserData(input.userId);
666
1515
  * });
1516
+ * ```
667
1517
  *
668
- * // With combined task
669
- * const result = await executor.exec(async () => {
670
- * return await fetchData();
1518
+ * @example With validation
1519
+ * ```typescript
1520
+ * const result = await executor.exec(async (data) => {
1521
+ * if (typeof data !== 'string') {
1522
+ * throw new Error('Data must be string');
1523
+ * }
1524
+ * return await processData(data);
671
1525
  * });
672
1526
  * ```
673
1527
  */
674
1528
  exec<Result, Params = unknown>(dataOrTask: Params | PromiseTask<Result, Params>, task?: PromiseTask<Result, Params>): Promise<Result>;
1529
+ /**
1530
+ * Execute core task logic with execHook support
1531
+ *
1532
+ * Core concept:
1533
+ * Handles the execution phase with optional plugin intervention
1534
+ *
1535
+ * Execution logic:
1536
+ * 1. Execute configured execHook (default: 'onExec')
1537
+ * 2. If no execHook was executed, run the actual task
1538
+ * 3. Otherwise, use the return value from execHook
1539
+ *
1540
+ * @template Result - Type of task return value
1541
+ * @template Params - Type of task input parameters
1542
+ * @param context - Execution context
1543
+ * @param actualTask - Task function to execute
1544
+ */
1545
+ protected runExec<Result, Params = unknown>(context: ExecutorContext<Params>, actualTask: PromiseTask<Result, Params>): Promise<void>;
675
1546
  /**
676
1547
  * Core task execution method with plugin hooks
677
1548
  *
678
- * - Purpose: Implements the complete execution pipeline
679
- * - Core Concept: Sequential hook execution with error handling
680
- * - Main Features:
681
- * - Before/After hooks
682
- * - Error handling hooks
683
- * - Result transformation
684
- * - Primary Use: Internal pipeline orchestration
1549
+ * Core concept:
1550
+ * Complete execution pipeline with configurable hook lifecycle
685
1551
  *
686
1552
  * Pipeline stages:
687
- * 1. onBefore hooks - Pre-process input data
688
- * 2. Task execution - Run the actual task
689
- * 3. onSuccess hooks - Post-process results
1553
+ * 1. beforeHooks - Pre-process input data (configurable, default: 'onBefore')
1554
+ * 2. Task execution - Run the actual task with execHook support
1555
+ * 3. afterHooks - Post-process results (configurable, default: 'onSuccess')
690
1556
  * 4. onError hooks - Handle any errors
691
1557
  *
692
- * @template T - Type of task return value
693
- * @template D - Type of task data
694
- * @param data - Input data for the task
695
- * @param actualTask - Task function to execute
1558
+ * Error handling strategy:
1559
+ * - Catches all errors
1560
+ * - Passes errors through plugin chain
1561
+ * - Wraps unhandled errors in ExecutorError
1562
+ * - Supports plugin error handling
1563
+ *
1564
+ * @template Result - Type of task return value
1565
+ * @template Params - Type of task input parameters
1566
+ * @param data - Data to pass to the task
1567
+ * @param actualTask - Actual task function to execute
696
1568
  * @throws {ExecutorError} When task execution fails
697
- * @returns Promise resolving to task result(context.returnValue)
1569
+ * @returns Promise resolving to task execution result
698
1570
  *
699
- * @example
1571
+ * @example Internal implementation
700
1572
  * ```typescript
701
- * private async run(data, task) {
1573
+ * protected async run(data, task) {
702
1574
  * try {
703
- * const preparedData = await this.runHook(this.plugins, 'onBefore', data);
704
- * const result = await task(preparedData);
705
- * return await this.runHook(this.plugins, 'onSuccess', result);
1575
+ * // Execute beforeHooks (configurable)
1576
+ * await this.runHooks(this.plugins, beforeHooks, context);
1577
+ *
1578
+ * // Execute core logic with execHook support
1579
+ * await this.runExec(context, actualTask);
1580
+ *
1581
+ * // Execute afterHooks (configurable)
1582
+ * await this.runHooks(this.plugins, afterHooks, context);
1583
+ *
1584
+ * return context.returnValue;
706
1585
  * } catch (error) {
707
- * const handledError = await this.runHook(
708
- * this.plugins,
709
- * 'onError',
710
- * error,
711
- * data
712
- * );
713
- * throw new ExecutorError('EXECUTION_FAILED', handledError);
1586
+ * // Handle errors with onError hooks
1587
+ * await this.runHook(this.plugins, 'onError', context);
714
1588
  * }
715
1589
  * }
716
1590
  * ```
717
1591
  */
718
- run<Result, Params = unknown>(data: Params, actualTask: PromiseTask<Result, Params>): Promise<Result>;
1592
+ protected run<Result, Params = unknown>(data: Params, actualTask: PromiseTask<Result, Params>): Promise<Result>;
719
1593
  }
720
1594
 
721
1595
  /**
722
1596
  * Synchronous executor class that extends the base Executor
723
1597
  * Provides synchronous task execution with plugin support
724
1598
  *
725
- * Key features:
726
- * 1. Synchronous plugin hook execution
727
- * 2. No Promise-based operations
728
- * 3. Immediate error handling
729
- * 4. Direct execution flow
1599
+ * Core concept:
1600
+ * Synchronous execution pipeline with plugin lifecycle management
1601
+ *
1602
+ * Main features:
1603
+ * - Synchronous plugin hook execution: All operations are immediate without Promise overhead
1604
+ * - Plugin lifecycle management: Support for onBefore, onExec, onSuccess, onError hooks
1605
+ * - Configurable hook execution: Customizable beforeHooks, afterHooks, and execHook
1606
+ * - Chain breaking support: Plugins can interrupt execution chain
1607
+ * - Error handling: Comprehensive error handling with plugin support
730
1608
  *
731
1609
  * Use this executor when:
732
- * 1. All operations are synchronous
733
- * 2. You need immediate results
734
- * 3. Performance is critical
735
- * 4. No async operations are involved
1610
+ * - All operations are synchronous
1611
+ * - You need immediate results
1612
+ * - Performance is critical
1613
+ * - No async operations are involved
736
1614
  *
737
1615
  * @extends Executor
738
1616
  *
739
- * @example
1617
+ * @example Basic usage
740
1618
  * ```typescript
741
- * // Create a sync executor
742
1619
  * const executor = new SyncExecutor();
743
- *
744
- * // Add plugins for different purposes
745
1620
  * executor.use(new ValidationPlugin());
746
1621
  * executor.use(new LoggerPlugin());
747
1622
  *
748
- * // Example 1: Basic sync task execution
749
1623
  * const result = executor.exec((data) => {
750
1624
  * return data.toUpperCase();
751
1625
  * });
1626
+ * ```
1627
+ *
1628
+ * @example With custom configuration
1629
+ * ```typescript
1630
+ * const executor = new SyncExecutor({
1631
+ * beforeHooks: ['onBefore', 'onValidate'],
1632
+ * afterHooks: ['onSuccess', 'onLog'],
1633
+ * execHook: 'onCustomExec'
1634
+ * });
752
1635
  *
753
- * // Example 2: Execution with input data
754
- * const data = { value: 'hello' };
755
1636
  * const result = executor.exec(data, (input) => {
756
1637
  * return input.value.toUpperCase();
757
1638
  * });
1639
+ * ```
758
1640
  *
759
- * // Example 3: Error handling with execNoError
1641
+ * @example Error handling
1642
+ * ```typescript
760
1643
  * const result = executor.execNoError(() => {
761
1644
  * throw new Error('Validation Error');
762
1645
  * }); // Returns ExecutorError instead of throwing
763
1646
  * ```
1647
+ *
764
1648
  * @category SyncExecutor
765
1649
  */
766
- declare class SyncExecutor<ExecutorConfig = unknown> extends Executor<ExecutorConfig> {
1650
+ declare class SyncExecutor<ExecutorConfig extends ExecutorConfigInterface = ExecutorConfigInterface> extends Executor<ExecutorConfig> {
1651
+ protected contextHandler: ContextHandler;
767
1652
  /**
768
- * Execute plugin hook functions synchronously
769
- * Manages the plugin execution chain and handles results
1653
+ * Execute a single plugin hook function synchronously
1654
+ *
1655
+ * Core concept:
1656
+ * Sequential plugin execution with chain breaking and return value handling
770
1657
  *
771
- * Plugin execution flow:
1658
+ * Execution flow:
772
1659
  * 1. Check if plugin is enabled for the hook
773
1660
  * 2. Execute plugin hook if available
774
1661
  * 3. Handle plugin results and chain breaking conditions
1662
+ * 4. Continue to next plugin or break chain
775
1663
  *
776
- * Key differences from AsyncExecutor:
777
- * - All operations are synchronous
778
- * - Results are immediately available
779
- * - No await statements needed
1664
+ * Key features:
1665
+ * - Plugin enablement checking
1666
+ * - Chain breaking support
1667
+ * - Return value management
1668
+ * - Runtime tracking
780
1669
  *
781
1670
  * @param plugins - Array of plugins to execute
782
1671
  * @param hookName - Name of the hook function to execute
783
- * @param args - Arguments to pass to the hook function
1672
+ * @param context - Execution context containing data and runtime information
1673
+ * @param args - Additional arguments to pass to the hook function
784
1674
  * @returns Result of the hook function execution
1675
+ * @since 2.1.0
785
1676
  *
786
- * @example
1677
+ * @example Internal usage
787
1678
  * ```typescript
788
- * // Internal usage example
789
1679
  * const result = this.runHook(
790
1680
  * this.plugins,
791
1681
  * 'onBefore',
792
- * { value: 'test' }
1682
+ * context,
1683
+ * data
793
1684
  * );
794
1685
  * ```
795
1686
  */
796
- runHooks<Params>(plugins: ExecutorPlugin[],
1687
+ protected runHook<Params>(plugins: ExecutorPlugin[],
797
1688
  /**
798
- * allow any string as hook name.
799
- * if the hook name is not a function, it will be skipped
1689
+ * Hook name to execute
1690
+ *
1691
+ * Allows any string as hook name. If the hook name is not a function,
1692
+ * the plugin will be skipped for this hook execution.
800
1693
  *
801
1694
  * @since 1.1.3
802
1695
  */
803
- hookName: string, context?: ExecutorContext<Params>, ...args: unknown[]): Params;
1696
+ hookName: HookType, context?: ExecutorContext<Params>, ...args: unknown[]): Params;
1697
+ /**
1698
+ * Execute multiple plugin hook functions synchronously
1699
+ * Supports executing multiple hook names in sequence
1700
+ *
1701
+ * Core concept:
1702
+ * Sequential execution of multiple hooks with chain breaking support
1703
+ *
1704
+ * Execution flow:
1705
+ * 1. For each hook name, check if plugin is enabled
1706
+ * 2. Execute plugin hook if available
1707
+ * 3. Handle plugin results and chain breaking conditions
1708
+ * 4. Continue to next hook name if chain is not broken
1709
+ *
1710
+ * Key features:
1711
+ * - Supports multiple hook names in sequence
1712
+ * - Chain breaking support for each hook
1713
+ * - Return value management across hooks
1714
+ * - Backward compatibility with single hook execution
1715
+ *
1716
+ * @param plugins - Array of plugins to execute
1717
+ * @param hookNames - Single hook name or array of hook names to execute in sequence
1718
+ * @param context - Execution context containing data and runtime information
1719
+ * @param args - Additional arguments to pass to the hook functions
1720
+ * @returns Result of the last executed hook function
1721
+ *
1722
+ * @example Execute multiple hooks in sequence
1723
+ * ```typescript
1724
+ * const result = this.runHooks(
1725
+ * this.plugins,
1726
+ * ['onBefore', 'onValidate', 'onProcess'],
1727
+ * context,
1728
+ * data
1729
+ * );
1730
+ * ```
1731
+ *
1732
+ * @example Execute single hook (backward compatibility)
1733
+ * ```typescript
1734
+ * const result = this.runHooks(
1735
+ * this.plugins,
1736
+ * 'onBefore',
1737
+ * context,
1738
+ * data
1739
+ * );
1740
+ * ```
1741
+ */
1742
+ runHooks<Params>(plugins: ExecutorPlugin[], hookNames: HookType | HookType[], context?: ExecutorContext<Params>, ...args: unknown[]): Params;
804
1743
  /**
805
1744
  * Execute task without throwing errors
806
1745
  * Wraps all errors in ExecutorError for safe error handling
807
1746
  *
1747
+ * Core concept:
1748
+ * Error-safe execution pipeline that returns errors instead of throwing
1749
+ *
808
1750
  * Advantages over try-catch:
809
- * 1. Standardized error handling
810
- * 2. No exception propagation
811
- * 3. Consistent error types
1751
+ * - Standardized error handling
1752
+ * - No exception propagation
1753
+ * - Consistent error types
1754
+ * - Plugin error handling support
812
1755
  *
813
- * @template T - Type of task return value
1756
+ * @template Result - Type of task return value
1757
+ * @template Params - Type of task input parameters
814
1758
  * @param dataOrTask - Task data or task function
815
- * @param task - Task function (optional)
816
- * @returns Task result or ExecutorError
1759
+ * @param task - Task function (optional when dataOrTask is a function)
1760
+ * @returns Task result or ExecutorError if execution fails
817
1761
  *
818
- * @example
1762
+ * @throws Never throws - all errors are wrapped in ExecutorError
1763
+ *
1764
+ * @example Basic usage
819
1765
  * ```typescript
820
1766
  * const result = executor.execNoError((data) => {
821
1767
  * if (!data.isValid) {
@@ -830,40 +1776,63 @@ declare class SyncExecutor<ExecutorConfig = unknown> extends Executor<ExecutorCo
830
1776
  * console.log('Task succeeded:', result);
831
1777
  * }
832
1778
  * ```
1779
+ *
1780
+ * @example With input data
1781
+ * ```typescript
1782
+ * const result = executor.execNoError(
1783
+ * { value: 'test' },
1784
+ * (data) => data.value.toUpperCase()
1785
+ * );
1786
+ * ```
833
1787
  */
834
1788
  execNoError<Result, Params = unknown>(dataOrTask: Params | SyncTask<Result, Params>, task?: SyncTask<Result, Params>): Result | ExecutorError;
835
1789
  /**
836
1790
  * Execute synchronous task with full plugin pipeline
837
1791
  * Core method for task execution with plugin support
838
1792
  *
1793
+ * Core concept:
1794
+ * Complete execution pipeline with plugin lifecycle management
1795
+ *
839
1796
  * Execution flow:
840
1797
  * 1. Validate and prepare task
841
- * 2. Check for custom execution plugins
842
- * 3. Execute task with plugin pipeline
1798
+ * 2. Execute beforeHooks (configured or default 'onBefore')
1799
+ * 3. Execute core task logic with execHook support
1800
+ * 4. Execute afterHooks (configured or default 'onSuccess')
1801
+ * 5. Handle errors with onError hooks if needed
843
1802
  *
844
1803
  * Performance considerations:
845
1804
  * - No async overhead
846
1805
  * - Direct execution path
847
1806
  * - Immediate results
1807
+ * - Plugin chain optimization
848
1808
  *
849
- * @template T - Type of task return value
850
- * @template D - Type of task data
1809
+ * @template Result - Type of task return value
1810
+ * @template Params - Type of task input parameters
851
1811
  * @param dataOrTask - Task data or task function
852
- * @param task - Task function (optional)
1812
+ * @param task - Task function (optional when dataOrTask is a function)
853
1813
  * @throws {Error} When task is not a function
1814
+ * @throws {ExecutorError} When task execution fails
854
1815
  * @returns Task execution result
855
1816
  *
856
- * @example
1817
+ * @example Basic task execution
1818
+ * ```typescript
1819
+ * const result = executor.exec((data) => {
1820
+ * return data.toUpperCase();
1821
+ * });
1822
+ * ```
1823
+ *
1824
+ * @example With input data
857
1825
  * ```typescript
858
- * // Example with data transformation
859
1826
  * const data = { numbers: [1, 2, 3] };
860
1827
  * const task = (input) => {
861
1828
  * return input.numbers.map(n => n * 2);
862
1829
  * };
863
1830
  *
864
1831
  * const result = executor.exec(data, task);
1832
+ * ```
865
1833
  *
866
- * // Example with validation
1834
+ * @example With validation
1835
+ * ```typescript
867
1836
  * const result = executor.exec((data) => {
868
1837
  * if (typeof data !== 'string') {
869
1838
  * throw new Error('Data must be string');
@@ -873,49 +1842,71 @@ declare class SyncExecutor<ExecutorConfig = unknown> extends Executor<ExecutorCo
873
1842
  * ```
874
1843
  */
875
1844
  exec<Result, Params = unknown>(dataOrTask: Params | SyncTask<Result, Params>, task?: SyncTask<Result, Params>): Result;
1845
+ /**
1846
+ * Execute core task logic with execHook support
1847
+ *
1848
+ * Core concept:
1849
+ * Handles the execution phase with optional plugin intervention
1850
+ *
1851
+ * Execution logic:
1852
+ * 1. Execute configured execHook (default: 'onExec')
1853
+ * 2. If no execHook was executed, run the actual task
1854
+ * 3. Otherwise, use the return value from execHook
1855
+ *
1856
+ * @template Result - Type of task return value
1857
+ * @template Params - Type of task input parameters
1858
+ * @param context - Execution context
1859
+ * @param actualTask - Task function to execute
1860
+ */
1861
+ protected runExec<Result, Params = unknown>(context: ExecutorContext<Params>, actualTask: SyncTask<Result, Params>): void;
876
1862
  /**
877
1863
  * Core method to run synchronous task with plugin hooks
878
1864
  * Implements the complete execution pipeline with all plugin hooks
879
1865
  *
1866
+ * Core concept:
1867
+ * Complete execution pipeline with configurable hook lifecycle
1868
+ *
880
1869
  * Pipeline stages:
881
- * 1. onBefore hooks - Pre-process input data
882
- * 2. Task execution - Run the actual task
883
- * 3. onSuccess hooks - Post-process results
1870
+ * 1. beforeHooks - Pre-process input data (configurable, default: 'onBefore')
1871
+ * 2. Task execution - Run the actual task with execHook support
1872
+ * 3. afterHooks - Post-process results (configurable, default: 'onSuccess')
884
1873
  * 4. onError hooks - Handle any errors
885
1874
  *
886
1875
  * Error handling strategy:
887
1876
  * - Catches all errors
888
1877
  * - Passes errors through plugin chain
889
1878
  * - Wraps unhandled errors in ExecutorError
1879
+ * - Supports plugin error handling
890
1880
  *
891
- * @template T - Type of task return value
892
- * @template D - Type of task data
1881
+ * @template Result - Type of task return value
1882
+ * @template Params - Type of task input parameters
893
1883
  * @param data - Data to pass to the task
894
1884
  * @param actualTask - Actual task function to execute
895
1885
  * @throws {ExecutorError} When task execution fails
896
1886
  * @returns Task execution result
897
1887
  *
898
- * @example
1888
+ * @example Internal implementation
899
1889
  * ```typescript
900
- * // Internal implementation example
901
- * private run(data, task) {
1890
+ * protected run(data, task) {
902
1891
  * try {
903
- * const preparedData = this.runHook(this.plugins, 'onBefore', data);
904
- * const result = task(preparedData);
905
- * return this.runHook(this.plugins, 'onSuccess', result);
1892
+ * // Execute beforeHooks (configurable)
1893
+ * this.runHooks(this.plugins, beforeHooks, context);
1894
+ *
1895
+ * // Execute core logic with execHook support
1896
+ * this.runExec(context, actualTask);
1897
+ *
1898
+ * // Execute afterHooks (configurable)
1899
+ * this.runHooks(this.plugins, afterHooks, context);
1900
+ *
1901
+ * return context.returnValue;
906
1902
  * } catch (error) {
907
- * const handledError = this.runHook(
908
- * this.plugins,
909
- * 'onError',
910
- * error,
911
- * data
912
- * );
913
- * // Error handling logic
1903
+ * // Handle errors with onError hooks
1904
+ * this.runHook(this.plugins, 'onError', context);
914
1905
  * }
915
1906
  * }
916
1907
  * ```
917
1908
  */
918
- run<Result, Params = unknown>(data: Params, actualTask: SyncTask<Result, Params>): Result;
1909
+ protected run<Result, Params = unknown>(data: Params, actualTask: SyncTask<Result, Params>): Result;
919
1910
  }
920
1911
 
921
1912
  /**
@@ -2956,4 +3947,4 @@ type Intersection<T1, T2> = {
2956
3947
  [P in keyof T1 & keyof T2]: T1[P] | T2[P];
2957
3948
  };
2958
3949
 
2959
- export { AsyncExecutor, type AsyncStorageInterface, Base64Serializer, type Encryptor, Executor, type ExecutorContext, ExecutorError, type ExecutorPlugin, type ExpireOptions, FetchAbortPlugin, FetchURLPlugin, type HookRuntimes, type Intersection, JSONSerializer, type JSONSerializerOptions, KeyStorage, KeyStorageInterface, type KeyStorageOptions, ObjectStorage, type ObjectStorageOptions, type PipeArg, type PromiseTask, RequestAdapterAxios, type RequestAdapterConfig, RequestAdapterFetch, type RequestAdapterFetchConfig, type RequestAdapterInterface, type RequestAdapterResponse, RequestError, RequestErrorID, RequestManager, RequestScheduler, RequestTransaction, type RequestTransactionInterface, type RetryOptions, RetryPlugin, type SerializerIneterface, type StorageValue, SyncExecutor, SyncStorage, type SyncStorageInterface, type SyncTask, type Task, type ValueOf };
3950
+ export { AsyncExecutor, type AsyncStorageInterface, Base64Serializer, type Encryptor, Executor, type ExecutorConfigInterface, type ExecutorContext, ExecutorError, type ExecutorPlugin, type ExpireOptions, FetchAbortPlugin, FetchURLPlugin, type HookRuntimes, type HookType, type Intersection, JSONSerializer, type JSONSerializerOptions, KeyStorage, KeyStorageInterface, type KeyStorageOptions, ObjectStorage, type ObjectStorageOptions, type PipeArg, type PromiseTask, RequestAdapterAxios, type RequestAdapterConfig, RequestAdapterFetch, type RequestAdapterFetchConfig, type RequestAdapterInterface, type RequestAdapterResponse, RequestError, RequestErrorID, RequestManager, RequestScheduler, RequestTransaction, type RequestTransactionInterface, type RetryOptions, RetryPlugin, type SerializerIneterface, type StorageValue, SyncExecutor, SyncStorage, type SyncStorageInterface, type SyncTask, type Task, type ValueOf };