@context-action/core 0.0.3 → 0.0.4

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.cts CHANGED
@@ -1,244 +1,670 @@
1
- //#region src/logger.d.ts
2
- /**
3
- * Log levels in order of severity (lowest to highest)
4
- */
5
- declare enum LogLevel {
6
- TRACE = 0,
7
- DEBUG = 1,
8
- INFO = 2,
9
- WARN = 3,
10
- ERROR = 4,
11
- FATAL = 5,
12
- }
13
- /**
14
- * Logger interface for custom logger implementations
15
- */
16
- interface Logger {
17
- trace(message: string, ...args: any[]): void;
18
- debug(message: string, ...args: any[]): void;
19
- info(message: string, ...args: any[]): void;
20
- warn(message: string, ...args: any[]): void;
21
- error(message: string, ...args: any[]): void;
22
- fatal(message: string, ...args: any[]): void;
23
- }
24
- /**
25
- * Default console logger implementation
26
- */
27
- declare class ConsoleLogger implements Logger {
28
- private level;
29
- constructor(level?: LogLevel);
30
- protected shouldLog(level: LogLevel): boolean;
31
- private formatMessage;
32
- trace(message: string, ...args: any[]): void;
33
- debug(message: string, ...args: any[]): void;
34
- info(message: string, ...args: any[]): void;
35
- warn(message: string, ...args: any[]): void;
36
- error(message: string, ...args: any[]): void;
37
- fatal(message: string, ...args: any[]): void;
38
- setLevel(level: LogLevel): void;
39
- }
40
- /**
41
- * Parse log level from string
42
- */
43
- declare function parseLogLevel(level: string): LogLevel;
44
- /**
45
- * Get log level from environment variable or default to ERROR
46
- */
47
- declare function getLogLevelFromEnv(): LogLevel;
48
- /**
49
- * Extract trace ID from payload if it exists
50
- */
51
- declare function extractTraceIdFromPayload(payload: any): string | undefined;
52
- /**
53
- * Extract session ID from payload if it exists
54
- */
55
- declare function extractSessionIdFromPayload(payload: any): string | undefined;
56
- /**
57
- * Create OTEL context from payload
58
- */
59
- declare function createOtelContextFromPayload(payload: any): OtelContext;
1
+ import { LogLevel, Logger } from "@context-action/logger";
2
+
3
+ //#region src/types.d.ts
4
+
60
5
  /**
61
- * OpenTelemetry context interface for tracing
6
+ * Base interface for defining action payload mappings
7
+ * @implements action-payload-map
8
+ * @implements type-safety
9
+ * @implements compile-time-validation
10
+ * @memberof core-concepts
11
+ * @since 1.0.0
12
+ *
13
+ * Maps action names to their corresponding payload types for type-safe dispatch
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * interface MyActions extends ActionPayloadMap {
18
+ * increment: void;
19
+ * setCount: number;
20
+ * updateUser: { id: string; name: string };
21
+ * deleteUser: { id: string };
22
+ * }
23
+ * ```
62
24
  */
63
- interface OtelContext {
64
- /** Session ID for tracking user sessions */
65
- sessionId?: string;
66
- /** Trace ID for distributed tracing */
67
- traceId?: string;
68
- /** Span ID for current operation */
69
- spanId?: string;
70
- /** Parent span ID for operation hierarchy */
71
- parentSpanId?: string;
72
- /** Additional context metadata */
73
- metadata?: Record<string, any>;
74
- }
75
- /**
76
- * Extended logger interface with OpenTelemetry support
77
- */
78
- interface OtelLogger extends Logger {
79
- /** Set OpenTelemetry context */
80
- setContext(context: OtelContext): void;
81
- /** Get current OpenTelemetry context */
82
- getContext(): OtelContext;
83
- /** Clear OpenTelemetry context */
84
- clearContext(): void;
85
- /** Log with OpenTelemetry context */
86
- logWithContext(level: LogLevel, message: string, ...args: any[]): void;
25
+ interface ActionPayloadMap {
26
+ [actionName: string]: unknown;
87
27
  }
88
- /**
89
- * OpenTelemetry-aware console logger implementation
90
- */
91
- declare class OtelConsoleLogger extends ConsoleLogger implements OtelLogger {
92
- private context;
93
- constructor(level?: LogLevel);
94
- setContext(context: OtelContext): void;
95
- getContext(): OtelContext;
96
- clearContext(): void;
97
- private formatWithContext;
98
- logWithContext(level: LogLevel, message: string, ...args: any[]): void;
99
- trace(message: string, ...args: any[]): void;
100
- debug(message: string, ...args: any[]): void;
101
- info(message: string, ...args: any[]): void;
102
- warn(message: string, ...args: any[]): void;
103
- error(message: string, ...args: any[]): void;
104
- fatal(message: string, ...args: any[]): void;
105
- }
106
- //# sourceMappingURL=logger.d.ts.map
107
- //#endregion
108
- //#region src/ActionRegister.d.ts
109
28
  /**
110
29
  * Controller object provided to action handlers for pipeline management
30
+ * @implements pipeline-controller
31
+ * @memberof core-concepts
32
+ * @since 1.0.0
33
+ *
34
+ * Provides methods for controlling pipeline flow and payload modification
35
+ *
111
36
  * @template T - The type of the payload being processed
112
37
  */
113
- type PipelineController<T = any> = {
38
+ interface PipelineController<T = any> {
114
39
  /** Continue to the next handler in the pipeline */
115
- next: () => void;
40
+ next(): void;
116
41
  /** Abort the pipeline execution with an optional reason */
117
- abort: (reason?: string) => void;
42
+ abort(reason?: string): void;
118
43
  /** Modify the payload that will be passed to subsequent handlers */
119
- modifyPayload: (modifier: (payload: T) => T) => void;
120
- };
44
+ modifyPayload(modifier: (payload: T) => T): void;
45
+ /** Get the current payload */
46
+ getPayload(): T;
47
+ /** Jump to a specific priority level in the pipeline */
48
+ jumpToPriority(priority: number): void;
49
+ }
121
50
  /**
122
- * Action handler function that processes actions in the pipeline
123
- * @template T - The type of the payload
124
- * @param payload - The data passed to the handler
51
+ * Action handler function type for processing actions in the pipeline
52
+ * @implements action-handler
53
+ * @memberof core-concepts
54
+ * @since 1.0.0
55
+ *
56
+ * Function signature for handlers that process specific actions within the pipeline.
57
+ * Handlers receive the action payload and a controller for managing pipeline flow.
58
+ *
59
+ * @template T - The type of the payload this handler processes
60
+ * @param payload - The action payload data
125
61
  * @param controller - Pipeline controller for flow management
126
- * @returns void or Promise<void> for async handlers
62
+ * @returns void or Promise<void> for async operations
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * const userUpdateHandler: ActionHandler<{id: string, name: string}> =
67
+ * async (payload, controller) => {
68
+ * // Validate payload
69
+ * if (!payload.id) {
70
+ * controller.abort('User ID is required');
71
+ * return;
72
+ * }
73
+ *
74
+ * // Update user store
75
+ * const user = userStore.getValue();
76
+ * userStore.setValue({ ...user, ...payload });
77
+ * };
78
+ * ```
127
79
  */
128
80
  type ActionHandler<T = any> = (payload: T, controller: PipelineController<T>) => void | Promise<void>;
129
81
  /**
130
82
  * Configuration options for action handlers
83
+ * @implements handler-configuration
84
+ * @memberof core-concepts
85
+ * @since 1.0.0
86
+ *
87
+ * Defines behavior and execution characteristics for action handlers in the pipeline.
88
+ * Supports priority-based execution, conditional execution, and performance optimizations.
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * const config: HandlerConfig = {
93
+ * priority: 10, // Higher priority runs first
94
+ * id: 'userValidator', // Unique identifier
95
+ * blocking: true, // Wait for async completion
96
+ * once: false, // Run multiple times
97
+ * condition: () => isLoggedIn(), // Conditional execution
98
+ * debounce: 500, // Debounce delay in ms
99
+ * throttle: 1000, // Throttle interval in ms
100
+ * validation: (payload) => payload?.id != null
101
+ * };
102
+ * ```
131
103
  */
132
- type HandlerConfig = {
104
+ interface HandlerConfig {
133
105
  /** Priority level (higher numbers execute first). Default: 0 */
134
106
  priority?: number;
135
107
  /** Unique identifier for the handler. Auto-generated if not provided */
136
108
  id?: string;
137
109
  /** Whether to wait for async handlers to complete. Default: false */
138
110
  blocking?: boolean;
139
- };
111
+ /** Whether this handler should run once and then be removed. Default: false */
112
+ once?: boolean;
113
+ /** Condition function to determine if handler should run */
114
+ condition?: () => boolean;
115
+ /** Debounce delay in milliseconds */
116
+ debounce?: number;
117
+ /** Throttle delay in milliseconds */
118
+ throttle?: number;
119
+ /** Validation function that must return true for handler to execute */
120
+ validation?: (payload: any) => boolean;
121
+ /** Mark this handler as middleware */
122
+ middleware?: boolean;
123
+ }
140
124
  /**
141
- * Base interface for defining action payload mappings
125
+ * Internal handler registration data
126
+ * @internal
127
+ */
128
+ interface HandlerRegistration<T = any> {
129
+ handler: ActionHandler<T>;
130
+ config: Required<HandlerConfig>;
131
+ id: string;
132
+ }
133
+ /**
134
+ * Execution modes for action pipeline
135
+ * @implements execution-mode
136
+ * @memberof core-concepts
137
+ * @since 1.0.0
138
+ *
139
+ * Defines how handlers are executed within the action pipeline.
140
+ * Each mode provides different execution strategies for various use cases.
141
+ *
142
+ * - `sequential`: Execute handlers one after another (default)
143
+ * - `parallel`: Execute all handlers simultaneously
144
+ * - `race`: Execute handlers simultaneously, use first completed result
145
+ *
142
146
  * @example
143
147
  * ```typescript
144
- * interface MyActions extends ActionPayloadMap {
145
- * increment: void;
146
- * setCount: number;
147
- * updateUser: { id: string; name: string };
148
- * }
148
+ * const register = new ActionRegister({
149
+ * defaultExecutionMode: 'parallel'
150
+ * });
151
+ *
152
+ * // Or set per action
153
+ * register.setExecutionMode('validateUser', 'sequential');
154
+ * register.setExecutionMode('fetchData', 'race');
149
155
  * ```
150
156
  */
151
- interface ActionPayloadMap {}
157
+ type ExecutionMode = 'sequential' | 'parallel' | 'race';
158
+ /**
159
+ * Internal execution context for action pipeline processing
160
+ * @implements pipeline-context
161
+ * @memberof api-terms
162
+ * @internal
163
+ * @since 1.0.0
164
+ *
165
+ * Maintains state during action pipeline execution including current payload,
166
+ * handler queue, execution status, and flow control information.
167
+ *
168
+ * @template T - The type of the payload being processed
169
+ *
170
+ * @example
171
+ * ```typescript
172
+ * // Internal usage in ActionRegister
173
+ * const context: PipelineContext<UserPayload> = {
174
+ * action: 'updateUser',
175
+ * payload: { id: '123', name: 'John' },
176
+ * handlers: registeredHandlers,
177
+ * aborted: false,
178
+ * currentIndex: 0,
179
+ * executionMode: 'sequential'
180
+ * };
181
+ * ```
182
+ */
183
+ interface PipelineContext<T = any> {
184
+ action: string;
185
+ payload: T;
186
+ handlers: HandlerRegistration<T>[];
187
+ aborted: boolean;
188
+ abortReason?: string;
189
+ currentIndex: number;
190
+ jumpToPriority?: number;
191
+ executionMode: ExecutionMode;
192
+ }
152
193
  /**
153
194
  * Configuration options for ActionRegister
195
+ * @implements actionregister-configuration
196
+ * @memberof api-terms
197
+ * @since 1.0.0
198
+ *
199
+ * Defines configuration options for ActionRegister instances, including
200
+ * logging setup, debugging options, and default execution behavior.
201
+ *
202
+ * @example
203
+ * ```typescript
204
+ * const config: ActionRegisterConfig = {
205
+ * logger: createLogger(LogLevel.DEBUG),
206
+ * logLevel: LogLevel.INFO,
207
+ * name: 'UserActions',
208
+ * debug: true,
209
+ * defaultExecutionMode: 'sequential'
210
+ * };
211
+ *
212
+ * const actionRegister = new ActionRegister(config);
213
+ * ```
154
214
  */
155
215
  interface ActionRegisterConfig {
156
216
  /** Custom logger implementation. Defaults to ConsoleLogger */
157
217
  logger?: Logger;
158
- /** Log level for the logger. Defaults to ERROR if not provided */
218
+ /** Log level for filtering output. Defaults to ERROR */
159
219
  logLevel?: LogLevel;
160
- /** OpenTelemetry context for tracing */
161
- otelContext?: OtelContext;
162
- /** Whether to use OTEL-aware logger. Defaults to false */
163
- useOtel?: boolean;
220
+ /** Name identifier for this ActionRegister instance */
221
+ name?: string;
222
+ /** Whether to enable debug mode with additional logging */
223
+ debug?: boolean;
224
+ /** Default execution mode for actions. Defaults to 'sequential' */
225
+ defaultExecutionMode?: ExecutionMode;
226
+ }
227
+ /**
228
+ * Unregister function returned by register method
229
+ * @implements cleanup-function
230
+ * @memberof api-terms
231
+ * @since 1.0.0
232
+ *
233
+ * Function type for unregistering action handlers from the pipeline.
234
+ * Returned by the register method to provide cleanup capability.
235
+ *
236
+ * @example
237
+ * ```typescript
238
+ * const unregister = actionRegister.register('updateUser', handler);
239
+ *
240
+ * // Later, remove the handler
241
+ * unregister();
242
+ * ```
243
+ */
244
+ type UnregisterFunction = () => void;
245
+ /**
246
+ * Type-safe action dispatcher interface
247
+ * @implements action-dispatcher
248
+ * @memberof api-terms
249
+ * @since 1.0.0
250
+ *
251
+ * Provides overloaded function signatures for dispatching actions with proper
252
+ * type checking. Supports both actions with payloads and void actions.
253
+ *
254
+ * @template T - Action payload map defining available actions
255
+ *
256
+ * @example
257
+ * ```typescript
258
+ * interface AppActions extends ActionPayloadMap {
259
+ * increment: void;
260
+ * setCount: number;
261
+ * updateUser: { id: string; name: string };
262
+ * }
263
+ *
264
+ * const dispatch: ActionDispatcher<AppActions> = actionRegister.dispatch;
265
+ *
266
+ * // Type-safe dispatching
267
+ * await dispatch('increment'); // No payload required
268
+ * await dispatch('setCount', 42); // Number payload required
269
+ * await dispatch('updateUser', { id: '1', name: 'John' }); // Object payload
270
+ * ```
271
+ */
272
+ interface ActionDispatcher<T extends ActionPayloadMap> {
273
+ /** Dispatch an action without payload */
274
+ <K extends keyof T>(action: T[K] extends void ? K : never): Promise<void>;
275
+ /** Dispatch an action with payload */
276
+ <K extends keyof T>(action: K, payload: T[K]): Promise<void>;
277
+ }
278
+ /**
279
+ * Performance metrics for action execution
280
+ * @implements action-metrics
281
+ * @implements performance-monitoring
282
+ * @memberof api-terms
283
+ * @since 1.0.0
284
+ *
285
+ * Provides detailed metrics for action execution performance and status.
286
+ * Used for monitoring, debugging, and performance optimization.
287
+ *
288
+ * @example
289
+ * ```typescript
290
+ * actionRegister.on('action:complete', ({ metrics }) => {
291
+ * console.log(`Action ${metrics.action} took ${metrics.executionTime}ms`);
292
+ * console.log(`Success: ${metrics.success}, Handlers: ${metrics.handlerCount}`);
293
+ * });
294
+ * ```
295
+ */
296
+ interface ActionMetrics {
297
+ action: string;
298
+ executionTime: number;
299
+ handlerCount: number;
300
+ success: boolean;
301
+ error?: string;
302
+ timestamp: number;
164
303
  }
165
304
  /**
166
- * Core action pipeline management system
305
+ * Event types emitted by ActionRegister
306
+ * @implements action-events
307
+ * @implements event-driven-architecture
308
+ * @memberof api-terms
309
+ * @since 1.0.0
310
+ *
311
+ * Defines all event types that can be emitted by ActionRegister instances.
312
+ * Enables reactive programming and monitoring of action lifecycle events.
313
+ *
314
+ * @template T - Action payload map defining available actions
315
+ *
316
+ * @example
317
+ * ```typescript
318
+ * interface AppActions extends ActionPayloadMap {
319
+ * updateUser: { id: string; name: string };
320
+ * }
321
+ *
322
+ * const actionRegister = new ActionRegister<AppActions>();
323
+ *
324
+ * actionRegister.on('action:start', ({ action, payload }) => {
325
+ * console.log(`Starting action: ${action}`, payload);
326
+ * });
327
+ *
328
+ * actionRegister.on('action:complete', ({ action, metrics }) => {
329
+ * console.log(`Completed: ${action} in ${metrics.executionTime}ms`);
330
+ * });
331
+ * ```
332
+ */
333
+ interface ActionRegisterEvents<T extends ActionPayloadMap = ActionPayloadMap> {
334
+ /** Emitted before action dispatch */
335
+ 'action:start': {
336
+ action: keyof T;
337
+ payload: any;
338
+ };
339
+ /** Emitted after successful action completion */
340
+ 'action:complete': {
341
+ action: keyof T;
342
+ payload: any;
343
+ metrics: ActionMetrics;
344
+ };
345
+ /** Emitted when action is aborted */
346
+ 'action:abort': {
347
+ action: keyof T;
348
+ payload: any;
349
+ reason?: string;
350
+ };
351
+ /** Emitted when action encounters an error */
352
+ 'action:error': {
353
+ action: keyof T;
354
+ payload: any;
355
+ error: Error;
356
+ };
357
+ /** Emitted when handler is registered */
358
+ 'handler:register': {
359
+ action: keyof T;
360
+ handlerId: string;
361
+ config: HandlerConfig;
362
+ };
363
+ /** Emitted when handler is unregistered */
364
+ 'handler:unregister': {
365
+ action: keyof T;
366
+ handlerId: string;
367
+ };
368
+ }
369
+ /**
370
+ * Event handler type for ActionRegister events
371
+ * @implements event-handler
372
+ * @memberof api-terms
373
+ * @since 1.0.0
374
+ *
375
+ * Function type for handling events emitted by ActionRegister.
376
+ *
377
+ * @template T - The type of event data
378
+ */
379
+ type EventHandler<T = any> = (data: T) => void;
380
+ /**
381
+ * Simple event emitter interface
382
+ * @implements event-emitter
383
+ * @memberof api-terms
384
+ * @since 1.0.0
385
+ *
386
+ * Basic event emitter interface for ActionRegister event system.
387
+ * Provides methods for subscribing, emitting, and unsubscribing from events.
388
+ *
389
+ * @template T - Record type defining available events and their data types
390
+ */
391
+ interface EventEmitter<T extends Record<string, any> = Record<string, any>> {
392
+ on<K extends keyof T>(event: K, handler: EventHandler<T[K]>): UnregisterFunction;
393
+ emit<K extends keyof T>(event: K, data: T[K]): void;
394
+ off<K extends keyof T>(event: K, handler: EventHandler<T[K]>): void;
395
+ removeAllListeners(event?: keyof T): void;
396
+ }
397
+ //# sourceMappingURL=types.d.ts.map
398
+ //#endregion
399
+ //#region src/ActionRegister.d.ts
400
+ /**
401
+ * Central action registration and dispatch system
402
+ * @implements action-pipeline-system
403
+ * @implements actionregister
404
+ * @memberof core-concepts
405
+ *
406
+ * Core action pipeline management system with type-safe action dispatch
167
407
  * @template T - Action payload map defining available actions and their payload types
408
+ *
168
409
  * @example
169
410
  * ```typescript
170
411
  * interface AppActions extends ActionPayloadMap {
171
412
  * increment: void;
172
413
  * setCount: number;
414
+ * updateUser: { id: string; name: string };
173
415
  * }
174
416
  *
175
417
  * const actionRegister = new ActionRegister<AppActions>();
176
418
  *
177
- * // Register handlers
178
- * actionRegister.register('increment', () => console.log('Incremented'));
179
- * actionRegister.register('setCount', (count) => console.log(`Count: ${count}`));
419
+ * // Register handlers with priority and configuration
420
+ * actionRegister.register('increment', (_, controller) => {
421
+ * console.log('Incremented');
422
+ * controller.next();
423
+ * }, { priority: 10 });
180
424
  *
181
- * // Dispatch actions
425
+ * actionRegister.register('setCount', (count, controller) => {
426
+ * console.log(`Count: ${count}`);
427
+ * controller.next();
428
+ * });
429
+ *
430
+ * // Dispatch actions with type safety
182
431
  * await actionRegister.dispatch('increment');
183
432
  * await actionRegister.dispatch('setCount', 42);
184
433
  * ```
185
434
  */
186
435
  declare class ActionRegister<T extends ActionPayloadMap = ActionPayloadMap> {
187
436
  private pipelines;
188
- private atomSetters;
189
437
  private handlerCounter;
190
- readonly logger: Logger;
438
+ private readonly logger;
439
+ private readonly events;
440
+ private readonly config;
441
+ private readonly actionGuard;
442
+ private executionMode;
443
+ private actionExecutionModes;
191
444
  constructor(config?: ActionRegisterConfig);
192
445
  /**
446
+ * Register action handler with pipeline
447
+ * @implements action-handler
448
+ *
193
449
  * Register a handler for an action in the pipeline
194
450
  * @param action - The action name to handle
195
451
  * @param handler - The handler function to execute
196
452
  * @param config - Optional configuration for the handler
197
453
  * @returns Unregister function to remove the handler
454
+ *
198
455
  * @example
199
456
  * ```typescript
200
- * const unregister = actionRegister.register('increment', () => {
201
- * console.log('Incremented!');
202
- * }, { priority: 10 });
457
+ * const unregister = actionRegister.register('updateUser',
458
+ * async (payload, controller) => {
459
+ * // Validate payload
460
+ * if (!payload.id) {
461
+ * controller.abort('User ID is required');
462
+ * return;
463
+ * }
464
+ *
465
+ * // Process update
466
+ * await updateUserInStore(payload);
467
+ * controller.next();
468
+ * },
469
+ * { priority: 10, blocking: true }
470
+ * );
203
471
  *
204
472
  * // Later, remove the handler
205
473
  * unregister();
206
474
  * ```
207
475
  */
208
- register<K extends keyof T>(action: K, handler: ActionHandler<T[K]>, config?: HandlerConfig): () => void;
209
- registerAtomSetter(name: string, setter: Function): void;
476
+ register<K extends keyof T>(action: K, handler: ActionHandler<T[K]>, config?: HandlerConfig): UnregisterFunction;
477
+ /**
478
+ * Dispatch action through pipeline
479
+ * @implements action-dispatcher
480
+ *
481
+ * Dispatch an action through the pipeline
482
+ * Overloaded to provide type safety for actions with and without payloads
483
+ */
484
+ dispatch: ActionDispatcher<T>;
485
+ /**
486
+ * Execute the pipeline with proper flow control
487
+ * @internal
488
+ */
489
+ private executePipeline;
490
+ /**
491
+ * Clean up one-time handlers after pipeline execution
492
+ * @internal
493
+ */
494
+ private cleanupOneTimeHandlers;
495
+ /**
496
+ * Get the number of handlers registered for an action
497
+ * @param action - The action to check
498
+ * @returns Number of handlers registered
499
+ */
500
+ getHandlerCount<K extends keyof T>(action: K): number;
210
501
  /**
211
- * Dispatch an action through the pipeline (for actions without payload)
212
- * @param action - The action to dispatch
213
- * @returns Promise that resolves when all handlers complete
502
+ * Check if any handlers are registered for an action
503
+ * @param action - The action to check
504
+ * @returns True if handlers are registered
214
505
  */
215
- dispatch<K extends keyof T>(action: T[K] extends void ? K : never): Promise<void>;
506
+ hasHandlers<K extends keyof T>(action: K): boolean;
216
507
  /**
217
- * Dispatch an action through the pipeline (for actions with payload)
218
- * @param action - The action to dispatch
219
- * @param payload - The payload data to pass to handlers
220
- * @returns Promise that resolves when all handlers complete
508
+ * Get all registered action names
509
+ * @returns Array of action names
221
510
  */
222
- dispatch<K extends keyof T>(action: K, payload: T[K]): Promise<void>;
223
- private sortPipeline;
511
+ getRegisteredActions(): (keyof T)[];
512
+ /**
513
+ * Clear all handlers for a specific action
514
+ * @param action - The action to clear
515
+ */
516
+ clearAction<K extends keyof T>(action: K): void;
517
+ /**
518
+ * Clear all handlers for all actions
519
+ */
520
+ clearAll(): void;
521
+ /**
522
+ * Add event listener for ActionRegister events
523
+ * @param event - Event name to listen for
524
+ * @param handler - Event handler function
525
+ * @returns Unregister function to remove the listener
526
+ */
527
+ on<K extends keyof ActionRegisterEvents<T>>(event: K, handler: EventHandler<ActionRegisterEvents<T>[K]>): UnregisterFunction;
528
+ /**
529
+ * Remove event listener
530
+ * @param event - Event name
531
+ * @param handler - Event handler to remove
532
+ */
533
+ off<K extends keyof ActionRegisterEvents<T>>(event: K, handler: EventHandler<ActionRegisterEvents<T>[K]>): void;
534
+ /**
535
+ * Get current configuration
536
+ * @returns Current ActionRegister configuration
537
+ */
538
+ getConfig(): Readonly<Required<ActionRegisterConfig>>;
539
+ /**
540
+ * Get logger instance
541
+ * @returns Current logger instance
542
+ */
543
+ getLogger(): Logger;
224
544
  }
225
545
  //# sourceMappingURL=ActionRegister.d.ts.map
226
546
  //#endregion
227
- //#region src/types.d.ts
228
- interface BaseActionPayloadMap {}
229
- type ActionType<T extends Record<string, any>> = keyof T;
230
- type ActionPayload<T extends Record<string, any>, K extends keyof T> = T[K];
231
- type ActionHandlerMap<T extends Record<string, any>> = { [K in keyof T]?: (payload: T[K]) => void | Promise<void> };
232
- declare function createAction<T extends Record<string, any>, K extends keyof T>(type: K, payload: T[K]): {
233
- type: K;
234
- payload: T[K];
235
- };
236
- declare function isAction<T extends Record<string, any>, K extends keyof T>(action: any, type: K): action is {
237
- type: K;
238
- payload: T[K];
239
- };
240
- //# sourceMappingURL=types.d.ts.map
547
+ //#region src/action-guard.d.ts
548
+ /**
549
+ * Action guard state tracking
550
+ * @internal
551
+ */
552
+ interface GuardState {
553
+ lastExecuted: number;
554
+ debounceTimer?: NodeJS.Timeout;
555
+ throttleTimer?: NodeJS.Timeout;
556
+ isThrottled: boolean;
557
+ }
558
+ /**
559
+ * Action Guard system for managing action execution timing
560
+ * @implements action-guard
561
+ * @implements performance-optimization
562
+ * @implements user-experience-optimization
563
+ * @memberof core-concepts
564
+ * @internal
565
+ * @since 1.0.0
566
+ *
567
+ * Provides debouncing, throttling, and blocking mechanisms for action execution
568
+ * to optimize performance and enhance user experience. Manages timing state
569
+ * per action to prevent unnecessary or excessive action invocations.
570
+ *
571
+ * Key Features:
572
+ * - Debouncing: Delay execution until activity stops
573
+ * - Throttling: Limit execution frequency to intervals
574
+ * - Per-action state management with automatic cleanup
575
+ * - Memory leak prevention through proper timer management
576
+ *
577
+ * @example
578
+ * ```typescript
579
+ * const guard = new ActionGuard(logger);
580
+ *
581
+ * // Debounce search input (wait 300ms after typing stops)
582
+ * if (await guard.debounce('search', 300)) {
583
+ * executeSearch();
584
+ * }
585
+ *
586
+ * // Throttle scroll handler (max once per 100ms)
587
+ * if (guard.throttle('scroll', 100)) {
588
+ * updateScrollPosition();
589
+ * }
590
+ * ```
591
+ */
592
+ declare class ActionGuard {
593
+ private guards;
594
+ private logger;
595
+ constructor(logger: Logger);
596
+ /**
597
+ * Check if action should be debounced
598
+ * @param actionKey - Unique key for the action
599
+ * @param debounceMs - Debounce delay in milliseconds
600
+ * @returns Promise that resolves when debounce period is complete
601
+ */
602
+ debounce(actionKey: string, debounceMs: number): Promise<boolean>;
603
+ /**
604
+ * Check if action should be throttled
605
+ * @param actionKey - Unique key for the action
606
+ * @param throttleMs - Throttle delay in milliseconds
607
+ * @returns True if action should proceed, false if throttled
608
+ */
609
+ throttle(actionKey: string, throttleMs: number): boolean;
610
+ /**
611
+ * Clear all guards for an action
612
+ * @param actionKey - Action key to clear
613
+ */
614
+ clearGuards(actionKey: string): void;
615
+ /**
616
+ * Clear all guards
617
+ */
618
+ clearAll(): void;
619
+ /**
620
+ * Get current guard state for debugging
621
+ * @param actionKey - Action key to inspect
622
+ */
623
+ getGuardState(actionKey: string): GuardState | undefined;
624
+ /**
625
+ * Get all active guards for debugging
626
+ */
627
+ getAllGuardStates(): Map<string, GuardState>;
628
+ }
629
+ //#endregion
630
+ //#region src/execution-modes.d.ts
631
+ /**
632
+ * Execute handlers in sequential mode (one after another)
633
+ * @implements execution-modes
634
+ * @implements sequential-execution
635
+ * @memberof core-concepts
636
+ * @internal
637
+ * @since 1.0.0
638
+ *
639
+ * Executes action handlers sequentially in priority order, supporting flow control,
640
+ * conditional execution, and priority jumping within the pipeline.
641
+ *
642
+ * @template T - The type of the payload being processed
643
+ * @param context - Pipeline execution context with handlers and state
644
+ * @param createController - Factory function for creating pipeline controllers
645
+ * @param logger - Logger instance for tracing execution
646
+ * @returns Promise that resolves when all handlers complete or pipeline aborts
647
+ *
648
+ * Features:
649
+ * - Priority-based execution order (higher priority first)
650
+ * - Support for priority jumping within execution
651
+ * - Conditional handler execution (condition/validation checks)
652
+ * - Blocking/non-blocking handler support
653
+ * - Comprehensive error handling and recovery
654
+ */
655
+ declare function executeSequential<T>(context: PipelineContext<T>, createController: (registration: HandlerRegistration<T>, index: number) => PipelineController<T>, logger: Logger): Promise<void>;
656
+ /**
657
+ * Execute handlers in parallel mode (all at once)
658
+ * @internal
659
+ */
660
+ declare function executeParallel<T>(context: PipelineContext<T>, createController: (registration: HandlerRegistration<T>, index: number) => PipelineController<T>, logger: Logger): Promise<void>;
661
+ /**
662
+ * Execute handlers in race mode (first to complete wins)
663
+ * @internal
664
+ */
665
+ declare function executeRace<T>(context: PipelineContext<T>, createController: (registration: HandlerRegistration<T>, index: number) => PipelineController<T>, logger: Logger): Promise<void>;
666
+ //# sourceMappingURL=execution-modes.d.ts.map
241
667
 
242
668
  //#endregion
243
- export { ActionHandler, ActionHandlerMap, ActionPayload, ActionPayloadMap, ActionRegister, ActionRegisterConfig, ActionType, BaseActionPayloadMap, ConsoleLogger, HandlerConfig, LogLevel, Logger, OtelConsoleLogger, OtelContext, OtelLogger, PipelineController, createAction, createOtelContextFromPayload, extractSessionIdFromPayload, extractTraceIdFromPayload, getLogLevelFromEnv, isAction, parseLogLevel };
669
+ export { type ActionDispatcher, ActionGuard, type ActionHandler, type ActionMetrics, type ActionPayloadMap, ActionRegister, type ActionRegisterConfig, type ActionRegisterEvents, type EventEmitter, type EventHandler, type ExecutionMode, type HandlerConfig, type HandlerRegistration, type PipelineContext, type PipelineController, type UnregisterFunction, executeParallel, executeRace, executeSequential };
244
670
  //# sourceMappingURL=index.d.cts.map