@context-action/core 1.1.0 โ 1.1.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/CHANGELOG.md +8 -0
- package/README.md +93 -20
- package/dist/index.d.cts +3 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["contextWithErrors"],"sources":["../src/action-guard.ts","../src/concurrency/OperationQueue.ts","../src/errors.ts","../src/execution-modes.ts","../src/types.ts","../src/ActionRegister.ts"],"sourcesContent":["/**\n * @fileoverview Action Guard system for debouncing, throttling and blocking\n * \n * Provides rate limiting and user experience optimization for actions through\n * debouncing (wait for pause) and throttling (limit frequency) mechanisms.\n * Used internally by ActionRegister to control action execution timing.\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/\n */\n\n\n/**\n * Action guard state tracking for debouncing and throttling\n * \n * Tracks timing and execution state for action execution control.\n * Maintains separate state for each action to enable independent\n * rate limiting per action type.\n * \n * @internal\n */\n\ntype TimerHandle = ReturnType<typeof setTimeout>;\n\ninterface GuardState {\n /** Timestamp of the last successful throttle admission. */\n lastThrottleExecutedAt: number;\n\n /** Timestamp of the last successful debounce settlement. */\n lastDebounceSettledAt: number;\n \n /** Active debounce timer - cleared when new debounce requests arrive */\n debounceTimer: TimerHandle | undefined;\n \n /** Active throttle timer - tracks when throttle period will end */\n throttleTimer: TimerHandle | undefined;\n \n /** Flag indicating if action is currently in throttled state */\n isThrottled: boolean;\n \n /** Resolve function for current debounce promise */\n debounceResolve: ((value: boolean) => void) | undefined;\n\n /** Cleanup for the current debounce AbortSignal listener. */\n debounceAbortCleanup: (() => void) | undefined;\n\n /** Identifies the current debounce request so stale timers cannot settle it. */\n debounceRequestId: number;\n}\n\n/**\n * Action Guard system for managing action execution timing\n * \n * Provides performance optimization and user experience enhancement through\n * debouncing and throttling mechanisms. Debouncing waits for a pause in calls\n * before executing, while throttling limits execution frequency.\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @example Manual Usage (Advanced)\n * ```typescript\n * const guard = new ActionGuard()\n * \n * // Manual debouncing\n * if (await guard.debounce('search', 300)) {\n * performSearch() // Only executes after 300ms pause\n * }\n * \n * // Manual throttling\n * if (guard.throttle('scroll', 100)) {\n * updateUI() // Max once per 100ms\n * }\n * ```\n * \n * @internal\n */\nexport class ActionGuard {\n private guards = new Map<string, GuardState>();\n private cleanupInterval: ReturnType<typeof setInterval> | undefined;\n private readonly autoCleanupEnabled: boolean;\n private readonly maxIdleTime: number = 60000; // 1 minute\n private readonly cleanupIntervalMs: number = 30000; // 30 seconds\n\n constructor(autoCleanup: boolean = true) {\n this.autoCleanupEnabled = autoCleanup;\n }\n\n /** Start cleanup only after the first guard is used. */\n private ensureAutoCleanup(): void {\n if (this.autoCleanupEnabled && !this.cleanupInterval) {\n this.startAutoCleanup();\n }\n }\n\n /**\n * Start automatic cleanup of idle guard states\n *\n * @internal\n */\n private startAutoCleanup(): void {\n if (this.cleanupInterval) return;\n\n this.cleanupInterval = setInterval(() => {\n this.performCleanup();\n }, this.cleanupIntervalMs);\n\n // A library-owned maintenance timer must not keep a Node.js process alive.\n (this.cleanupInterval as { unref?: () => void }).unref?.();\n }\n\n private stopAutoCleanup(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n }\n\n /**\n * ๐ง Optimized cleanup with early exit and batched operations\n *\n * @internal\n */\n private performCleanup(): void {\n if (this.guards.size === 0) {\n this.stopAutoCleanup();\n return;\n }\n\n const now = Date.now();\n for (const [key, state] of this.guards) {\n const isIdle = now - Math.max(\n state.lastThrottleExecutedAt,\n state.lastDebounceSettledAt,\n ) > this.maxIdleTime;\n const hasActiveTimers = state.debounceTimer || state.throttleTimer;\n if (isIdle && !hasActiveTimers) {\n this.guards.delete(key);\n }\n }\n\n if (this.guards.size === 0) {\n this.stopAutoCleanup();\n }\n }\n\n /**\n * Apply debouncing to an action\n * \n * Debouncing waits for a specified delay after the last call before allowing\n * execution. Each new call resets the timer. Useful for search inputs, resize\n * handlers, and other high-frequency user interactions.\n * \n * @param actionKey - Unique identifier for the action being debounced\n * @param debounceMs - Delay in milliseconds to wait after the last call\n * \n * @returns Promise resolving to true if execution should proceed, false if cancelled\n * \n * @example Search Input Debouncing\n * ```typescript\n * // Only search after user stops typing for 300ms\n * if (await guard.debounce('userSearch', 300)) {\n * performSearch(query)\n * }\n * ```\n * \n * @internal\n */\n async debounce(\n actionKey: string,\n debounceMs: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n this.ensureAutoCleanup();\n\n if (signal?.aborted) return false;\n\n /** Get or create guard state for this action */\n let state = this.guards.get(actionKey);\n if (!state) {\n /** Initialize new guard state with default values */\n state = {\n lastThrottleExecutedAt: 0,\n lastDebounceSettledAt: 0,\n isThrottled: false,\n debounceTimer: undefined,\n throttleTimer: undefined,\n debounceResolve: undefined as ((value: boolean) => void) | undefined,\n debounceAbortCleanup: undefined,\n debounceRequestId: 0,\n };\n this.guards.set(actionKey, state);\n }\n\n /** Clear any existing debounce timer to restart the delay period */\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n // Resolve previous debounce with false if exists\n if (state.debounceResolve) {\n state.debounceResolve(false);\n state.debounceResolve = undefined as ((value: boolean) => void) | undefined;\n }\n state.debounceAbortCleanup?.();\n state.debounceAbortCleanup = undefined;\n }\n\n const requestId = ++state.debounceRequestId;\n\n /** Create a new abort-aware debounce promise. */\n return new Promise<boolean>((resolve) => {\n let settled = false;\n let abortCleanup: (() => void) | undefined;\n\n const finish = (allowed: boolean) => {\n if (settled) return;\n settled = true;\n\n if (state!.debounceRequestId === requestId) {\n if (state!.debounceTimer) clearTimeout(state!.debounceTimer);\n state!.debounceTimer = undefined;\n state!.debounceResolve = undefined;\n state!.debounceAbortCleanup = undefined;\n if (allowed) state!.lastDebounceSettledAt = Date.now();\n }\n\n abortCleanup?.();\n resolve(allowed);\n };\n\n state!.debounceResolve = finish;\n state!.debounceTimer = setTimeout(() => finish(true), debounceMs);\n\n if (signal) {\n const abort = () => finish(false);\n signal.addEventListener('abort', abort, { once: true });\n abortCleanup = () => signal.removeEventListener('abort', abort);\n state!.debounceAbortCleanup = abortCleanup;\n }\n });\n }\n\n /**\n * Apply throttling to an action\n * \n * Throttling limits execution frequency by ensuring a minimum interval between\n * calls. Unlike debouncing, throttling executes immediately on the first call\n * and then blocks subsequent calls until the interval expires.\n * \n * @param actionKey - Unique identifier for the action being throttled\n * @param throttleMs - Minimum interval in milliseconds between executions\n * \n * @returns True if execution should proceed, false if currently throttled\n * \n * @example Scroll Handler Throttling\n * ```typescript\n * // Update scroll position max once per 100ms\n * if (guard.throttle('scrollUpdate', 100)) {\n * updateScrollPosition()\n * }\n * ```\n * \n * @internal\n */\n throttle(actionKey: string, throttleMs: number, signal?: AbortSignal): boolean {\n this.ensureAutoCleanup();\n\n if (signal?.aborted) return false;\n\n /** Get or create guard state for this action */\n let state = this.guards.get(actionKey);\n if (!state) {\n /** Initialize new guard state with default values */\n state = {\n lastThrottleExecutedAt: 0,\n lastDebounceSettledAt: 0,\n isThrottled: false,\n debounceTimer: undefined,\n throttleTimer: undefined,\n debounceResolve: undefined as ((value: boolean) => void) | undefined,\n debounceAbortCleanup: undefined,\n debounceRequestId: 0,\n };\n this.guards.set(actionKey, state);\n }\n\n const now = Date.now();\n const timeSinceLastExecution = now - state.lastThrottleExecutedAt;\n\n /** Check if enough time has passed since last execution */\n /** If throttle period has elapsed, allow immediate execution */\n if (timeSinceLastExecution >= throttleMs) {\n /** Update execution timestamp and clear throttled state */\n state.lastThrottleExecutedAt = now;\n state.isThrottled = false;\n \n \n return true;\n }\n\n /** If already in throttled state, don't create duplicate timers */\n /** This prevents timer accumulation and unnecessary processing */\n if (state.isThrottled) {\n return false;\n }\n\n /** Set throttle timer to automatically clear the throttled state */\n /** Calculate remaining time until throttle period expires */\n state.isThrottled = true;\n const remainingTime = throttleMs - timeSinceLastExecution;\n \n /** Create timer to reset throttled state when period expires */\n state.throttleTimer = setTimeout(() => {\n /** Clear throttled state and timer reference */\n state!.isThrottled = false;\n state!.throttleTimer = undefined;\n }, remainingTime);\n\n\n return false;\n }\n\n /**\n * Clear all guard state for a specific action\n * \n * Removes debounce and throttle timers for the specified action,\n * preventing memory leaks and allowing immediate re-execution.\n * \n * @param actionKey - Action identifier to clear guards for\n * \n * @internal\n */\n clearGuards(actionKey: string): void {\n const state = this.guards.get(actionKey);\n if (state) {\n // Clear debounce timer and cancel pending promises to prevent memory leaks\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n if (state.debounceResolve) {\n state.debounceResolve(false);\n state.debounceResolve = undefined;\n }\n state.debounceTimer = undefined;\n }\n state.debounceAbortCleanup?.();\n state.debounceAbortCleanup = undefined;\n \n // Clear throttle timer to prevent memory leaks\n if (state.throttleTimer) {\n clearTimeout(state.throttleTimer);\n state.throttleTimer = undefined;\n }\n \n \n // Remove guard state from memory\n this.guards.delete(actionKey);\n if (this.guards.size === 0) {\n this.stopAutoCleanup();\n }\n }\n }\n\n /**\n * Clear all guard states for all actions\n * \n * Removes all active debounce and throttle timers, useful for cleanup\n * when shutting down the action system or resetting state.\n * \n * @internal\n */\n clearAll(): void {\n \n /** Iterate through all guard states and clear their timers */\n /** This prevents memory leaks when clearing the entire guard system */\n this.guards.forEach((state) => {\n /** Clear any active debounce timers */\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n // Cancel waiting debounce calls\n if (state.debounceResolve) {\n state.debounceResolve(false);\n }\n }\n state.debounceAbortCleanup?.();\n /** Clear any active throttle timers */\n if (state.throttleTimer) {\n clearTimeout(state.throttleTimer);\n }\n });\n \n /** Remove all guard states from memory */\n this.guards.clear();\n this.stopAutoCleanup();\n }\n\n /**\n * Get current guard state for debugging purposes\n * \n * Returns the internal state for a specific action, including timer\n * information and execution timestamps.\n * \n * @param actionKey - Action identifier to inspect\n * @returns Guard state or undefined if no state exists\n * \n * @internal\n */\n getGuardState(actionKey: string): GuardState | undefined {\n return this.guards.get(actionKey);\n }\n\n /**\n * Get all active guard states for debugging purposes\n * \n * Returns a copy of all current guard states, useful for monitoring\n * and debugging rate limiting behavior across all actions.\n * \n * @returns Map of action keys to their guard states\n * \n * @internal\n */\n getAllGuardStates(): Map<string, GuardState> {\n return new Map(this.guards);\n }\n\n /**\n * ๐ Explicit destroy method for comprehensive cleanup\n * \n * Cleans up all timers, promises, and intervals to prevent memory leaks.\n * Should be called when ActionGuard is no longer needed.\n * \n * @internal\n */\n destroy(): void {\n // Clear all existing guards\n this.clearAll();\n }\n\n /**\n * ๐ Get statistics about active guards\n * \n * @returns Statistics about guard usage\n * \n * @internal\n */\n getStats(): { activeGuards: number; withTimers: number } {\n let withTimers = 0;\n this.guards.forEach(state => {\n if (state.debounceTimer || state.throttleTimer) {\n withTimers++;\n }\n });\n \n return {\n activeGuards: this.guards.size,\n withTimers\n };\n }\n}\n","/**\n * ๋์์ฑ ๋ฌธ์ ํด๊ฒฐ์ ์ํ ์์
ํ ์์คํ
\n * \n * ๋ชจ๋ ์ํ ๋ณ๊ฒฝ ์์
์ ์ง๋ ฌํํ์ฌ race condition์ ๋ฐฉ์งํฉ๋๋ค.\n */\n\nexport interface QueuedOperation<T = unknown> {\n id: string;\n operation: () => T | Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n priority?: number;\n timestamp: number;\n}\n\nexport interface QueuedOperationHandle<T> {\n promise: Promise<T>;\n /** Cancels only while the operation is still waiting in the queue. */\n cancel(reason?: unknown): boolean;\n}\n\n/**\n * ์์
ํ ๊ด๋ฆฌ์\n *\n * ํต์ฌ ๊ธฐ๋ฅ:\n * 1. ์์
์ง๋ ฌํ - ๋ชจ๋ ์์
์ ์์๋๋ก ์คํ\n * 2. ์ฐ์ ์์ ์ง์ - ์ค์ํ ์์
์ฐ์ ์ฒ๋ฆฌ\n * 3. ์๋ฌ ์ฒ๋ฆฌ - ๊ฐ๋ณ ์์
์คํจ๊ฐ ์ ์ฒด์ ์ํฅ ์ฃผ์ง ์์\n * 4. ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ - ์๋ฃ๋ ์์
์๋ ์ ๋ฆฌ\n * 5. ๐ ๋์์ฑ ์ ์ด - maxConcurrency๋ก ๋์ ์คํ ์ ํ\n * 6. ๐ ๋น๋๊ธฐ ์ง์ - Promise.all() ์๋ฒฝ ์ง์\n * 7. ๐ ์ด๋ฒคํธ ๊ธฐ๋ฐ ์ฒ๋ฆฌ - ํจ์จ์ ์ธ ํ ์ฒ๋ฆฌ ์์คํ
\n */\nexport class OperationQueue {\n private queue: Array<QueuedOperation<unknown>> = [];\n private processingPromise: Promise<void> | null = null;\n private operationCounter = 0;\n \n // ๐ Concurrency control\n private activeOperations = 0;\n private readonly maxConcurrency: number;\n \n constructor(\n private name: string = 'OperationQueue', \n maxConcurrency: number = 1\n ) {\n this.maxConcurrency = Math.max(1, maxConcurrency);\n }\n\n /**\n * ์์
์ ํ์ ์ถ๊ฐํ๊ณ ์คํ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํ\n * \n * @param operation ์คํํ ์์
\n * @param priority ์ฐ์ ์์ (๋์์๋ก ๋จผ์ ์คํ)\n * @returns Promise๋ก ๋ํ๋ ์์
๊ฒฐ๊ณผ\n */\n enqueue<T>(operation: () => T | Promise<T>, priority: number = 0): Promise<T> {\n return this.enqueueWithHandle(operation, priority).promise;\n }\n\n /** Enqueue an operation and retain a handle for pre-start cancellation. */\n enqueueWithHandle<T>(\n operation: () => T | Promise<T>,\n priority: number = 0\n ): QueuedOperationHandle<T> {\n let queuedOperation!: QueuedOperation<T>;\n const promise = new Promise<T>((resolve, reject) => {\n queuedOperation = {\n id: `${this.name}-${++this.operationCounter}`,\n operation,\n resolve,\n reject,\n priority,\n timestamp: Date.now()\n };\n\n\n // ์ฐ์ ์์์ ๋ฐ๋ผ ์ฝ์
์์น ๊ฒฐ์ (๋์ ์ฐ์ ์์๊ฐ ์์ชฝ)\n let insertIndex = this.queue.length;\n for (let i = 0; i < this.queue.length; i++) {\n const item = this.queue[i];\n // ํ์ฌ ์์ดํ
์ ์ฐ์ ์์๊ฐ ์ ์์ดํ
๋ณด๋ค ๋ฎ์ผ๋ฉด, ์ ์์ดํ
์ ์์ ์ฝ์
\n if (item && (item.priority || 0) < priority) {\n insertIndex = i;\n break;\n }\n }\n\n this.queue.splice(insertIndex, 0, queuedOperation as unknown as QueuedOperation<unknown>);\n\n // ํ ์ฒ๋ฆฌ ์์ (์ด๋ฏธ ์ฒ๋ฆฌ ์ค์ด๋ฉด ๋ฌด์๋จ)\n if (this.processingPromise) {\n // ์ด๋ฏธ ์ฒ๋ฆฌ ์ค์ด๋ผ๋ฉด, ๋๊ธฐ ์ค์ธ ํ๋ก์ธ์ค์๊ฒ ์๋ก์ด ์์
์ด ์ถ๊ฐ๋์์์ ์๋ฆผ\n this.notifyNewOperation();\n }\n this.processQueue();\n });\n\n return {\n promise,\n cancel: (reason = new Error('Queue operation cancelled')) => {\n const index = this.queue.indexOf(queuedOperation as unknown as QueuedOperation<unknown>);\n if (index === -1) return false;\n\n this.queue.splice(index, 1);\n queuedOperation.reject(reason);\n this.notifyNewOperation();\n return true;\n },\n };\n }\n\n /**\n * ๐ ํ ์ฒ๋ฆฌ ๋ฉ์ธ ๋ก์ง - ๋์์ฑ ์ ์ด ๋ฐ ๋น๋๊ธฐ ์ง์\n *\n * ์ฃผ์ ํน์ง:\n * - maxConcurrency์ ๋ฐ๋ผ ๋์ ์คํ ์์
์๋ฅผ ์ ํํ์ฌ ๋์์ฑ ๋ฌธ์ ๋ฐฉ์ง\n * - Promise.all() ์๋๋ฆฌ์ค์์ ์๋ฒฝํ ์์ฐจ์ ์คํ ๋ณด์ฅ\n * - ์ด๋ฒคํธ ๊ธฐ๋ฐ ์๋ฆผ ์์คํ
์ผ๋ก ํจ์จ์ ์ธ ๋น๋๊ธฐ ์ฒ๋ฆฌ\n * - ์์
์๋ฃ ์ ๋๊ธฐ ์ค์ธ ํ๋ก์ธ์ค์๊ฒ ์๋ ์๋ฆผ\n */\n private async processQueue(): Promise<void> {\n if (this.processingPromise) {\n // Wait for current processing to complete, then check if we need to process more\n await this.processingPromise;\n // After waiting, check if there are new items to process\n if (this.queue.length > 0 && !this.processingPromise) {\n return this.processQueue();\n }\n return;\n }\n\n this.processingPromise = this._doProcess();\n try {\n await this.processingPromise;\n } finally {\n this.processingPromise = null;\n }\n }\n \n private async _doProcess(): Promise<void> {\n while (this.queue.length > 0 || this.activeOperations > 0) {\n // ๐ ๋์์ฑ ์ ์ด: maxConcurrency ๋งํผ๋ง ๋์ ์คํ\n while (this.queue.length > 0 && this.activeOperations < this.maxConcurrency) {\n const operation = this.queue.shift()!;\n\n // ๐ ๋น๋๊ธฐ ์์
์คํ (await๋ฅผ ์ฌ์ฉํ์ง ์์ - ๋ณ๋ ฌ ์คํ์ ์ํด)\n this.startOperation(operation);\n }\n\n // ๐ ์คํ ์ค์ธ ์์
์ด ์์ผ๋ฉด ํ๋๊ฐ ์๋ฃ๋ ๋๊น์ง ๋๊ธฐ\n if (this.activeOperations > 0) {\n await this.waitForAnyOperation();\n }\n }\n }\n\n /**\n * ๐ ๊ฐ๋ณ ์์
์ ์์ํ๊ณ ์๋ฃ๋ฅผ ์ถ์ \n */\n private startOperation(operation: QueuedOperation<unknown>): void {\n this.activeOperations++;\n\n // ๋น๋๊ธฐ๋ก ์์
์คํ\n this.executeOperation(operation)\n .finally(() => {\n this.activeOperations--;\n\n // ๋๊ธฐ ์ค์ธ ํ๋ก์ธ์ค์๊ฒ ์ ํธ ๋ณด๋ด๊ธฐ\n this.notifyOperationComplete();\n });\n }\n\n private pendingResolvers: Array<() => void> = [];\n\n /**\n * ๐ ํ๋์ ์์
์ด ์๋ฃ๋ ๋๊น์ง ๋๊ธฐํ๊ฑฐ๋ ์๋ก์ด ์์
์ด ์ถ๊ฐ๋ ๋๊น์ง ๋๊ธฐ\n */\n private waitForAnyOperation(): Promise<void> {\n return new Promise<void>((resolve) => {\n this.pendingResolvers.push(resolve);\n });\n }\n\n /**\n * ๐ ์์
์๋ฃ ์ ํธ - ๋๊ธฐ ์ค์ธ ํ๋ก์ธ์ค๋ค์๊ฒ ์๋ฆผ\n */\n private notifyOperationComplete(): void {\n // ๋๊ธฐ ์ค์ธ ๋ชจ๋ ๋ฆฌ์กธ๋ฒ๋ฅผ ๊นจ์ฐ๊ธฐ\n const resolvers = this.pendingResolvers.splice(0);\n resolvers.forEach(resolve => resolve());\n }\n\n /**\n * ๐ ์๋ก์ด ์์
์ถ๊ฐ ์ ํธ - processQueue์์ ํธ์ถ\n */\n private notifyNewOperation(): void {\n // ์๋ก์ด ์์
์ด ์ถ๊ฐ๋์์ผ๋ฏ๋ก ๋๊ธฐ ์ค์ธ ํ๋ก์ธ์ค๋ฅผ ๊นจ์์ ๋ค์ ํ์ธํ๋๋ก ํจ\n this.notifyOperationComplete();\n }\n \n /**\n * ๐ ๊ฐ๋ณ ์์
์คํ ๋ก์ง\n */\n private async executeOperation(operation: QueuedOperation<unknown>): Promise<void> {\n try {\n // ์์
์คํ (๋๊ธฐ/๋น๋๊ธฐ ๋ชจ๋ ์ง์)\n const result = await Promise.resolve(operation.operation());\n operation.resolve(result);\n } catch (error) {\n // ๊ฐ๋ณ ์์
์คํจ๋ ์ ์ฒด ํ์ ์ํฅ ์ฃผ์ง ์์\n operation.reject(error);\n }\n }\n\n /**\n * ๐ ํ์ฌ ํ ์ํ ์กฐํ (๋๋ฒ๊น
์ฉ) - ๋์์ฑ ์ ๋ณด ํฌํจ\n */\n getQueueInfo() {\n return {\n name: this.name,\n queueLength: this.queue.length,\n isProcessing: Boolean(this.processingPromise),\n activeOperations: this.activeOperations,\n maxConcurrency: this.maxConcurrency,\n operations: this.queue.map(op => ({\n id: op.id,\n priority: op.priority,\n timestamp: op.timestamp\n }))\n };\n }\n \n /**\n * ๐ ๋์์ฑ ์ค์ ์กฐํ\n */\n getConcurrencyInfo() {\n return {\n maxConcurrency: this.maxConcurrency,\n activeOperations: this.activeOperations,\n availableSlots: this.maxConcurrency - this.activeOperations,\n queuedOperations: this.queue.length,\n efficiency: this.activeOperations / this.maxConcurrency\n };\n }\n\n /**\n * ํ ๋น์ฐ๊ธฐ (ํ
์คํธ์ฉ)\n */\n clear(options: { rejectPending?: boolean; reason?: unknown } = {}): void {\n const rejectPending = options.rejectPending ?? true;\n const reason = options.reason ?? new Error('Queue cleared');\n\n // Settle queued operations so callers are never left with pending promises.\n this.queue.forEach(operation => {\n if (rejectPending) {\n operation.reject(reason);\n } else {\n operation.resolve(undefined as never);\n }\n });\n\n this.queue = [];\n\n // ๋๊ธฐ ์ค์ธ ๋ฆฌ์กธ๋ฒ๋ค๋ ์ ๋ฆฌ\n const resolvers = this.pendingResolvers.splice(0);\n resolvers.forEach(resolve => resolve());\n }\n\n /**\n * ํ ํฌ๊ธฐ ์กฐํ\n */\n get size(): number {\n return this.queue.length;\n }\n\n /**\n * ์ฒ๋ฆฌ ์ค ์ฌ๋ถ ์กฐํ \n */\n get processing(): boolean {\n return Boolean(this.processingPromise);\n }\n}\n","/**\n * Action Validation Errors\n *\n * Zod ์คํค๋ง ๊ธฐ๋ฐ ๊ฒ์ฆ ์คํจ ์ ๋ฐ์ํ๋ ์๋ฌ ํด๋์ค๋ค\n */\n\n// ============================================\n// Zod Error Compatible Types\n// ============================================\n\n/**\n * Zod Issue interface (loose typing for Zod 4 compatibility)\n */\nexport interface ZodIssueLike {\n message: string;\n path: readonly (string | number | symbol)[];\n code: string;\n}\n\n/**\n * Zod Error interface (loose typing for Zod 4 compatibility)\n * Accepts any object with these minimum required properties\n */\nexport interface ZodErrorLike {\n message: string;\n issues: readonly ZodIssueLike[];\n format?: () => unknown;\n flatten?: () => unknown;\n}\n\n/** Raised when dispatch result aggregation options cannot be processed. */\nexport class ActionResultProcessingError extends Error {\n override name = 'ActionResultProcessingError';\n\n constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, ActionResultProcessingError.prototype);\n }\n}\n\n/** Signals work from a completed race attempt to stop before the next retry. */\nexport class ActionAttemptSupersededError extends Error {\n override name = 'ActionAttemptSupersededError';\n\n constructor(public readonly attempt: number) {\n super(`Action attempt ${attempt} was superseded by a retry.`);\n Object.setPrototypeOf(this, ActionAttemptSupersededError.prototype);\n }\n}\n\nexport function isActionResultProcessingError(\n error: unknown,\n): error is ActionResultProcessingError {\n return error instanceof ActionResultProcessingError;\n}\n\n// ============================================\n// Action Validation Error\n// ============================================\n\n/**\n * Action payload ๊ฒ์ฆ ์คํจ ์๋ฌ\n *\n * dispatch ์ Zod ์คํค๋ง ๊ฒ์ฆ์ด ์คํจํ๋ฉด ๋ฐ์ํฉ๋๋ค.\n * (validationMode๊ฐ 'strict'์ผ ๋๋ง throw)\n *\n * @example\n * ```typescript\n * try {\n * dispatch('updateUser', { id: '', name: 'John' });\n * } catch (error) {\n * if (error instanceof ActionValidationError) {\n * console.log('Action:', error.action);\n * console.log('Issues:', error.issues);\n * console.log('Formatted:', error.formattedErrors);\n * }\n * }\n * ```\n */\nexport class ActionValidationError extends Error {\n /** ์๋ฌ ์ด๋ฆ */\n override name = 'ActionValidationError';\n\n /** ์๋ณธ Zod ์๋ฌ ๊ฐ์ฒด */\n public readonly zodError: unknown;\n\n /**\n * @param action - ๊ฒ์ฆ ์คํจํ action ์ด๋ฆ\n * @param zodError - Zod ๊ฒ์ฆ ์๋ฌ ๊ฐ์ฒด (ZodError compatible)\n */\n constructor(action: string, zodError: unknown) {\n const errorMessage =\n zodError && typeof zodError === 'object' && 'message' in zodError\n ? String((zodError as { message: unknown }).message)\n : 'Validation failed';\n\n const message = `Action \"${action}\" payload validation failed: ${errorMessage}`;\n super(message);\n\n this.action = action;\n this.zodError = zodError;\n\n // Error ์์ ์ prototype chain ๋ณต์ (ES5 ํธํ)\n Object.setPrototypeOf(this, ActionValidationError.prototype);\n }\n\n /** ๊ฒ์ฆ ์คํจํ action ์ด๋ฆ */\n public readonly action: string;\n\n /**\n * Zod ๊ฒ์ฆ ์ด์ ๋ชฉ๋ก\n */\n get issues(): readonly ZodIssueLike[] {\n if (\n this.zodError &&\n typeof this.zodError === 'object' &&\n 'issues' in this.zodError &&\n Array.isArray((this.zodError as { issues: unknown }).issues)\n ) {\n return (this.zodError as { issues: readonly ZodIssueLike[] }).issues;\n }\n return [];\n }\n\n /**\n * ํฌ๋งท๋ ์๋ฌ ๊ฐ์ฒด (ํ๋๋ณ ์๋ฌ ๋ฉ์์ง)\n */\n get formattedErrors(): unknown {\n if (\n this.zodError &&\n typeof this.zodError === 'object' &&\n 'format' in this.zodError &&\n typeof (this.zodError as { format: unknown }).format === 'function'\n ) {\n return (this.zodError as { format: () => unknown }).format();\n }\n return {};\n }\n\n /**\n * ํ๋ซ ์๋ฌ ๋งต (ํ๋๋ช
โ ์๋ฌ ๋ฉ์์ง ๋ฐฐ์ด)\n */\n get flattenedErrors(): unknown {\n if (\n this.zodError &&\n typeof this.zodError === 'object' &&\n 'flatten' in this.zodError &&\n typeof (this.zodError as { flatten: unknown }).flatten === 'function'\n ) {\n return (this.zodError as { flatten: () => unknown }).flatten();\n }\n return { fieldErrors: {}, formErrors: [] };\n }\n\n /**\n * ์ฒซ ๋ฒ์งธ ์๋ฌ ๋ฉ์์ง\n */\n get firstError(): string | undefined {\n return this.issues[0]?.message;\n }\n\n /**\n * ์๋ฌ ๋ฐ์ ํ๋ ๊ฒฝ๋ก ๋ชฉ๋ก\n */\n get errorPaths(): string[] {\n return this.issues.map((issue) =>\n issue.path.map((p) => String(p)).join('.')\n );\n }\n\n /**\n * JSON ์ง๋ ฌํ\n */\n toJSON() {\n return {\n name: this.name,\n action: this.action,\n message: this.message,\n issues: this.issues,\n };\n }\n}\n\n/**\n * Raised when a dispatch exceeds its configured wall-clock timeout.\n * The underlying handler receives an aborted controller signal and the internal\n * queue keeps draining it safely, while the caller is released immediately with\n * this error.\n */\nexport class ActionTimeoutError extends Error {\n override name = 'ActionTimeoutError';\n\n constructor(\n public readonly action: string,\n public readonly timeout: number\n ) {\n super(`Action \"${action}\" timed out after ${timeout}ms`);\n Object.setPrototypeOf(this, ActionTimeoutError.prototype);\n }\n}\n\n/** Raised when work is submitted after an ActionRegister begins shutdown. */\nexport class ActionRegisterDestroyedError extends Error {\n override name = 'ActionRegisterDestroyedError';\n\n constructor(\n public readonly registerName: string,\n public readonly state: 'closing' | 'destroyed'\n ) {\n super(`ActionRegister \"${registerName}\" is ${state} and cannot accept new work`);\n Object.setPrototypeOf(this, ActionRegisterDestroyedError.prototype);\n }\n}\n\n// ============================================\n// Type Guard\n// ============================================\n\n/**\n * ActionValidationError ํ์
๊ฐ๋\n */\nexport function isActionValidationError(\n error: unknown\n): error is ActionValidationError {\n return error instanceof ActionValidationError;\n}\n\n/** ActionTimeoutError type guard. */\nexport function isActionTimeoutError(\n error: unknown\n): error is ActionTimeoutError {\n return error instanceof ActionTimeoutError;\n}\n\n/** ActionRegisterDestroyedError type guard. */\nexport function isActionRegisterDestroyedError(\n error: unknown\n): error is ActionRegisterDestroyedError {\n return error instanceof ActionRegisterDestroyedError;\n}\n","/**\n * @fileoverview Execution mode implementations for ActionRegister\n * \n * Provides three different execution strategies for action handler pipelines:\n * - Sequential: Execute handlers one after another in priority order\n * - Parallel: Execute all handlers simultaneously\n * - Race: First handler to complete wins, other started handlers keep running\n */\n\nimport type { \n HandlerError,\n HandlerExecutionOutcome,\n HandlerRegistration, \n PipelineContext,\n PipelineController,\n PipelineControllerState,\n} from './types.js';\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\nfunction beginOutcome<T, R>(registration: HandlerRegistration<T, R>): HandlerExecutionOutcome<R> {\n return {\n id: registration.id,\n status: 'running',\n executed: true,\n duration: undefined,\n result: undefined,\n error: undefined,\n metadata: registration.config.metadata\n ? { ...registration.config.metadata }\n : undefined,\n };\n}\n\nfunction createSkippedOutcome<T, R>(\n registration: HandlerRegistration<T, R>,\n): HandlerExecutionOutcome<R> {\n return {\n id: registration.id,\n status: 'skipped',\n executed: false,\n duration: 0,\n result: undefined,\n error: undefined,\n metadata: registration.config.metadata\n ? { ...registration.config.metadata }\n : undefined,\n };\n}\n\nfunction finishOutcome<R>(\n outcome: HandlerExecutionOutcome<R>,\n startedAt: number,\n status: 'succeeded' | 'failed',\n result?: R,\n error?: Error,\n): void {\n outcome.status = status;\n outcome.duration = Date.now() - startedAt;\n outcome.result = result;\n outcome.error = error;\n}\n\nfunction appendLocalResults<T, R>(\n context: PipelineContext<T, R>,\n state: PipelineControllerState<T, R>,\n returnedResult: R | undefined,\n registration: HandlerRegistration<T, R>,\n target: R[] = context.results,\n): void {\n if (registration.role === 'guard') return;\n if (state.results.length > 0) target.push(...state.results);\n if (returnedResult !== undefined && !state.terminated) {\n target.push(returnedResult);\n }\n}\n\n/**\n * Create standardized error handling for handlers\n * \n * @param error - The error that occurred\n * @param registration - The handler registration that failed\n * @returns Standardized HandlerError object\n * \n * @internal\n */\nfunction handleExecutionError<T, R>(\n error: unknown,\n registration: HandlerRegistration<T, R>\n): HandlerError {\n const errorObj = error instanceof Error ? error : new Error(String(error));\n return {\n handlerId: registration.id,\n error: errorObj,\n timestamp: Date.now(),\n severity: registration.config.errorPolicy === 'fatal' ? 'blocking' : 'non-blocking'\n };\n}\n\n/**\n * Execute handlers in sequential mode (one after another)\n * \n * Executes action handlers one at a time in priority order (highest first).\n * Supports both blocking and non-blocking handlers, with proper abort and\n * termination handling. Handlers can modify payload for subsequent handlers\n * and jump to different priority levels.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When a blocking handler fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns\n * \n * @public\n */\nexport async function executeSequential<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (registration: HandlerRegistration<T, R>, index: number) => PipelineController<T, R>\n): Promise<void> {\n\n let i = 0;\n const nonBlockingPromises: Array<Promise<unknown>> = [];\n const errors: HandlerError[] = [];\n \n while (i < context.handlers.length) {\n // Check for abort or termination\n if (context.aborted || context.terminated) {\n break;\n }\n\n const registration = context.handlers[i];\n if (!registration) {\n continue; // Skip if handler not found\n }\n context.currentIndex = i;\n const controller = createController(registration, i);\n\n // A condition is part of the dispatch contract, not a best-effort handler.\n // Evaluate it outside the non-blocking handler error path so a broken\n // predicate is never silently converted into a skipped handler.\n if (registration.config.condition) {\n const shouldExecute = registration.config.condition(context.payload);\n if (!shouldExecute) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n i++;\n continue;\n }\n }\n\n if (context.claimOnce && !context.claimOnce(registration)) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n i++;\n continue;\n }\n\n const outcome = beginOutcome(registration);\n const startedAt = Date.now();\n (context.handlerOutcomes ??= []).push(outcome);\n\n try {\n // Check for abort before executing handler\n if (context.aborted) {\n outcome.status = 'cancelled';\n outcome.executed = false;\n outcome.duration = 0;\n break;\n }\n\n (context.executedHandlers ??= []).push(registration);\n const result = registration.handler(context.payload, controller);\n const asyncResult = isPromiseLike(result) ? Promise.resolve(result) : undefined;\n const trackedResult = asyncResult && context.trackHandlerPromise\n ? context.trackHandlerPromise<unknown>(asyncResult)\n : asyncResult;\n\n if (registration.config.scheduling === 'await-before-next') {\n // Sequential mode is genuinely sequential by default: an async\n // handler settles before the next priority slot starts.\n const handlerResult = trackedResult\n ? await trackedResult\n : result;\n finishOutcome(\n outcome,\n startedAt,\n 'succeeded',\n registration.role === 'guard' ? undefined : handlerResult as R | undefined,\n );\n if (\n registration.role !== 'guard' &&\n handlerResult !== undefined &&\n !context.terminated\n ) {\n context.results.push(handlerResult as R);\n }\n } else {\n // ๐ Non-blocking handlers: Handle differently for sync vs async\n if (trackedResult) {\n // Non-blocking async: Track promise with error handling\n const promiseWithErrorHandling = trackedResult\n .then(asyncResult => {\n finishOutcome(\n outcome,\n startedAt,\n 'succeeded',\n registration.role === 'guard' ? undefined : asyncResult as R | undefined,\n );\n if (\n registration.role !== 'guard' &&\n asyncResult !== undefined &&\n !context.terminated\n ) {\n context.results.push(asyncResult as R);\n }\n return asyncResult;\n })\n .catch(error => {\n // ๐ Non-blocking async handler error collection\n const handlerError = handleExecutionError(error, registration);\n errors.push(handlerError);\n finishOutcome(\n outcome,\n startedAt,\n 'failed',\n undefined,\n handlerError.error,\n );\n return undefined; // Return undefined for failed non-blocking handlers\n });\n \n nonBlockingPromises.push(promiseWithErrorHandling);\n } else if (\n registration.role !== 'guard' &&\n result !== undefined &&\n !context.terminated\n ) {\n // Non-blocking sync: Immediately collect result\n finishOutcome(outcome, startedAt, 'succeeded', result as R);\n context.results.push(result as R);\n } else {\n finishOutcome(\n outcome,\n startedAt,\n 'succeeded',\n registration.role === 'guard' ? undefined : result as R | undefined,\n );\n }\n }\n\n outcome.terminationRequested = context.terminated;\n if (context.terminated) outcome.terminationResult = context.terminationResult;\n\n /** Check if pipeline was terminated by controller.return() */\n if (context.terminated) {\n break;\n }\n\n /** Handle jump to priority AFTER handler execution */\n if (context.jumpToPriority !== undefined) {\n // Check if we've exceeded maximum jumps to prevent infinite loops\n context.jumpCount = (context.jumpCount || 0) + 1;\n if (context.jumpCount > (context.maxJumps || 10)) {\n context.aborted = true;\n context.abortReason = `Maximum jump limit exceeded (${context.jumpCount} jumps)`;\n context.jumpToPriority = undefined;\n break;\n }\n\n // Find first handler with priority <= jumpToPriority\n const jumpIndex = context.handlers.findIndex(\n handler => (handler.config.priority || 0) <= context.jumpToPriority!\n );\n\n if (jumpIndex !== -1 && jumpIndex !== i) {\n // The bounded jump counter protects both forward and backward jumps\n // without emitting diagnostics from the execution primitive.\n i = jumpIndex;\n context.jumpToPriority = undefined;\n } else {\n // No valid jump target found, or jumping to same handler\n context.jumpToPriority = undefined;\n i++;\n }\n } else {\n i++;\n }\n\n } catch (error: unknown) {\n // ๐ง Fix: Handle errors gracefully and continue pipeline execution\n const handlerError = handleExecutionError(error, registration);\n finishOutcome(outcome, startedAt, 'failed', undefined, handlerError.error);\n errors.push(handlerError);\n (context.collectedErrors ??= []).push(handlerError);\n\n // Fatal errors terminate the pipeline; collected errors let it continue.\n if (registration.config.errorPolicy === 'fatal') {\n throw handlerError.error;\n }\n\n // For non-blocking handlers, continue to next handler\n i++;\n }\n }\n \n // ๐ Wait for all non-blocking promises with error collection\n if (nonBlockingPromises.length > 0) {\n await Promise.allSettled(nonBlockingPromises);\n }\n\n if (errors.length > 0) {\n context.collectedErrors = errors;\n }\n\n // A fatal handler may already have allowed lower-priority work to start,\n // but it must still reject the final dispatch once that work has settled.\n const fatalError = errors.find(error => error.severity === 'blocking');\n if (fatalError) throw fatalError.error;\n}\n\n/**\n * Execute handlers in parallel mode (all at once)\n * \n * Executes all qualifying action handlers simultaneously using Promise.allSettled.\n * Supports both blocking and non-blocking handlers. Blocking handlers can still\n * fail the entire pipeline if they throw errors.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When any blocking handler fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns#parallel-execution\n * \n * @public\n */\nexport async function executeParallel<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (\n registration: HandlerRegistration<T, R>,\n index: number,\n state: PipelineControllerState<T, R>,\n ) => PipelineController<T, R>\n): Promise<void> {\n\n /**\n * Conditions are dispatch preconditions in concurrent modes. Evaluate them\n * before any handler starts so a predicate error rejects the dispatch rather\n * than being mistaken for a non-blocking handler failure.\n */\n const runnableHandlers: HandlerRegistration<T, R>[] = [];\n for (const registration of context.handlers) {\n if (registration.config.condition && !registration.config.condition(context.payload)) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n continue;\n }\n if (context.claimOnce && !context.claimOnce(registration)) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n continue;\n }\n runnableHandlers.push(registration);\n }\n\n const terminationSlots: Array<{\n requested: boolean;\n result: R | undefined;\n }> = runnableHandlers.map(() => ({ requested: false, result: undefined }));\n const resultSlots: R[][] = runnableHandlers.map(() => []);\n\n /** Create promises for all handlers */\n const handlerPromises = runnableHandlers.map(async (registration, _index) => {\n const state: PipelineControllerState<T, R> = {\n payload: context.payload,\n aborted: false,\n abortReason: undefined,\n jumpToPriority: undefined,\n terminated: false,\n terminationResult: undefined,\n results: [],\n };\n const controller = createController(registration, _index, state);\n const outcome = beginOutcome(registration);\n const startedAt = Date.now();\n (context.handlerOutcomes ??= []).push(outcome);\n\n try {\n (context.executedHandlers ??= []).push(registration);\n const result = registration.handler(state.payload, controller);\n \n const handlerResult = (\n isPromiseLike(result) ? await Promise.resolve(result) : result\n ) as R | undefined;\n \n finishOutcome(\n outcome,\n startedAt,\n 'succeeded',\n registration.role === 'guard' ? undefined : handlerResult,\n );\n outcome.terminationRequested = state.terminated;\n if (state.terminated && registration.role !== 'guard') {\n outcome.terminationResult = state.terminationResult;\n terminationSlots[_index] = {\n requested: true,\n result: state.terminationResult,\n };\n }\n appendLocalResults(context, state, handlerResult, registration, resultSlots[_index]);\n return { \n success: true, \n handlerId: registration.id, \n result: handlerResult,\n terminated: state.terminated,\n state,\n outcome,\n };\n \n } catch (error: unknown) {\n // ๐ Consistent error object creation\n const handlerError = handleExecutionError(error, registration);\n finishOutcome(outcome, startedAt, 'failed', undefined, handlerError.error);\n (context.collectedErrors ??= []).push(handlerError);\n \n if (handlerError.severity === 'blocking') {\n throw handlerError.error;\n }\n \n return {\n success: false,\n handlerId: registration.id,\n error: handlerError.error,\n state,\n outcome,\n registration,\n };\n }\n });\n\n const trackedHandlerPromises = context.trackHandlerPromise\n ? handlerPromises.map(promise => context.trackHandlerPromise!(promise))\n : handlerPromises;\n\n /** Wait for all handlers to complete */\n const results = await Promise.allSettled(trackedHandlerPromises);\n\n // Completion timing is intentionally concurrent, but collected result\n // order follows the priority-sorted handler order. This makes first/last/\n // all strategies deterministic across runs.\n context.results.push(...resultSlots.flat());\n \n /** Check for any rejected blocking handlers */\n const failures = results.filter((result, index) => {\n if (result.status === 'rejected') {\n const registration = runnableHandlers[index];\n return registration?.config.errorPolicy === 'fatal';\n }\n return false;\n });\n\n if (failures.length > 0) {\n const firstFailure = failures[0] as PromiseRejectedResult;\n throw firstFailure.reason;\n }\n\n /** Check if any handler terminated the pipeline */\n const firstTerminated = terminationSlots.find(slot => slot.requested);\n if (firstTerminated) {\n context.terminated = true;\n context.terminationResult = firstTerminated.result;\n }\n}\n\n/**\n * Execute handlers in race mode (first to complete wins)\n * \n * Executes all qualifying handlers simultaneously using Promise.race, where\n * the first handler to complete determines the pipeline result. Other handlers\n * continue in the background and remain tracked for lifecycle cleanup; handlers\n * must observe the controller signal for cooperative external cancellation.\n * Useful for scenarios where you want the fastest response from multiple\n * equivalent handlers.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When the winning handler fails and is blocking\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns#race-execution\n * \n * @public\n */\nexport async function executeRace<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (\n registration: HandlerRegistration<T, R>,\n index: number,\n state: PipelineControllerState<T, R>,\n ) => PipelineController<T, R>\n): Promise<void> {\n\n /** See executeParallel: condition errors are dispatch errors in concurrent modes. */\n const runnableHandlers: HandlerRegistration<T, R>[] = [];\n for (const registration of context.handlers) {\n if (registration.config.condition && !registration.config.condition(context.payload)) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n continue;\n }\n if (context.claimOnce && !context.claimOnce(registration)) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n continue;\n }\n runnableHandlers.push(registration);\n }\n\n if (runnableHandlers.length === 0) {\n return;\n }\n\n /** Create promises for all handlers */\n const handlerPromises = runnableHandlers.map(async (registration, _index) => {\n const state: PipelineControllerState<T, R> = {\n payload: context.payload,\n aborted: false,\n abortReason: undefined,\n jumpToPriority: undefined,\n terminated: false,\n terminationResult: undefined,\n results: [],\n };\n const controller = createController(registration, _index, state);\n const outcome = beginOutcome(registration);\n const startedAt = Date.now();\n (context.handlerOutcomes ??= []).push(outcome);\n\n try {\n (context.executedHandlers ??= []).push(registration);\n const result = registration.handler(state.payload, controller);\n \n const handlerResult = (\n isPromiseLike(result) ? await Promise.resolve(result) : result\n ) as R | undefined;\n \n finishOutcome(\n outcome,\n startedAt,\n 'succeeded',\n registration.role === 'guard' ? undefined : handlerResult,\n );\n outcome.terminationRequested = state.terminated;\n if (state.terminated) outcome.terminationResult = state.terminationResult;\n\n return {\n success: true, \n handlerId: registration.id, \n registration,\n result: handlerResult,\n terminated: state.terminated,\n state,\n outcome,\n };\n \n } catch (error: unknown) {\n // ๐ Consistent error object creation\n const handlerError = handleExecutionError(error, registration);\n finishOutcome(outcome, startedAt, 'failed', undefined, handlerError.error);\n return {\n success: false,\n handlerId: registration.id,\n error: handlerError.error,\n registration,\n state,\n outcome,\n };\n }\n });\n\n const trackedHandlerPromises = context.trackHandlerPromise\n ? handlerPromises.map(promise => context.trackHandlerPromise!(promise))\n : handlerPromises;\n\n // Guards are executed by the register before race arbitration. Retain this\n // filtering for callers of this low-level primitive.\n const winnerCandidates = runnableHandlers.some(handler => handler.role !== 'guard')\n ? trackedHandlerPromises.filter((_, index) => (\n runnableHandlers[index]?.role !== 'guard'\n ))\n : trackedHandlerPromises;\n\n /** Race all handlers while retaining every loser for lifecycle draining. */\n const winner = await Promise.race(winnerCandidates);\n context.raceWinnerId = winner.handlerId;\n context.raceLoserOutcomes = (context.handlerOutcomes ?? [])\n .filter(outcome => outcome.id !== winner.handlerId)\n .map(outcome => ({ ...outcome, metadata: outcome.metadata ? { ...outcome.metadata } : undefined }));\n\n /** If the winner failed and was blocking, throw the error */\n if (!winner.success && winner.registration?.config.errorPolicy === 'fatal') {\n (context.collectedErrors ??= []).push(handleExecutionError(\n winner.error,\n winner.registration,\n ));\n throw winner.error;\n }\n\n // Losers are diagnostics-only. Their asynchronous completion must not\n // change the result, outcome, or errors selected by the winning handler.\n if (!winner.success) {\n (context.collectedErrors ??= []).push(handleExecutionError(\n winner.error,\n winner.registration,\n ));\n }\n\n /** Only the winner contributes results to the race snapshot. */\n if (winner.success) {\n appendLocalResults(context, winner.state, winner.result, winner.registration);\n if (winner.state.aborted) {\n context.aborted = true;\n context.abortReason = winner.state.abortReason;\n }\n }\n\n /** Check if the winning handler terminated the pipeline */\n if (winner.success && winner.terminated) {\n context.terminated = true;\n context.terminationResult = winner.state.terminationResult;\n }\n}\n","\n/**\n * Action payload mapping interface for type-safe action dispatching\n * \n * Defines the mapping between action names and their corresponding payload types.\n * This interface serves as the foundation for type-safe action handling throughout\n * the Context-Action framework.\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/type-system\n * \n * @public\n */\n/**\n * Marker type for action payload maps.\n *\n * Deliberately does not declare a string index signature: adding one would\n * widen `keyof` to `string | number` and make unknown action names compile.\n * Applications extend this type from an interface with literal action keys.\n */\nexport type ActionPayloadMap = object;\n\n/**\n * Minimal runtime contract consumed by ActionRegister for payload validation.\n *\n * The concrete Zod-backed action schema lives in\n * `@context-action/tool-protocol`; keeping this structural contract here\n * avoids coupling the action runtime to transport and schema adapters.\n */\nexport interface ActionSchemaLike {\n safeParse(value: unknown):\n | { success: true; data: unknown }\n | {\n success: false;\n error: {\n message: string;\n issues: readonly { message: string }[];\n };\n };\n}\n\n/**\n * Strict action payload map that prevents certain problematic types\n */\nexport type StrictActionPayloadMap = {\n readonly [K in string]: Exclude<unknown, Function | symbol>;\n};\n\n/**\n * Brand type utilities for enhanced type safety\n */\ndeclare const __brand: unique symbol;\n\n/**\n * Creates a branded type for nominal typing\n */\nexport type Brand<T, B extends string> = T & { readonly [__brand]: B };\n\n/**\n * Branded action key for type safety\n */\nexport type ActionKey<T extends string = string> = Brand<T, 'ActionKey'>;\n\n/**\n * Branded store identifier for type safety\n */\nexport type StoreId<T extends string = string> = Brand<T, 'StoreId'>;\n\n/**\n * Branded handler identifier for type safety\n */\nexport type HandlerId<T extends string = string> = Brand<T, 'HandlerId'>;\n\n/**\n * Creates an action key with type branding\n */\nexport function createActionKey<T extends string>(key: T): ActionKey<T> {\n return key as ActionKey<T>;\n}\n\n/**\n * Creates a store ID with type branding\n */\nexport function createStoreId<T extends string>(id: T): StoreId<T> {\n return id as StoreId<T>;\n}\n\n/**\n * Creates a handler ID with type branding\n */\nexport function createHandlerId<T extends string>(id: T): HandlerId<T> {\n return id as HandlerId<T>;\n}\n\n/**\n * Valid result strategies for type safety\n */\nexport type ValidResultStrategy = 'first' | 'last' | 'all' | 'merge' | 'custom';\n\n/**\n * Advanced type utilities for result processing with strict constraints\n */\nexport type ResultStrategyType<Strategy extends ValidResultStrategy, R> =\n Strategy extends 'all'\n ? readonly R[]\n : Strategy extends 'first' | 'last'\n ? R | undefined\n : Strategy extends 'merge' | 'custom'\n ? R\n : never;\n\n/**\n * Infer result type based on strategy and collect options\n */\nexport type InferResultType<\n R,\n Options extends { strategy?: string; collect?: boolean } | undefined\n> = Options extends { strategy: infer Strategy }\n ? Strategy extends ValidResultStrategy\n ? ResultStrategyType<Strategy, R>\n : R\n : Options extends { collect: true }\n ? readonly R[]\n : R;\n\n/**\n * Advanced type-level utilities for Context-Action framework\n */\nexport namespace TypeUtils {\n /**\n * Extracts payload type for a specific action\n */\n export type ExtractPayload<T extends ActionPayloadMap, K extends keyof T> = T[K];\n\n /**\n * Ensures all values in an object are of the same type\n */\n export type Homogeneous<T, U> = {\n readonly [K in keyof T]: U;\n };\n\n /**\n * Makes specific properties required\n */\n export type RequireFields<T, K extends keyof T> = T & Required<Pick<T, K>>;\n\n /**\n * Makes specific properties optional\n */\n export type PartialFields<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\n\n /**\n * Deep readonly type for immutable structures\n */\n export type DeepReadonly<T> = {\n readonly [P in keyof T]: T[P] extends (infer U)[]\n ? readonly DeepReadonly<U>[]\n : T[P] extends readonly (infer U)[]\n ? readonly DeepReadonly<U>[]\n : T[P] extends Record<string, unknown>\n ? DeepReadonly<T[P]>\n : T[P];\n };\n\n /**\n * Strict non-nullable type\n */\n export type NonNullable<T> = T extends null | undefined ? never : T;\n\n /**\n * Type-safe key extraction\n */\n export type KeysOfType<T, U> = {\n [K in keyof T]: T[K] extends U ? K : never;\n }[keyof T];\n\n /**\n * Function parameter extraction\n */\n export type Parameters<T> = T extends (...args: infer P) => unknown ? P : never;\n\n /**\n * Function return type extraction\n */\n export type ReturnType<T> = T extends (...args: unknown[]) => infer R ? R : never;\n\n /**\n * Promise unwrapping\n */\n export type Awaited<T> = T extends Promise<infer U> ? U : T;\n}\n\n/**\n * Utility type to extract action names from ActionPayloadMap\n * \n * @template T - The ActionPayloadMap interface\n * @example\n * ```typescript\n * type MyActions = ActionNames<AppActions> // 'updateUser' | 'deleteUser' | 'resetUser'\n * ```\n */\n/** String action names supported by the registry and action proxies. */\nexport type ActionNames<T extends ActionPayloadMap> = Extract<keyof T, string>;\n\n/**\n * Utility type to extract payload type for a specific action\n * \n * @template T - The ActionPayloadMap interface \n * @template K - The action name\n * @example\n * ```typescript\n * type UpdateUserPayload = ActionPayload<AppActions, 'updateUser'>\n * // { id: string; name: string; email: string }\n * ```\n */\nexport type ActionPayload<T extends ActionPayloadMap, K extends keyof T> = T[K];\n\n/**\n * Optional action-keyed result contract for `dispatchWithResult`.\n *\n * The legacy API allows callers to provide an explicit result generic. New\n * code can instead associate result types with action keys at the register\n * level so the result type is inferred from the dispatched action.\n */\nexport type ActionResultMap<T extends ActionPayloadMap> = Partial<\n Record<ActionNames<T>, unknown>\n>;\n\n/** Resolve the configured result type for an action, falling back to void. */\nexport type ActionResult<\n TResultMap extends ActionPayloadMap,\n K extends PropertyKey,\n> = K extends keyof TResultMap ? TResultMap[K]\n // biome-ignore lint/suspicious/noConfusingVoidType: void preserves the legacy no-result dispatch contract.\n : void;\n\n/**\n * Pipeline controller interface for managing execution flow and payload modification\n * \n * Provides action handlers with powerful control over the action pipeline execution,\n * including the ability to abort execution, modify payloads, jump to specific priorities,\n * and manage results. This is the primary interface for implementing business logic\n * within action handlers.\n * \n * @template T - The payload type for this action\n * @template R - The result type for this action\n * \n * @example Basic Pipeline Control\n * ```typescript\n * register.register('validateAndProcess', async (payload, controller) => {\n * // Input validation\n * if (!payload.email.includes('@')) {\n * controller.abort('Invalid email format')\n * return\n * }\n * \n * // Process and modify payload for next handlers\n * controller.modifyPayload(data => ({\n * ...data,\n * processed: true,\n * timestamp: Date.now(),\n * normalized: data.email.toLowerCase()\n * }))\n * \n * // Set intermediate result\n * controller.setResult({ validated: true, userId: payload.id })\n * })\n * ```\n * \n * @example Early Return with Result\n * ```typescript\n * register.register('checkCache', async (payload, controller) => {\n * const cached = await cache.get(payload.key)\n * \n * if (cached) {\n * // Return early and skip remaining handlers\n * controller.return({ source: 'cache', data: cached })\n * return\n * }\n * \n * // Continue to next handlers if not cached\n * })\n * ```\n * \n * @example Priority Jumping\n * ```typescript\n * register.register('securityCheck', async (payload, controller) => {\n * if (payload.requiresElevatedPermissions) {\n * // Jump to high-priority security handlers\n * controller.jumpToPriority(1000)\n * }\n * }, { priority: 50 })\n * ```\n * \n * @public\n */\nexport interface PipelineController<T = unknown, R = void> {\n /**\n * Signal for the current dispatch lifecycle.\n *\n * Handlers should observe this signal when they can stop cooperatively. It is\n * aborted by caller cancellation, timeout, provider teardown, or registry\n * shutdown.\n */\n readonly signal?: AbortSignal;\n\n /** Abort the pipeline execution with an optional reason */\n abort(reason?: string): void;\n \n /** Modify the payload that will be passed to subsequent handlers */\n modifyPayload(modifier: (payload: T) => T): void;\n \n /** Get the current payload */\n getPayload(): T;\n\n /**\n * Jump to a specific priority level in the pipeline\n *\n * โ ๏ธ **WARNING**: Backward jumps (to higher priority handlers) can cause infinite loops!\n * Always use with a `condition` in the target handler to prevent re-execution.\n *\n * The system will automatically abort after 10 jumps (configurable) to prevent infinite loops.\n *\n * @param priority - The priority level to jump to (finds first handler with priority <= this value)\n *\n * @example Safe retry pattern with condition\n * ```typescript\n * let retryCount = 0;\n *\n * register.register('process', (payload, controller) => {\n * retryCount++;\n * if (shouldRetry() && retryCount < 3) {\n * controller.jumpToPriority(100); // Jump back to validation\n * }\n * }, { priority: 50 });\n *\n * register.register('validate', (payload) => {\n * // Validation logic\n * }, {\n * priority: 100,\n * condition: () => retryCount === 0 // Only run on first attempt\n * });\n * ```\n */\n jumpToPriority(priority: number): void;\n \n // New result handling methods\n /** Return a result and terminate the pipeline. The result is returned for ergonomic result handlers. */\n return(result: R): R;\n \n /** Set a result but continue pipeline execution */\n setResult(result: R): void;\n \n /** Get all results from previously executed handlers */\n getResults(): R[];\n \n /** Merge current result with previous results using a custom merger function */\n mergeResult(merger: (previousResults: R[], currentResult: R) => R): void;\n}\n\n/** Controller available to observer-only effect handlers. */\nexport interface ActionEffectController<T = unknown> {\n readonly signal?: AbortSignal;\n getPayload(): T;\n}\n\n/** Controller available to preflight guards. Guards may reject or normalize input,\n * but cannot publish a result or terminate a result pipeline. */\nexport interface ActionGuardController<T = unknown> extends ActionEffectController<T> {\n abort(reason?: string): void;\n modifyPayload(modifier: (payload: T) => T): void;\n}\n\n/** Controller for a result-producing handler. Concurrent result handlers do\n * not receive payload mutation or priority-jump capabilities. */\nexport interface ActionResultController<T = unknown, R = void>\n extends ActionEffectController<T> {\n abort(reason?: string): void;\n return(result: R): R;\n setResult(result: R): void;\n getResults(): readonly R[];\n mergeResult(merger: (previousResults: readonly R[], currentResult: R) => R): void;\n}\n\n/** The explicit execution role of a registered handler. */\nexport type HandlerRole = 'guard' | 'result' | 'observer' | 'legacy';\n\n/** Immutable terminal event delivered to observer handlers. */\nexport interface ActionObserverEvent<T = unknown, R = void> {\n readonly action: string;\n readonly payload: Readonly<T>;\n readonly outcome: ExecutionResult<R>['outcome'];\n readonly result: R | readonly R[] | undefined;\n readonly errors: readonly HandlerError[];\n readonly signal?: AbortSignal;\n}\n\n/** A post-result side effect. Observer return values are deliberately ignored. */\nexport type ActionObserverHandler<T = unknown, R = void> = (\n event: ActionObserverEvent<T, R>,\n) => void | Promise<void>;\n\n/** Scheduling and terminal-path selection for a post-result observer. */\nexport interface ObserverConfig<T = unknown> extends Omit<HandlerConfig<T>,\n 'debounce' | 'throttle' | 'blocking' | 'errorPolicy'> {\n when?: 'success' | 'failure' | 'always';\n}\n\n/** Configuration accepted by an admission guard. Guard failures always deny\n * admission, so scheduling and error-policy controls are intentionally not\n * configurable. */\nexport interface GuardConfig<T = unknown> extends Omit<HandlerConfig<T>,\n 'blocking' | 'scheduling' | 'errorPolicy' | 'debounce' | 'throttle' | 'when'> {}\n\n/** Configuration for the supported `registerEffect()` convenience API.\n * New code with a statically known role may call `registerGuard()` or\n * `registerObserver()` directly. */\nexport interface EffectConfig<T = unknown> extends HandlerConfig<T> {\n /** Select the explicit phase that owns this legacy effect. */\n effectKind: 'guard' | 'observer';\n}\n\n/**\n * Action handler function type for processing actions within the pipeline\n * \n * Defines the signature for action handler functions that contain the business logic\n * for processing specific actions. Handlers follow the Store Integration Pattern:\n * 1. Read current state from stores\n * 2. Execute business logic\n * 3. Update stores with new state\n * \n * @template T - The payload type for this action\n * @template R - The return type for this handler\n * \n * @param payload - The action payload data\n * @param controller - Pipeline controller for managing execution flow\n * \n * @returns The result value or Promise resolving to result\n * \n * @example Store Integration Pattern\n * ```typescript\n * const updateUserHandler: ActionHandler<{id: string, name: string, email: string}> = \n * async (payload, controller) => {\n * // 1. Read current state from stores\n * const currentUser = userStore.getValue()\n * const settings = settingsStore.getValue()\n * \n * // 2. Execute business logic\n * if (!settings.allowUserUpdates) {\n * controller.abort('User updates are disabled')\n * return\n * }\n * \n * const updatedUser = {\n * ...currentUser,\n * ...payload,\n * updatedAt: new Date().toISOString()\n * }\n * \n * // 3. Update stores\n * userStore.setValue(updatedUser)\n * \n * // Set result for other handlers or components\n * controller.setResult({ success: true, user: updatedUser })\n * }\n * ```\n * \n * @example Async Handler with Error Handling\n * ```typescript\n * const saveUserHandler: ActionHandler<UserData, SaveResult> = \n * async (payload, controller) => {\n * try {\n * const result = await userService.save(payload)\n * \n * // Update local store with server response\n * userStore.setValue(result.user)\n * \n * return { success: true, userId: result.user.id }\n * } catch (error) {\n * controller.abort(`Save failed: ${error.message}`)\n * return { success: false, error: error.message }\n * }\n * }\n * ```\n * \n * @public\n */\nexport type ActionHandler<T = unknown, R = void> = (\n payload: T,\n controller: PipelineController<T, R>\n) => R | Promise<R> | void | Promise<void>;\n\n/** A side-effect observer. Its return value and result APIs are intentionally unavailable. */\nexport type ActionEffectHandler<T = unknown> = (\n payload: T,\n controller: ActionEffectController<T>,\n) => void | Promise<void>;\n\n/** A preflight validator/authorizer. */\nexport type ActionGuardHandler<T = unknown> = (\n payload: T,\n controller: ActionGuardController<T>,\n) => void | Promise<void>;\n\n/**\n * Strict handler contract used when an action result map declares a result.\n * Unlike the legacy ActionHandler type, a mapped handler must return the\n * declared result (or a promise of it).\n */\nexport type ActionResultHandler<T = unknown, R = void> = (\n payload: T,\n controller: ActionResultController<T, R>\n) => R | Promise<R>;\n\n/** Controls whether an async handler must settle before the next sequential handler starts. */\nexport type HandlerScheduling = 'await-before-next' | 'start-and-continue';\n\n/** Controls whether a handler failure terminates the pipeline or is reported as a collected error. */\nexport type HandlerErrorPolicy = 'fatal' | 'collect';\n\n/**\n * Handler configuration interface for controlling handler behavior within the pipeline\n * \n * Configuration options that control how handlers are executed,\n * including priority, timing controls, and execution behavior.\n * \n * @example Basic Handler Configuration\n * ```typescript\n * register.register('searchUsers', searchHandler, {\n * priority: 100, // Execute before lower priority handlers\n * debounce: 300, // Wait 300ms after last call\n * throttle: 1000, // Limit to once per second\n * once: false // Can be executed multiple times\n * })\n * ```\n * \n * @example Production Handler\n * ```typescript\n * register.register('processPayment', paymentHandler, {\n * priority: 200,\n * blocking: true, // Wait for completion\n * id: 'payment-handler' // Custom ID\n * })\n * ```\n * \n * @public\n */\nexport interface HandlerConfig<T = unknown> {\n /** Priority level (higher numbers execute first). Default: 0 */\n priority?: number;\n \n /** Unique identifier for the handler. Auto-generated if not provided */\n id?: string;\n \n /**\n * Supported 1.x shorthand for scheduling and error policy. `true` maps to\n * `await-before-next` + `fatal`; `false` maps to `start-and-continue` + `collect`.\n * Explicit `scheduling` or `errorPolicy` takes precedence for that field.\n */\n blocking?: boolean;\n\n /** Async scheduling in sequential mode. Default: `await-before-next`. */\n scheduling?: HandlerScheduling;\n\n /** Error behavior for this handler. Default: `collect`. */\n errorPolicy?: HandlerErrorPolicy;\n \n /** Whether this handler should run once and then be removed. Default: false */\n once?: boolean;\n \n /** Debounce delay in milliseconds */\n debounce?: number;\n \n /** Throttle delay in milliseconds */\n throttle?: number;\n \n /** Replace existing handler with same ID. Default: true for backward compatibility */\n replaceExisting?: boolean;\n \n /** Cleanup function to call when handler is unregistered */\n cleanup?: () => void;\n\n /** Condition function to determine if handler should execute. Default: always execute */\n condition?: (payload: T) => boolean;\n\n /** Optional metadata copied into execution outcomes for diagnostics. */\n metadata?: Record<string, unknown>;\n\n /** Terminal path selection; consumed only by `registerObserver()`. */\n when?: 'success' | 'failure' | 'always';\n}\n\n/**\n * Internal handler configuration with defaults resolved.\n *\n * Timing, cleanup, and condition values remain optional because registration\n * does not synthesize them when they are omitted at runtime.\n */\nexport interface ResolvedHandlerConfig<T = unknown> {\n priority: number;\n id: string;\n blocking: boolean;\n scheduling: HandlerScheduling;\n errorPolicy: HandlerErrorPolicy;\n once: boolean;\n replaceExisting: boolean;\n debounce?: number;\n throttle?: number;\n cleanup?: () => void;\n condition?: (payload: T) => boolean;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Resolve the supported `blocking` shorthand and all registration\n * defaults in one place. Adapters should pass their original config to the\n * registry and use this helper only when they need to expose resolved values.\n */\nexport function resolveHandlerConfig<T = unknown>(\n config: HandlerConfig<T> | undefined,\n handlerId: string,\n): ResolvedHandlerConfig<T> {\n return {\n priority: config?.priority ?? 0,\n id: handlerId,\n blocking: config?.errorPolicy === 'fatal' || config?.blocking === true,\n scheduling: config?.scheduling\n ?? (config?.blocking === false ? 'start-and-continue' : 'await-before-next'),\n errorPolicy: config?.errorPolicy\n ?? (config?.blocking === true ? 'fatal' : 'collect'),\n once: config?.once ?? false,\n debounce: config?.debounce,\n throttle: config?.throttle,\n replaceExisting: config?.replaceExisting ?? true,\n cleanup: config?.cleanup,\n condition: config?.condition,\n metadata: config?.metadata,\n };\n}\n\n\n/**\n * Internal handler registration container\n * \n * Contains the registered handler function along with its complete configuration\n * and unique identifier. This is used internally by ActionRegister to manage\n * the handler pipeline.\n * \n * @template T - The payload type for this handler\n * @template R - The return type for this handler\n * \n * @internal\n */\nexport interface HandlerRegistration<T = unknown, R = void> {\n /** The handler function */\n handler: ActionHandler<T, R>;\n \n /** Complete handler configuration with all defaults applied */\n config: ResolvedHandlerConfig<T>;\n \n /** Unique identifier for this handler registration */\n id: string;\n\n /**\n * Runtime execution role. Effect handlers can control flow but never add a\n * value to result collection; result and legacy handlers may do both.\n */\n role?: HandlerRole;\n}\n\n/** The lifecycle state recorded for one handler invocation. */\nexport type HandlerExecutionStatus =\n | 'running'\n | 'succeeded'\n | 'failed'\n | 'skipped'\n | 'cancelled';\n\n/**\n * Concrete outcome produced by an execution mode. Keeping this record beside\n * the executor avoids reconstructing execution metrics from cursor indexes.\n */\nexport interface HandlerExecutionOutcome<R = void> {\n id: string;\n status: HandlerExecutionStatus;\n executed: boolean;\n duration: number | undefined;\n result: R | undefined;\n error: Error | undefined;\n metadata: Record<string, unknown> | undefined;\n terminationRequested?: boolean;\n terminationResult?: R;\n}\n\n/** Controller state isolated to one concurrent handler invocation. */\nexport interface PipelineControllerState<T = unknown, R = void> {\n payload: T;\n aborted: boolean;\n abortReason: string | undefined;\n jumpToPriority: number | undefined;\n terminated: boolean;\n terminationResult: R | undefined;\n results: R[];\n}\n\n/**\n * Execution mode for action handler pipeline\n * \n * Determines how multiple handlers for the same action are executed:\n * - `sequential`: Handlers execute one after another in priority order\n * - `parallel`: All handlers execute simultaneously\n * - `race`: First handler to complete wins; other started handlers keep running\n * and remain tracked until they settle\n * \n * @example\n * ```typescript\n * // Sequential execution (default)\n * register.setActionExecutionMode('updateUser', 'sequential')\n * \n * // Parallel execution for independent operations\n * register.setActionExecutionMode('logEvent', 'parallel')\n * \n * // Race execution for fastest response\n * register.setActionExecutionMode('fetchData', 'race')\n * ```\n * \n * @public\n */\nexport type ExecutionMode = 'sequential' | 'parallel' | 'race';\n\n/**\n * Internal pipeline execution context\n * \n * Contains the state and metadata for a single action pipeline execution.\n * This includes the action payload, registered handlers, execution progress,\n * and result collection.\n * \n * @template T - The payload type for this execution\n * @template R - The result type for this execution\n * \n * @internal\n */\nexport interface PipelineContext<T = unknown, R = void> {\n /** The action name being executed */\n action: string;\n \n /** The payload for this execution */\n payload: T;\n \n /** Handlers to execute in this pipeline */\n handlers: HandlerRegistration<T, R>[];\n\n /** Registrations whose handler functions were actually invoked */\n executedHandlers?: HandlerRegistration<T, R>[];\n\n /** Outcomes recorded directly by the execution mode. */\n handlerOutcomes?: HandlerExecutionOutcome<R>[];\n\n /** Race arbitration is reported separately from loser diagnostics. */\n raceWinnerId?: string;\n raceLoserOutcomes?: HandlerExecutionOutcome<R>[];\n\n /** Defer once-handler removal to the outer retry lifecycle */\n deferOnceCleanup?: boolean;\n\n /**\n * Atomically reserve a once registration immediately before invocation.\n * A false return means another concurrent dispatch already consumed it.\n *\n * @internal\n */\n claimOnce?(registration: HandlerRegistration<T, R>): boolean;\n\n /** Effective signal shared with controllers for cooperative cancellation */\n signal?: AbortSignal;\n\n /** Track handler work that may outlive the exposed dispatch promise */\n trackHandlerPromise?<V>(promise: Promise<V>): Promise<V>;\n\n /** Errors collected from non-blocking handler execution */\n collectedErrors?: HandlerError[];\n \n /** Whether execution has been aborted */\n aborted: boolean;\n \n /** Reason for abortion if aborted */\n abortReason: string | undefined;\n \n /** Current handler index being executed */\n currentIndex: number;\n \n /** Priority level to jump to (if requested) */\n jumpToPriority: number | undefined;\n\n /** Counter for jump operations to detect potential infinite loops */\n jumpCount?: number;\n\n /** Maximum allowed jumps before aborting (to prevent infinite loops) */\n maxJumps?: number;\n\n /** Execution mode for this pipeline */\n executionMode: ExecutionMode;\n \n /** Results collected from handlers */\n results: R[];\n \n /** Whether execution was terminated early */\n terminated: boolean;\n \n /** Result from terminated execution */\n terminationResult: R | undefined;\n}\n\n/**\n * Configuration options for ActionRegister initialization\n * \n * Provides comprehensive configuration options for customizing ActionRegister\n * behavior including debugging, execution modes, and cleanup policies.\n * \n * @example Basic Configuration\n * ```typescript\n * const register = new ActionRegister<AppActions>({\n * name: 'UserActionRegister',\n * registry: {\n * debug: true,\n * defaultExecutionMode: 'sequential'\n * }\n * })\n * ```\n * \n * @example Development Configuration\n * ```typescript\n * const devRegister = new ActionRegister<AppActions>({\n * name: 'DevRegister',\n * registry: {\n * debug: true,\n * autoCleanup: true,\n * defaultExecutionMode: 'parallel'\n * }\n * })\n * ```\n * \n * @public\n */\nexport interface ActionRegisterConfig {\n /** Name identifier for this ActionRegister instance */\n name?: string;\n \n /** Registry-specific configuration options */\n registry?: {\n /** Debug mode for registry operations - enables detailed logging */\n debug?: boolean;\n\n /** Auto-cleanup configuration for one-time handlers */\n autoCleanup?: boolean;\n\n /** Default execution mode for actions */\n defaultExecutionMode?: ExecutionMode;\n\n /** Serialize independent dispatches through the optional queue. Default: false. */\n useConcurrencyQueue?: boolean;\n\n /**\n * Optional maximum number of handlers per action. Defaults to `Infinity`.\n * A configured finite limit rejects an overflowing registration instead of\n * silently dropping the handler.\n */\n maxHandlersPerAction?: number;\n\n /**\n * Maximum controller priority jumps in one dispatch. Default: 10; use\n * `Infinity` only when the caller owns a separate termination invariant.\n */\n maxJumps?: number;\n\n /** Global error handler for unhandled errors */\n errorHandler?: (error: Error, context: unknown) => void | Promise<void>;\n\n // ---- Zod Schema Validation Options (optional) ----\n\n /**\n * Action schema map for runtime payload validation\n * When provided, enables Zod-based validation on dispatch\n * @see ActionSchemaMap from '@context-action/tool-protocol'\n */\n schema?: Record<string, ActionSchemaLike>;\n\n /**\n * Enable/disable validation on dispatch\n * Default: true when schema is provided\n */\n validateOnDispatch?: boolean;\n\n /**\n * Validation mode when schema validation fails\n * - 'strict': throw ActionValidationError (default)\n * - 'warn': console.warn and continue execution\n * - 'silent': ignore validation errors silently\n */\n validationMode?: 'strict' | 'warn' | 'silent';\n };\n}\n\n/**\n * Comprehensive dispatch options for controlling action execution\n * \n * Provides fine-grained control over how actions are dispatched and executed,\n * including timing controls, handler filtering, result processing, and abort handling.\n * \n * @example Basic Dispatch Options\n * ```typescript\n * await register.dispatch('searchUsers', { query: 'john' }, {\n * debounce: 300, // Wait 300ms after last call\n * throttle: 1000, // Limit to once per second\n * executionMode: 'parallel'\n * })\n * ```\n * \n * @example Handler Filtering\n * ```typescript\n * await register.dispatch('updateUser', userData, {\n * filter: {\n * handlerIds: ['validation', 'business-logic'], // Only these handlers\n * excludeHandlerIds: ['analytics'], // Skip selected handlers\n * priority: { min: 10 } // Minimum priority\n * }\n * })\n * ```\n * \n * @example Result Collection\n * ```typescript\n * const result = await register.dispatchWithResult('processOrder', order, {\n * result: {\n * collect: true,\n * strategy: 'merge',\n * maxResults: 5,\n * merger: (results) => results.reduce((acc, curr) => ({ ...acc, ...curr }), {})\n * }\n * })\n * ```\n * \n * @example Abort Control\n * ```typescript\n * const controller = new AbortController()\n * \n * // Auto-abort with custom controller\n * await register.dispatch('longRunningTask', data, {\n * autoAbort: {\n * enabled: true,\n * allowHandlerAbort: true,\n * onControllerCreated: (ctrl) => {\n * setTimeout(() => ctrl.abort('Timeout'), 5000)\n * }\n * }\n * })\n * ```\n * \n * @public\n */\nexport interface DispatchOptions {\n /** Debounce delay in milliseconds - wait for this delay after last call */\n debounce?: number;\n \n /** Throttle delay in milliseconds - limit execution to once per this period */\n throttle?: number;\n \n /** Execution mode override for this specific dispatch */\n executionMode?: ExecutionMode;\n \n /** Abort signal for cancelling the dispatch */\n signal?: AbortSignal;\n \n /** Bypass queue and execute immediately */\n immediate?: boolean;\n \n /** Priority in dispatch queue (higher = earlier execution) */\n queuePriority?: number;\n \n /**\n * Non-negative finite wall-clock timeout in milliseconds, including queue\n * wait and retry delay. Rejects with ActionTimeoutError and aborts the\n * dispatch signal. Invalid values throw RangeError.\n */\n timeout?: number;\n \n /**\n * Retry configuration for error recovery. Retries reuse the handler\n * selection and timing settings resolved when the dispatch starts, except\n * handlers already consumed by the `once` lifecycle.\n */\n retryOnError?: {\n /** Maximum total attempts, including the initial attempt. Minimum: 1 */\n maxAttempts: number;\n /** Delay between retries in milliseconds */\n delay: number;\n /**\n * Retry boundary for work started by a race attempt. `abort-and-drain` is\n * the safe default for race; `abort-and-overlap` is an explicit opt-in for\n * idempotent/read-only handlers. Both modes abort the superseded attempt;\n * only the former waits for its started work to settle.\n */\n attemptBarrier?: 'abort-and-drain' | 'abort-and-overlap';\n };\n \n /** Auto-abort options for automatic AbortController management */\n autoAbort?: {\n /** Create and manage AbortController automatically */\n enabled: boolean;\n \n /** Provide access to the created AbortController */\n onControllerCreated?: (controller: AbortController) => void;\n \n /** Enable pipeline abort trigger from handlers */\n allowHandlerAbort?: boolean;\n };\n \n /** Handler filtering options */\n filter?: {\n /** Only execute handlers with these IDs */\n handlerIds?: string[];\n \n /** Exclude handlers with these IDs */\n excludeHandlerIds?: string[];\n \n /** Priority-based filtering */\n priority?: {\n /** Minimum priority threshold */\n min?: number;\n /** Maximum priority threshold */\n max?: number;\n };\n \n /** Custom filter function. Receives an immutable config snapshot. */\n custom?: (config: Readonly<ResolvedHandlerConfig>) => boolean;\n };\n \n /** Result collection and processing options */\n result?: {\n /** How to handle multiple results. In parallel mode, results follow priority order. */\n strategy?: 'first' | 'last' | 'all' | 'merge' | 'custom';\n \n /** Custom result merger function (used with 'merge' or 'custom' strategy) */\n merger?: <R>(results: Array<R | undefined>) => R;\n \n /** Whether to collect results from all handlers */\n collect?: boolean;\n \n /** Maximum number of results to aggregate. A value of 0 produces no aggregated results. */\n maxResults?: number;\n \n /** @deprecated Errors are always exposed through ExecutionResult.errors and failedResults. */\n includeErrors?: boolean;\n };\n}\n\n/**\n * Comprehensive result of pipeline execution with detailed execution information\n * \n * Contains complete information about the pipeline execution including success status,\n * results, handler details, and any errors that occurred.\n * \n * @template R - The result type for this execution\n * \n * @example Basic Result Handling\n * ```typescript\n * const result = await register.dispatchWithResult('updateUser', userData)\n * \n * if (result.success) {\n * console.log(`Execution completed in ${result.execution.duration}ms`)\n * console.log(`${result.execution.handlersExecuted} handlers executed`)\n * } else {\n * console.error('Execution failed:', result.abortReason)\n * }\n * ```\n * \n * @example Advanced Result Processing\n * ```typescript\n * const result = await register.dispatchWithResult('processOrder', order, {\n * result: { collect: true, strategy: 'all' }\n * })\n * \n * // Access all handler results - now properly typed\n * result.successResults.forEach((handlerResult, index) => {\n * console.log(`Handler ${index} result:`, handlerResult)\n * })\n * \n * // Check individual handler performance\n * result.handlers.forEach(handler => {\n * if (handler.duration && handler.duration > 1000) {\n * console.warn(`Slow handler ${handler.id}: ${handler.duration}ms`)\n * }\n * })\n * ```\n * \n * @public\n */\nexport interface ExecutionResult<R = void> {\n /** Whether the execution completed successfully */\n success: boolean;\n \n /** Whether caller or pipeline cancellation aborted the execution */\n aborted: boolean;\n \n /** Reason for abortion if aborted */\n abortReason: string | undefined;\n \n /** Whether the execution was terminated early via controller.return() */\n terminated: boolean;\n\n /** High-level terminal state, including timing-guard rejections. */\n outcome: 'completed' | 'completed_with_errors' | 'failed' | 'cancelled' | 'debounced' | 'throttled';\n\n /** Runtime payload validation outcome when a schema was configured */\n validation?: {\n passed: boolean;\n errors: string[];\n };\n \n /** Final result based on result strategy - only present for non-void results */\n result: R | R[] | undefined;\n \n /** ๐ง Type safety fix: Separate successful results from failed ones */\n /** All successful handler results (guaranteed non-undefined) */\n successResults: R[];\n \n /** All handler results including undefined from failed handlers (legacy compatibility) */\n results: Array<R | undefined>;\n \n /** Failed handler results with error context */\n failedResults: Array<{\n handlerId: string;\n error: Error;\n /** @deprecated Runtime execution cannot infer the TypeScript result type. */\n expectedType: string;\n }>;\n \n /** Execution metadata */\n execution: {\n /** Total canonical dispatch duration in milliseconds, including admission\n * and queue wait. Awaited observer notification time is intentionally\n * excluded because observers cannot alter the terminal result. */\n duration: number;\n\n /** Validation and timing-guard admission duration in milliseconds. */\n admissionDuration: number;\n\n /** Time spent waiting in the dispatch queue in milliseconds. */\n queueWaitDuration: number;\n\n /** Handler pipeline duration in milliseconds. */\n pipelineDuration: number;\n\n /** Backoff time consumed between whole-action retry attempts. */\n retryDelayDuration?: number;\n\n /** Time spent aggregating raw handler values into the public result. */\n resultProcessingDuration?: number;\n\n /** Per-attempt pipeline timing, including attempts that are retried. */\n attempts?: Array<{\n startTime: number;\n endTime: number;\n duration: number;\n outcome: 'succeeded' | 'failed' | 'retried' | 'cancelled';\n }>;\n \n /** Number of handlers that were executed */\n handlersExecuted: number;\n \n /** Number of handlers that were skipped */\n handlersSkipped: number;\n \n /** Number of handlers that failed */\n handlersFailed: number;\n \n /** Execution start timestamp */\n startTime: number;\n \n /** Execution end timestamp */\n endTime: number;\n };\n \n /** Detailed information about each handler */\n handlers: Array<{\n /** Handler unique identifier */\n id: string;\n \n /** Whether this handler was executed */\n executed: boolean;\n\n /** Final lifecycle state observed for this handler */\n status: HandlerExecutionStatus;\n \n /** Handler execution duration in milliseconds (only present if executed) */\n duration: number | undefined;\n \n /** Result returned by this handler - properly typed for success/failure */\n result: R | undefined;\n \n /** Error thrown by this handler if any */\n error: Error | undefined;\n \n /** Custom metadata for this handler */\n metadata: Record<string, unknown> | undefined;\n }>;\n\n /** Race-only snapshots. Loser failures never change the winner contract. */\n raceDiagnostics?: {\n winnerId?: string;\n /** Immutable winner outcome captured at dispatch return. */\n winner?: HandlerExecutionOutcome<R>;\n loserSnapshots: Array<HandlerExecutionOutcome<R>>;\n /** Losers still running when the canonical winner result was returned. */\n pendingLosersAtReturn: number;\n /** Failed losers observable at that same snapshot point. */\n observedLoserFailures: number;\n };\n \n /** Errors that occurred during execution */\n errors: HandlerError[];\n}\n\n/**\n * Handler error information for unified error handling\n * \n * @public\n */\nexport interface HandlerError {\n handlerId: string;\n error: Error;\n timestamp: number;\n severity: 'blocking' | 'non-blocking';\n}\n\n/**\n * Function type for unregistering action handlers\n * \n * Returned by the register method to allow removal of specific handlers.\n * Calling this function removes the handler from the action pipeline.\n * \n * @example\n * ```typescript\n * const unregister = register.register('updateUser', userHandler)\n * \n * // Later, remove the handler\n * unregister()\n * ```\n * \n * @public\n */\nexport type UnregisterFunction = () => void;\n\n/**\n * Helper types for better ActionDispatcher type safety\n */\nexport type VoidActions<T extends ActionPayloadMap> = {\n // biome-ignore lint/suspicious/noConfusingVoidType: void is the public no-payload marker.\n [K in keyof T]: [T[K]] extends [void] ? K : never\n}[keyof T];\n\nexport type PayloadActions<T extends ActionPayloadMap> = {\n // biome-ignore lint/suspicious/noConfusingVoidType: void is the public no-payload marker.\n [K in keyof T]: [T[K]] extends [void] ? never : K\n}[keyof T];\n\n/**\n * Arguments accepted by a dispatch method for a single action payload.\n * Payload-bearing actions must provide their payload; void actions may omit it.\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: void is the public no-payload marker.\nexport type DispatchArgs<P> = [P] extends [void]\n ? [payload?: undefined, options?: DispatchOptions]\n : [payload: P, options?: DispatchOptions];\n\n/** Property names reserved by the callable action proxy protocol. */\nexport type ReservedActionKey =\n | 'then'\n | 'catch'\n | 'finally'\n | 'toJSON'\n | 'constructor'\n | '__proto__'\n | 'prototype';\n\n/** Action keys that can be exposed through `register.actions` proxies. */\nexport type ProxyActionKey<T extends ActionPayloadMap> = Exclude<ActionNames<T>, ReservedActionKey>;\n\n/**\n * Type-safe dispatchWithResult interface\n * \n * Provides type-safe method overloads for dispatchWithResult operations\n * that maintain payload type checking while returning ExecutionResult.\n * \n * @template T - The action payload map interface\n */\n/** Dispatch an action with the payload contract defined by its action key. */\nexport type ActionDispatcherWithResult<\n T extends ActionPayloadMap,\n TResultMap extends ActionResultMap<T> = {},\n> = <\n K extends ActionNames<T>,\n R = ActionResult<TResultMap, K>\n>(action: K, ...args: DispatchArgs<T[K]>) => Promise<ExecutionResult<R>>;\n\n/**\n * Type-safe action dispatcher interface\n * \n * Provides overloaded dispatch methods that enforce correct payload types\n * based on the action being dispatched. Automatically handles actions\n * that require no payload versus those that do.\n * \n * @template T - The action payload map interface\n * \n * @example\n * ```typescript\n * interface AppActions extends ActionPayloadMap {\n * resetApp: void\n * updateUser: { id: string; name: string }\n * }\n * \n * const dispatch: ActionDispatcher<AppActions> = register.dispatch.bind(register)\n * \n * // No payload required - type-checked\n * await dispatch('resetApp')\n * \n * // Payload required and type-checked\n * await dispatch('updateUser', { id: '123', name: 'John' })\n * ```\n * \n * @public\n */\n/** Dispatch an action with the payload contract defined by its action key. */\nexport type ActionDispatcher<T extends ActionPayloadMap> = <K extends ActionNames<T>>(\n action: K,\n ...args: DispatchArgs<T[K]>\n) => Promise<void>;\n\n/**\n * Registry information interface for ActionRegister introspection\n * \n * Provides comprehensive information about the current state of an ActionRegister\n * instance, including registered actions, handler counts, and execution modes.\n * Similar to DeclarativeStoreRegistry pattern for consistent registry management.\n * \n * @template T - The action payload map interface\n * \n * @example\n * ```typescript\n * const info = register.getRegistryInfo()\n * \n * console.log(`Registry: ${info.name}`)\n * console.log(`Total actions: ${info.totalActions}`)\n * console.log(`Total handlers: ${info.totalHandlers}`)\n * console.log(`Registered actions:`, info.registeredActions)\n * ```\n * \n * @public\n */\nexport interface ActionRegistryInfo<T extends ActionPayloadMap> {\n /** Registry name */\n name: string;\n \n /** Total number of registered actions */\n totalActions: number;\n \n /** Total number of registered handlers across all actions */\n totalHandlers: number;\n \n /** List of all registered actions */\n registeredActions: Array<keyof T>;\n \n /** Execution mode settings per action */\n actionExecutionModes: Map<keyof T, ExecutionMode>;\n \n /** Default execution mode */\n defaultExecutionMode: ExecutionMode;\n}\n\n/**\n * Handler statistics interface for registry monitoring and debugging\n * \n * Provides detailed statistics about handlers for a specific action,\n * including handler organization and basic execution data.\n * \n * @template T - The action payload map interface\n * \n * @example\n * ```typescript\n * const stats = register.getActionStats('updateUser')\n * \n * if (stats) {\n * console.log(`Action: ${stats.action}`)\n * console.log(`Handler count: ${stats.handlerCount}`)\n * \n * stats.handlersByPriority.forEach(group => {\n * console.log(`Priority ${group.priority}:`, group.handlers.length, 'handlers')\n * })\n * \n * if (stats.executionStats) {\n * console.log(`Success rate: ${stats.executionStats.successRate}%`)\n * console.log(`Average duration: ${stats.executionStats.averageDuration}ms`)\n * }\n * }\n * ```\n * \n * @public\n */\nexport interface ActionHandlerStats<T extends ActionPayloadMap> {\n /** Action name */\n action: keyof T;\n \n /** Number of handlers for this action */\n handlerCount: number;\n \n /** Total number of handlers for this action (alias for handlerCount) */\n totalHandlers: number;\n \n /** When the last handler was registered */\n lastRegistered?: Date;\n \n /** Handler configurations grouped by priority */\n handlersByPriority: Array<{\n priority: number;\n handlers: Array<{\n id: string;\n }>;\n }>;\n \n /** Execution statistics - removed in favor of simplified architecture */\n executionStats?: undefined;\n}\n","// biome-ignore-all lint/suspicious/noExplicitAny: heterogeneous runtime pipeline storage.\n\nimport { ActionGuard } from './action-guard.js';\nimport { OperationQueue } from './concurrency/OperationQueue.js';\nimport {\n ActionAttemptSupersededError,\n ActionRegisterDestroyedError,\n ActionResultProcessingError,\n ActionTimeoutError,\n ActionValidationError,\n} from './errors.js';\nimport { executeParallel, executeRace, executeSequential } from './execution-modes.js';\nimport {\n ActionHandler,\n ActionEffectHandler,\n EffectConfig,\n ActionGuardHandler,\n ActionObserverEvent,\n ActionObserverHandler,\n ActionNames,\n ActionHandlerStats,\n ActionPayloadMap,\n ActionRegisterConfig,\n ActionRegistryInfo,\n ActionResult,\n ActionResultHandler,\n ActionResultMap,\n DispatchArgs,\n DispatchOptions,\n ExecutionMode,\n ExecutionResult,\n HandlerConfig,\n GuardConfig,\n HandlerError,\n HandlerExecutionOutcome,\n HandlerRegistration,\n HandlerRole,\n ObserverConfig,\n PipelineContext,\n PipelineController,\n PipelineControllerState,\n ProxyActionKey,\n ReservedActionKey,\n resolveHandlerConfig,\n UnregisterFunction,\n} from './types.js';\n\ntype DispatchHandlerPromises = Set<Promise<unknown>>;\n\ntype RetryTelemetry = {\n pipelineDuration: number;\n retryDelayDuration: number;\n attempts: NonNullable<ExecutionResult<unknown>['execution']['attempts']>;\n};\n\ntype TimingGuardAdmission = {\n reason?: 'Debounced execution' | 'Throttled execution';\n aborted: boolean;\n};\n\ntype GuardPhaseResult<T> = {\n allowed: boolean;\n payload: T;\n aborted: boolean;\n abortReason: string | undefined;\n error: Error | undefined;\n errors: HandlerError[];\n outcomes: HandlerExecutionOutcome<unknown>[];\n executedHandlers: HandlerRegistration<any, any>[];\n duration: number;\n};\n\n/** Immutable handler selection and scheduling decisions for one dispatch. */\ntype DispatchPlan = {\n pipelineSnapshot: readonly HandlerRegistration<any, any>[];\n /** Selected registrations, retained for admission metrics and compatibility. */\n eligibleHandlers: readonly HandlerRegistration<any, any>[];\n guards: readonly HandlerRegistration<any, any>[];\n results: readonly HandlerRegistration<any, any>[];\n observers: readonly HandlerRegistration<any, any>[];\n debounceMs?: number;\n throttleMs?: number;\n executionMode: ExecutionMode;\n};\n\nconst RESERVED_PROXY_KEYS = new Set<ReservedActionKey>([\n 'then',\n 'catch',\n 'finally',\n 'toJSON',\n 'constructor',\n '__proto__',\n 'prototype',\n]);\nconst ATTEMPT_SIGNAL_CLEANUP = Symbol('attemptSignalCleanup');\ntype AttemptDispatchOptions = DispatchOptions & {\n [ATTEMPT_SIGNAL_CLEANUP]?: () => void;\n};\n\nfunction snapshotHandlerOutcome<R>(outcome: HandlerExecutionOutcome<R>): HandlerExecutionOutcome<R> {\n return {\n ...outcome,\n metadata: outcome.metadata ? { ...outcome.metadata } : undefined,\n };\n}\n\nfunction normalizePositiveLimit(\n value: number | undefined,\n fallback: number,\n label: string,\n): number {\n const limit = value ?? fallback;\n if (limit === Infinity) return limit;\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new RangeError(`${label} must be a positive safe integer or Infinity.`);\n }\n return limit;\n}\n\n/**\n * Action Register for managing action handlers with priority-based execution\n * \n * Central action registration and dispatch system providing type-safe action pipeline management.\n * Supports sequential, parallel, and race execution modes with advanced handler filtering,\n * throttling, debouncing, and comprehensive result collection.\n * \n * @template TActionMap - Action payload mapping interface extending ActionPayloadMap\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/\n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/register-delegation\n * \n * @public\n */\n\nexport class ActionRegister<\n T extends ActionPayloadMap = Record<string, unknown>,\n TResultMap extends ActionResultMap<T> = {},\n> {\n private pipelines = new Map<keyof T, Array<HandlerRegistration<any, any>>>();\n /** Observer callbacks are intentionally stored outside the executable\n * pipeline so they cannot participate in result arbitration. */\n private readonly observerHandlers = new Map<\n HandlerRegistration<any, any>,\n { handler: ActionObserverHandler<any, any>; when: 'success' | 'failure' | 'always' }\n >();\n /** A once handler is removed from the registry before its callback starts.\n * Keep its claim separately so resource cleanup can still run on settlement. */\n private readonly claimedOnceHandlers = new WeakSet<HandlerRegistration<any, any>>();\n private readonly actionGuard: ActionGuard;\n private executionMode: ExecutionMode = 'sequential';\n private actionExecutionModes = new Map<keyof T, ExecutionMode>();\n \n // ๐ Advanced unregister function management system\n private unregisterFunctions = new Map<keyof T, Map<string, UnregisterFunction>>();\n\n // ๐ง Fix: Track last registration timestamps for getActionStats\n private lastRegisteredTimestamps = new Map<keyof T, Date>();\n \n public readonly name: string;\n private readonly registryConfig: ActionRegisterConfig['registry'];\n\n // ๐ Performance optimizations\n private readonly isDebugMode: boolean;\n private readonly maxHandlersPerAction: number;\n private readonly maxJumps: number;\n\n // ๐ ๋์์ฑ ๋ฌธ์ ํด๊ฒฐ์ ์ํ ํ ์์คํ
(conditional)\n private dispatchQueue?: OperationQueue;\n\n // ๐ง Performance optimization: Fast handler ID generation counter\n private handlerIdCounter = 0;\n\n // ๐ง Performance optimization: PipelineController pool for object reuse\n\n private lifecycleState: 'active' | 'closing' | 'destroyed' = 'active';\n private readonly lifecycleController = new AbortController();\n private readonly activeDispatches = new Set<Promise<unknown>>();\n private readonly activeHandlerPromises = new Set<Promise<unknown>>();\n private destroyAsyncPromise: Promise<void> | undefined;\n private dispatchConstructionDepth = 0;\n\n // ๐ง Performance optimization: Cached Proxy instances for actions getters\n private _actionsProxy?: {\n [K in ProxyActionKey<T>]: (...args: DispatchArgs<T[K]>) => Promise<void>\n };\n private _actionsWithResultProxy?: {\n [K in ProxyActionKey<T>]: (...args: DispatchArgs<T[K]>) => Promise<ExecutionResult<ActionResult<TResultMap, K>>>\n };\n private readonly actionDispatchers = new Map<\n PropertyKey,\n (...args: any[]) => Promise<unknown>\n >();\n private readonly actionResultDispatchers = new Map<\n PropertyKey,\n (...args: any[]) => Promise<unknown>\n >();\n\n constructor(config: ActionRegisterConfig = {}) {\n this.name = config.name || 'ActionRegister';\n this.registryConfig = config.registry;\n this.maxHandlersPerAction = normalizePositiveLimit(\n config.registry?.maxHandlersPerAction,\n Infinity,\n 'maxHandlersPerAction',\n );\n this.maxJumps = normalizePositiveLimit(\n config.registry?.maxJumps,\n 10,\n 'maxJumps',\n );\n this.isDebugMode = this.registryConfig?.debug === true;\n \n // Guard creation with improved cleanup handling\n this.actionGuard = new ActionGuard(this.registryConfig?.autoCleanup !== false);\n \n // ๐ Conditional queue system initialization\n if (config.registry?.useConcurrencyQueue === true) {\n this.dispatchQueue = new OperationQueue(`${this.name}-Dispatch`);\n }\n \n if (this.registryConfig?.defaultExecutionMode) {\n this.executionMode = this.registryConfig.defaultExecutionMode;\n }\n \n this.log('ActionRegister initialized', {\n defaultExecutionMode: this.executionMode,\n autoCleanup: this.registryConfig?.autoCleanup !== false,\n concurrencyQueue: Boolean(this.dispatchQueue),\n debugMode: this.isDebugMode\n });\n }\n\n /**\n * ๐ Action-based dispatcher\n *\n * Provides function-based access to actions for more convenient dispatching.\n * Each action becomes a callable function that can be invoked directly.\n *\n * @example\n * ```typescript\n * interface MyActions extends ActionPayloadMap {\n * userLogin: { userId: string; email: string };\n * resetApp: void;\n * }\n * \n * const registry = new ActionRegister<MyActions>();\n * \n * // Function-based dispatching\n * await registry.actions.userLogin({ userId: '123', email: 'test@example.com' });\n * await registry.actions.resetApp();\n * await registry.actions.resetApp(undefined, { debounce: 100 });\n * ```\n * \n * @public\n */\n get actions(): {\n [K in ProxyActionKey<T>]: (...args: DispatchArgs<T[K]>) => Promise<void>\n } {\n // ๐ง Performance: Return cached Proxy instance\n if (!this._actionsProxy) {\n this._actionsProxy = new Proxy({} as any, {\n get: (_target, prop: string | symbol) => {\n if (typeof prop !== 'string') return undefined;\n if (RESERVED_PROXY_KEYS.has(prop as ReservedActionKey)) return undefined;\n const actionKey = prop as ProxyActionKey<T>;\n\n let dispatcher = this.actionDispatchers.get(prop);\n if (!dispatcher) {\n dispatcher = (payload?: T[typeof actionKey], options?: DispatchOptions) =>\n this.dispatch(\n actionKey,\n ...( [payload, options] as DispatchArgs<T[typeof actionKey]> )\n );\n this.actionDispatchers.set(prop, dispatcher);\n }\n return dispatcher;\n }\n });\n }\n return this._actionsProxy!;\n }\n\n /**\n * Actions-based dispatching with result collection\n * \n * Provides a function-based interface for dispatching actions with detailed execution results.\n * Each registered action becomes a callable function that returns ExecutionResult.\n * \n * @example\n * ```typescript\n * // Actions with payload\n * const result = await registry.actionsWithResult.userLogin({ userId: '123', email: 'user@example.com' });\n * \n * // Actions without payload\n * const result = await registry.actionsWithResult.userLogout();\n * const debouncedResult = await registry.actionsWithResult.userLogout(\n * undefined,\n * { debounce: 100 }\n * );\n * \n * // With options\n * const result = await registry.actionsWithResult.processData(\n * { data: { name: 'test' }, type: 'json' },\n * { executionMode: 'parallel' }\n * );\n * ```\n * \n * @returns Proxy object with action functions that return ExecutionResult\n */\n get actionsWithResult(): {\n [K in ProxyActionKey<T>]: (...args: DispatchArgs<T[K]>) => Promise<ExecutionResult<ActionResult<TResultMap, K>>>\n } {\n // ๐ง Performance: Return cached Proxy instance\n if (!this._actionsWithResultProxy) {\n this._actionsWithResultProxy = new Proxy({} as any, {\n get: (_target, prop: string | symbol) => {\n if (typeof prop !== 'string') return undefined;\n if (RESERVED_PROXY_KEYS.has(prop as ReservedActionKey)) return undefined;\n const actionKey = prop as ProxyActionKey<T>;\n\n let dispatcher = this.actionResultDispatchers.get(prop);\n if (!dispatcher) {\n const dispatchAction = this.dispatchWithResult.bind(this) as (\n action: ProxyActionKey<T>,\n ...args: DispatchArgs<T[ProxyActionKey<T>]>\n ) => Promise<ExecutionResult<unknown>>;\n dispatcher = (payload?: T[typeof actionKey], options?: DispatchOptions) =>\n dispatchAction(\n actionKey,\n ...( [payload, options] as DispatchArgs<T[typeof actionKey]> )\n );\n this.actionResultDispatchers.set(prop, dispatcher);\n }\n return dispatcher;\n }\n });\n }\n return this._actionsWithResultProxy!;\n }\n\n /**\n * Register an action handler with optional configuration\n * \n * @param action - The action type to register handler for\n * @param handler - The handler function to execute\n * @param config - Optional handler configuration including priority, timing, and lifecycle options.\n * \n * @returns Unregister function to remove this handler\n * \n * @throws {Error} When maximum handlers limit is reached\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n register<K extends ActionNames<T> & keyof TResultMap>(\n action: K,\n handler: ActionResultHandler<T[K], ActionResult<TResultMap, K>>,\n config?: HandlerConfig<T[K]>\n ): UnregisterFunction;\n register<K extends Exclude<ActionNames<T>, keyof TResultMap>, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config?: HandlerConfig<T[K]>\n ): UnregisterFunction;\n register<K extends ActionNames<T>, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config: HandlerConfig<T[K]> = {}\n ): UnregisterFunction {\n return this.registerWithRole(action, handler, config, 'legacy');\n }\n\n /**\n * Register a side-effect-only handler in an explicit guard or observer\n * phase. This is a supported 1.x compatibility convenience for callers\n * that configure the phase dynamically.\n *\n * Prefer `registerGuard()` for admission and `registerObserver()` for a\n * statically known post-result effect. `effectKind` remains required so this\n * API cannot participate in result arbitration implicitly.\n * @public\n */\n registerEffect<K extends ActionNames<T>>(\n action: K,\n handler: ActionGuardHandler<T[K]>,\n config: EffectConfig<T[K]> & { effectKind: 'guard' },\n ): UnregisterFunction;\n registerEffect<K extends ActionNames<T>>(\n action: K,\n handler: ActionEffectHandler<T[K]>,\n config: EffectConfig<T[K]> & { effectKind: 'observer' },\n ): UnregisterFunction;\n registerEffect<K extends ActionNames<T>>(\n action: K,\n handler: ActionEffectHandler<T[K]> | ActionGuardHandler<T[K]>,\n config: EffectConfig<T[K]>,\n ): UnregisterFunction {\n if (config.effectKind === 'guard') {\n return this.registerGuard(action, handler as ActionGuardHandler<T[K]>, config);\n }\n return this.registerObserver(action, event => (handler as ActionEffectHandler<T[K]>)(event.payload as T[K], {\n signal: event.signal,\n getPayload: () => event.payload as T[K],\n }), config);\n }\n\n /** Register an authorization or validation guard that always runs before\n * concurrent result arbitration. */\n registerGuard<K extends ActionNames<T>>(\n action: K,\n handler: ActionGuardHandler<T[K]>,\n config: GuardConfig<T[K]> = {},\n ): UnregisterFunction {\n // Runtime callers can still pass an unsafe cast or plain JavaScript\n // configuration. Admission must never become fail-open as a result.\n return this.registerWithRole(action, handler as ActionHandler<T[K], void>, {\n ...config,\n scheduling: 'await-before-next',\n errorPolicy: 'fatal',\n }, 'guard');\n }\n\n /** Register a terminal observer. It runs after result aggregation and has\n * no controller, result, payload, or winner-selection capabilities. */\n registerObserver<\n K extends ActionNames<T>,\n R = ActionResult<TResultMap, K>,\n H extends (event: ActionObserverEvent<T[K], R>) => unknown = ActionObserverHandler<T[K], R>,\n >(\n action: K,\n handler: H & (ReturnType<H> extends void | Promise<void> ? unknown : never),\n config: ObserverConfig<T[K]> = {},\n ): UnregisterFunction {\n const handlerId = config.id ?? this.generateHandlerId(action);\n const existing = this.pipelines.get(action)?.find(item => item.id === handlerId);\n if (existing && (existing.role ?? 'legacy') !== 'observer') {\n throw new Error(\n `Action handler role conflict for \"${String(action)}\" and id \"${handlerId}\": `\n + `cannot replace ${(existing.role ?? 'legacy')} with observer.`,\n );\n }\n // A duplicate observer must not acquire ownership of another registration\n // (or overwrite its callback) when replacement was explicitly disabled.\n if (existing && config.replaceExisting === false) return () => {};\n const unregister = this.registerWithRole(\n action,\n (() => undefined) as ActionHandler<T[K], void>,\n { ...config, id: handlerId },\n 'observer',\n );\n const registration = this.pipelines.get(action)?.find(item => item.id === handlerId);\n if (!registration) {\n unregister();\n throw new Error(`Observer registration \"${handlerId}\" was not retained.`);\n }\n this.observerHandlers.set(registration, {\n handler: handler as ActionObserverHandler<any, any>,\n when: config.when ?? 'always',\n });\n return () => {\n this.observerHandlers.delete(registration);\n unregister();\n };\n }\n\n /**\n * Register a handler that contributes the result declared for an action.\n *\n * @public\n */\n registerResult<K extends ActionNames<T> & keyof TResultMap>(\n action: K,\n handler: ActionResultHandler<T[K], ActionResult<TResultMap, K>>,\n config?: HandlerConfig<T[K]>,\n ): UnregisterFunction {\n return this.registerWithRole(\n action,\n handler as ActionHandler<T[K], ActionResult<TResultMap, K>>,\n config ?? {},\n 'result',\n );\n }\n\n private registerWithRole<K extends keyof T, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config: HandlerConfig<T[K]>,\n role: HandlerRole,\n ): UnregisterFunction {\n this.assertStringActionKey(action);\n this.assertAcceptingWork();\n const handlerId = config.id || this.generateHandlerId(action);\n return this._performRegistrationSync(action, handler, config, handlerId, role);\n }\n\n /**\n * ๐ Unified logging method with cached debug mode check\n */\n private log(message: string, data?: unknown, level: 'log' | 'warn' | 'error' = 'log') {\n if (this.isDebugMode) {\n const timestamp = new Date().toISOString();\n console[level](`๐ฏ [${timestamp}] [${this.name}] ${message}`, data || '');\n }\n }\n\n private assertAcceptingWork(): void {\n if (this.lifecycleState !== 'active') {\n throw new ActionRegisterDestroyedError(this.name, this.lifecycleState);\n }\n }\n\n private assertStringActionKey(action: PropertyKey): void {\n if (typeof action !== 'string') {\n throw new TypeError('Action keys must be strings.');\n }\n }\n\n private rejectedLifecyclePromise<R>(): Promise<R> {\n const error = new ActionRegisterDestroyedError(\n this.name,\n this.lifecycleState === 'active' ? 'destroyed' : this.lifecycleState\n );\n const rejected = Promise.reject<R>(error);\n void rejected.catch(() => {});\n return rejected;\n }\n\n /**\n * ๐ง Generate unique handler ID using optimized counter-based approach\n */\n private generateHandlerId<K extends keyof T>(action: K): string {\n // ๐ง Performance: Use simple counter instead of crypto.randomUUID()\n // This is safe for single-process apps and ~70% faster\n return `${String(action)}_${this.name}_${++this.handlerIdCounter}`;\n }\n\n /**\n * ๐ง Create and merge AbortSignal instances with proper cleanup\n * \n * @param options Dispatch options containing signal and autoAbort configuration\n * @returns [effectiveSignal, autoAbortController, cleanupFunction]\n */\n private createAbortSignal(options?: DispatchOptions): [\n AbortSignal | undefined, \n AbortController | undefined, \n () => void\n ] {\n const signals: AbortSignal[] = [];\n const cleanups: (() => void)[] = [];\n let autoAbortController: AbortController | undefined;\n\n // Add existing signal if provided\n if (options?.signal) {\n signals.push(options.signal);\n }\n\n // Create auto-abort controller if enabled\n if (options?.autoAbort?.enabled) {\n autoAbortController = new AbortController();\n signals.push(autoAbortController.signal);\n }\n\n // No signals to merge\n if (signals.length === 0) {\n return [undefined, autoAbortController, () => {}];\n }\n\n // Single signal - no merge needed\n if (signals.length === 1) {\n return [signals[0], autoAbortController, () => cleanups.forEach(c => c())];\n }\n\n // Multiple signals - use AbortSignal.any() if available, fallback to manual merge\n let effectiveSignal: AbortSignal;\n \n if (typeof (AbortSignal as any).any === 'function') {\n // Modern browsers with AbortSignal.any()\n effectiveSignal = (AbortSignal as any).any(signals);\n } else {\n // Fallback: Create controller and link all signals\n const mergedController = new AbortController();\n effectiveSignal = mergedController.signal;\n \n signals.forEach(signal => {\n if (signal.aborted) {\n mergedController.abort();\n } else {\n const abortHandler = () => mergedController.abort();\n signal.addEventListener('abort', abortHandler, { once: true });\n cleanups.push(() => signal.removeEventListener('abort', abortHandler));\n }\n });\n }\n\n const cleanup = () => {\n cleanups.forEach(c => {\n try {\n c();\n } catch (error) {\n this.log('Cleanup error during AbortSignal cleanup', error, 'warn');\n }\n });\n };\n\n return [effectiveSignal, autoAbortController, cleanup];\n }\n\n /**\n * ๐ Perform synchronous handler registration\n */\n private _performRegistrationSync<K extends keyof T, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config: HandlerConfig<T[K]>,\n handlerId: string,\n role: HandlerRole = 'legacy',\n ): UnregisterFunction {\n // Create handler registration with defaults\n const registration: HandlerRegistration<T[K], R> = {\n handler,\n config: resolveHandlerConfig(config, handlerId),\n id: handlerId,\n role,\n };\n \n // Initialize pipeline if it doesn't exist\n if (!this.pipelines.has(action)) {\n this.pipelines.set(action, []);\n }\n\n const pipeline = this.pipelines.get(action)!;\n const actionUnregisterFunctions = this.getUnregisterFunctions(action);\n \n const existingIndex = pipeline.findIndex(reg => reg.id === handlerId);\n\n // Replacement keeps the pipeline size stable. Apply a finite limit only\n // when the registration would add a distinct handler.\n if (existingIndex === -1 && pipeline.length >= this.maxHandlersPerAction) {\n throw new RangeError(\n `Handler limit (${this.maxHandlersPerAction}) reached for action \"${String(action)}\".`,\n );\n }\n\n // ๐ Enhanced duplicate ID handling with replaceExisting support and cleanup\n if (existingIndex !== -1) {\n const existing = pipeline[existingIndex];\n const existingUnregister = actionUnregisterFunctions.get(handlerId);\n\n if (existing && (existing.role ?? 'legacy') !== role) {\n throw new Error(\n `Action handler role conflict for \"${String(action)}\" and id \"${handlerId}\": `\n + `cannot replace ${(existing.role ?? 'legacy')} with ${role}.`,\n );\n }\n \n if (registration.config.replaceExisting) {\n // ๐ง Fix: Clean up existing handler properly without removing from pipeline\n\n // Call cleanup if available on the old handler\n if (existing?.config.cleanup && typeof existing.config.cleanup === 'function') {\n try {\n existing.config.cleanup();\n } catch (cleanupError) {\n this.log(`Cleanup error for replaced handler: ${String(action)}`, cleanupError, 'warn');\n }\n }\n if (existing) this.observerHandlers.delete(existing);\n\n // Clean up existing unregister function\n if (existingUnregister) {\n actionUnregisterFunctions.delete(handlerId);\n }\n\n // Replace existing handler directly in pipeline\n pipeline[existingIndex] = registration;\n pipeline.sort((a, b) => b.config.priority - a.config.priority);\n // Cache disabled\n\n // ๐ง Fix: Update last registered timestamp when replacing\n this.lastRegisteredTimestamps.set(action, new Date());\n\n // Create new unregister function and store it\n const newUnregister = this.createUnregisterFunction(action, handlerId, registration);\n actionUnregisterFunctions.set(handlerId, newUnregister);\n \n this.log(`Handler replaced: ${String(action)}`, {\n handlerId,\n priority: config.priority,\n totalHandlers: pipeline.length,\n hadExistingUnregister: Boolean(existingUnregister)\n });\n \n return newUnregister;\n } else {\n // The rejected registration does not own the existing handler. Returning\n // its unregister function would let the rejected caller tear down a\n // registration created by somebody else.\n if (!existing) {\n throw new Error('Internal error: existing handler should be defined in duplicate handler block');\n }\n \n this.log(`Handler duplicate ignored, returning no-op unregister: ${String(action)}`, {\n handlerId,\n existingPriority: existing.config.priority,\n newPriority: config.priority,\n existingBlocking: existing.config.blocking,\n newBlocking: config.blocking,\n note: 'Use replaceExisting:true to replace'\n }, 'warn');\n \n return () => {};\n }\n }\n \n // Add handler to pipeline\n pipeline.push(registration);\n pipeline.sort((a, b) => b.config.priority - a.config.priority);\n // Cache disabled\n\n // ๐ง Fix: Update last registered timestamp\n this.lastRegisteredTimestamps.set(action, new Date());\n\n // Create and store unregister function\n const unregister = this.createUnregisterFunction(action, handlerId, registration);\n actionUnregisterFunctions.set(handlerId, unregister);\n\n this.log(`Handler registered: ${String(action)}`, {\n handlerId,\n priority: config.priority,\n totalHandlers: pipeline.length\n });\n\n return unregister;\n }\n\n\n /**\n * Dispatch an action with optional execution options\n * \n * @param action - The action type to dispatch\n * @param args - The payload/options tuple for the selected action: payload-bearing actions require a payload, while void actions may omit it; dispatch options are optional.\n * \n * @returns Promise that resolves when all handlers complete\n * \n * @throws {Error} When action dispatching fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n // Overload for actions with payload (more specific)\n dispatch<K extends ActionNames<T>>(action: K, ...args: DispatchArgs<T[K]>): Promise<void>;\n \n // Implementation (least specific)\n dispatch<K extends ActionNames<T>>(action: K, ...args: DispatchArgs<T[K]>): Promise<void> {\n this.assertStringActionKey(action);\n const [payload, options] = args as [T[K] | undefined, DispatchOptions | undefined];\n if (this.lifecycleState !== 'active') {\n return this.rejectedLifecyclePromise<void>();\n }\n\n const timeoutScope = this.createTimeoutScope(action, options);\n const dispatchHandlerPromises: DispatchHandlerPromises = new Set();\n const attemptState = { count: 0 };\n const plan = this.resolveDispatchPlan(action, options);\n const hasTimingGuard = plan.debounceMs !== undefined || plan.throttleMs !== undefined;\n const notifiedObservers = new Set<HandlerRegistration<any, any>>();\n const notifiedObserverOutcomes = new Set<ActionObserverEvent<T[K], unknown>['outcome']>();\n let terminalErrorReported = false;\n const reportTerminalError = (error: unknown) => {\n if (terminalErrorReported) return;\n terminalErrorReported = true;\n this.invokeErrorHandler(error, action, payload, options, attemptState.count);\n };\n // Void dispatch still aggregates handler values for terminal observers;\n // only the public dispatch return type is void.\n const notifyObservers = async (event: ActionObserverEvent<T[K], unknown>) => {\n if (notifiedObserverOutcomes.has(event.outcome)) return;\n notifiedObserverOutcomes.add(event.outcome);\n await this.executeObservers(action, plan, event, notifiedObservers);\n };\n const pipelineOperation = async () => {\n const guard = plan.guards.length > 0\n ? await this.executeGuardPhase(\n action, payload as T[K], timeoutScope.options, plan, dispatchHandlerPromises,\n )\n : {\n allowed: true, payload: payload as T[K], aborted: false,\n abortReason: undefined, error: undefined, errors: [], outcomes: [], executedHandlers: [], duration: 0,\n };\n this.cleanupOneTimeHandlers(action, guard.executedHandlers, dispatchHandlerPromises);\n if (!guard.allowed) {\n await notifyObservers({\n action: String(action),\n payload: guard.payload,\n outcome: guard.aborted ? 'cancelled' : 'failed',\n result: undefined,\n errors: guard.errors,\n signal: timeoutScope.options?.signal,\n });\n // An explicit controller abort is an expected cancellation. A thrown\n // guard error remains fatal for dispatch(), matching errorPolicy.\n if (!guard.aborted && guard.errors.length > 0) {\n throw guard.error\n ?? guard.errors[0]?.error\n ?? new Error(`Guard phase failed for \"${String(action)}\"`);\n }\n return;\n }\n const execution = await this.executeWithRetry(async attemptSignal => {\n const executedHandlers: HandlerRegistration<any, any>[] = [];\n try {\n return await this._performDispatchWithResult<K, void>(\n action,\n guard.payload,\n this.withAttemptSignal(timeoutScope.options, attemptSignal),\n undefined,\n plan,\n executedHandlers,\n dispatchHandlerPromises\n );\n } finally {\n this.cleanupOneTimeHandlers(\n action,\n executedHandlers,\n dispatchHandlerPromises\n );\n }\n }, timeoutScope.options, attemptState, result => result.outcome === 'failed', () => (\n this.getAttemptHandlers(action, plan).length > 0\n ), undefined, this.shouldDrainBeforeRetry(plan, timeoutScope.options)\n ? () => this.drainAttemptHandlers(dispatchHandlerPromises)\n : undefined);\n if (timeoutScope.options?.signal?.aborted) {\n // The timeout signal shares the cancellation channel, but its public\n // terminal contract remains a failed ActionTimeoutError.\n if (timeoutScope.options.signal.reason instanceof ActionTimeoutError) {\n throw timeoutScope.options.signal.reason;\n }\n await notifyObservers({\n action: String(action),\n payload: guard.payload,\n outcome: 'cancelled',\n result: undefined,\n errors: execution.errors,\n signal: timeoutScope.options.signal,\n });\n return;\n }\n if (execution.outcome === 'failed') {\n throw execution.errors[execution.errors.length - 1]?.error\n ?? new Error(`Action \"${String(action)}\" failed`);\n }\n const result = this.processResults<unknown>(\n execution.results as unknown[],\n execution.terminated,\n execution.terminated ? execution.result : undefined,\n options?.result,\n );\n await notifyObservers({\n action: String(action),\n payload: guard.payload,\n outcome: execution.outcome,\n result,\n errors: execution.errors,\n signal: timeoutScope.options?.signal,\n });\n };\n const operation = async () => {\n if (timeoutScope.options?.signal?.aborted) {\n await notifyObservers({ action: String(action), payload: payload as T[K], outcome: 'cancelled',\n result: undefined, errors: [], signal: timeoutScope.options?.signal });\n return;\n }\n\n // Strict validation must complete before timing guards mutate admission state.\n this.validatePayload(action, payload);\n this.validateResultOptions(options?.result);\n if (timeoutScope.options?.signal?.aborted) {\n await notifyObservers({ action: String(action), payload: payload as T[K], outcome: 'cancelled',\n result: undefined, errors: [], signal: timeoutScope.options?.signal });\n return;\n }\n\n if (hasTimingGuard) {\n const admission = await this.evaluateTimingGuards(\n String(action),\n plan,\n timeoutScope.options?.signal,\n );\n if (admission.aborted || timeoutScope.options?.signal?.aborted || admission.reason) {\n await notifyObservers({\n action: String(action), payload: payload as T[K],\n outcome: admission.aborted || timeoutScope.options?.signal?.aborted\n ? 'cancelled'\n : admission.reason === 'Debounced execution' ? 'debounced' : 'throttled',\n result: undefined, errors: admission.reason ? [{\n handlerId: 'admission', error: new Error(admission.reason),\n timestamp: Date.now(), severity: 'blocking',\n }] : [],\n signal: timeoutScope.options?.signal,\n });\n return;\n }\n }\n\n if (timeoutScope.options?.signal?.aborted) {\n await notifyObservers({ action: String(action), payload: payload as T[K], outcome: 'cancelled',\n result: undefined, errors: [], signal: timeoutScope.options?.signal });\n return;\n }\n\n if (timeoutScope.options?.immediate || !this.dispatchQueue) {\n return pipelineOperation();\n }\n\n const queued = this.dispatchQueue.enqueueWithHandle(\n pipelineOperation,\n timeoutScope.options?.queuePriority ?? 0\n );\n timeoutScope.onTimeout(error => queued.cancel(error));\n return queued.promise;\n };\n\n let dispatchPromise: Promise<void>;\n let observedDispatchPromise: Promise<void>;\n this.dispatchConstructionDepth += 1;\n try {\n dispatchPromise = operation();\n observedDispatchPromise = dispatchPromise.catch(async error => {\n reportTerminalError(error);\n await notifyObservers({\n action: String(action), payload: payload as T[K], outcome: 'failed', result: undefined,\n errors: [{ handlerId: 'dispatch', error: error instanceof Error ? error : new Error(String(error)),\n timestamp: Date.now(), severity: 'blocking' }], signal: timeoutScope.options?.signal,\n });\n throw error;\n });\n this.trackDispatchPromise(observedDispatchPromise);\n } finally {\n this.dispatchConstructionDepth -= 1;\n }\n const exposedPromise = this.raceWithTimeout(\n observedDispatchPromise!,\n timeoutScope,\n dispatchHandlerPromises\n );\n const observedPromise = exposedPromise.catch(async error => {\n reportTerminalError(error);\n // The public timeout is already terminal. Failure observers remain\n // shutdown-owned best-effort work, but a non-cooperative observer must\n // not hold the timed-out caller open indefinitely.\n const observerNotification = this.trackGlobalHandlerPromise(notifyObservers({\n action: String(action), payload: payload as T[K], outcome: 'failed', result: undefined,\n errors: [{ handlerId: 'dispatch', error: error instanceof Error ? error : new Error(String(error)),\n timestamp: Date.now(), severity: 'blocking' }], signal: timeoutScope.options?.signal,\n }));\n void observerNotification.catch(observerError => {\n this.log(`Failure observer delivery failed for ${String(action)}`, observerError, 'warn');\n });\n throw error;\n });\n\n // Preserve rejection semantics for observers without leaking fire-and-forget\n // dispatches as process-level unhandled rejections.\n void observedPromise.catch(() => {});\n return observedPromise;\n }\n\n /** Execute a dispatch operation with an optional whole-action retry policy. */\n private async executeWithRetry<R>(\n operation: (attemptSignal: AbortSignal) => Promise<R>,\n options: DispatchOptions | undefined,\n attemptState: { count: number },\n shouldRetryResult?: (result: R) => boolean,\n canRetry: () => boolean = () => true,\n telemetry?: RetryTelemetry,\n beforeRetry?: () => Promise<void>,\n ): Promise<R> {\n const configuredAttempts = options?.retryOnError?.maxAttempts ?? 1;\n const maxAttempts = Number.isFinite(configuredAttempts)\n ? Math.max(1, Math.floor(configuredAttempts))\n : 1;\n const retryDelay = Math.max(0, options?.retryOnError?.delay ?? 0);\n\n while (attemptState.count < maxAttempts) {\n attemptState.count += 1;\n const attemptStartedAt = Date.now();\n const attemptController = new AbortController();\n\n try {\n const result = await operation(attemptController.signal);\n const shouldRetry = shouldRetryResult?.(result) ?? false;\n const canRetryAttempt = (\n shouldRetry &&\n attemptState.count < maxAttempts &&\n !options?.signal?.aborted &&\n canRetry()\n );\n const attemptEndedAt = Date.now();\n telemetry?.attempts.push({\n startTime: attemptStartedAt,\n endTime: attemptEndedAt,\n duration: attemptEndedAt - attemptStartedAt,\n outcome: shouldRetry\n ? (canRetryAttempt ? 'retried' : 'failed')\n : 'succeeded',\n });\n if (telemetry) telemetry.pipelineDuration += attemptEndedAt - attemptStartedAt;\n if (!canRetryAttempt) {\n return result;\n }\n attemptController.abort(new ActionAttemptSupersededError(attemptState.count));\n await beforeRetry?.();\n const retryStartedAt = Date.now();\n const shouldContinue = await this.waitForRetry(retryDelay, options?.signal);\n if (telemetry) telemetry.retryDelayDuration += Date.now() - retryStartedAt;\n if (!shouldContinue) {\n telemetry?.attempts.push({\n startTime: Date.now(), endTime: Date.now(), duration: 0, outcome: 'cancelled',\n });\n return result;\n }\n } catch (error) {\n const attemptEndedAt = Date.now();\n const canRetryAttempt = !(\n error instanceof ActionValidationError ||\n attemptState.count >= maxAttempts ||\n options?.signal?.aborted ||\n !canRetry()\n );\n telemetry?.attempts.push({\n startTime: attemptStartedAt,\n endTime: attemptEndedAt,\n duration: attemptEndedAt - attemptStartedAt,\n outcome: canRetryAttempt ? 'retried' : 'failed',\n });\n if (telemetry) telemetry.pipelineDuration += attemptEndedAt - attemptStartedAt;\n if (!canRetryAttempt) {\n throw error;\n }\n attemptController.abort(new ActionAttemptSupersededError(attemptState.count));\n await beforeRetry?.();\n const retryStartedAt = Date.now();\n const shouldContinue = await this.waitForRetry(retryDelay, options?.signal);\n if (telemetry) telemetry.retryDelayDuration += Date.now() - retryStartedAt;\n if (!shouldContinue) throw error;\n }\n }\n\n // The loop always returns or throws. This protects the generic return type\n // if an invalid retry configuration somehow reaches this point.\n const terminalAttempt = new AbortController();\n return operation(terminalAttempt.signal);\n }\n\n private trackDispatchPromise<R>(promise: Promise<R>): Promise<R> {\n this.activeDispatches.add(promise);\n const remove = () => this.activeDispatches.delete(promise);\n void promise.then(remove, remove);\n return promise;\n }\n\n private trackHandlerPromise<R>(\n promise: Promise<R>,\n dispatchHandlerPromises: DispatchHandlerPromises\n ): Promise<R> {\n this.activeHandlerPromises.add(promise);\n dispatchHandlerPromises.add(promise);\n const remove = () => {\n this.activeHandlerPromises.delete(promise);\n dispatchHandlerPromises.delete(promise);\n };\n void promise.then(remove, remove);\n return promise;\n }\n\n private withAttemptSignal(\n options: DispatchOptions | undefined,\n attemptSignal: AbortSignal,\n ): AttemptDispatchOptions {\n const outerSignal = options?.signal;\n if (!outerSignal) return { ...options, signal: attemptSignal };\n if (typeof AbortSignal.any === 'function') {\n return { ...options, signal: AbortSignal.any([outerSignal, attemptSignal]) };\n }\n const controller = new AbortController();\n const forwardOuter = () => controller.abort(outerSignal.reason);\n const forwardAttempt = () => controller.abort(attemptSignal.reason);\n if (outerSignal.aborted) forwardOuter();\n else outerSignal.addEventListener('abort', forwardOuter, { once: true });\n if (attemptSignal.aborted) forwardAttempt();\n else attemptSignal.addEventListener('abort', forwardAttempt, { once: true });\n const cleanup = () => {\n outerSignal.removeEventListener('abort', forwardOuter);\n attemptSignal.removeEventListener('abort', forwardAttempt);\n };\n controller.signal.addEventListener('abort', cleanup, { once: true });\n return { ...options, signal: controller.signal, [ATTEMPT_SIGNAL_CLEANUP]: cleanup };\n }\n\n private shouldDrainBeforeRetry(\n plan: DispatchPlan,\n options: DispatchOptions | undefined,\n ): boolean {\n const barrier = options?.retryOnError?.attemptBarrier\n ?? (plan.executionMode === 'race' ? 'abort-and-drain' : 'abort-and-overlap');\n return barrier === 'abort-and-drain';\n }\n\n /** Do not begin a whole-action retry while a previous race loser is still\n * running. Handlers should still observe their signal for cancellation. */\n private async drainAttemptHandlers(\n dispatchHandlerPromises: DispatchHandlerPromises,\n ): Promise<void> {\n const pending = [...dispatchHandlerPromises];\n if (pending.length > 0) await Promise.allSettled(pending);\n }\n\n private trackGlobalHandlerPromise<R>(promise: Promise<R>): Promise<R> {\n this.activeHandlerPromises.add(promise);\n const remove = () => this.activeHandlerPromises.delete(promise);\n void promise.then(remove, remove);\n return promise;\n }\n\n /** Abort-aware retry delay so cancellation does not wait for the full backoff. */\n private waitForRetry(delay: number, signal?: AbortSignal): Promise<boolean> {\n if (signal?.aborted) return Promise.resolve(false);\n if (delay <= 0) return Promise.resolve(true);\n\n return new Promise(resolve => {\n const timer = setTimeout(finish, delay);\n const abort = () => finish(false);\n\n function finish(shouldContinue = true) {\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n resolve(shouldContinue);\n }\n\n signal?.addEventListener('abort', abort, { once: true });\n });\n }\n\n /** Build a wall-clock timeout that also participates in pipeline cancellation. */\n private createTimeoutScope<K extends keyof T>(\n action: K,\n options?: DispatchOptions\n ): {\n options: DispatchOptions | undefined;\n timeoutPromise?: Promise<never>;\n onTimeout: (callback: (error: ActionTimeoutError) => void) => void;\n cleanup: () => void;\n cleanupSignals: () => void;\n } {\n const configuredTimeout = options?.timeout;\n if (\n configuredTimeout !== undefined &&\n (!Number.isFinite(configuredTimeout) || configuredTimeout < 0)\n ) {\n throw new RangeError('timeout must be a non-negative finite number.');\n }\n const hasTimeout = configuredTimeout !== undefined;\n const timeout = configuredTimeout;\n const timeoutController = hasTimeout ? new AbortController() : undefined;\n const signalCleanups: Array<() => void> = [];\n const timeoutCallbacks = new Set<(error: ActionTimeoutError) => void>();\n const signals = [\n this.lifecycleController.signal,\n options?.signal,\n timeoutController?.signal,\n ].filter((candidate): candidate is AbortSignal => Boolean(candidate));\n let signal = signals[0]!;\n\n if (signals.length > 1) {\n if (typeof (AbortSignal as typeof AbortSignal & {\n any?: (signals: AbortSignal[]) => AbortSignal;\n }).any === 'function') {\n signal = (AbortSignal as typeof AbortSignal & {\n any: (signals: AbortSignal[]) => AbortSignal;\n }).any(signals);\n } else {\n const mergedController = new AbortController();\n const forwardAbort = (source: AbortSignal) => {\n if (!mergedController.signal.aborted) mergedController.abort(source.reason);\n };\n\n for (const source of signals) {\n if (source.aborted) {\n forwardAbort(source);\n break;\n }\n const listener = () => forwardAbort(source);\n source.addEventListener('abort', listener, { once: true });\n signalCleanups.push(() => source.removeEventListener('abort', listener));\n }\n signal = mergedController.signal;\n }\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = timeoutController && timeout !== undefined\n ? new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const error = new ActionTimeoutError(String(action), timeout);\n timeoutController.abort(error);\n timeoutCallbacks.forEach(callback => callback(error));\n reject(error);\n }, timeout);\n })\n : undefined;\n\n return {\n options: { ...options, signal },\n timeoutPromise,\n onTimeout: callback => timeoutCallbacks.add(callback),\n cleanup: () => {\n if (timer !== undefined) clearTimeout(timer);\n timeoutCallbacks.clear();\n },\n cleanupSignals: () => signalCleanups.forEach(cleanup => cleanup()),\n };\n }\n\n /** Expose timeout failure while allowing the queued operation to drain safely. */\n private raceWithTimeout<R>(\n operation: Promise<R>,\n scope: {\n timeoutPromise?: Promise<never>;\n cleanup: () => void;\n cleanupSignals: () => void;\n },\n dispatchHandlerPromises: DispatchHandlerPromises\n ): Promise<R> {\n const exposed = scope.timeoutPromise\n ? Promise.race([operation, scope.timeoutPromise])\n : operation;\n const cleanupAfterStartedHandlers = () => {\n // Successful completion must cancel the ref'ed timeout timer immediately.\n // Only fallback signal-forwarding listeners need to outlive race losers.\n scope.cleanup();\n this.cleanupSignalsAfterStartedHandlers(\n scope.cleanupSignals,\n dispatchHandlerPromises\n );\n };\n void exposed.then(cleanupAfterStartedHandlers, cleanupAfterStartedHandlers);\n return exposed;\n }\n\n private cleanupSignalsAfterStartedHandlers(\n cleanup: () => void,\n dispatchHandlerPromises: DispatchHandlerPromises\n ): void {\n const handlersStillRunning = [...dispatchHandlerPromises];\n if (handlersStillRunning.length === 0) {\n cleanup();\n return;\n }\n\n // In AbortSignal.any() fallback environments, this dispatch's signal\n // forwarding listeners must outlive its race-mode losers even though the\n // exposed dispatch resolved. Unrelated dispatches must not delay cleanup.\n void Promise.allSettled(handlersStillRunning).then(cleanup);\n }\n\n /** Invoke the configured error handler without allowing it to replace the dispatch error. */\n private invokeErrorHandler<K extends keyof T>(\n error: unknown,\n action: K,\n payload: T[K] | undefined,\n options: DispatchOptions | undefined,\n attempts: number\n ): void {\n const errorHandler = this.registryConfig?.errorHandler;\n if (!errorHandler) return;\n\n const normalizedError = error instanceof Error ? error : new Error(String(error));\n try {\n const handlerResult = errorHandler(normalizedError, {\n action: String(action),\n payload,\n options,\n attempts,\n phase: normalizedError instanceof ActionTimeoutError\n ? 'timeout'\n : normalizedError instanceof ActionValidationError\n ? 'validation'\n : 'execution',\n });\n if (handlerResult && typeof (handlerResult as PromiseLike<void>).then === 'function') {\n void Promise.resolve(handlerResult).catch(handlerError => {\n this.log('Global async error handler failed', handlerError, 'warn');\n });\n }\n } catch (handlerError) {\n this.log('Global error handler failed', handlerError, 'warn');\n }\n }\n\n /**\n * Validate an action payload against the configured schema.\n * Shared by all dispatch paths so result collection cannot bypass validation.\n */\n private validatePayload<K extends keyof T>(\n action: K,\n payload?: T[K]\n ): ExecutionResult<never>['validation'] {\n if (\n !this.registryConfig?.schema ||\n this.registryConfig.validateOnDispatch === false\n ) {\n return undefined;\n }\n\n const actionName = String(action);\n const actionSchema = this.registryConfig.schema[actionName];\n if (!actionSchema) {\n return undefined;\n }\n\n let result: ReturnType<typeof actionSchema.safeParse>;\n try {\n result = actionSchema.safeParse(payload);\n } catch (error) {\n throw new ActionValidationError(actionName, error);\n }\n if (result.success) {\n return { passed: true, errors: [] };\n }\n\n const mode = this.registryConfig.validationMode ?? 'strict';\n if (mode === 'strict') {\n throw new ActionValidationError(actionName, result.error);\n }\n\n if (mode === 'warn') {\n console.warn(\n `Action \"${actionName}\" payload validation failed:`,\n result.error.message\n );\n this.log(`Validation warning for action '${actionName}'`, {\n issues: result.error.issues,\n }, 'warn');\n }\n\n return {\n passed: false,\n errors: result.error.issues.map(issue => issue.message),\n };\n }\n\n private createAbortedExecutionResult<R>(\n startTime: number,\n skippedRegistrations: readonly HandlerRegistration<any, any>[] = [],\n validation?: ExecutionResult<R>['validation']\n ): ExecutionResult<R> {\n const endTime = Date.now();\n const handlers = skippedRegistrations.map(registration => ({\n id: registration.id,\n status: 'skipped' as const,\n executed: false,\n duration: 0,\n result: undefined,\n error: undefined,\n metadata: registration.config.metadata ? { ...registration.config.metadata } : undefined,\n }));\n\n return {\n success: false,\n aborted: true,\n abortReason: 'Action dispatch aborted by signal',\n terminated: false,\n outcome: 'cancelled',\n validation,\n result: undefined,\n successResults: [],\n results: [],\n failedResults: [],\n execution: {\n duration: endTime - startTime,\n admissionDuration: endTime - startTime,\n queueWaitDuration: 0,\n pipelineDuration: 0,\n handlersExecuted: 0,\n handlersSkipped: handlers.length,\n handlersFailed: 0,\n startTime,\n endTime,\n },\n handlers,\n errors: [],\n };\n }\n\n private resolveDispatchPlan<K extends keyof T>(\n action: K,\n options?: DispatchOptions,\n ): DispatchPlan {\n const pipelineSnapshot = [...(this.pipelines.get(action) ?? [])];\n // Guards are admission controls. Ordinary dispatch filters can select\n // result/observer work, but may never bypass validation or authorization.\n const guards = pipelineSnapshot.filter(handler => handler.role === 'guard');\n const filterableHandlers = pipelineSnapshot.filter(handler => handler.role !== 'guard');\n const filteredHandlers = options?.filter\n ? this.filterHandlers(filterableHandlers, options.filter)\n : filterableHandlers;\n const eligibleHandlers = [...guards, ...filteredHandlers];\n const admissionHandlers = eligibleHandlers.filter(handler => handler.role !== 'observer');\n const debounceMs = options?.debounce\n ?? admissionHandlers.find(handler => handler.config.debounce !== undefined)?.config.debounce;\n const throttleMs = options?.throttle\n ?? admissionHandlers.find(handler => handler.config.throttle !== undefined)?.config.throttle;\n\n return {\n pipelineSnapshot,\n eligibleHandlers,\n guards,\n results: filteredHandlers.filter(handler => handler.role !== 'observer'),\n observers: filteredHandlers.filter(handler => handler.role === 'observer'),\n debounceMs,\n throttleMs,\n executionMode: options?.executionMode\n ?? this.actionExecutionModes.get(action)\n ?? this.executionMode,\n };\n }\n\n private async evaluateTimingGuards(\n actionKey: string,\n plan: DispatchPlan,\n signal?: AbortSignal,\n ): Promise<TimingGuardAdmission> {\n const { debounceMs, throttleMs } = plan;\n\n if (signal?.aborted) return { aborted: true };\n\n if (debounceMs !== undefined && !(await this.actionGuard.debounce(actionKey, debounceMs, signal))) {\n return signal?.aborted\n ? { aborted: true }\n : { aborted: false, reason: 'Debounced execution' };\n }\n if (throttleMs !== undefined && !this.actionGuard.throttle(actionKey, throttleMs, signal)) {\n return signal?.aborted\n ? { aborted: true }\n : { aborted: false, reason: 'Throttled execution' };\n }\n return { aborted: false };\n }\n\n /**\n * Keep the dispatch plan stable across retries while honoring handlers that\n * were consumed by the `once` lifecycle after an earlier attempt.\n */\n private getAttemptHandlers<K extends keyof T>(\n action: K,\n plan: DispatchPlan,\n ): HandlerRegistration<any, any>[] {\n const activePipeline = this.pipelines.get(action) ?? [];\n return plan.results.filter(\n handler => !handler.config.once || activePipeline.includes(handler),\n );\n }\n\n private getObservers<K extends keyof T>(\n action: K,\n plan: DispatchPlan,\n ): Array<[\n HandlerRegistration<any, any>,\n { handler: ActionObserverHandler<any, any>; when: 'success' | 'failure' | 'always' }\n ]> {\n const activePipeline = this.pipelines.get(action) ?? [];\n return plan.observers.flatMap(registration => {\n const observer = this.observerHandlers.get(registration);\n return registration.role === 'observer'\n && activePipeline.includes(registration)\n && observer\n ? [[registration, observer] as [\n HandlerRegistration<any, any>,\n { handler: ActionObserverHandler<any, any>; when: 'success' | 'failure' | 'always' }\n ]]\n : [];\n });\n }\n\n /** Observers run after the canonical result has been constructed. Their\n * failures are isolated from that immutable result; detached observers are\n * still tracked for registry shutdown. */\n private async executeObservers<K extends keyof T, R>(\n action: K,\n plan: DispatchPlan,\n event: ActionObserverEvent<T[K], R>,\n notifiedObservers = new Set<HandlerRegistration<any, any>>(),\n ): Promise<void> {\n const observerEvent = this.safeSnapshotObserverEvent(event);\n const selectedObservers: Array<[\n HandlerRegistration<any, any>,\n { handler: ActionObserverHandler<any, any>; when: 'success' | 'failure' | 'always' },\n ]> = [];\n\n // Assign every terminal-path-eligible observer to this immutable event\n // before awaiting any callback. Conditions are deliberately evaluated in\n // the invocation loop below: a lower-priority observer must see state\n // changes made by an awaited higher-priority observer, while remaining\n // reserved to this canonical event if a timeout races that observer chain.\n for (const [registration, observerEntry] of this.getObservers(action, plan)) {\n if (notifiedObservers.has(registration)) continue;\n const successful = observerEvent.outcome === 'completed' || observerEvent.outcome === 'completed_with_errors';\n if (observerEntry.when === 'success' && !successful) continue;\n if (observerEntry.when === 'failure' && successful) continue;\n notifiedObservers.add(registration);\n selectedObservers.push([registration, observerEntry]);\n }\n\n for (const [registration, observerEntry] of selectedObservers) {\n let shouldRun = true;\n try {\n shouldRun = registration.config.condition?.(observerEvent.payload as T[K]) ?? true;\n } catch (error) {\n this.log(`Observer condition failed for ${String(action)}`, error, 'warn');\n continue;\n }\n if (!shouldRun) continue;\n // Detach before invocation so a concurrent dispatch cannot observe and\n // invoke the same once observer. Cleanup remains tied to settlement.\n const detachedOnce = registration.config.once\n && this.removeRegistration(action, registration, false);\n const cleanupOnce = () => {\n if (detachedOnce) this.runRegistrationCleanup(action, registration);\n };\n const invocation = Promise.resolve().then(() => observerEntry.handler(observerEvent));\n if (registration.config.scheduling === 'start-and-continue') {\n void this.trackGlobalHandlerPromise(invocation).then(cleanupOnce, error => {\n this.log(`Observer failed for ${String(action)}`, error, 'warn');\n cleanupOnce();\n });\n } else {\n try {\n await invocation;\n } catch (error) {\n this.log(`Observer failed for ${String(action)}`, error, 'warn');\n } finally {\n cleanupOnce();\n }\n }\n }\n }\n\n /** Give JavaScript observers an isolated, shallowly immutable terminal view.\n * Result payloads are intentionally not deep-cloned: arbitrary result values\n * may be class instances, streams, or identity-bearing domain objects. */\n private snapshotObserverEvent<TPayload, R>(\n event: ActionObserverEvent<TPayload, R>,\n ): ActionObserverEvent<TPayload, R> {\n const freezeValue = <V>(value: V): V => {\n if (Array.isArray(value)) return Object.freeze([...value]) as V;\n if (value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {\n return Object.freeze({ ...(value as Record<string, unknown>) }) as V;\n }\n return value;\n };\n return Object.freeze({\n ...event,\n payload: freezeValue(event.payload),\n result: freezeValue(event.result),\n errors: Object.freeze(event.errors.map(error => Object.freeze({ ...error }))),\n });\n }\n\n /** A diagnostic observer must never make an already constructed canonical\n * result reject, including when shallow-copying a Proxy/getter throws. */\n private safeSnapshotObserverEvent<TPayload, R>(\n event: ActionObserverEvent<TPayload, R>,\n ): ActionObserverEvent<TPayload, R> {\n try {\n return this.snapshotObserverEvent(event);\n } catch (error) {\n this.log('Observer snapshot failed', error, 'warn');\n return Object.freeze({\n action: event.action,\n payload: event.payload,\n outcome: event.outcome,\n result: undefined,\n errors: Object.freeze([]),\n ...(event.signal === undefined ? {} : { signal: event.signal }),\n });\n }\n }\n\n /** Execute the selected guard snapshot once for the whole dispatch. Guards\n * are deliberately outside the retry loop: authorization and normalization\n * belong to admission, not to each provider attempt. */\n private async executeGuardPhase<K extends keyof T>(\n action: K,\n payload: T[K],\n options: DispatchOptions | undefined,\n plan: DispatchPlan,\n dispatchHandlerPromises: DispatchHandlerPromises,\n ): Promise<GuardPhaseResult<T[K]>> {\n if (plan.guards.length === 0) {\n return {\n allowed: true, payload, aborted: false, abortReason: undefined,\n error: undefined, errors: [], outcomes: [], executedHandlers: [], duration: 0,\n };\n }\n const [signal, autoAbortController, cleanup] = this.createAbortSignal(options);\n const context: PipelineContext<T[K], unknown> = {\n action: String(action),\n payload,\n handlers: [...plan.guards] as HandlerRegistration<T[K], unknown>[],\n executedHandlers: [],\n handlerOutcomes: [],\n claimOnce: registration => this.claimOnceRegistration(action, registration),\n signal: signal ?? this.lifecycleController.signal,\n trackHandlerPromise: promise => this.trackHandlerPromise(promise, dispatchHandlerPromises),\n aborted: false,\n abortReason: undefined,\n currentIndex: 0,\n jumpToPriority: undefined,\n jumpCount: 0,\n maxJumps: this.maxJumps,\n executionMode: 'sequential',\n results: [],\n terminated: false,\n terminationResult: undefined,\n };\n const abortHandler = signal ? () => {\n context.aborted = true;\n context.abortReason = typeof signal.reason === 'string'\n ? signal.reason\n : 'Action dispatch aborted by signal';\n } : undefined;\n signal?.addEventListener('abort', abortHandler!, { once: true });\n let error: Error | undefined;\n try {\n await executeSequential(context, (registration, _index) => {\n const controller = this.createController(\n context,\n autoAbortController,\n options?.autoAbort,\n undefined,\n false,\n );\n return {\n signal: controller.signal,\n getPayload: controller.getPayload,\n modifyPayload: controller.modifyPayload,\n abort: controller.abort,\n } as PipelineController<T[K], unknown>;\n });\n } catch (caught) {\n error = caught instanceof Error ? caught : new Error(String(caught));\n } finally {\n if (signal && abortHandler) signal.removeEventListener('abort', abortHandler);\n this.cleanupSignalsAfterStartedHandlers(() => {\n cleanup();\n (options as AttemptDispatchOptions | undefined)?.[ATTEMPT_SIGNAL_CLEANUP]?.();\n }, dispatchHandlerPromises);\n }\n const errors = [...(context.collectedErrors ?? [])];\n if (error && !errors.some(entry => entry.error === error)) {\n errors.push({\n handlerId: 'guard', error, timestamp: Date.now(), severity: 'blocking',\n });\n }\n return {\n allowed: !context.aborted && error === undefined && errors.length === 0,\n payload: context.payload,\n aborted: context.aborted,\n abortReason: context.abortReason,\n error,\n errors,\n outcomes: (context.handlerOutcomes ?? []).map(snapshotHandlerOutcome),\n executedHandlers: context.executedHandlers ?? [],\n duration: (context.handlerOutcomes ?? []).reduce((total, outcome) => total + (outcome.duration ?? 0), 0),\n };\n }\n\n private createGuardRejectedResult<R>(\n startTime: number,\n validation: ExecutionResult<R>['validation'],\n guard: GuardPhaseResult<unknown>,\n selectedHandlers: readonly HandlerRegistration<any, any>[],\n ): ExecutionResult<R> {\n const endTime = Date.now();\n const outcomeById = new Map(guard.outcomes.map(outcome => [outcome.id, outcome]));\n const handlers = selectedHandlers.map(registration => {\n const outcome = outcomeById.get(registration.id);\n return outcome ? { ...snapshotHandlerOutcome(outcome), result: undefined } : {\n id: registration.id, status: 'skipped' as const, executed: false,\n duration: 0, result: undefined, error: undefined,\n metadata: registration.config.metadata ? { ...registration.config.metadata } : undefined,\n };\n });\n return {\n success: false,\n aborted: guard.aborted,\n abortReason: guard.abortReason ?? guard.error?.message,\n terminated: false,\n outcome: guard.aborted ? 'cancelled' : 'failed',\n validation,\n result: undefined,\n successResults: [],\n results: [],\n failedResults: guard.errors.map(error => ({\n handlerId: error.handlerId, error: error.error, expectedType: 'unknown',\n })),\n execution: {\n duration: endTime - startTime, admissionDuration: 0, queueWaitDuration: 0,\n pipelineDuration: endTime - startTime,\n handlersExecuted: handlers.filter(handler => handler.executed).length,\n handlersSkipped: handlers.filter(handler => !handler.executed).length,\n handlersFailed: handlers.filter(handler => handler.status === 'failed').length,\n startTime, endTime,\n },\n handlers,\n errors: guard.errors,\n };\n }\n\n private createTimingGuardResult<R>(\n reason: string,\n startTime: number,\n handlers: readonly HandlerRegistration<any, any>[],\n validation?: ExecutionResult<R>['validation'],\n ): ExecutionResult<R> {\n const endTime = Date.now();\n return {\n success: false,\n // A timing guard rejects admission; it does not cancel an in-flight\n // dispatch or consume a caller AbortSignal.\n aborted: false,\n abortReason: reason,\n terminated: false,\n outcome: reason === 'Debounced execution' ? 'debounced' : 'throttled',\n validation,\n result: undefined,\n successResults: [],\n results: [],\n failedResults: [],\n execution: {\n duration: endTime - startTime,\n admissionDuration: endTime - startTime,\n queueWaitDuration: 0,\n pipelineDuration: 0,\n handlersExecuted: 0,\n handlersSkipped: handlers.length,\n handlersFailed: 0,\n startTime,\n endTime,\n },\n handlers: handlers.map(handler => ({\n id: handler.id,\n status: 'skipped' as const,\n executed: false,\n duration: 0,\n result: undefined,\n error: undefined,\n metadata: handler.config.metadata ? { ...handler.config.metadata } : undefined,\n })),\n errors: [],\n };\n }\n\n /**\n * Dispatch an action and return detailed execution results\n * \n * @param action - The action type to dispatch\n * @param args - The payload/options tuple for the selected action: payload-bearing actions require a payload, while void actions may omit it; dispatch options, including result collection, are optional.\n * \n * @returns Promise resolving to comprehensive execution results\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n dispatchWithResult<K extends ActionNames<T> & keyof TResultMap>(\n action: K,\n ...args: DispatchArgs<T[K]>\n ): Promise<ExecutionResult<ActionResult<TResultMap, K>>>;\n dispatchWithResult<K extends Exclude<ActionNames<T>, keyof TResultMap>, R = void>(\n action: K,\n ...args: DispatchArgs<T[K]>\n ): Promise<ExecutionResult<R>>;\n dispatchWithResult<K extends ActionNames<T>, R = ActionResult<TResultMap, K>>(\n action: K,\n ...args: DispatchArgs<T[K]>\n ): Promise<ExecutionResult<R>> {\n this.assertStringActionKey(action);\n const [payload, options] = args as [T[K] | undefined, DispatchOptions | undefined];\n if (this.lifecycleState !== 'active') {\n return this.rejectedLifecyclePromise<ExecutionResult<R>>();\n }\n\n const timeoutScope = this.createTimeoutScope(action, options);\n const dispatchStartTime = Date.now();\n const dispatchHandlerPromises: DispatchHandlerPromises = new Set();\n const attemptState = { count: 0 };\n let validation: ExecutionResult<R>['validation'];\n let observerPayload = payload as T[K];\n let admissionEndedAt = dispatchStartTime;\n let pipelineStartedAt: number | undefined;\n const retryTelemetry: RetryTelemetry = {\n pipelineDuration: 0,\n retryDelayDuration: 0,\n attempts: [],\n };\n const plan = this.resolveDispatchPlan(action, options);\n const hasTimingGuard = plan.debounceMs !== undefined || plan.throttleMs !== undefined;\n\n const pipelineOperation = async () => {\n pipelineStartedAt = Date.now();\n const guard = plan.guards.length > 0\n ? await this.executeGuardPhase(\n action, payload as T[K], timeoutScope.options, plan, dispatchHandlerPromises,\n )\n : {\n allowed: true, payload: payload as T[K], aborted: false,\n abortReason: undefined, error: undefined, errors: [], outcomes: [], executedHandlers: [], duration: 0,\n };\n this.cleanupOneTimeHandlers(action, guard.executedHandlers, dispatchHandlerPromises);\n observerPayload = guard.payload;\n if (!guard.allowed) {\n return this.createGuardRejectedResult<R>(\n pipelineStartedAt,\n validation,\n guard,\n [...plan.guards, ...plan.results],\n );\n }\n const rawExecution = await this.executeWithRetry(async attemptSignal => {\n const executedHandlers: HandlerRegistration<any, any>[] = [];\n try {\n return await this._performDispatchWithResult<K, R>(\n action,\n guard.payload,\n this.withAttemptSignal(timeoutScope.options, attemptSignal),\n validation,\n plan,\n executedHandlers,\n dispatchHandlerPromises\n );\n } finally {\n this.cleanupOneTimeHandlers(\n action,\n executedHandlers,\n dispatchHandlerPromises\n );\n }\n }, timeoutScope.options, attemptState, result => (\n result.outcome === 'failed'\n ), () => this.getAttemptHandlers(action, plan).length > 0, retryTelemetry,\n this.shouldDrainBeforeRetry(plan, timeoutScope.options)\n ? () => this.drainAttemptHandlers(dispatchHandlerPromises)\n : undefined);\n\n // A caller/lifecycle cancellation during retry backoff is terminal for\n // the dispatch, while the timeout channel remains a failed dispatch.\n if (timeoutScope.options?.signal?.aborted) {\n if (timeoutScope.options.signal.reason instanceof ActionTimeoutError) {\n throw timeoutScope.options.signal.reason;\n }\n return {\n ...rawExecution,\n success: false,\n aborted: true,\n abortReason: typeof timeoutScope.options.signal.reason === 'string'\n ? timeoutScope.options.signal.reason\n : 'Action dispatch aborted by signal',\n outcome: 'cancelled' as const,\n };\n }\n\n const executionWithGuards: ExecutionResult<R> = {\n ...rawExecution,\n handlers: [\n ...guard.outcomes.map(outcome => ({ ...outcome, result: undefined })),\n ...rawExecution.handlers,\n ] as ExecutionResult<R>['handlers'],\n execution: {\n ...rawExecution.execution,\n handlersExecuted: guard.outcomes.filter(outcome => outcome.executed).length\n + rawExecution.execution.handlersExecuted,\n handlersSkipped: guard.outcomes.filter(outcome => !outcome.executed).length\n + rawExecution.execution.handlersSkipped,\n handlersFailed: guard.outcomes.filter(outcome => outcome.status === 'failed').length\n + rawExecution.execution.handlersFailed,\n },\n };\n const resultProcessingStartedAt = Date.now();\n const result = this.processResults(\n executionWithGuards.results,\n executionWithGuards.terminated,\n executionWithGuards.terminated ? executionWithGuards.result : undefined,\n options?.result,\n );\n const resultProcessingDuration = Date.now() - resultProcessingStartedAt;\n const completed = {\n ...executionWithGuards,\n result,\n execution: {\n ...executionWithGuards.execution,\n pipelineDuration: guard.duration + retryTelemetry.pipelineDuration,\n retryDelayDuration: retryTelemetry.retryDelayDuration,\n resultProcessingDuration,\n attempts: retryTelemetry.attempts,\n },\n };\n return completed;\n };\n\n const operation = async () => {\n if (timeoutScope.options?.signal?.aborted) {\n admissionEndedAt = Date.now();\n return this.createAbortedExecutionResult<R>(\n dispatchStartTime,\n [...plan.guards, ...plan.results],\n );\n }\n\n // Strict validation must complete before timing guards mutate admission state.\n validation = this.validatePayload(action, payload);\n if (timeoutScope.options?.signal?.aborted) {\n admissionEndedAt = Date.now();\n return this.createAbortedExecutionResult<R>(\n dispatchStartTime,\n [...plan.guards, ...plan.results],\n validation,\n );\n }\n\n this.validateResultOptions(options?.result);\n if (hasTimingGuard) {\n const admission = await this.evaluateTimingGuards(\n String(action),\n plan,\n timeoutScope.options?.signal,\n );\n if (admission.aborted || timeoutScope.options?.signal?.aborted) {\n admissionEndedAt = Date.now();\n return this.createAbortedExecutionResult<R>(\n dispatchStartTime,\n [...plan.guards, ...plan.results],\n validation,\n );\n }\n if (admission.reason) {\n admissionEndedAt = Date.now();\n return this.createTimingGuardResult<R>(\n admission.reason,\n dispatchStartTime,\n [...plan.guards, ...plan.results],\n validation,\n );\n }\n }\n\n if (timeoutScope.options?.signal?.aborted) {\n admissionEndedAt = Date.now();\n return this.createAbortedExecutionResult<R>(\n dispatchStartTime,\n [...plan.guards, ...plan.results],\n validation,\n );\n }\n\n admissionEndedAt = Date.now();\n\n if (timeoutScope.options?.immediate || !this.dispatchQueue) {\n return pipelineOperation();\n }\n\n const queued = this.dispatchQueue.enqueueWithHandle(\n pipelineOperation,\n timeoutScope.options?.queuePriority ?? 0\n );\n timeoutScope.onTimeout(error => queued.cancel(error));\n return queued.promise;\n };\n\n const notifiedObservers = new Set<HandlerRegistration<any, any>>();\n const notifiedObserverOutcomes = new Set<ActionObserverEvent<T[K], R>['outcome']>();\n let terminalErrorReported = false;\n const reportTerminalError = (error: unknown) => {\n if (terminalErrorReported) return;\n terminalErrorReported = true;\n this.invokeErrorHandler(error, action, payload, options, attemptState.count);\n };\n const notifyObservers = async (event: ActionObserverEvent<T[K], R>) => {\n if (notifiedObserverOutcomes.has(event.outcome)) return;\n notifiedObserverOutcomes.add(event.outcome);\n await this.executeObservers(action, plan, event, notifiedObservers);\n };\n let dispatchPromise: Promise<ExecutionResult<R>>;\n let observedDispatchPromise: Promise<ExecutionResult<R>>;\n this.dispatchConstructionDepth += 1;\n try {\n dispatchPromise = operation();\n observedDispatchPromise = dispatchPromise.then(async result => {\n const dispatchEndedAt = Date.now();\n const pipelineDuration = pipelineStartedAt === undefined\n ? 0\n : result.execution.pipelineDuration;\n const completedResult: ExecutionResult<R> = {\n ...result,\n execution: {\n ...result.execution,\n duration: dispatchEndedAt - dispatchStartTime,\n admissionDuration: Math.max(0, admissionEndedAt - dispatchStartTime),\n queueWaitDuration: pipelineStartedAt === undefined\n ? 0\n : Math.max(0, pipelineStartedAt - admissionEndedAt),\n pipelineDuration,\n startTime: dispatchStartTime,\n endTime: dispatchEndedAt,\n },\n };\n if (completedResult.outcome === 'failed') {\n const terminalError = completedResult.errors[completedResult.errors.length - 1]?.error\n ?? new Error(`Action \"${String(action)}\" failed`);\n reportTerminalError(terminalError);\n }\n await notifyObservers({\n action: String(action), payload: observerPayload,\n outcome: completedResult.outcome, result: completedResult.result,\n errors: completedResult.errors, signal: timeoutScope.options?.signal,\n });\n return completedResult;\n }, async error => {\n reportTerminalError(error);\n await notifyObservers({\n action: String(action), payload: observerPayload, outcome: 'failed', result: undefined,\n errors: [{\n handlerId: 'dispatch',\n error: error instanceof Error ? error : new Error(String(error)),\n timestamp: Date.now(), severity: 'blocking',\n }],\n signal: timeoutScope.options?.signal,\n });\n throw error;\n });\n this.trackDispatchPromise(observedDispatchPromise);\n } finally {\n this.dispatchConstructionDepth -= 1;\n }\n const exposedPromise = this.raceWithTimeout(\n observedDispatchPromise!,\n timeoutScope,\n dispatchHandlerPromises\n );\n const observedPromise = exposedPromise.catch(async error => {\n // A timeout rejects the exposed promise before the canonical operation\n // settles. Notify once and track that observer work for shutdown.\n reportTerminalError(error);\n const observerNotification = this.trackGlobalHandlerPromise(notifyObservers({\n action: String(action), payload: observerPayload, outcome: 'failed', result: undefined,\n errors: [{\n handlerId: 'dispatch',\n error: error instanceof Error ? error : new Error(String(error)),\n timestamp: Date.now(), severity: 'blocking',\n }],\n signal: timeoutScope.options?.signal,\n }));\n void observerNotification.catch(observerError => {\n this.log(`Failure observer delivery failed for ${String(action)}`, observerError, 'warn');\n });\n throw error;\n });\n\n void observedPromise.catch(() => {});\n return observedPromise;\n }\n\n private async _performDispatchWithResult<K extends keyof T, R = void>(\n action: K,\n payload: T[K] | undefined,\n options: DispatchOptions | undefined,\n validation: ExecutionResult<R>['validation'],\n plan: DispatchPlan,\n executedHandlers: HandlerRegistration<any, any>[],\n dispatchHandlerPromises: DispatchHandlerPromises\n ): Promise<ExecutionResult<R>> {\n const _startTime = Date.now();\n \n // ๐ง Improved AbortSignal handling with cleaner merge logic (same as dispatch)\n const [effectiveSignal, autoAbortController, cleanup] = this.createAbortSignal(options);\n \n if (options?.autoAbort?.onControllerCreated && autoAbortController) {\n options.autoAbort.onControllerCreated(autoAbortController);\n }\n \n // Check if dispatch is aborted before starting\n if (effectiveSignal?.aborted) {\n cleanup();\n return this.createAbortedExecutionResult<R>(_startTime, plan.results, validation);\n }\n \n const pipeline = plan.pipelineSnapshot;\n \n if (!pipeline || pipeline.length === 0) {\n this.log(`Pipeline lookup for '${String(action)}'`, {\n pipelineExists: false,\n handlersCount: 0,\n allRegisteredActions: Array.from(this.pipelines.keys()),\n });\n // ๐จ ๊ฒฝ๊ณ : ํธ๋ค๋ฌ๊ฐ ๋ฑ๋ก๋์ง ์์ ์ก์
์คํ\n const warningMessage = `โ ๏ธ Action '${String(action)}' has no registered handlers. This action will be ignored.`;\n \n if (this.isDebugMode) {\n console.warn(warningMessage);\n console.warn('๐ก Tip: Register a handler using registry.register() before dispatching this action.');\n console.warn('๐ Available actions:', Array.from(this.pipelines.keys()));\n }\n this.log(`No handlers found for action '${String(action)}', dispatch cancelled`, {}, 'warn');\n \n cleanup();\n return {\n success: true,\n aborted: false,\n abortReason: undefined as string | undefined,\n terminated: false,\n outcome: 'completed',\n validation,\n result: undefined as any,\n successResults: [] as any,\n results: [],\n failedResults: [],\n execution: {\n duration: 0,\n admissionDuration: 0,\n queueWaitDuration: 0,\n pipelineDuration: 0,\n handlersExecuted: 0,\n handlersSkipped: 0,\n handlersFailed: 0,\n startTime: _startTime,\n endTime: _startTime,\n },\n handlers: [],\n errors: [],\n };\n }\n\n const filteredHandlers = this.getAttemptHandlers(action, plan);\n\n // Create pipeline execution context\n const context: PipelineContext<T[K], R> = {\n action: String(action),\n payload: payload as T[K],\n handlers: [...filteredHandlers],\n executedHandlers: [],\n handlerOutcomes: [],\n deferOnceCleanup: true,\n claimOnce: registration => this.claimOnceRegistration(action, registration),\n signal: effectiveSignal ?? this.lifecycleController.signal,\n trackHandlerPromise: promise => this.trackHandlerPromise(\n promise,\n dispatchHandlerPromises\n ),\n aborted: false,\n abortReason: undefined as string | undefined,\n currentIndex: 0,\n jumpToPriority: undefined as number | undefined,\n jumpCount: 0,\n maxJumps: this.maxJumps,\n executionMode: plan.executionMode,\n \n // Result collection fields\n results: [],\n terminated: false,\n terminationResult: undefined as R | undefined,\n };\n\n let executionError: Error | undefined;\n // Add abort listener if signal provided (use effectiveSignal for auto-abort)\n const abortHandler = effectiveSignal ? () => {\n context.aborted = true;\n context.abortReason = typeof effectiveSignal.reason === 'string'\n ? effectiveSignal.reason\n : 'Action dispatch aborted by signal';\n } : undefined;\n \n if (effectiveSignal && abortHandler) {\n effectiveSignal.addEventListener('abort', abortHandler, { once: true });\n }\n \n // ๐ง Initialize errors array (will be updated after pipeline execution)\n let errors: HandlerError[] = [];\n \n try {\n await this.executePipeline(\n context,\n dispatchHandlerPromises,\n autoAbortController,\n options?.autoAbort\n );\n \n // ๐ง Collect errors from execution context after pipeline execution\n const contextWithErrors = context as PipelineContext<any, any> & { collectedErrors?: HandlerError[] };\n errors = contextWithErrors.collectedErrors || [];\n \n } catch (error) {\n // ๐ง Collect errors from execution context before adding pipeline error\n const contextWithErrors = context as PipelineContext<any, any> & { collectedErrors?: HandlerError[] };\n errors = contextWithErrors.collectedErrors || [];\n \n executionError = error instanceof Error ? error : new Error(String(error));\n errors.push({\n handlerId: 'pipeline',\n error: executionError,\n timestamp: Date.now(),\n severity: 'blocking'\n });\n \n } finally {\n executedHandlers.push(...(context.executedHandlers ?? []));\n if (effectiveSignal && abortHandler) {\n effectiveSignal.removeEventListener('abort', abortHandler);\n }\n this.cleanupSignalsAfterStartedHandlers(() => {\n cleanup();\n (options as AttemptDispatchOptions | undefined)?.[ATTEMPT_SIGNAL_CLEANUP]?.();\n }, dispatchHandlerPromises);\n }\n\n const endTime = Date.now();\n \n const recordedOutcomes = context.handlerOutcomes ?? [];\n const outcomesById = new Map(recordedOutcomes.map(outcome => [outcome.id, outcome]));\n const handlerResults: HandlerExecutionOutcome<R>[] = filteredHandlers.map(handler => {\n const outcome = outcomesById.get(handler.id);\n return outcome\n ? snapshotHandlerOutcome(outcome)\n : {\n id: handler.id,\n status: 'skipped' as const,\n executed: false,\n duration: 0,\n result: undefined,\n error: undefined,\n metadata: handler.config.metadata ? { ...handler.config.metadata } : undefined,\n };\n });\n const handlerErrors = errors.filter(error => error.handlerId !== 'pipeline');\n // Keep the public terminal-error view backward compatible: fatal pipeline\n // failures are represented by the pipeline error, while per-handler\n // diagnostics remain available through `handlers` and `failedResults`.\n const reportedErrors = executionError\n ? errors.filter(error => error.handlerId === 'pipeline')\n : errors;\n const executionHandlersCount = handlerResults.filter(handler => handler.executed).length;\n\n // ๐ง Type safety: Separate successful results from failed ones\n const successResults = context.results.filter((result): result is R => result !== undefined);\n const failedResults = handlerErrors.map(err => ({\n handlerId: err.handlerId,\n error: err.error,\n expectedType: 'unknown'\n }));\n\n // Build execution result with improved type safety\n const executionResult: ExecutionResult<R> = {\n success: !executionError && !context.aborted,\n aborted: context.aborted,\n abortReason: context.abortReason,\n terminated: context.terminated,\n outcome: context.aborted\n ? 'cancelled'\n : executionError\n ? 'failed'\n : handlerErrors.length > 0\n ? 'completed_with_errors'\n : 'completed',\n validation,\n // Result aggregation happens after the retry boundary in dispatchWithResult.\n // Preserve controller.return() here so the post-processing step can retain it.\n result: context.terminated ? context.terminationResult : undefined,\n successResults: successResults,\n results: context.results,\n failedResults,\n execution: {\n duration: endTime - _startTime,\n admissionDuration: 0,\n queueWaitDuration: 0,\n pipelineDuration: endTime - _startTime,\n handlersExecuted: executionHandlersCount,\n handlersSkipped: Math.max(0, filteredHandlers.length - executionHandlersCount),\n handlersFailed: context.executionMode === 'race'\n ? (context.raceWinnerId && outcomesById.get(context.raceWinnerId)?.status === 'failed' ? 1 : 0)\n : handlerResults.filter(handler => handler.status === 'failed').length,\n startTime: _startTime,\n endTime,\n },\n handlers: handlerResults,\n ...(context.executionMode !== 'race' ? {} : {\n raceDiagnostics: {\n ...(context.raceWinnerId === undefined ? {} : { winnerId: context.raceWinnerId }),\n ...(context.raceWinnerId === undefined\n ? {}\n : { winner: snapshotHandlerOutcome(outcomesById.get(context.raceWinnerId)!) }),\n loserSnapshots: (context.raceLoserOutcomes ?? []).map(snapshotHandlerOutcome),\n pendingLosersAtReturn: (context.raceLoserOutcomes ?? [])\n .filter(outcome => outcome.status === 'running').length,\n observedLoserFailures: (context.raceLoserOutcomes ?? [])\n .filter(outcome => outcome.status === 'failed').length,\n },\n }),\n errors: reportedErrors.map(err => ({\n handlerId: err.handlerId,\n error: err.error,\n timestamp: err.timestamp,\n severity: err.severity\n })),\n };\n\n return executionResult;\n }\n\n /** Create a pipeline controller for one handler execution. */\n private createController<K extends keyof T>(\n context: PipelineContext<T[K], any>, \n autoAbortController?: AbortController,\n autoAbortOptions?: { allowHandlerAbort?: boolean },\n isolatedState?: PipelineControllerState<T[K], any>,\n collectResults = true,\n ): PipelineController<T[K], any> {\n const controller = {} as PipelineController<T[K], any>;\n\n // Configure/reset the controller for current context\n (controller as { signal: AbortSignal }).signal =\n context.signal ?? this.lifecycleController.signal;\n\n const state = isolatedState ?? context;\n\n controller.abort = (reason?: string) => {\n state.aborted = true;\n state.abortReason = reason;\n const propagateAbort = !isolatedState || context.executionMode !== 'race';\n if (propagateAbort) {\n context.aborted = true;\n context.abortReason = reason;\n }\n \n // Auto-abort: Handler can trigger pipeline abort if enabled\n if (propagateAbort && autoAbortController && autoAbortOptions?.allowHandlerAbort) {\n autoAbortController.abort(reason);\n }\n };\n\n controller.modifyPayload = (modifier: (payload: T[K]) => T[K]) => {\n state.payload = modifier(state.payload);\n };\n\n controller.getPayload = () => state.payload;\n\n controller.jumpToPriority = (priority: number) => {\n state.jumpToPriority = priority;\n };\n\n controller.return = (result: any) => {\n state.terminated = true;\n state.terminationResult = collectResults ? result : undefined;\n if (!isolatedState) {\n context.terminated = true;\n context.terminationResult = collectResults ? result : undefined;\n }\n return result;\n };\n\n controller.setResult = (result: any) => {\n if (collectResults) state.results.push(result);\n };\n\n controller.getResults = () => {\n return [...state.results];\n };\n\n controller.mergeResult = (merger: (previousResults: any[], currentResult: any) => any) => {\n if (!collectResults) return;\n const currentResult = state.results[state.results.length - 1];\n const previousResults = state.results.slice(0, -1);\n const mergedResult = merger(previousResults, currentResult);\n state.results[state.results.length - 1] = mergedResult;\n };\n\n return controller;\n }\n\n private filterHandlers(\n handlers: HandlerRegistration<any, any>[],\n filterOptions?: DispatchOptions['filter']\n ): HandlerRegistration<any, any>[] {\n if (!filterOptions) {\n return handlers;\n }\n\n // Cache disabled for memory stability\n\n // Cache disabled - using direct filtering for memory stability\n\n // Create Sets for fast lookup if arrays are provided\n const handlerIdSet = filterOptions.handlerIds ? new Set(filterOptions.handlerIds) : null;\n const excludeIdSet = filterOptions.excludeHandlerIds ? new Set(filterOptions.excludeHandlerIds) : null;\n\n // Filter handlers with optimized checks\n const filtered = handlers.filter(registration => {\n const config = registration.config;\n\n // Fast Set-based inclusion check\n if (handlerIdSet && !handlerIdSet.has(config.id)) {\n return false;\n }\n\n // Fast Set-based exclusion check\n if (excludeIdSet?.has(config.id)) {\n return false;\n }\n\n // Priority range check\n if (filterOptions.priority) {\n const priority = config.priority;\n if (filterOptions.priority.min !== undefined && priority < filterOptions.priority.min) {\n return false;\n }\n if (filterOptions.priority.max !== undefined && priority > filterOptions.priority.max) {\n return false;\n }\n }\n\n // Evaluate user code against a frozen snapshot. This prevents a custom\n // filter from changing the registration that the current plan executes.\n if (filterOptions.custom) {\n const configSnapshot = Object.freeze({\n ...config,\n metadata: config.metadata\n ? Object.freeze({ ...config.metadata })\n : undefined,\n });\n if (!filterOptions.custom(configSnapshot)) {\n return false;\n }\n }\n\n return true;\n });\n\n // Cache disabled for memory stability\n\n return filtered;\n }\n\n private validateResultOptions(resultOptions?: DispatchOptions['result']): void {\n if (!resultOptions) return;\n\n if (resultOptions.strategy === 'custom' && typeof resultOptions.merger !== 'function') {\n throw new ActionResultProcessingError(\n 'Custom result strategy requires a merger function',\n );\n }\n\n if (\n resultOptions.maxResults !== undefined &&\n (!Number.isSafeInteger(resultOptions.maxResults) || resultOptions.maxResults < 0)\n ) {\n throw new RangeError('maxResults must be a non-negative safe integer.');\n }\n }\n\n private processResults<R>(\n results: Array<R | undefined>,\n terminated: boolean,\n terminationResult: R | R[] | undefined,\n resultOptions?: DispatchOptions['result']\n ): R | R[] | undefined {\n // controller.return() is authoritative even when its explicit value is undefined.\n if (terminated) {\n return terminationResult;\n }\n\n // ๐ง Fix: Return undefined only if no results options specified AND no results available\n if (!resultOptions) {\n // If no result options specified but we have results, return the last one\n return results.length > 0 ? results[results.length - 1] : undefined;\n }\n\n // ๐ง Fix: Process results even when collect is false if we have a strategy specified\n if (!resultOptions.collect && !resultOptions.strategy) {\n return undefined;\n }\n\n // Apply maxResults limit\n const collectedResults = results.filter((result): result is R => result !== undefined);\n const limitedResults = resultOptions.maxResults !== undefined\n ? collectedResults.slice(0, resultOptions.maxResults)\n : collectedResults;\n\n if (limitedResults.length === 0) {\n if (resultOptions.strategy === 'all' || (resultOptions.collect && !resultOptions.strategy)) {\n return [];\n }\n if (resultOptions.strategy === 'custom' || (resultOptions.strategy === 'merge' && resultOptions.merger)) {\n return resultOptions.merger!(limitedResults);\n }\n return undefined;\n }\n\n // Process results based on strategy with improved type handling\n switch (resultOptions.strategy) {\n case 'first':\n return limitedResults[0];\n case 'last':\n return limitedResults[limitedResults.length - 1];\n case 'all':\n return limitedResults;\n case 'merge':\n if (resultOptions.merger) {\n return resultOptions.merger(limitedResults);\n }\n // Default merge: return last result\n return limitedResults[limitedResults.length - 1];\n case 'custom':\n if (resultOptions.merger) {\n return resultOptions.merger(limitedResults);\n }\n throw new Error('Custom result strategy requires a merger function');\n default:\n // ๐ง Fix: If collect is true but no strategy specified, return all results\n if (resultOptions.collect) {\n return limitedResults;\n }\n // Default: return last result if no strategy specified\n return limitedResults[limitedResults.length - 1];\n }\n }\n\n private async executePipeline<K extends keyof T>(\n context: PipelineContext<T[K], any>,\n dispatchHandlerPromises: DispatchHandlerPromises,\n autoAbortController?: AbortController,\n autoAbortOptions?: { allowHandlerAbort?: boolean }\n ): Promise<void> {\n const createController = (\n registration: HandlerRegistration<T[K], any>,\n _index: number,\n state?: PipelineControllerState<T[K], any>,\n ): PipelineController<T[K], any> => {\n const controller = this.createController(\n context,\n autoAbortController,\n autoAbortOptions,\n state,\n registration.role !== 'guard',\n );\n // Runtime mirrors the narrow public controller contracts. This also\n // prevents JavaScript consumers from accidentally publishing guard\n // results through an API that would be ignored.\n if (registration.role === 'guard') {\n return {\n signal: controller.signal,\n getPayload: controller.getPayload,\n modifyPayload: controller.modifyPayload,\n abort: controller.abort,\n } as PipelineController<T[K], any>;\n }\n if (registration.role === 'result') {\n return {\n signal: controller.signal,\n getPayload: controller.getPayload,\n abort: controller.abort,\n return: controller.return,\n setResult: controller.setResult,\n getResults: controller.getResults,\n mergeResult: controller.mergeResult,\n } as PipelineController<T[K], any>;\n }\n return controller;\n };\n\n // Guards are a preflight phase in every mode, before result arbitration.\n const originalHandlers = context.handlers;\n const preflightHandlers = originalHandlers.filter(handler => handler.role === 'guard');\n if (preflightHandlers.length > 0) {\n context.handlers = preflightHandlers;\n await executeSequential<T[K], any>(context, createController);\n if (context.aborted || context.terminated) {\n context.handlers = originalHandlers;\n return;\n }\n }\n context.handlers = originalHandlers.filter(handler => (\n !preflightHandlers.includes(handler) && handler.role !== 'observer'\n ));\n\n switch (context.executionMode) {\n case 'sequential':\n await executeSequential<T[K], any>(context, createController);\n break;\n case 'parallel':\n await executeParallel<T[K], any>(context, createController);\n break;\n case 'race':\n await executeRace<T[K], any>(context, createController);\n break;\n default:\n throw new Error(`Unknown execution mode: ${context.executionMode}`);\n }\n context.handlers = originalHandlers;\n\n if (!context.deferOnceCleanup) {\n this.cleanupOneTimeHandlers(\n context.action as K,\n context.executedHandlers ?? [],\n dispatchHandlerPromises\n );\n }\n }\n\n private cleanupOneTimeHandlers<K extends keyof T>(\n action: K,\n executedHandlers: HandlerRegistration<any, any>[],\n dispatchHandlerPromises: DispatchHandlerPromises\n ): void {\n const oneTimeHandlers = executedHandlers.filter(reg => reg.config.once);\n if (oneTimeHandlers.length === 0) return;\n\n // Race mode returns its winner while loser handlers can still be active.\n // Detach every invoked once-handler immediately so retries cannot invoke it\n // again, but defer resource cleanup until this dispatch's started handler\n // work drains. Unrelated dispatches must not delay cleanup.\n const handlersStillRunning = [...dispatchHandlerPromises];\n const shouldDeferCleanup = handlersStillRunning.length > 0;\n\n oneTimeHandlers.forEach(registration => {\n const claimed = this.claimedOnceHandlers.delete(registration);\n const removed = claimed || this.removeRegistration(action, registration, !shouldDeferCleanup);\n if (removed) {\n if (claimed && !shouldDeferCleanup) {\n this.runRegistrationCleanup(action, registration);\n }\n if (\n shouldDeferCleanup &&\n typeof registration.config.cleanup === 'function'\n ) {\n const cleanupPromise = Promise.allSettled(handlersStillRunning).then(() => {\n this.runRegistrationCleanup(action, registration);\n });\n void this.trackGlobalHandlerPromise(cleanupPromise).catch(() => {});\n }\n\n this.log(`One-time handler removed: ${String(action)}`, {\n handlerId: registration.id,\n remainingHandlers: this.pipelines.get(action)?.length ?? 0\n });\n }\n });\n }\n\n /** Reserve a once registration before user code starts. This is synchronous,\n * so independent dispatches cannot both invoke the same registration. */\n private claimOnceRegistration<K extends keyof T>(\n action: K,\n registration: HandlerRegistration<any, any>,\n ): boolean {\n if (!registration.config.once) return true;\n if (this.claimedOnceHandlers.has(registration)) return false;\n if (!this.removeRegistration(action, registration, false)) return false;\n this.claimedOnceHandlers.add(registration);\n return true;\n }\n\n\n /**\n * Get the number of registered handlers for an action\n * \n * @param action - The action type to count handlers for\n * \n * @returns Number of registered handlers\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getHandlerCount<K extends ActionNames<T>>(action: K): number {\n const pipeline = this.pipelines.get(action);\n return pipeline ? pipeline.length : 0;\n }\n\n /**\n * Check if an action has any registered handlers\n * \n * @param action - The action type to check\n * \n * @returns True if action has handlers, false otherwise\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n hasHandlers<K extends ActionNames<T>>(action: K): boolean {\n return this.getHandlerCount(action) > 0;\n }\n\n /**\n * Get all registered action types\n * \n * @returns Array of all registered action types\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getRegisteredActions(): (keyof T)[] {\n return Array.from(this.pipelines.keys());\n }\n\n /**\n * Remove all handlers for a specific action\n * \n * @param action - The action type to clear handlers for\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n clearAction<K extends ActionNames<T>>(action: K): void {\n const pipeline = this.pipelines.get(action);\n if (pipeline) {\n [...pipeline].forEach(registration => {\n this.removeRegistration(action, registration);\n });\n }\n\n this.pipelines.delete(action);\n this.lastRegisteredTimestamps.delete(action);\n this.actionGuard.clearGuards(String(action));\n }\n\n /**\n * Remove all handlers for all actions\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n clearAll(): void {\n [...this.pipelines.keys()].forEach(action => {\n this.clearAction(action as ActionNames<T>);\n });\n\n this.pipelines.clear();\n this.lastRegisteredTimestamps.clear();\n this.unregisterFunctions.forEach(unregisters => unregisters.clear());\n this.unregisterFunctions.clear();\n this.actionGuard.clearAll();\n this.observerHandlers.clear();\n }\n\n /**\n * Get the name of this action register\n * \n * @returns The register name\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getName(): string {\n return this.name;\n }\n\n /**\n * Get comprehensive registry information (similar to DeclarativeStoreRegistry pattern)\n * \n * @returns Registry information including actions, handlers, and execution modes\n */\n getRegistryInfo(): ActionRegistryInfo<T> {\n const totalHandlers = Array.from(this.pipelines.values()).reduce(\n (total, pipeline) => total + pipeline.length, \n 0\n );\n \n return {\n name: this.name,\n totalActions: this.pipelines.size,\n totalHandlers,\n registeredActions: Array.from(this.pipelines.keys()),\n actionExecutionModes: new Map(this.actionExecutionModes),\n defaultExecutionMode: this.executionMode,\n };\n }\n\n /**\n * Get detailed statistics for a specific action\n * \n * @param action Action name to get statistics for\n * @returns Detailed handler statistics\n */\n getActionStats<K extends ActionNames<T>>(action: K): ActionHandlerStats<T> | null {\n const pipeline = this.pipelines.get(action);\n if (!pipeline) {\n return null;\n }\n\n // Group handlers by priority\n const priorityMap = new Map<number, typeof pipeline>();\n pipeline.forEach(handler => {\n if (!priorityMap.has(handler.config.priority)) {\n priorityMap.set(handler.config.priority, []);\n }\n priorityMap.get(handler.config.priority)!.push(handler);\n });\n\n const handlersByPriority = Array.from(priorityMap.entries())\n .sort(([a], [b]) => b - a) // Sort by priority (highest first)\n .map(([priority, handlers]) => ({\n priority,\n handlers: handlers.map(h => ({\n id: h.config.id,\n }))\n }));\n\n // Execution statistics are no longer tracked\n const executionStats = undefined;\n\n return {\n action,\n handlerCount: pipeline.length,\n totalHandlers: pipeline.length,\n handlersByPriority,\n executionStats,\n lastRegistered: this.lastRegisteredTimestamps.get(action),\n };\n }\n\n /**\n * Get statistics for all registered actions\n * \n * @returns Array of statistics for all actions\n */\n getAllActionStats(): Array<ActionHandlerStats<T>> {\n return Array.from(this.pipelines.keys())\n .map(action => this.getActionStats(action as ActionNames<T>))\n .filter((stats): stats is ActionHandlerStats<T> => stats !== null);\n }\n\n\n /**\n * Set global execution mode for all actions\n * \n * @param mode Execution mode to set\n */\n setExecutionMode(mode: ExecutionMode): void {\n this.executionMode = mode;\n \n if (this.isDebugMode) {\n console.log(`๐ฏ Global execution mode set to: ${mode}`);\n }\n }\n\n /**\n * Set execution mode for a specific action\n * \n * @param action Action name\n * @param mode Execution mode to set\n */\n setActionExecutionMode<K extends ActionNames<T>>(action: K, mode: ExecutionMode): void {\n this.actionExecutionModes.set(action, mode);\n \n if (this.isDebugMode) {\n console.log(`๐ฏ Execution mode set for action '${String(action)}': ${mode}`);\n }\n }\n\n /**\n * Get execution mode for a specific action\n * \n * @param action Action name\n * @returns Execution mode for the action, or default if not set\n */\n getActionExecutionMode<K extends ActionNames<T>>(action: K): ExecutionMode {\n return this.actionExecutionModes.get(action) || this.executionMode;\n }\n\n /**\n * Remove execution mode override for a specific action\n * \n * @param action Action name\n */\n removeActionExecutionMode<K extends ActionNames<T>>(action: K): void {\n this.actionExecutionModes.delete(action);\n \n if (this.isDebugMode) {\n console.log(`๐ฏ Execution mode reset for action '${String(action)}' to default: ${this.executionMode}`);\n }\n }\n\n\n /**\n * Get registry configuration (for debugging and inspection)\n * \n * @returns Current registry configuration\n */\n getRegistryConfig(): ActionRegisterConfig['registry'] {\n return this.registryConfig;\n }\n\n /**\n * Check if registry has debug mode enabled\n * \n * @returns Whether debug mode is enabled\n */\n isDebugEnabled(): boolean {\n return this.isDebugMode;\n }\n\n /**\n * Creates a consistent unregister function for a handler\n * \n * @param action - Action key\n * @param handlerId - Handler identifier\n * @param registration - Handler registration object\n * @returns Unregister function\n * @private\n */\n private createUnregisterFunction<K extends keyof T>(\n action: K,\n handlerId: string,\n registration: HandlerRegistration<any, any>\n ): UnregisterFunction {\n return () => {\n if (this.removeRegistration(action, registration)) {\n this.log(`Handler unregistered: ${String(action)}`, {\n handlerId,\n remainingHandlers: this.pipelines.get(action)?.length ?? 0,\n actionRemoved: !this.pipelines.has(action)\n });\n }\n };\n }\n\n private getUnregisterFunctions<K extends keyof T>(action: K): Map<string, UnregisterFunction> {\n let unregisters = this.unregisterFunctions.get(action);\n if (!unregisters) {\n unregisters = new Map();\n this.unregisterFunctions.set(action, unregisters);\n }\n return unregisters;\n }\n\n /** Remove a registration and release every resource owned by it exactly once. */\n private removeRegistration<K extends keyof T>(\n action: K,\n registration: HandlerRegistration<any, any>,\n runCleanup = true\n ): boolean {\n const pipeline = this.pipelines.get(action);\n if (!pipeline) return false;\n\n const index = pipeline.indexOf(registration);\n if (index === -1) return false;\n\n pipeline.splice(index, 1);\n this.observerHandlers.delete(registration);\n const actionUnregisterFunctions = this.unregisterFunctions.get(action);\n actionUnregisterFunctions?.delete(registration.id);\n\n if (runCleanup) {\n this.runRegistrationCleanup(action, registration);\n }\n\n if (pipeline.length === 0) {\n this.pipelines.delete(action);\n this.lastRegisteredTimestamps.delete(action);\n this.unregisterFunctions.delete(action);\n }\n\n return true;\n }\n\n private runRegistrationCleanup<K extends keyof T>(\n action: K,\n registration: HandlerRegistration<any, any>\n ): void {\n if (!registration.config.cleanup) return;\n\n try {\n registration.config.cleanup();\n } catch (cleanupError) {\n this.log(`Cleanup error while removing handler: ${String(action)}`, cleanupError, 'warn');\n }\n }\n\n /**\n * Gets the total count of registered unregister functions\n * \n * @returns Number of unregister functions\n * @public\n */\n getUnregisterFunctionCount(): number {\n let count = 0;\n this.unregisterFunctions.forEach(unregisters => {\n count += unregisters.size;\n });\n return count;\n }\n \n /**\n * Checks if an unregister function exists for the given handler ID\n * \n * @param handlerId - Handler identifier to check\n * @returns True if unregister function exists\n * @public\n */\n hasUnregisterFunction(handlerId: string): boolean {\n for (const unregisters of this.unregisterFunctions.values()) {\n if (unregisters.has(handlerId)) return true;\n }\n return false;\n }\n\n /** Reject queued dispatches without releasing registered handlers. */\n cancelPendingDispatches(): void {\n this.dispatchQueue?.clear({ rejectPending: true });\n }\n\n private beginShutdown(deferCleanup = false): Promise<void> {\n if (this.destroyAsyncPromise) return this.destroyAsyncPromise;\n\n if (this.lifecycleState === 'destroyed') {\n this.destroyAsyncPromise = Promise.resolve();\n return this.destroyAsyncPromise;\n }\n\n this.lifecycleState = 'closing';\n const shutdownError = new ActionRegisterDestroyedError(this.name, 'closing');\n\n // Store the stable shutdown promise before aborting signals: abort listeners\n // run synchronously and may re-enter destroyAsync().\n let resolveShutdown!: () => void;\n let rejectShutdown!: (error: unknown) => void;\n this.destroyAsyncPromise = new Promise<void>((resolve, reject) => {\n resolveShutdown = resolve;\n rejectShutdown = reject;\n });\n\n if (!this.lifecycleController.signal.aborted) {\n this.lifecycleController.abort(shutdownError);\n }\n\n // Stop guard timers immediately and reject operations that have not begun.\n // Registered handler cleanup is deferred until every started handler settles.\n this.actionGuard.destroy();\n this.dispatchQueue?.clear({ rejectPending: true, reason: shutdownError });\n\n const canFinalizeSynchronously = (\n !deferCleanup &&\n this.dispatchConstructionDepth === 0 &&\n this.activeDispatches.size === 0 &&\n this.activeHandlerPromises.size === 0\n );\n\n if (canFinalizeSynchronously) {\n this.finalizeDestroy();\n resolveShutdown();\n return this.destroyAsyncPromise;\n }\n\n const drainAndFinalize = async () => {\n // Handler promises can be created by a dispatch that was already starting\n // when shutdown began, so drain until both dynamic sets stay empty.\n while (this.activeDispatches.size > 0 || this.activeHandlerPromises.size > 0) {\n await Promise.allSettled([\n ...this.activeDispatches,\n ...this.activeHandlerPromises,\n ]);\n }\n\n this.finalizeDestroy();\n };\n // Dispatch and queue construction call handlers synchronously before their\n // promises can be inserted into the active sets. Start draining on the next\n // microtask so handler-initiated shutdown cannot finalize through that gap.\n void Promise.resolve()\n .then(drainAndFinalize)\n .then(resolveShutdown, rejectShutdown);\n\n // destroy() is intentionally fire-and-forget; keep its internal promise\n // observed while destroyAsync() remains available to callers that need proof.\n void this.destroyAsyncPromise.catch(error => {\n this.log('ActionRegister async destroy failed', error, 'warn');\n });\n return this.destroyAsyncPromise;\n }\n\n private finalizeDestroy(): void {\n if (this.lifecycleState === 'destroyed') return;\n\n this.clearAll();\n this.actionExecutionModes.clear();\n this.lifecycleState = 'destroyed';\n this.log('ActionRegister destroyed');\n }\n\n /**\n * ๐ Destroy method for comprehensive cleanup\n *\n * Begins terminal cleanup of pipelines, guards, queues, and statistics. Cleanup\n * remains synchronous when no work has started; otherwise active handlers drain\n * in the background. Use destroyAsync() when completion must be observed.\n *\n * @public\n */\n destroy(): void {\n void this.beginShutdown();\n }\n\n /**\n * Begin terminal shutdown and resolve after all started handlers have settled\n * and their registered cleanup functions have run.\n *\n * `deferCleanup` closes the register synchronously while deferring final\n * registered cleanup until the next microtask. This is useful for React\n * commit phases that must invalidate stale dispatchers immediately without\n * invoking user cleanup code inside the commit hook itself.\n *\n * Repeated calls return the same promise. New registrations and dispatches are\n * rejected as soon as shutdown begins.\n *\n * @public\n */\n destroyAsync(options: { deferCleanup?: boolean } = {}): Promise<void> {\n return this.beginShutdown(options.deferCleanup ?? false);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,IAAa,cAAb,MAAyB;CAOvB,YAAY,cAAuB,MAAM;EANzC,KAAQ,yBAAS,IAAI,IAAwB;EAG7C,KAAiB,cAAsB;EACvC,KAAiB,oBAA4B;EAG3C,KAAK,qBAAqB;CAC5B;;CAGA,AAAQ,oBAA0B;EAChC,IAAI,KAAK,sBAAsB,CAAC,KAAK,iBACnC,KAAK,iBAAiB;CAE1B;;;;;;CAO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AChC,KAAK,iBAAiB;EACtB,KAAK,IAAI,0BAA0B;CACrC;;;;;;;;;;CAWA,UAAgB;EACd,AAAK,KAAK,cAAc;CAC1B;;;;;;;;;;;;;;;CAgBA,aAAa,UAAsC,CAAC,GAAkB;EACpE,OAAO,KAAK,cAAc,QAAQ,gBAAgB,KAAK;CACzD;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["contextWithErrors"],"sources":["../src/action-guard.ts","../src/concurrency/OperationQueue.ts","../src/errors.ts","../src/execution-modes.ts","../src/types.ts","../src/ActionRegister.ts"],"sourcesContent":["/**\n * @fileoverview Action Guard system for debouncing, throttling and blocking\n * \n * Provides rate limiting and user experience optimization for actions through\n * debouncing (wait for pause) and throttling (limit frequency) mechanisms.\n * Used internally by ActionRegister to control action execution timing.\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/\n */\n\n\n/**\n * Action guard state tracking for debouncing and throttling\n * \n * Tracks timing and execution state for action execution control.\n * Maintains separate state for each action to enable independent\n * rate limiting per action type.\n * \n * @internal\n */\n\ntype TimerHandle = ReturnType<typeof setTimeout>;\n\ninterface GuardState {\n /** Timestamp of the last successful throttle admission. */\n lastThrottleExecutedAt: number;\n\n /** Timestamp of the last successful debounce settlement. */\n lastDebounceSettledAt: number;\n \n /** Active debounce timer - cleared when new debounce requests arrive */\n debounceTimer: TimerHandle | undefined;\n \n /** Active throttle timer - tracks when throttle period will end */\n throttleTimer: TimerHandle | undefined;\n \n /** Flag indicating if action is currently in throttled state */\n isThrottled: boolean;\n \n /** Resolve function for current debounce promise */\n debounceResolve: ((value: boolean) => void) | undefined;\n\n /** Cleanup for the current debounce AbortSignal listener. */\n debounceAbortCleanup: (() => void) | undefined;\n\n /** Identifies the current debounce request so stale timers cannot settle it. */\n debounceRequestId: number;\n}\n\n/**\n * Action Guard system for managing action execution timing\n * \n * Provides performance optimization and user experience enhancement through\n * debouncing and throttling mechanisms. Debouncing waits for a pause in calls\n * before executing, while throttling limits execution frequency.\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @example Manual Usage (Advanced)\n * ```typescript\n * const guard = new ActionGuard()\n * \n * // Manual debouncing\n * if (await guard.debounce('search', 300)) {\n * performSearch() // Only executes after 300ms pause\n * }\n * \n * // Manual throttling\n * if (guard.throttle('scroll', 100)) {\n * updateUI() // Max once per 100ms\n * }\n * ```\n * \n * @internal\n */\nexport class ActionGuard {\n private guards = new Map<string, GuardState>();\n private cleanupInterval: ReturnType<typeof setInterval> | undefined;\n private readonly autoCleanupEnabled: boolean;\n private readonly maxIdleTime: number = 60000; // 1 minute\n private readonly cleanupIntervalMs: number = 30000; // 30 seconds\n\n constructor(autoCleanup: boolean = true) {\n this.autoCleanupEnabled = autoCleanup;\n }\n\n /** Start cleanup only after the first guard is used. */\n private ensureAutoCleanup(): void {\n if (this.autoCleanupEnabled && !this.cleanupInterval) {\n this.startAutoCleanup();\n }\n }\n\n /**\n * Start automatic cleanup of idle guard states\n *\n * @internal\n */\n private startAutoCleanup(): void {\n if (this.cleanupInterval) return;\n\n this.cleanupInterval = setInterval(() => {\n this.performCleanup();\n }, this.cleanupIntervalMs);\n\n // A library-owned maintenance timer must not keep a Node.js process alive.\n (this.cleanupInterval as { unref?: () => void }).unref?.();\n }\n\n private stopAutoCleanup(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n }\n\n /**\n * ๐ง Optimized cleanup with early exit and batched operations\n *\n * @internal\n */\n private performCleanup(): void {\n if (this.guards.size === 0) {\n this.stopAutoCleanup();\n return;\n }\n\n const now = Date.now();\n for (const [key, state] of this.guards) {\n const isIdle = now - Math.max(\n state.lastThrottleExecutedAt,\n state.lastDebounceSettledAt,\n ) > this.maxIdleTime;\n const hasActiveTimers = state.debounceTimer || state.throttleTimer;\n if (isIdle && !hasActiveTimers) {\n this.guards.delete(key);\n }\n }\n\n if (this.guards.size === 0) {\n this.stopAutoCleanup();\n }\n }\n\n /**\n * Apply debouncing to an action\n * \n * Debouncing waits for a specified delay after the last call before allowing\n * execution. Each new call resets the timer. Useful for search inputs, resize\n * handlers, and other high-frequency user interactions.\n * \n * @param actionKey - Unique identifier for the action being debounced\n * @param debounceMs - Delay in milliseconds to wait after the last call\n * \n * @returns Promise resolving to true if execution should proceed, false if cancelled\n * \n * @example Search Input Debouncing\n * ```typescript\n * // Only search after user stops typing for 300ms\n * if (await guard.debounce('userSearch', 300)) {\n * performSearch(query)\n * }\n * ```\n * \n * @internal\n */\n async debounce(\n actionKey: string,\n debounceMs: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n this.ensureAutoCleanup();\n\n if (signal?.aborted) return false;\n\n /** Get or create guard state for this action */\n let state = this.guards.get(actionKey);\n if (!state) {\n /** Initialize new guard state with default values */\n state = {\n lastThrottleExecutedAt: 0,\n lastDebounceSettledAt: 0,\n isThrottled: false,\n debounceTimer: undefined,\n throttleTimer: undefined,\n debounceResolve: undefined as ((value: boolean) => void) | undefined,\n debounceAbortCleanup: undefined,\n debounceRequestId: 0,\n };\n this.guards.set(actionKey, state);\n }\n\n /** Clear any existing debounce timer to restart the delay period */\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n // Resolve previous debounce with false if exists\n if (state.debounceResolve) {\n state.debounceResolve(false);\n state.debounceResolve = undefined as ((value: boolean) => void) | undefined;\n }\n state.debounceAbortCleanup?.();\n state.debounceAbortCleanup = undefined;\n }\n\n const requestId = ++state.debounceRequestId;\n\n /** Create a new abort-aware debounce promise. */\n return new Promise<boolean>((resolve) => {\n let settled = false;\n let abortCleanup: (() => void) | undefined;\n\n const finish = (allowed: boolean) => {\n if (settled) return;\n settled = true;\n\n if (state!.debounceRequestId === requestId) {\n if (state!.debounceTimer) clearTimeout(state!.debounceTimer);\n state!.debounceTimer = undefined;\n state!.debounceResolve = undefined;\n state!.debounceAbortCleanup = undefined;\n if (allowed) state!.lastDebounceSettledAt = Date.now();\n }\n\n abortCleanup?.();\n resolve(allowed);\n };\n\n state!.debounceResolve = finish;\n state!.debounceTimer = setTimeout(() => finish(true), debounceMs);\n\n if (signal) {\n const abort = () => finish(false);\n signal.addEventListener('abort', abort, { once: true });\n abortCleanup = () => signal.removeEventListener('abort', abort);\n state!.debounceAbortCleanup = abortCleanup;\n }\n });\n }\n\n /**\n * Apply throttling to an action\n * \n * Throttling limits execution frequency by ensuring a minimum interval between\n * calls. Unlike debouncing, throttling executes immediately on the first call\n * and then blocks subsequent calls until the interval expires.\n * \n * @param actionKey - Unique identifier for the action being throttled\n * @param throttleMs - Minimum interval in milliseconds between executions\n * \n * @returns True if execution should proceed, false if currently throttled\n * \n * @example Scroll Handler Throttling\n * ```typescript\n * // Update scroll position max once per 100ms\n * if (guard.throttle('scrollUpdate', 100)) {\n * updateScrollPosition()\n * }\n * ```\n * \n * @internal\n */\n throttle(actionKey: string, throttleMs: number, signal?: AbortSignal): boolean {\n this.ensureAutoCleanup();\n\n if (signal?.aborted) return false;\n\n /** Get or create guard state for this action */\n let state = this.guards.get(actionKey);\n if (!state) {\n /** Initialize new guard state with default values */\n state = {\n lastThrottleExecutedAt: 0,\n lastDebounceSettledAt: 0,\n isThrottled: false,\n debounceTimer: undefined,\n throttleTimer: undefined,\n debounceResolve: undefined as ((value: boolean) => void) | undefined,\n debounceAbortCleanup: undefined,\n debounceRequestId: 0,\n };\n this.guards.set(actionKey, state);\n }\n\n const now = Date.now();\n const timeSinceLastExecution = now - state.lastThrottleExecutedAt;\n\n /** Check if enough time has passed since last execution */\n /** If throttle period has elapsed, allow immediate execution */\n if (timeSinceLastExecution >= throttleMs) {\n /** Update execution timestamp and clear throttled state */\n state.lastThrottleExecutedAt = now;\n state.isThrottled = false;\n \n \n return true;\n }\n\n /** If already in throttled state, don't create duplicate timers */\n /** This prevents timer accumulation and unnecessary processing */\n if (state.isThrottled) {\n return false;\n }\n\n /** Set throttle timer to automatically clear the throttled state */\n /** Calculate remaining time until throttle period expires */\n state.isThrottled = true;\n const remainingTime = throttleMs - timeSinceLastExecution;\n \n /** Create timer to reset throttled state when period expires */\n state.throttleTimer = setTimeout(() => {\n /** Clear throttled state and timer reference */\n state!.isThrottled = false;\n state!.throttleTimer = undefined;\n }, remainingTime);\n\n\n return false;\n }\n\n /**\n * Clear all guard state for a specific action\n * \n * Removes debounce and throttle timers for the specified action,\n * preventing memory leaks and allowing immediate re-execution.\n * \n * @param actionKey - Action identifier to clear guards for\n * \n * @internal\n */\n clearGuards(actionKey: string): void {\n const state = this.guards.get(actionKey);\n if (state) {\n // Clear debounce timer and cancel pending promises to prevent memory leaks\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n if (state.debounceResolve) {\n state.debounceResolve(false);\n state.debounceResolve = undefined;\n }\n state.debounceTimer = undefined;\n }\n state.debounceAbortCleanup?.();\n state.debounceAbortCleanup = undefined;\n \n // Clear throttle timer to prevent memory leaks\n if (state.throttleTimer) {\n clearTimeout(state.throttleTimer);\n state.throttleTimer = undefined;\n }\n \n \n // Remove guard state from memory\n this.guards.delete(actionKey);\n if (this.guards.size === 0) {\n this.stopAutoCleanup();\n }\n }\n }\n\n /**\n * Clear all guard states for all actions\n * \n * Removes all active debounce and throttle timers, useful for cleanup\n * when shutting down the action system or resetting state.\n * \n * @internal\n */\n clearAll(): void {\n \n /** Iterate through all guard states and clear their timers */\n /** This prevents memory leaks when clearing the entire guard system */\n this.guards.forEach((state) => {\n /** Clear any active debounce timers */\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n // Cancel waiting debounce calls\n if (state.debounceResolve) {\n state.debounceResolve(false);\n }\n }\n state.debounceAbortCleanup?.();\n /** Clear any active throttle timers */\n if (state.throttleTimer) {\n clearTimeout(state.throttleTimer);\n }\n });\n \n /** Remove all guard states from memory */\n this.guards.clear();\n this.stopAutoCleanup();\n }\n\n /**\n * Get current guard state for debugging purposes\n * \n * Returns the internal state for a specific action, including timer\n * information and execution timestamps.\n * \n * @param actionKey - Action identifier to inspect\n * @returns Guard state or undefined if no state exists\n * \n * @internal\n */\n getGuardState(actionKey: string): GuardState | undefined {\n return this.guards.get(actionKey);\n }\n\n /**\n * Get all active guard states for debugging purposes\n * \n * Returns a copy of all current guard states, useful for monitoring\n * and debugging rate limiting behavior across all actions.\n * \n * @returns Map of action keys to their guard states\n * \n * @internal\n */\n getAllGuardStates(): Map<string, GuardState> {\n return new Map(this.guards);\n }\n\n /**\n * ๐ Explicit destroy method for comprehensive cleanup\n * \n * Cleans up all timers, promises, and intervals to prevent memory leaks.\n * Should be called when ActionGuard is no longer needed.\n * \n * @internal\n */\n destroy(): void {\n // Clear all existing guards\n this.clearAll();\n }\n\n /**\n * ๐ Get statistics about active guards\n * \n * @returns Statistics about guard usage\n * \n * @internal\n */\n getStats(): { activeGuards: number; withTimers: number } {\n let withTimers = 0;\n this.guards.forEach(state => {\n if (state.debounceTimer || state.throttleTimer) {\n withTimers++;\n }\n });\n \n return {\n activeGuards: this.guards.size,\n withTimers\n };\n }\n}\n","/**\n * ๋์์ฑ ๋ฌธ์ ํด๊ฒฐ์ ์ํ ์์
ํ ์์คํ
\n * \n * ๋ชจ๋ ์ํ ๋ณ๊ฒฝ ์์
์ ์ง๋ ฌํํ์ฌ race condition์ ๋ฐฉ์งํฉ๋๋ค.\n */\n\nexport interface QueuedOperation<T = unknown> {\n id: string;\n operation: () => T | Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n priority?: number;\n timestamp: number;\n}\n\nexport interface QueuedOperationHandle<T> {\n promise: Promise<T>;\n /** Cancels only while the operation is still waiting in the queue. */\n cancel(reason?: unknown): boolean;\n}\n\n/**\n * ์์
ํ ๊ด๋ฆฌ์\n *\n * ํต์ฌ ๊ธฐ๋ฅ:\n * 1. ์์
์ง๋ ฌํ - ๋ชจ๋ ์์
์ ์์๋๋ก ์คํ\n * 2. ์ฐ์ ์์ ์ง์ - ์ค์ํ ์์
์ฐ์ ์ฒ๋ฆฌ\n * 3. ์๋ฌ ์ฒ๋ฆฌ - ๊ฐ๋ณ ์์
์คํจ๊ฐ ์ ์ฒด์ ์ํฅ ์ฃผ์ง ์์\n * 4. ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ - ์๋ฃ๋ ์์
์๋ ์ ๋ฆฌ\n * 5. ๐ ๋์์ฑ ์ ์ด - maxConcurrency๋ก ๋์ ์คํ ์ ํ\n * 6. ๐ ๋น๋๊ธฐ ์ง์ - Promise.all() ์๋ฒฝ ์ง์\n * 7. ๐ ์ด๋ฒคํธ ๊ธฐ๋ฐ ์ฒ๋ฆฌ - ํจ์จ์ ์ธ ํ ์ฒ๋ฆฌ ์์คํ
\n */\nexport class OperationQueue {\n private queue: Array<QueuedOperation<unknown>> = [];\n private processingPromise: Promise<void> | null = null;\n private operationCounter = 0;\n \n // ๐ Concurrency control\n private activeOperations = 0;\n private readonly maxConcurrency: number;\n \n constructor(\n private name: string = 'OperationQueue', \n maxConcurrency: number = 1\n ) {\n this.maxConcurrency = Math.max(1, maxConcurrency);\n }\n\n /**\n * ์์
์ ํ์ ์ถ๊ฐํ๊ณ ์คํ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํ\n * \n * @param operation ์คํํ ์์
\n * @param priority ์ฐ์ ์์ (๋์์๋ก ๋จผ์ ์คํ)\n * @returns Promise๋ก ๋ํ๋ ์์
๊ฒฐ๊ณผ\n */\n enqueue<T>(operation: () => T | Promise<T>, priority: number = 0): Promise<T> {\n return this.enqueueWithHandle(operation, priority).promise;\n }\n\n /** Enqueue an operation and retain a handle for pre-start cancellation. */\n enqueueWithHandle<T>(\n operation: () => T | Promise<T>,\n priority: number = 0\n ): QueuedOperationHandle<T> {\n let queuedOperation!: QueuedOperation<T>;\n const promise = new Promise<T>((resolve, reject) => {\n queuedOperation = {\n id: `${this.name}-${++this.operationCounter}`,\n operation,\n resolve,\n reject,\n priority,\n timestamp: Date.now()\n };\n\n\n // ์ฐ์ ์์์ ๋ฐ๋ผ ์ฝ์
์์น ๊ฒฐ์ (๋์ ์ฐ์ ์์๊ฐ ์์ชฝ)\n let insertIndex = this.queue.length;\n for (let i = 0; i < this.queue.length; i++) {\n const item = this.queue[i];\n // ํ์ฌ ์์ดํ
์ ์ฐ์ ์์๊ฐ ์ ์์ดํ
๋ณด๋ค ๋ฎ์ผ๋ฉด, ์ ์์ดํ
์ ์์ ์ฝ์
\n if (item && (item.priority || 0) < priority) {\n insertIndex = i;\n break;\n }\n }\n\n this.queue.splice(insertIndex, 0, queuedOperation as unknown as QueuedOperation<unknown>);\n\n // ํ ์ฒ๋ฆฌ ์์ (์ด๋ฏธ ์ฒ๋ฆฌ ์ค์ด๋ฉด ๋ฌด์๋จ)\n if (this.processingPromise) {\n // ์ด๋ฏธ ์ฒ๋ฆฌ ์ค์ด๋ผ๋ฉด, ๋๊ธฐ ์ค์ธ ํ๋ก์ธ์ค์๊ฒ ์๋ก์ด ์์
์ด ์ถ๊ฐ๋์์์ ์๋ฆผ\n this.notifyNewOperation();\n }\n this.processQueue();\n });\n\n return {\n promise,\n cancel: (reason = new Error('Queue operation cancelled')) => {\n const index = this.queue.indexOf(queuedOperation as unknown as QueuedOperation<unknown>);\n if (index === -1) return false;\n\n this.queue.splice(index, 1);\n queuedOperation.reject(reason);\n this.notifyNewOperation();\n return true;\n },\n };\n }\n\n /**\n * ๐ ํ ์ฒ๋ฆฌ ๋ฉ์ธ ๋ก์ง - ๋์์ฑ ์ ์ด ๋ฐ ๋น๋๊ธฐ ์ง์\n *\n * ์ฃผ์ ํน์ง:\n * - maxConcurrency์ ๋ฐ๋ผ ๋์ ์คํ ์์
์๋ฅผ ์ ํํ์ฌ ๋์์ฑ ๋ฌธ์ ๋ฐฉ์ง\n * - Promise.all() ์๋๋ฆฌ์ค์์ ์๋ฒฝํ ์์ฐจ์ ์คํ ๋ณด์ฅ\n * - ์ด๋ฒคํธ ๊ธฐ๋ฐ ์๋ฆผ ์์คํ
์ผ๋ก ํจ์จ์ ์ธ ๋น๋๊ธฐ ์ฒ๋ฆฌ\n * - ์์
์๋ฃ ์ ๋๊ธฐ ์ค์ธ ํ๋ก์ธ์ค์๊ฒ ์๋ ์๋ฆผ\n */\n private async processQueue(): Promise<void> {\n if (this.processingPromise) {\n // Wait for current processing to complete, then check if we need to process more\n await this.processingPromise;\n // After waiting, check if there are new items to process\n if (this.queue.length > 0 && !this.processingPromise) {\n return this.processQueue();\n }\n return;\n }\n\n this.processingPromise = this._doProcess();\n try {\n await this.processingPromise;\n } finally {\n this.processingPromise = null;\n }\n }\n \n private async _doProcess(): Promise<void> {\n while (this.queue.length > 0 || this.activeOperations > 0) {\n // ๐ ๋์์ฑ ์ ์ด: maxConcurrency ๋งํผ๋ง ๋์ ์คํ\n while (this.queue.length > 0 && this.activeOperations < this.maxConcurrency) {\n const operation = this.queue.shift()!;\n\n // ๐ ๋น๋๊ธฐ ์์
์คํ (await๋ฅผ ์ฌ์ฉํ์ง ์์ - ๋ณ๋ ฌ ์คํ์ ์ํด)\n this.startOperation(operation);\n }\n\n // ๐ ์คํ ์ค์ธ ์์
์ด ์์ผ๋ฉด ํ๋๊ฐ ์๋ฃ๋ ๋๊น์ง ๋๊ธฐ\n if (this.activeOperations > 0) {\n await this.waitForAnyOperation();\n }\n }\n }\n\n /**\n * ๐ ๊ฐ๋ณ ์์
์ ์์ํ๊ณ ์๋ฃ๋ฅผ ์ถ์ \n */\n private startOperation(operation: QueuedOperation<unknown>): void {\n this.activeOperations++;\n\n // ๋น๋๊ธฐ๋ก ์์
์คํ\n this.executeOperation(operation)\n .finally(() => {\n this.activeOperations--;\n\n // ๋๊ธฐ ์ค์ธ ํ๋ก์ธ์ค์๊ฒ ์ ํธ ๋ณด๋ด๊ธฐ\n this.notifyOperationComplete();\n });\n }\n\n private pendingResolvers: Array<() => void> = [];\n\n /**\n * ๐ ํ๋์ ์์
์ด ์๋ฃ๋ ๋๊น์ง ๋๊ธฐํ๊ฑฐ๋ ์๋ก์ด ์์
์ด ์ถ๊ฐ๋ ๋๊น์ง ๋๊ธฐ\n */\n private waitForAnyOperation(): Promise<void> {\n return new Promise<void>((resolve) => {\n this.pendingResolvers.push(resolve);\n });\n }\n\n /**\n * ๐ ์์
์๋ฃ ์ ํธ - ๋๊ธฐ ์ค์ธ ํ๋ก์ธ์ค๋ค์๊ฒ ์๋ฆผ\n */\n private notifyOperationComplete(): void {\n // ๋๊ธฐ ์ค์ธ ๋ชจ๋ ๋ฆฌ์กธ๋ฒ๋ฅผ ๊นจ์ฐ๊ธฐ\n const resolvers = this.pendingResolvers.splice(0);\n resolvers.forEach(resolve => resolve());\n }\n\n /**\n * ๐ ์๋ก์ด ์์
์ถ๊ฐ ์ ํธ - processQueue์์ ํธ์ถ\n */\n private notifyNewOperation(): void {\n // ์๋ก์ด ์์
์ด ์ถ๊ฐ๋์์ผ๋ฏ๋ก ๋๊ธฐ ์ค์ธ ํ๋ก์ธ์ค๋ฅผ ๊นจ์์ ๋ค์ ํ์ธํ๋๋ก ํจ\n this.notifyOperationComplete();\n }\n \n /**\n * ๐ ๊ฐ๋ณ ์์
์คํ ๋ก์ง\n */\n private async executeOperation(operation: QueuedOperation<unknown>): Promise<void> {\n try {\n // ์์
์คํ (๋๊ธฐ/๋น๋๊ธฐ ๋ชจ๋ ์ง์)\n const result = await Promise.resolve(operation.operation());\n operation.resolve(result);\n } catch (error) {\n // ๊ฐ๋ณ ์์
์คํจ๋ ์ ์ฒด ํ์ ์ํฅ ์ฃผ์ง ์์\n operation.reject(error);\n }\n }\n\n /**\n * ๐ ํ์ฌ ํ ์ํ ์กฐํ (๋๋ฒ๊น
์ฉ) - ๋์์ฑ ์ ๋ณด ํฌํจ\n */\n getQueueInfo() {\n return {\n name: this.name,\n queueLength: this.queue.length,\n isProcessing: Boolean(this.processingPromise),\n activeOperations: this.activeOperations,\n maxConcurrency: this.maxConcurrency,\n operations: this.queue.map(op => ({\n id: op.id,\n priority: op.priority,\n timestamp: op.timestamp\n }))\n };\n }\n \n /**\n * ๐ ๋์์ฑ ์ค์ ์กฐํ\n */\n getConcurrencyInfo() {\n return {\n maxConcurrency: this.maxConcurrency,\n activeOperations: this.activeOperations,\n availableSlots: this.maxConcurrency - this.activeOperations,\n queuedOperations: this.queue.length,\n efficiency: this.activeOperations / this.maxConcurrency\n };\n }\n\n /**\n * ํ ๋น์ฐ๊ธฐ (ํ
์คํธ์ฉ)\n */\n clear(options: { rejectPending?: boolean; reason?: unknown } = {}): void {\n const rejectPending = options.rejectPending ?? true;\n const reason = options.reason ?? new Error('Queue cleared');\n\n // Settle queued operations so callers are never left with pending promises.\n this.queue.forEach(operation => {\n if (rejectPending) {\n operation.reject(reason);\n } else {\n operation.resolve(undefined as never);\n }\n });\n\n this.queue = [];\n\n // ๋๊ธฐ ์ค์ธ ๋ฆฌ์กธ๋ฒ๋ค๋ ์ ๋ฆฌ\n const resolvers = this.pendingResolvers.splice(0);\n resolvers.forEach(resolve => resolve());\n }\n\n /**\n * ํ ํฌ๊ธฐ ์กฐํ\n */\n get size(): number {\n return this.queue.length;\n }\n\n /**\n * ์ฒ๋ฆฌ ์ค ์ฌ๋ถ ์กฐํ \n */\n get processing(): boolean {\n return Boolean(this.processingPromise);\n }\n}\n","/**\n * Action Validation Errors\n *\n * Zod ์คํค๋ง ๊ธฐ๋ฐ ๊ฒ์ฆ ์คํจ ์ ๋ฐ์ํ๋ ์๋ฌ ํด๋์ค๋ค\n */\n\n// ============================================\n// Zod Error Compatible Types\n// ============================================\n\n/**\n * Zod Issue interface (loose typing for Zod 4 compatibility)\n */\nexport interface ZodIssueLike {\n message: string;\n path: readonly (string | number | symbol)[];\n code: string;\n}\n\n/**\n * Zod Error interface (loose typing for Zod 4 compatibility)\n * Accepts any object with these minimum required properties\n */\nexport interface ZodErrorLike {\n message: string;\n issues: readonly ZodIssueLike[];\n format?: () => unknown;\n flatten?: () => unknown;\n}\n\n/** Raised when dispatch result aggregation options cannot be processed. */\nexport class ActionResultProcessingError extends Error {\n override name = 'ActionResultProcessingError';\n\n constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, ActionResultProcessingError.prototype);\n }\n}\n\n/** Signals work from a completed race attempt to stop before the next retry. */\nexport class ActionAttemptSupersededError extends Error {\n override name = 'ActionAttemptSupersededError';\n\n constructor(public readonly attempt: number) {\n super(`Action attempt ${attempt} was superseded by a retry.`);\n Object.setPrototypeOf(this, ActionAttemptSupersededError.prototype);\n }\n}\n\nexport function isActionResultProcessingError(\n error: unknown,\n): error is ActionResultProcessingError {\n return error instanceof ActionResultProcessingError;\n}\n\n// ============================================\n// Action Validation Error\n// ============================================\n\n/**\n * Action payload ๊ฒ์ฆ ์คํจ ์๋ฌ\n *\n * dispatch ์ Zod ์คํค๋ง ๊ฒ์ฆ์ด ์คํจํ๋ฉด ๋ฐ์ํฉ๋๋ค.\n * (validationMode๊ฐ 'strict'์ผ ๋๋ง throw)\n *\n * @example\n * ```typescript\n * try {\n * dispatch('updateUser', { id: '', name: 'John' });\n * } catch (error) {\n * if (error instanceof ActionValidationError) {\n * console.log('Action:', error.action);\n * console.log('Issues:', error.issues);\n * console.log('Formatted:', error.formattedErrors);\n * }\n * }\n * ```\n */\nexport class ActionValidationError extends Error {\n /** ์๋ฌ ์ด๋ฆ */\n override name = 'ActionValidationError';\n\n /** ์๋ณธ Zod ์๋ฌ ๊ฐ์ฒด */\n public readonly zodError: unknown;\n\n /**\n * @param action - ๊ฒ์ฆ ์คํจํ action ์ด๋ฆ\n * @param zodError - Zod ๊ฒ์ฆ ์๋ฌ ๊ฐ์ฒด (ZodError compatible)\n */\n constructor(action: string, zodError: unknown) {\n const errorMessage =\n zodError && typeof zodError === 'object' && 'message' in zodError\n ? String((zodError as { message: unknown }).message)\n : 'Validation failed';\n\n const message = `Action \"${action}\" payload validation failed: ${errorMessage}`;\n super(message);\n\n this.action = action;\n this.zodError = zodError;\n\n // Error ์์ ์ prototype chain ๋ณต์ (ES5 ํธํ)\n Object.setPrototypeOf(this, ActionValidationError.prototype);\n }\n\n /** ๊ฒ์ฆ ์คํจํ action ์ด๋ฆ */\n public readonly action: string;\n\n /**\n * Zod ๊ฒ์ฆ ์ด์ ๋ชฉ๋ก\n */\n get issues(): readonly ZodIssueLike[] {\n if (\n this.zodError &&\n typeof this.zodError === 'object' &&\n 'issues' in this.zodError &&\n Array.isArray((this.zodError as { issues: unknown }).issues)\n ) {\n return (this.zodError as { issues: readonly ZodIssueLike[] }).issues;\n }\n return [];\n }\n\n /**\n * ํฌ๋งท๋ ์๋ฌ ๊ฐ์ฒด (ํ๋๋ณ ์๋ฌ ๋ฉ์์ง)\n */\n get formattedErrors(): unknown {\n if (\n this.zodError &&\n typeof this.zodError === 'object' &&\n 'format' in this.zodError &&\n typeof (this.zodError as { format: unknown }).format === 'function'\n ) {\n return (this.zodError as { format: () => unknown }).format();\n }\n return {};\n }\n\n /**\n * ํ๋ซ ์๋ฌ ๋งต (ํ๋๋ช
โ ์๋ฌ ๋ฉ์์ง ๋ฐฐ์ด)\n */\n get flattenedErrors(): unknown {\n if (\n this.zodError &&\n typeof this.zodError === 'object' &&\n 'flatten' in this.zodError &&\n typeof (this.zodError as { flatten: unknown }).flatten === 'function'\n ) {\n return (this.zodError as { flatten: () => unknown }).flatten();\n }\n return { fieldErrors: {}, formErrors: [] };\n }\n\n /**\n * ์ฒซ ๋ฒ์งธ ์๋ฌ ๋ฉ์์ง\n */\n get firstError(): string | undefined {\n return this.issues[0]?.message;\n }\n\n /**\n * ์๋ฌ ๋ฐ์ ํ๋ ๊ฒฝ๋ก ๋ชฉ๋ก\n */\n get errorPaths(): string[] {\n return this.issues.map((issue) =>\n issue.path.map((p) => String(p)).join('.')\n );\n }\n\n /**\n * JSON ์ง๋ ฌํ\n */\n toJSON() {\n return {\n name: this.name,\n action: this.action,\n message: this.message,\n issues: this.issues,\n };\n }\n}\n\n/**\n * Raised when a dispatch exceeds its configured wall-clock timeout.\n * The underlying handler receives an aborted controller signal and the internal\n * queue keeps draining it safely, while the caller is released immediately with\n * this error.\n */\nexport class ActionTimeoutError extends Error {\n override name = 'ActionTimeoutError';\n\n constructor(\n public readonly action: string,\n public readonly timeout: number\n ) {\n super(`Action \"${action}\" timed out after ${timeout}ms`);\n Object.setPrototypeOf(this, ActionTimeoutError.prototype);\n }\n}\n\n/** Raised when work is submitted after an ActionRegister begins shutdown. */\nexport class ActionRegisterDestroyedError extends Error {\n override name = 'ActionRegisterDestroyedError';\n\n constructor(\n public readonly registerName: string,\n public readonly state: 'closing' | 'destroyed'\n ) {\n super(`ActionRegister \"${registerName}\" is ${state} and cannot accept new work`);\n Object.setPrototypeOf(this, ActionRegisterDestroyedError.prototype);\n }\n}\n\n// ============================================\n// Type Guard\n// ============================================\n\n/**\n * ActionValidationError ํ์
๊ฐ๋\n */\nexport function isActionValidationError(\n error: unknown\n): error is ActionValidationError {\n return error instanceof ActionValidationError;\n}\n\n/** ActionTimeoutError type guard. */\nexport function isActionTimeoutError(\n error: unknown\n): error is ActionTimeoutError {\n return error instanceof ActionTimeoutError;\n}\n\n/** ActionRegisterDestroyedError type guard. */\nexport function isActionRegisterDestroyedError(\n error: unknown\n): error is ActionRegisterDestroyedError {\n return error instanceof ActionRegisterDestroyedError;\n}\n","/**\n * @fileoverview Execution mode implementations for ActionRegister\n * \n * Provides three different execution strategies for action handler pipelines:\n * - Sequential: Execute handlers one after another in priority order\n * - Parallel: Execute all handlers simultaneously\n * - Race: First handler to complete wins, other started handlers keep running\n */\n\nimport type { \n HandlerError,\n HandlerExecutionOutcome,\n HandlerRegistration, \n PipelineContext,\n PipelineController,\n PipelineControllerState,\n} from './types.js';\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\nfunction beginOutcome<T, R>(registration: HandlerRegistration<T, R>): HandlerExecutionOutcome<R> {\n return {\n id: registration.id,\n status: 'running',\n executed: true,\n duration: undefined,\n result: undefined,\n error: undefined,\n metadata: registration.config.metadata\n ? { ...registration.config.metadata }\n : undefined,\n };\n}\n\nfunction createSkippedOutcome<T, R>(\n registration: HandlerRegistration<T, R>,\n): HandlerExecutionOutcome<R> {\n return {\n id: registration.id,\n status: 'skipped',\n executed: false,\n duration: 0,\n result: undefined,\n error: undefined,\n metadata: registration.config.metadata\n ? { ...registration.config.metadata }\n : undefined,\n };\n}\n\nfunction finishOutcome<R>(\n outcome: HandlerExecutionOutcome<R>,\n startedAt: number,\n status: 'succeeded' | 'failed',\n result?: R,\n error?: Error,\n): void {\n outcome.status = status;\n outcome.duration = Date.now() - startedAt;\n outcome.result = result;\n outcome.error = error;\n}\n\nfunction appendLocalResults<T, R>(\n context: PipelineContext<T, R>,\n state: PipelineControllerState<T, R>,\n returnedResult: R | undefined,\n registration: HandlerRegistration<T, R>,\n target: R[] = context.results,\n): void {\n if (registration.role === 'guard') return;\n if (state.results.length > 0) target.push(...state.results);\n if (returnedResult !== undefined && !state.terminated) {\n target.push(returnedResult);\n }\n}\n\n/**\n * Create standardized error handling for handlers\n * \n * @param error - The error that occurred\n * @param registration - The handler registration that failed\n * @returns Standardized HandlerError object\n * \n * @internal\n */\nfunction handleExecutionError<T, R>(\n error: unknown,\n registration: HandlerRegistration<T, R>\n): HandlerError {\n const errorObj = error instanceof Error ? error : new Error(String(error));\n return {\n handlerId: registration.id,\n error: errorObj,\n timestamp: Date.now(),\n severity: registration.config.errorPolicy === 'fatal' ? 'blocking' : 'non-blocking'\n };\n}\n\n/**\n * Execute handlers in sequential mode (one after another)\n * \n * Executes action handlers one at a time in priority order (highest first).\n * Supports both blocking and non-blocking handlers, with proper abort and\n * termination handling. Handlers can modify payload for subsequent handlers\n * and jump to different priority levels.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When a blocking handler fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns\n * \n * @public\n */\nexport async function executeSequential<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (registration: HandlerRegistration<T, R>, index: number) => PipelineController<T, R>\n): Promise<void> {\n\n let i = 0;\n const nonBlockingPromises: Array<Promise<unknown>> = [];\n const errors: HandlerError[] = [];\n \n while (i < context.handlers.length) {\n // Check for abort or termination\n if (context.aborted || context.terminated) {\n break;\n }\n\n const registration = context.handlers[i];\n if (!registration) {\n continue; // Skip if handler not found\n }\n context.currentIndex = i;\n const controller = createController(registration, i);\n\n // A condition is part of the dispatch contract, not a best-effort handler.\n // Evaluate it outside the non-blocking handler error path so a broken\n // predicate is never silently converted into a skipped handler.\n if (registration.config.condition) {\n const shouldExecute = registration.config.condition(context.payload);\n if (!shouldExecute) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n i++;\n continue;\n }\n }\n\n if (context.claimOnce && !context.claimOnce(registration)) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n i++;\n continue;\n }\n\n const outcome = beginOutcome(registration);\n const startedAt = Date.now();\n (context.handlerOutcomes ??= []).push(outcome);\n\n try {\n // Check for abort before executing handler\n if (context.aborted) {\n outcome.status = 'cancelled';\n outcome.executed = false;\n outcome.duration = 0;\n break;\n }\n\n (context.executedHandlers ??= []).push(registration);\n const result = registration.handler(context.payload, controller);\n const asyncResult = isPromiseLike(result) ? Promise.resolve(result) : undefined;\n const trackedResult = asyncResult && context.trackHandlerPromise\n ? context.trackHandlerPromise<unknown>(asyncResult)\n : asyncResult;\n\n if (registration.config.scheduling === 'await-before-next') {\n // Sequential mode is genuinely sequential by default: an async\n // handler settles before the next priority slot starts.\n const handlerResult = trackedResult\n ? await trackedResult\n : result;\n finishOutcome(\n outcome,\n startedAt,\n 'succeeded',\n registration.role === 'guard' ? undefined : handlerResult as R | undefined,\n );\n if (\n registration.role !== 'guard' &&\n handlerResult !== undefined &&\n !context.terminated\n ) {\n context.results.push(handlerResult as R);\n }\n } else {\n // ๐ Non-blocking handlers: Handle differently for sync vs async\n if (trackedResult) {\n // Non-blocking async: Track promise with error handling\n const promiseWithErrorHandling = trackedResult\n .then(asyncResult => {\n finishOutcome(\n outcome,\n startedAt,\n 'succeeded',\n registration.role === 'guard' ? undefined : asyncResult as R | undefined,\n );\n if (\n registration.role !== 'guard' &&\n asyncResult !== undefined &&\n !context.terminated\n ) {\n context.results.push(asyncResult as R);\n }\n return asyncResult;\n })\n .catch(error => {\n // ๐ Non-blocking async handler error collection\n const handlerError = handleExecutionError(error, registration);\n errors.push(handlerError);\n finishOutcome(\n outcome,\n startedAt,\n 'failed',\n undefined,\n handlerError.error,\n );\n return undefined; // Return undefined for failed non-blocking handlers\n });\n \n nonBlockingPromises.push(promiseWithErrorHandling);\n } else if (\n registration.role !== 'guard' &&\n result !== undefined &&\n !context.terminated\n ) {\n // Non-blocking sync: Immediately collect result\n finishOutcome(outcome, startedAt, 'succeeded', result as R);\n context.results.push(result as R);\n } else {\n finishOutcome(\n outcome,\n startedAt,\n 'succeeded',\n registration.role === 'guard' ? undefined : result as R | undefined,\n );\n }\n }\n\n outcome.terminationRequested = context.terminated;\n if (context.terminated) outcome.terminationResult = context.terminationResult;\n\n /** Check if pipeline was terminated by controller.return() */\n if (context.terminated) {\n break;\n }\n\n /** Handle jump to priority AFTER handler execution */\n if (context.jumpToPriority !== undefined) {\n // Check if we've exceeded maximum jumps to prevent infinite loops\n context.jumpCount = (context.jumpCount || 0) + 1;\n if (context.jumpCount > (context.maxJumps || 10)) {\n context.aborted = true;\n context.abortReason = `Maximum jump limit exceeded (${context.jumpCount} jumps)`;\n context.jumpToPriority = undefined;\n break;\n }\n\n // Find first handler with priority <= jumpToPriority\n const jumpIndex = context.handlers.findIndex(\n handler => (handler.config.priority || 0) <= context.jumpToPriority!\n );\n\n if (jumpIndex !== -1 && jumpIndex !== i) {\n // The bounded jump counter protects both forward and backward jumps\n // without emitting diagnostics from the execution primitive.\n i = jumpIndex;\n context.jumpToPriority = undefined;\n } else {\n // No valid jump target found, or jumping to same handler\n context.jumpToPriority = undefined;\n i++;\n }\n } else {\n i++;\n }\n\n } catch (error: unknown) {\n // ๐ง Fix: Handle errors gracefully and continue pipeline execution\n const handlerError = handleExecutionError(error, registration);\n finishOutcome(outcome, startedAt, 'failed', undefined, handlerError.error);\n errors.push(handlerError);\n (context.collectedErrors ??= []).push(handlerError);\n\n // Fatal errors terminate the pipeline; collected errors let it continue.\n if (registration.config.errorPolicy === 'fatal') {\n throw handlerError.error;\n }\n\n // For non-blocking handlers, continue to next handler\n i++;\n }\n }\n \n // ๐ Wait for all non-blocking promises with error collection\n if (nonBlockingPromises.length > 0) {\n await Promise.allSettled(nonBlockingPromises);\n }\n\n if (errors.length > 0) {\n context.collectedErrors = errors;\n }\n\n // A fatal handler may already have allowed lower-priority work to start,\n // but it must still reject the final dispatch once that work has settled.\n const fatalError = errors.find(error => error.severity === 'blocking');\n if (fatalError) throw fatalError.error;\n}\n\n/**\n * Execute handlers in parallel mode (all at once)\n * \n * Executes all qualifying action handlers simultaneously using Promise.allSettled.\n * Supports both blocking and non-blocking handlers. Blocking handlers can still\n * fail the entire pipeline if they throw errors.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When any blocking handler fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns#parallel-execution\n * \n * @public\n */\nexport async function executeParallel<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (\n registration: HandlerRegistration<T, R>,\n index: number,\n state: PipelineControllerState<T, R>,\n ) => PipelineController<T, R>\n): Promise<void> {\n\n /**\n * Conditions are dispatch preconditions in concurrent modes. Evaluate them\n * before any handler starts so a predicate error rejects the dispatch rather\n * than being mistaken for a non-blocking handler failure.\n */\n const runnableHandlers: HandlerRegistration<T, R>[] = [];\n for (const registration of context.handlers) {\n if (registration.config.condition && !registration.config.condition(context.payload)) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n continue;\n }\n if (context.claimOnce && !context.claimOnce(registration)) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n continue;\n }\n runnableHandlers.push(registration);\n }\n\n const terminationSlots: Array<{\n requested: boolean;\n result: R | undefined;\n }> = runnableHandlers.map(() => ({ requested: false, result: undefined }));\n const resultSlots: R[][] = runnableHandlers.map(() => []);\n\n /** Create promises for all handlers */\n const handlerPromises = runnableHandlers.map(async (registration, _index) => {\n const state: PipelineControllerState<T, R> = {\n payload: context.payload,\n aborted: false,\n abortReason: undefined,\n jumpToPriority: undefined,\n terminated: false,\n terminationResult: undefined,\n results: [],\n };\n const controller = createController(registration, _index, state);\n const outcome = beginOutcome(registration);\n const startedAt = Date.now();\n (context.handlerOutcomes ??= []).push(outcome);\n\n try {\n (context.executedHandlers ??= []).push(registration);\n const result = registration.handler(state.payload, controller);\n \n const handlerResult = (\n isPromiseLike(result) ? await Promise.resolve(result) : result\n ) as R | undefined;\n \n finishOutcome(\n outcome,\n startedAt,\n 'succeeded',\n registration.role === 'guard' ? undefined : handlerResult,\n );\n outcome.terminationRequested = state.terminated;\n if (state.terminated && registration.role !== 'guard') {\n outcome.terminationResult = state.terminationResult;\n terminationSlots[_index] = {\n requested: true,\n result: state.terminationResult,\n };\n }\n appendLocalResults(context, state, handlerResult, registration, resultSlots[_index]);\n return { \n success: true, \n handlerId: registration.id, \n result: handlerResult,\n terminated: state.terminated,\n state,\n outcome,\n };\n \n } catch (error: unknown) {\n // ๐ Consistent error object creation\n const handlerError = handleExecutionError(error, registration);\n finishOutcome(outcome, startedAt, 'failed', undefined, handlerError.error);\n (context.collectedErrors ??= []).push(handlerError);\n \n if (handlerError.severity === 'blocking') {\n throw handlerError.error;\n }\n \n return {\n success: false,\n handlerId: registration.id,\n error: handlerError.error,\n state,\n outcome,\n registration,\n };\n }\n });\n\n const trackedHandlerPromises = context.trackHandlerPromise\n ? handlerPromises.map(promise => context.trackHandlerPromise!(promise))\n : handlerPromises;\n\n /** Wait for all handlers to complete */\n const results = await Promise.allSettled(trackedHandlerPromises);\n\n // Completion timing is intentionally concurrent, but collected result\n // order follows the priority-sorted handler order. This makes first/last/\n // all strategies deterministic across runs.\n context.results.push(...resultSlots.flat());\n \n /** Check for any rejected blocking handlers */\n const failures = results.filter((result, index) => {\n if (result.status === 'rejected') {\n const registration = runnableHandlers[index];\n return registration?.config.errorPolicy === 'fatal';\n }\n return false;\n });\n\n if (failures.length > 0) {\n const firstFailure = failures[0] as PromiseRejectedResult;\n throw firstFailure.reason;\n }\n\n /** Check if any handler terminated the pipeline */\n const firstTerminated = terminationSlots.find(slot => slot.requested);\n if (firstTerminated) {\n context.terminated = true;\n context.terminationResult = firstTerminated.result;\n }\n}\n\n/**\n * Execute handlers in race mode (first to complete wins)\n * \n * Executes all qualifying handlers simultaneously using Promise.race, where\n * the first handler to complete determines the pipeline result. Other handlers\n * continue in the background and remain tracked for lifecycle cleanup; handlers\n * must observe the controller signal for cooperative external cancellation.\n * Useful for scenarios where you want the fastest response from multiple\n * equivalent handlers.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When the winning handler fails and is blocking\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns#race-execution\n * \n * @public\n */\nexport async function executeRace<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (\n registration: HandlerRegistration<T, R>,\n index: number,\n state: PipelineControllerState<T, R>,\n ) => PipelineController<T, R>\n): Promise<void> {\n\n /** See executeParallel: condition errors are dispatch errors in concurrent modes. */\n const runnableHandlers: HandlerRegistration<T, R>[] = [];\n for (const registration of context.handlers) {\n if (registration.config.condition && !registration.config.condition(context.payload)) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n continue;\n }\n if (context.claimOnce && !context.claimOnce(registration)) {\n (context.handlerOutcomes ??= []).push(createSkippedOutcome(registration));\n continue;\n }\n runnableHandlers.push(registration);\n }\n\n if (runnableHandlers.length === 0) {\n return;\n }\n\n /** Create promises for all handlers */\n const handlerPromises = runnableHandlers.map(async (registration, _index) => {\n const state: PipelineControllerState<T, R> = {\n payload: context.payload,\n aborted: false,\n abortReason: undefined,\n jumpToPriority: undefined,\n terminated: false,\n terminationResult: undefined,\n results: [],\n };\n const controller = createController(registration, _index, state);\n const outcome = beginOutcome(registration);\n const startedAt = Date.now();\n (context.handlerOutcomes ??= []).push(outcome);\n\n try {\n (context.executedHandlers ??= []).push(registration);\n const result = registration.handler(state.payload, controller);\n \n const handlerResult = (\n isPromiseLike(result) ? await Promise.resolve(result) : result\n ) as R | undefined;\n \n finishOutcome(\n outcome,\n startedAt,\n 'succeeded',\n registration.role === 'guard' ? undefined : handlerResult,\n );\n outcome.terminationRequested = state.terminated;\n if (state.terminated) outcome.terminationResult = state.terminationResult;\n\n return {\n success: true, \n handlerId: registration.id, \n registration,\n result: handlerResult,\n terminated: state.terminated,\n state,\n outcome,\n };\n \n } catch (error: unknown) {\n // ๐ Consistent error object creation\n const handlerError = handleExecutionError(error, registration);\n finishOutcome(outcome, startedAt, 'failed', undefined, handlerError.error);\n return {\n success: false,\n handlerId: registration.id,\n error: handlerError.error,\n registration,\n state,\n outcome,\n };\n }\n });\n\n const trackedHandlerPromises = context.trackHandlerPromise\n ? handlerPromises.map(promise => context.trackHandlerPromise!(promise))\n : handlerPromises;\n\n // Guards are executed by the register before race arbitration. Retain this\n // filtering for callers of this low-level primitive.\n const winnerCandidates = runnableHandlers.some(handler => handler.role !== 'guard')\n ? trackedHandlerPromises.filter((_, index) => (\n runnableHandlers[index]?.role !== 'guard'\n ))\n : trackedHandlerPromises;\n\n /** Race all handlers while retaining every loser for lifecycle draining. */\n const winner = await Promise.race(winnerCandidates);\n context.raceWinnerId = winner.handlerId;\n context.raceLoserOutcomes = (context.handlerOutcomes ?? [])\n .filter(outcome => outcome.id !== winner.handlerId)\n .map(outcome => ({ ...outcome, metadata: outcome.metadata ? { ...outcome.metadata } : undefined }));\n\n /** If the winner failed and was blocking, throw the error */\n if (!winner.success && winner.registration?.config.errorPolicy === 'fatal') {\n (context.collectedErrors ??= []).push(handleExecutionError(\n winner.error,\n winner.registration,\n ));\n throw winner.error;\n }\n\n // Losers are diagnostics-only. Their asynchronous completion must not\n // change the result, outcome, or errors selected by the winning handler.\n if (!winner.success) {\n (context.collectedErrors ??= []).push(handleExecutionError(\n winner.error,\n winner.registration,\n ));\n }\n\n /** Only the winner contributes results to the race snapshot. */\n if (winner.success) {\n appendLocalResults(context, winner.state, winner.result, winner.registration);\n if (winner.state.aborted) {\n context.aborted = true;\n context.abortReason = winner.state.abortReason;\n }\n }\n\n /** Check if the winning handler terminated the pipeline */\n if (winner.success && winner.terminated) {\n context.terminated = true;\n context.terminationResult = winner.state.terminationResult;\n }\n}\n","\n/**\n * Action payload mapping interface for type-safe action dispatching\n * \n * Defines the mapping between action names and their corresponding payload types.\n * This interface serves as the foundation for type-safe action handling throughout\n * the Context-Action framework.\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/type-system\n * \n * @public\n */\n/**\n * Marker type for action payload maps.\n *\n * Deliberately does not declare a string index signature: adding one would\n * widen `keyof` to `string | number` and make unknown action names compile.\n * Applications extend this type from an interface with literal action keys.\n */\nexport type ActionPayloadMap = object;\n\n/**\n * Minimal runtime contract consumed by ActionRegister for payload validation.\n *\n * The concrete Zod-backed action schema lives in\n * `@context-action/tool-protocol`; keeping this structural contract here\n * avoids coupling the action runtime to transport and schema adapters.\n */\nexport interface ActionSchemaLike {\n safeParse(value: unknown):\n | { success: true; data: unknown }\n | {\n success: false;\n error: {\n message: string;\n issues: readonly { message: string }[];\n };\n };\n}\n\n/**\n * Strict action payload map that prevents certain problematic types\n */\nexport type StrictActionPayloadMap = {\n readonly [K in string]: Exclude<unknown, Function | symbol>;\n};\n\n/**\n * Brand type utilities for enhanced type safety\n */\ndeclare const __brand: unique symbol;\n\n/**\n * Creates a branded type for nominal typing\n */\nexport type Brand<T, B extends string> = T & { readonly [__brand]: B };\n\n/**\n * Branded action key for type safety\n */\nexport type ActionKey<T extends string = string> = Brand<T, 'ActionKey'>;\n\n/**\n * Branded store identifier for type safety\n */\nexport type StoreId<T extends string = string> = Brand<T, 'StoreId'>;\n\n/**\n * Branded handler identifier for type safety\n */\nexport type HandlerId<T extends string = string> = Brand<T, 'HandlerId'>;\n\n/**\n * Creates an action key with type branding\n */\nexport function createActionKey<T extends string>(key: T): ActionKey<T> {\n return key as ActionKey<T>;\n}\n\n/**\n * Creates a store ID with type branding\n */\nexport function createStoreId<T extends string>(id: T): StoreId<T> {\n return id as StoreId<T>;\n}\n\n/**\n * Creates a handler ID with type branding\n */\nexport function createHandlerId<T extends string>(id: T): HandlerId<T> {\n return id as HandlerId<T>;\n}\n\n/**\n * Valid result strategies for type safety\n */\nexport type ValidResultStrategy = 'first' | 'last' | 'all' | 'merge' | 'custom';\n\n/**\n * Advanced type utilities for result processing with strict constraints\n */\nexport type ResultStrategyType<Strategy extends ValidResultStrategy, R> =\n Strategy extends 'all'\n ? readonly R[]\n : Strategy extends 'first' | 'last'\n ? R | undefined\n : Strategy extends 'merge' | 'custom'\n ? R\n : never;\n\n/**\n * Infer result type based on strategy and collect options\n */\nexport type InferResultType<\n R,\n Options extends { strategy?: string; collect?: boolean } | undefined\n> = Options extends { strategy: infer Strategy }\n ? Strategy extends ValidResultStrategy\n ? ResultStrategyType<Strategy, R>\n : R\n : Options extends { collect: true }\n ? readonly R[]\n : R;\n\n/**\n * Advanced type-level utilities for Context-Action framework\n */\nexport namespace TypeUtils {\n /**\n * Extracts payload type for a specific action\n */\n export type ExtractPayload<T extends ActionPayloadMap, K extends keyof T> = T[K];\n\n /**\n * Ensures all values in an object are of the same type\n */\n export type Homogeneous<T, U> = {\n readonly [K in keyof T]: U;\n };\n\n /**\n * Makes specific properties required\n */\n export type RequireFields<T, K extends keyof T> = T & Required<Pick<T, K>>;\n\n /**\n * Makes specific properties optional\n */\n export type PartialFields<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\n\n /**\n * Deep readonly type for immutable structures\n */\n export type DeepReadonly<T> = {\n readonly [P in keyof T]: T[P] extends (infer U)[]\n ? readonly DeepReadonly<U>[]\n : T[P] extends readonly (infer U)[]\n ? readonly DeepReadonly<U>[]\n : T[P] extends Record<string, unknown>\n ? DeepReadonly<T[P]>\n : T[P];\n };\n\n /**\n * Strict non-nullable type\n */\n export type NonNullable<T> = T extends null | undefined ? never : T;\n\n /**\n * Type-safe key extraction\n */\n export type KeysOfType<T, U> = {\n [K in keyof T]: T[K] extends U ? K : never;\n }[keyof T];\n\n /**\n * Function parameter extraction\n */\n export type Parameters<T> = T extends (...args: infer P) => unknown ? P : never;\n\n /**\n * Function return type extraction\n */\n export type ReturnType<T> = T extends (...args: unknown[]) => infer R ? R : never;\n\n /**\n * Promise unwrapping\n */\n export type Awaited<T> = T extends Promise<infer U> ? U : T;\n}\n\n/**\n * Utility type to extract action names from ActionPayloadMap\n * \n * @template T - The ActionPayloadMap interface\n * @example\n * ```typescript\n * type MyActions = ActionNames<AppActions> // 'updateUser' | 'deleteUser' | 'resetUser'\n * ```\n */\n/** String action names supported by the registry and action proxies. */\nexport type ActionNames<T extends ActionPayloadMap> = Extract<keyof T, string>;\n\n/**\n * Utility type to extract payload type for a specific action\n * \n * @template T - The ActionPayloadMap interface \n * @template K - The action name\n * @example\n * ```typescript\n * type UpdateUserPayload = ActionPayload<AppActions, 'updateUser'>\n * // { id: string; name: string; email: string }\n * ```\n */\nexport type ActionPayload<T extends ActionPayloadMap, K extends keyof T> = T[K];\n\n/**\n * Optional action-keyed result contract for `dispatchWithResult`.\n *\n * The legacy API allows callers to provide an explicit result generic. New\n * code can instead associate result types with action keys at the register\n * level so the result type is inferred from the dispatched action.\n */\nexport type ActionResultMap<T extends ActionPayloadMap> = Partial<\n Record<ActionNames<T>, unknown>\n>;\n\n/** Resolve the configured result type for an action, falling back to void. */\nexport type ActionResult<\n TResultMap extends ActionPayloadMap,\n K extends PropertyKey,\n> = K extends keyof TResultMap ? TResultMap[K]\n // biome-ignore lint/suspicious/noConfusingVoidType: void preserves the legacy no-result dispatch contract.\n : void;\n\n/**\n * Pipeline controller interface for managing execution flow and payload modification\n * \n * Provides action handlers with powerful control over the action pipeline execution,\n * including the ability to abort execution, modify payloads, jump to specific priorities,\n * and manage results. This is the primary interface for implementing business logic\n * within action handlers.\n * \n * @template T - The payload type for this action\n * @template R - The result type for this action\n * \n * @example Basic Pipeline Control\n * ```typescript\n * register.register('validateAndProcess', async (payload, controller) => {\n * // Input validation\n * if (!payload.email.includes('@')) {\n * controller.abort('Invalid email format')\n * return\n * }\n * \n * // Process and modify payload for next handlers\n * controller.modifyPayload(data => ({\n * ...data,\n * processed: true,\n * timestamp: Date.now(),\n * normalized: data.email.toLowerCase()\n * }))\n * \n * // Set intermediate result\n * controller.setResult({ validated: true, userId: payload.id })\n * })\n * ```\n * \n * @example Early Return with Result\n * ```typescript\n * register.register('checkCache', async (payload, controller) => {\n * const cached = await cache.get(payload.key)\n * \n * if (cached) {\n * // Return early and skip remaining handlers\n * controller.return({ source: 'cache', data: cached })\n * return\n * }\n * \n * // Continue to next handlers if not cached\n * })\n * ```\n * \n * @example Priority Jumping\n * ```typescript\n * register.register('securityCheck', async (payload, controller) => {\n * if (payload.requiresElevatedPermissions) {\n * // Jump to high-priority security handlers\n * controller.jumpToPriority(1000)\n * }\n * }, { priority: 50 })\n * ```\n * \n * @public\n */\nexport interface PipelineController<T = unknown, R = void> {\n /**\n * Signal for the current dispatch lifecycle.\n *\n * Handlers should observe this signal when they can stop cooperatively. It is\n * aborted by caller cancellation, timeout, provider teardown, or registry\n * shutdown.\n */\n readonly signal?: AbortSignal;\n\n /** Abort the pipeline execution with an optional reason */\n abort(reason?: string): void;\n \n /** Modify the payload that will be passed to subsequent handlers */\n modifyPayload(modifier: (payload: T) => T): void;\n \n /** Get the current payload */\n getPayload(): T;\n\n /**\n * Jump to a specific priority level in the pipeline\n *\n * โ ๏ธ **WARNING**: Backward jumps (to higher priority handlers) can cause infinite loops!\n * Always use with a `condition` in the target handler to prevent re-execution.\n *\n * The system will automatically abort after 10 jumps (configurable) to prevent infinite loops.\n *\n * @param priority - The priority level to jump to (finds first handler with priority <= this value)\n *\n * @example Safe retry pattern with condition\n * ```typescript\n * let retryCount = 0;\n *\n * register.register('process', (payload, controller) => {\n * retryCount++;\n * if (shouldRetry() && retryCount < 3) {\n * controller.jumpToPriority(100); // Jump back to validation\n * }\n * }, { priority: 50 });\n *\n * register.register('validate', (payload) => {\n * // Validation logic\n * }, {\n * priority: 100,\n * condition: () => retryCount === 0 // Only run on first attempt\n * });\n * ```\n */\n jumpToPriority(priority: number): void;\n \n // New result handling methods\n /** Return a result and terminate the pipeline. The result is returned for ergonomic result handlers. */\n return(result: R): R;\n \n /** Set a result but continue pipeline execution */\n setResult(result: R): void;\n \n /** Get all results from previously executed handlers */\n getResults(): R[];\n \n /** Merge current result with previous results using a custom merger function */\n mergeResult(merger: (previousResults: R[], currentResult: R) => R): void;\n}\n\n/** Controller available to observer-only effect handlers. */\nexport interface ActionEffectController<T = unknown> {\n readonly signal?: AbortSignal;\n getPayload(): T;\n}\n\n/** Controller available to preflight guards. Guards may reject or normalize input,\n * but cannot publish a result or terminate a result pipeline. */\nexport interface ActionGuardController<T = unknown> extends ActionEffectController<T> {\n abort(reason?: string): void;\n modifyPayload(modifier: (payload: T) => T): void;\n}\n\n/** Controller for a result-producing handler. Concurrent result handlers do\n * not receive payload mutation or priority-jump capabilities. */\nexport interface ActionResultController<T = unknown, R = void>\n extends ActionEffectController<T> {\n abort(reason?: string): void;\n return(result: R): R;\n setResult(result: R): void;\n getResults(): readonly R[];\n mergeResult(merger: (previousResults: readonly R[], currentResult: R) => R): void;\n}\n\n/** The explicit execution role of a registered handler. */\nexport type HandlerRole = 'guard' | 'result' | 'observer' | 'legacy';\n\n/** Immutable terminal event delivered to observer handlers. */\nexport interface ActionObserverEvent<T = unknown, R = void> {\n readonly action: string;\n readonly payload: Readonly<T>;\n readonly outcome: ExecutionResult<R>['outcome'];\n readonly result: R | readonly R[] | undefined;\n readonly errors: readonly HandlerError[];\n readonly signal?: AbortSignal;\n}\n\n/** A post-result side effect. Observer return values are deliberately ignored. */\nexport type ActionObserverHandler<T = unknown, R = void> = (\n event: ActionObserverEvent<T, R>,\n) => void | Promise<void>;\n\n/** Scheduling and terminal-path selection for a post-result observer. */\nexport interface ObserverConfig<T = unknown> extends Omit<HandlerConfig<T>,\n 'debounce' | 'throttle' | 'blocking' | 'errorPolicy'> {\n when?: 'success' | 'failure' | 'always';\n}\n\n/** Configuration accepted by an admission guard. Guard failures always deny\n * admission, so scheduling and error-policy controls are intentionally not\n * configurable. */\nexport interface GuardConfig<T = unknown> extends Omit<HandlerConfig<T>,\n 'blocking' | 'scheduling' | 'errorPolicy' | 'debounce' | 'throttle' | 'when'> {}\n\n/** Configuration for the supported `registerEffect()` convenience API.\n * New code with a statically known role may call `registerGuard()` or\n * `registerObserver()` directly. */\nexport interface EffectConfig<T = unknown> extends HandlerConfig<T> {\n /** Select the explicit phase that owns this legacy effect. */\n effectKind: 'guard' | 'observer';\n}\n\n/**\n * Action handler function type for processing actions within the pipeline\n * \n * Defines the signature for action handler functions that contain the business logic\n * for processing specific actions. Handlers follow the Store Integration Pattern:\n * 1. Read current state from stores\n * 2. Execute business logic\n * 3. Update stores with new state\n * \n * @template T - The payload type for this action\n * @template R - The return type for this handler\n * \n * @param payload - The action payload data\n * @param controller - Pipeline controller for managing execution flow\n * \n * @returns The result value or Promise resolving to result\n * \n * @example Store Integration Pattern\n * ```typescript\n * const updateUserHandler: ActionHandler<{id: string, name: string, email: string}> = \n * async (payload, controller) => {\n * // 1. Read current state from stores\n * const currentUser = userStore.getValue()\n * const settings = settingsStore.getValue()\n * \n * // 2. Execute business logic\n * if (!settings.allowUserUpdates) {\n * controller.abort('User updates are disabled')\n * return\n * }\n * \n * const updatedUser = {\n * ...currentUser,\n * ...payload,\n * updatedAt: new Date().toISOString()\n * }\n * \n * // 3. Update stores\n * userStore.setValue(updatedUser)\n * \n * // Set result for other handlers or components\n * controller.setResult({ success: true, user: updatedUser })\n * }\n * ```\n * \n * @example Async Handler with Error Handling\n * ```typescript\n * const saveUserHandler: ActionHandler<UserData, SaveResult> = \n * async (payload, controller) => {\n * try {\n * const result = await userService.save(payload)\n * \n * // Update local store with server response\n * userStore.setValue(result.user)\n * \n * return { success: true, userId: result.user.id }\n * } catch (error) {\n * controller.abort(`Save failed: ${error.message}`)\n * return { success: false, error: error.message }\n * }\n * }\n * ```\n * \n * @public\n */\nexport type ActionHandler<T = unknown, R = void> = (\n payload: T,\n controller: PipelineController<T, R>\n) => R | Promise<R> | void | Promise<void>;\n\n/** A side-effect observer. Its return value and result APIs are intentionally unavailable. */\nexport type ActionEffectHandler<T = unknown> = (\n payload: T,\n controller: ActionEffectController<T>,\n) => void | Promise<void>;\n\n/** A preflight validator/authorizer. */\nexport type ActionGuardHandler<T = unknown> = (\n payload: T,\n controller: ActionGuardController<T>,\n) => void | Promise<void>;\n\n/**\n * Strict handler contract used when an action result map declares a result.\n * Unlike the legacy ActionHandler type, a mapped handler must return the\n * declared result (or a promise of it).\n */\nexport type ActionResultHandler<T = unknown, R = void> = (\n payload: T,\n controller: ActionResultController<T, R>\n) => R | Promise<R>;\n\n/** Controls whether an async handler must settle before the next sequential handler starts. */\nexport type HandlerScheduling = 'await-before-next' | 'start-and-continue';\n\n/** Controls whether a handler failure terminates the pipeline or is reported as a collected error. */\nexport type HandlerErrorPolicy = 'fatal' | 'collect';\n\n/**\n * Handler configuration interface for controlling handler behavior within the pipeline\n * \n * Configuration options that control how handlers are executed,\n * including priority, timing controls, and execution behavior.\n * \n * @example Basic Handler Configuration\n * ```typescript\n * register.register('searchUsers', searchHandler, {\n * priority: 100, // Execute before lower priority handlers\n * debounce: 300, // Wait 300ms after last call\n * throttle: 1000, // Limit to once per second\n * once: false // Can be executed multiple times\n * })\n * ```\n * \n * @example Production Handler\n * ```typescript\n * register.register('processPayment', paymentHandler, {\n * priority: 200,\n * blocking: true, // Wait for completion\n * id: 'payment-handler' // Custom ID\n * })\n * ```\n * \n * @public\n */\nexport interface HandlerConfig<T = unknown> {\n /** Priority level (higher numbers execute first). Default: 0 */\n priority?: number;\n \n /** Unique identifier for the handler. Auto-generated if not provided */\n id?: string;\n \n /**\n * Supported 1.x shorthand for scheduling and error policy. `true` maps to\n * `await-before-next` + `fatal`; `false` maps to `start-and-continue` + `collect`.\n * Explicit `scheduling` or `errorPolicy` takes precedence for that field.\n */\n blocking?: boolean;\n\n /** Async scheduling in sequential mode. Default: `await-before-next`. */\n scheduling?: HandlerScheduling;\n\n /** Error behavior for this handler. Default: `collect`. */\n errorPolicy?: HandlerErrorPolicy;\n \n /** Whether this handler should run once and then be removed. Default: false */\n once?: boolean;\n \n /** Debounce delay in milliseconds */\n debounce?: number;\n \n /** Throttle delay in milliseconds */\n throttle?: number;\n \n /** Replace existing handler with same ID. Default: true for backward compatibility */\n replaceExisting?: boolean;\n \n /** Cleanup function to call when handler is unregistered */\n cleanup?: () => void;\n\n /** Condition function to determine if handler should execute. Default: always execute */\n condition?: (payload: T) => boolean;\n\n /** Optional metadata copied into execution outcomes for diagnostics. */\n metadata?: Record<string, unknown>;\n\n /** Terminal path selection; consumed only by `registerObserver()`. */\n when?: 'success' | 'failure' | 'always';\n}\n\n/**\n * Internal handler configuration with defaults resolved.\n *\n * Timing, cleanup, and condition values remain optional because registration\n * does not synthesize them when they are omitted at runtime.\n */\nexport interface ResolvedHandlerConfig<T = unknown> {\n priority: number;\n id: string;\n blocking: boolean;\n scheduling: HandlerScheduling;\n errorPolicy: HandlerErrorPolicy;\n once: boolean;\n replaceExisting: boolean;\n debounce?: number;\n throttle?: number;\n cleanup?: () => void;\n condition?: (payload: T) => boolean;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Resolve the supported `blocking` shorthand and all registration\n * defaults in one place. Adapters should pass their original config to the\n * registry and use this helper only when they need to expose resolved values.\n */\nexport function resolveHandlerConfig<T = unknown>(\n config: HandlerConfig<T> | undefined,\n handlerId: string,\n): ResolvedHandlerConfig<T> {\n return {\n priority: config?.priority ?? 0,\n id: handlerId,\n blocking: config?.errorPolicy === 'fatal' || config?.blocking === true,\n scheduling: config?.scheduling\n ?? (config?.blocking === false ? 'start-and-continue' : 'await-before-next'),\n errorPolicy: config?.errorPolicy\n ?? (config?.blocking === true ? 'fatal' : 'collect'),\n once: config?.once ?? false,\n debounce: config?.debounce,\n throttle: config?.throttle,\n replaceExisting: config?.replaceExisting ?? true,\n cleanup: config?.cleanup,\n condition: config?.condition,\n metadata: config?.metadata,\n };\n}\n\n\n/**\n * Internal handler registration container\n * \n * Contains the registered handler function along with its complete configuration\n * and unique identifier. This is used internally by ActionRegister to manage\n * the handler pipeline.\n * \n * @template T - The payload type for this handler\n * @template R - The return type for this handler\n * \n * @internal\n */\nexport interface HandlerRegistration<T = unknown, R = void> {\n /** The handler function */\n handler: ActionHandler<T, R>;\n \n /** Complete handler configuration with all defaults applied */\n config: ResolvedHandlerConfig<T>;\n \n /** Unique identifier for this handler registration */\n id: string;\n\n /**\n * Runtime execution role. Effect handlers can control flow but never add a\n * value to result collection; result and legacy handlers may do both.\n */\n role?: HandlerRole;\n}\n\n/** The lifecycle state recorded for one handler invocation. */\nexport type HandlerExecutionStatus =\n | 'running'\n | 'succeeded'\n | 'failed'\n | 'skipped'\n | 'cancelled';\n\n/**\n * Concrete outcome produced by an execution mode. Keeping this record beside\n * the executor avoids reconstructing execution metrics from cursor indexes.\n */\nexport interface HandlerExecutionOutcome<R = void> {\n id: string;\n status: HandlerExecutionStatus;\n executed: boolean;\n duration: number | undefined;\n result: R | undefined;\n error: Error | undefined;\n metadata: Record<string, unknown> | undefined;\n terminationRequested?: boolean;\n terminationResult?: R;\n}\n\n/** Controller state isolated to one concurrent handler invocation. */\nexport interface PipelineControllerState<T = unknown, R = void> {\n payload: T;\n aborted: boolean;\n abortReason: string | undefined;\n jumpToPriority: number | undefined;\n terminated: boolean;\n terminationResult: R | undefined;\n results: R[];\n}\n\n/**\n * Execution mode for action handler pipeline\n * \n * Determines how multiple handlers for the same action are executed:\n * - `sequential`: Handlers execute one after another in priority order\n * - `parallel`: All handlers execute simultaneously\n * - `race`: First handler to complete wins; other started handlers keep running\n * and remain tracked until they settle\n * \n * @example\n * ```typescript\n * // Sequential execution (default)\n * register.setActionExecutionMode('updateUser', 'sequential')\n * \n * // Parallel execution for independent operations\n * register.setActionExecutionMode('logEvent', 'parallel')\n * \n * // Race execution for fastest response\n * register.setActionExecutionMode('fetchData', 'race')\n * ```\n * \n * @public\n */\nexport type ExecutionMode = 'sequential' | 'parallel' | 'race';\n\n/**\n * Internal pipeline execution context\n * \n * Contains the state and metadata for a single action pipeline execution.\n * This includes the action payload, registered handlers, execution progress,\n * and result collection.\n * \n * @template T - The payload type for this execution\n * @template R - The result type for this execution\n * \n * @internal\n */\nexport interface PipelineContext<T = unknown, R = void> {\n /** The action name being executed */\n action: string;\n \n /** The payload for this execution */\n payload: T;\n \n /** Handlers to execute in this pipeline */\n handlers: HandlerRegistration<T, R>[];\n\n /** Registrations whose handler functions were actually invoked */\n executedHandlers?: HandlerRegistration<T, R>[];\n\n /** Outcomes recorded directly by the execution mode. */\n handlerOutcomes?: HandlerExecutionOutcome<R>[];\n\n /** Race arbitration is reported separately from loser diagnostics. */\n raceWinnerId?: string;\n raceLoserOutcomes?: HandlerExecutionOutcome<R>[];\n\n /** Defer once-handler removal to the outer retry lifecycle */\n deferOnceCleanup?: boolean;\n\n /**\n * Atomically reserve a once registration immediately before invocation.\n * A false return means another concurrent dispatch already consumed it.\n *\n * @internal\n */\n claimOnce?(registration: HandlerRegistration<T, R>): boolean;\n\n /** Effective signal shared with controllers for cooperative cancellation */\n signal?: AbortSignal;\n\n /** Track handler work that may outlive the exposed dispatch promise */\n trackHandlerPromise?<V>(promise: Promise<V>): Promise<V>;\n\n /** Errors collected from non-blocking handler execution */\n collectedErrors?: HandlerError[];\n \n /** Whether execution has been aborted */\n aborted: boolean;\n \n /** Reason for abortion if aborted */\n abortReason: string | undefined;\n \n /** Current handler index being executed */\n currentIndex: number;\n \n /** Priority level to jump to (if requested) */\n jumpToPriority: number | undefined;\n\n /** Counter for jump operations to detect potential infinite loops */\n jumpCount?: number;\n\n /** Maximum allowed jumps before aborting (to prevent infinite loops) */\n maxJumps?: number;\n\n /** Execution mode for this pipeline */\n executionMode: ExecutionMode;\n \n /** Results collected from handlers */\n results: R[];\n \n /** Whether execution was terminated early */\n terminated: boolean;\n \n /** Result from terminated execution */\n terminationResult: R | undefined;\n}\n\n/**\n * Configuration options for ActionRegister initialization\n * \n * Provides comprehensive configuration options for customizing ActionRegister\n * behavior including debugging, execution modes, and cleanup policies.\n * \n * @example Basic Configuration\n * ```typescript\n * const register = new ActionRegister<AppActions>({\n * name: 'UserActionRegister',\n * registry: {\n * debug: true,\n * defaultExecutionMode: 'sequential'\n * }\n * })\n * ```\n * \n * @example Development Configuration\n * ```typescript\n * const devRegister = new ActionRegister<AppActions>({\n * name: 'DevRegister',\n * registry: {\n * debug: true,\n * autoCleanup: true,\n * defaultExecutionMode: 'parallel'\n * }\n * })\n * ```\n * \n * @public\n */\nexport interface ActionRegisterConfig {\n /** Name identifier for this ActionRegister instance */\n name?: string;\n \n /** Registry-specific configuration options */\n registry?: {\n /** Debug mode for registry operations - enables detailed logging */\n debug?: boolean;\n\n /** Auto-cleanup configuration for one-time handlers */\n autoCleanup?: boolean;\n\n /** Default execution mode for actions */\n defaultExecutionMode?: ExecutionMode;\n\n /** Serialize independent dispatches through the optional queue. Default: false. */\n useConcurrencyQueue?: boolean;\n\n /**\n * Optional maximum number of handlers per action. Defaults to `Infinity`.\n * A configured finite limit rejects an overflowing registration instead of\n * silently dropping the handler.\n */\n maxHandlersPerAction?: number;\n\n /**\n * Maximum controller priority jumps in one dispatch. Default: 10; use\n * `Infinity` only when the caller owns a separate termination invariant.\n */\n maxJumps?: number;\n\n /** Global error handler for unhandled errors */\n errorHandler?: (error: Error, context: unknown) => void | Promise<void>;\n\n // ---- Zod Schema Validation Options (optional) ----\n\n /**\n * Action schema map for runtime payload validation\n * When provided, enables Zod-based validation on dispatch\n * @see ActionSchemaMap from '@context-action/tool-protocol'\n */\n schema?: Record<string, ActionSchemaLike>;\n\n /**\n * Enable/disable validation on dispatch\n * Default: true when schema is provided\n */\n validateOnDispatch?: boolean;\n\n /**\n * Validation mode when schema validation fails\n * - 'strict': throw ActionValidationError (default)\n * - 'warn': console.warn and continue execution\n * - 'silent': ignore validation errors silently\n */\n validationMode?: 'strict' | 'warn' | 'silent';\n };\n}\n\n/**\n * Comprehensive dispatch options for controlling action execution\n * \n * Provides fine-grained control over how actions are dispatched and executed,\n * including timing controls, handler filtering, result processing, and abort handling.\n * \n * @example Basic Dispatch Options\n * ```typescript\n * await register.dispatch('searchUsers', { query: 'john' }, {\n * debounce: 300, // Wait 300ms after last call\n * throttle: 1000, // Limit to once per second\n * executionMode: 'parallel'\n * })\n * ```\n * \n * @example Handler Filtering\n * ```typescript\n * await register.dispatch('updateUser', userData, {\n * filter: {\n * handlerIds: ['validation', 'business-logic'], // Only these handlers\n * excludeHandlerIds: ['analytics'], // Skip selected handlers\n * priority: { min: 10 } // Minimum priority\n * }\n * })\n * ```\n * \n * @example Result Collection\n * ```typescript\n * const result = await register.dispatchWithResult('processOrder', order, {\n * result: {\n * collect: true,\n * strategy: 'merge',\n * maxResults: 5,\n * merger: (results) => results.reduce((acc, curr) => ({ ...acc, ...curr }), {})\n * }\n * })\n * ```\n * \n * @example Abort Control\n * ```typescript\n * const controller = new AbortController()\n * \n * // Auto-abort with custom controller\n * await register.dispatch('longRunningTask', data, {\n * autoAbort: {\n * enabled: true,\n * allowHandlerAbort: true,\n * onControllerCreated: (ctrl) => {\n * setTimeout(() => ctrl.abort('Timeout'), 5000)\n * }\n * }\n * })\n * ```\n * \n * @public\n */\nexport interface DispatchOptions {\n /** Debounce delay in milliseconds - wait for this delay after last call */\n debounce?: number;\n \n /** Throttle delay in milliseconds - limit execution to once per this period */\n throttle?: number;\n \n /** Execution mode override for this specific dispatch */\n executionMode?: ExecutionMode;\n \n /** Abort signal for cancelling the dispatch */\n signal?: AbortSignal;\n \n /** Bypass queue and execute immediately */\n immediate?: boolean;\n \n /** Priority in dispatch queue (higher = earlier execution) */\n queuePriority?: number;\n \n /**\n * Non-negative finite wall-clock timeout in milliseconds, including queue\n * wait and retry delay. Rejects with ActionTimeoutError and aborts the\n * dispatch signal. Invalid values throw RangeError.\n */\n timeout?: number;\n \n /**\n * Retry configuration for error recovery. Retries reuse the handler\n * selection and timing settings resolved when the dispatch starts, except\n * handlers already consumed by the `once` lifecycle.\n */\n retryOnError?: {\n /** Maximum total attempts, including the initial attempt. Minimum: 1 */\n maxAttempts: number;\n /** Delay between retries in milliseconds */\n delay: number;\n /**\n * Retry boundary for work started by a race attempt. `abort-and-drain` is\n * the safe default for race; `abort-and-overlap` is an explicit opt-in for\n * idempotent/read-only handlers. Both modes abort the superseded attempt;\n * only the former waits for its started work to settle.\n */\n attemptBarrier?: 'abort-and-drain' | 'abort-and-overlap';\n };\n \n /** Auto-abort options for automatic AbortController management */\n autoAbort?: {\n /** Create and manage AbortController automatically */\n enabled: boolean;\n \n /** Provide access to the created AbortController */\n onControllerCreated?: (controller: AbortController) => void;\n \n /** Enable pipeline abort trigger from handlers */\n allowHandlerAbort?: boolean;\n };\n \n /** Handler filtering options */\n filter?: {\n /** Only execute handlers with these IDs */\n handlerIds?: string[];\n \n /** Exclude handlers with these IDs */\n excludeHandlerIds?: string[];\n \n /** Priority-based filtering */\n priority?: {\n /** Minimum priority threshold */\n min?: number;\n /** Maximum priority threshold */\n max?: number;\n };\n \n /** Custom filter function. Receives an immutable config snapshot. */\n custom?: (config: Readonly<ResolvedHandlerConfig>) => boolean;\n };\n \n /** Result collection and processing options */\n result?: {\n /** How to handle multiple results. In parallel mode, results follow priority order. */\n strategy?: 'first' | 'last' | 'all' | 'merge' | 'custom';\n \n /** Custom result merger function (used with 'merge' or 'custom' strategy) */\n merger?: <R>(results: Array<R | undefined>) => R;\n \n /** Whether to collect results from all handlers */\n collect?: boolean;\n \n /** Maximum number of results to aggregate. A value of 0 produces no aggregated results. */\n maxResults?: number;\n \n /** @deprecated Errors are always exposed through ExecutionResult.errors and failedResults. */\n includeErrors?: boolean;\n };\n}\n\n/**\n * Comprehensive result of pipeline execution with detailed execution information\n * \n * Contains complete information about the pipeline execution including success status,\n * results, handler details, and any errors that occurred.\n * \n * @template R - The result type for this execution\n * \n * @example Basic Result Handling\n * ```typescript\n * const result = await register.dispatchWithResult('updateUser', userData)\n * \n * if (result.success) {\n * console.log(`Execution completed in ${result.execution.duration}ms`)\n * console.log(`${result.execution.handlersExecuted} handlers executed`)\n * } else {\n * console.error('Execution failed:', result.abortReason)\n * }\n * ```\n * \n * @example Advanced Result Processing\n * ```typescript\n * const result = await register.dispatchWithResult('processOrder', order, {\n * result: { collect: true, strategy: 'all' }\n * })\n * \n * // Access all handler results - now properly typed\n * result.successResults.forEach((handlerResult, index) => {\n * console.log(`Handler ${index} result:`, handlerResult)\n * })\n * \n * // Check individual handler performance\n * result.handlers.forEach(handler => {\n * if (handler.duration && handler.duration > 1000) {\n * console.warn(`Slow handler ${handler.id}: ${handler.duration}ms`)\n * }\n * })\n * ```\n * \n * @public\n */\nexport interface ExecutionResult<R = void> {\n /** Whether the execution completed successfully */\n success: boolean;\n \n /** Whether caller or pipeline cancellation aborted the execution */\n aborted: boolean;\n \n /** Reason for abortion if aborted */\n abortReason: string | undefined;\n \n /** Whether the execution was terminated early via controller.return() */\n terminated: boolean;\n\n /** High-level terminal state, including timing-guard rejections. */\n outcome: 'completed' | 'completed_with_errors' | 'failed' | 'cancelled' | 'debounced' | 'throttled';\n\n /** Runtime payload validation outcome when a schema was configured */\n validation?: {\n passed: boolean;\n errors: string[];\n };\n \n /** Final result based on result strategy - only present for non-void results */\n result: R | R[] | undefined;\n \n /** ๐ง Type safety fix: Separate successful results from failed ones */\n /** All successful handler results (guaranteed non-undefined) */\n successResults: R[];\n \n /** All handler results including undefined from failed handlers (legacy compatibility) */\n results: Array<R | undefined>;\n \n /** Failed handler results with error context */\n failedResults: Array<{\n handlerId: string;\n error: Error;\n /** @deprecated Runtime execution cannot infer the TypeScript result type. */\n expectedType: string;\n }>;\n \n /** Execution metadata */\n execution: {\n /** Total canonical dispatch duration in milliseconds, including admission\n * and queue wait. Awaited observer notification time is intentionally\n * excluded because observers cannot alter the terminal result. */\n duration: number;\n\n /** Validation and timing-guard admission duration in milliseconds. */\n admissionDuration: number;\n\n /** Time spent waiting in the dispatch queue in milliseconds. */\n queueWaitDuration: number;\n\n /** Handler pipeline duration in milliseconds. */\n pipelineDuration: number;\n\n /** Backoff time consumed between whole-action retry attempts. */\n retryDelayDuration?: number;\n\n /** Time spent aggregating raw handler values into the public result. */\n resultProcessingDuration?: number;\n\n /** Per-attempt pipeline timing, including attempts that are retried. */\n attempts?: Array<{\n startTime: number;\n endTime: number;\n duration: number;\n outcome: 'succeeded' | 'failed' | 'retried' | 'cancelled';\n }>;\n \n /** Number of handlers that were executed */\n handlersExecuted: number;\n \n /** Number of handlers that were skipped */\n handlersSkipped: number;\n \n /** Number of handlers that failed */\n handlersFailed: number;\n \n /** Execution start timestamp */\n startTime: number;\n \n /** Execution end timestamp */\n endTime: number;\n };\n \n /** Detailed information about each handler */\n handlers: Array<{\n /** Handler unique identifier */\n id: string;\n \n /** Whether this handler was executed */\n executed: boolean;\n\n /** Final lifecycle state observed for this handler */\n status: HandlerExecutionStatus;\n \n /** Handler execution duration in milliseconds (only present if executed) */\n duration: number | undefined;\n \n /** Result returned by this handler - properly typed for success/failure */\n result: R | undefined;\n \n /** Error thrown by this handler if any */\n error: Error | undefined;\n \n /** Custom metadata for this handler */\n metadata: Record<string, unknown> | undefined;\n }>;\n\n /** Race-only snapshots. Loser failures never change the winner contract. */\n raceDiagnostics?: {\n winnerId?: string;\n /** Immutable winner outcome captured at dispatch return. */\n winner?: HandlerExecutionOutcome<R>;\n loserSnapshots: Array<HandlerExecutionOutcome<R>>;\n /** Losers still running when the canonical winner result was returned. */\n pendingLosersAtReturn: number;\n /** Failed losers observable at that same snapshot point. */\n observedLoserFailures: number;\n };\n \n /** Errors that occurred during execution */\n errors: HandlerError[];\n}\n\n/**\n * Handler error information for unified error handling\n * \n * @public\n */\nexport interface HandlerError {\n handlerId: string;\n error: Error;\n timestamp: number;\n severity: 'blocking' | 'non-blocking';\n}\n\n/**\n * Function type for unregistering action handlers\n * \n * Returned by the register method to allow removal of specific handlers.\n * Calling this function removes the handler from the action pipeline.\n * \n * @example\n * ```typescript\n * const unregister = register.register('updateUser', userHandler)\n * \n * // Later, remove the handler\n * unregister()\n * ```\n * \n * @public\n */\nexport type UnregisterFunction = () => void;\n\n/**\n * Helper types for better ActionDispatcher type safety\n */\nexport type VoidActions<T extends ActionPayloadMap> = {\n // biome-ignore lint/suspicious/noConfusingVoidType: void is the public no-payload marker.\n [K in keyof T]: [T[K]] extends [void] ? K : never\n}[keyof T];\n\nexport type PayloadActions<T extends ActionPayloadMap> = {\n // biome-ignore lint/suspicious/noConfusingVoidType: void is the public no-payload marker.\n [K in keyof T]: [T[K]] extends [void] ? never : K\n}[keyof T];\n\n/**\n * Arguments accepted by a dispatch method for a single action payload.\n * Payload-bearing actions must provide their payload; void actions may omit it.\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: void is the public no-payload marker.\nexport type DispatchArgs<P> = [P] extends [void]\n ? [payload?: undefined, options?: DispatchOptions]\n : [payload: P, options?: DispatchOptions];\n\n/** Property names reserved by the callable action proxy protocol. */\nexport type ReservedActionKey =\n | 'then'\n | 'catch'\n | 'finally'\n | 'toJSON'\n | 'constructor'\n | '__proto__'\n | 'prototype';\n\n/** Action keys that can be exposed through `register.actions` proxies. */\nexport type ProxyActionKey<T extends ActionPayloadMap> = Exclude<ActionNames<T>, ReservedActionKey>;\n\n/**\n * Type-safe dispatchWithResult interface\n * \n * Provides type-safe method overloads for dispatchWithResult operations\n * that maintain payload type checking while returning ExecutionResult.\n * \n * @template T - The action payload map interface\n */\n/** Dispatch an action with the payload contract defined by its action key. */\nexport type ActionDispatcherWithResult<\n T extends ActionPayloadMap,\n TResultMap extends ActionResultMap<T> = {},\n> = <\n K extends ActionNames<T>,\n R = ActionResult<TResultMap, K>\n>(action: K, ...args: DispatchArgs<T[K]>) => Promise<ExecutionResult<R>>;\n\n/**\n * Type-safe action dispatcher interface\n * \n * Provides overloaded dispatch methods that enforce correct payload types\n * based on the action being dispatched. Automatically handles actions\n * that require no payload versus those that do.\n * \n * @template T - The action payload map interface\n * \n * @example\n * ```typescript\n * interface AppActions extends ActionPayloadMap {\n * resetApp: void\n * updateUser: { id: string; name: string }\n * }\n * \n * const dispatch: ActionDispatcher<AppActions> = register.dispatch.bind(register)\n * \n * // No payload required - type-checked\n * await dispatch('resetApp')\n * \n * // Payload required and type-checked\n * await dispatch('updateUser', { id: '123', name: 'John' })\n * ```\n * \n * @public\n */\n/** Dispatch an action with the payload contract defined by its action key. */\nexport type ActionDispatcher<T extends ActionPayloadMap> = <K extends ActionNames<T>>(\n action: K,\n ...args: DispatchArgs<T[K]>\n) => Promise<void>;\n\n/**\n * Registry information interface for ActionRegister introspection\n * \n * Provides comprehensive information about the current state of an ActionRegister\n * instance, including registered actions, handler counts, and execution modes.\n * Similar to DeclarativeStoreRegistry pattern for consistent registry management.\n * \n * @template T - The action payload map interface\n * \n * @example\n * ```typescript\n * const info = register.getRegistryInfo()\n * \n * console.log(`Registry: ${info.name}`)\n * console.log(`Total actions: ${info.totalActions}`)\n * console.log(`Total handlers: ${info.totalHandlers}`)\n * console.log(`Registered actions:`, info.registeredActions)\n * ```\n * \n * @public\n */\nexport interface ActionRegistryInfo<T extends ActionPayloadMap> {\n /** Registry name */\n name: string;\n \n /** Total number of registered actions */\n totalActions: number;\n \n /** Total number of registered handlers across all actions */\n totalHandlers: number;\n \n /** List of all registered actions */\n registeredActions: Array<keyof T>;\n \n /** Execution mode settings per action */\n actionExecutionModes: Map<keyof T, ExecutionMode>;\n \n /** Default execution mode */\n defaultExecutionMode: ExecutionMode;\n}\n\n/**\n * Handler statistics interface for registry monitoring and debugging\n * \n * Provides detailed statistics about handlers for a specific action,\n * including handler organization and basic execution data.\n * \n * @template T - The action payload map interface\n * \n * @example\n * ```typescript\n * const stats = register.getActionStats('updateUser')\n * \n * if (stats) {\n * console.log(`Action: ${stats.action}`)\n * console.log(`Handler count: ${stats.handlerCount}`)\n *\n * stats.handlersByPriority.forEach(group => {\n * console.log(`Priority ${group.priority}:`, group.handlers.length, 'handlers')\n * })\n *\n * if (stats.executionStats) {\n * console.log(`Success rate: ${stats.executionStats.successRate}%`)\n * console.log(`Average duration: ${stats.executionStats.averageDuration}ms`)\n * }\n * }\n * ```\n * \n * @public\n */\nexport interface ActionHandlerStats<T extends ActionPayloadMap> {\n /** Action name */\n action: keyof T;\n \n /** Number of handlers for this action */\n handlerCount: number;\n \n /** Total number of handlers for this action (alias for handlerCount) */\n totalHandlers: number;\n \n /** When the last handler was registered */\n lastRegistered?: Date;\n \n /** Handler configurations grouped by priority */\n handlersByPriority: Array<{\n priority: number;\n handlers: Array<{\n id: string;\n }>;\n }>;\n \n /** Execution statistics - removed in favor of simplified architecture */\n executionStats?: undefined;\n}\n","// biome-ignore-all lint/suspicious/noExplicitAny: heterogeneous runtime pipeline storage.\n\nimport { ActionGuard } from './action-guard.js';\nimport { OperationQueue } from './concurrency/OperationQueue.js';\nimport {\n ActionAttemptSupersededError,\n ActionRegisterDestroyedError,\n ActionResultProcessingError,\n ActionTimeoutError,\n ActionValidationError,\n} from './errors.js';\nimport { executeParallel, executeRace, executeSequential } from './execution-modes.js';\nimport {\n ActionHandler,\n ActionEffectHandler,\n EffectConfig,\n ActionGuardHandler,\n ActionObserverEvent,\n ActionObserverHandler,\n ActionNames,\n ActionHandlerStats,\n ActionPayloadMap,\n ActionRegisterConfig,\n ActionRegistryInfo,\n ActionResult,\n ActionResultHandler,\n ActionResultMap,\n DispatchArgs,\n DispatchOptions,\n ExecutionMode,\n ExecutionResult,\n HandlerConfig,\n GuardConfig,\n HandlerError,\n HandlerExecutionOutcome,\n HandlerRegistration,\n HandlerRole,\n ObserverConfig,\n PipelineContext,\n PipelineController,\n PipelineControllerState,\n ProxyActionKey,\n ReservedActionKey,\n resolveHandlerConfig,\n UnregisterFunction,\n} from './types.js';\n\ntype DispatchHandlerPromises = Set<Promise<unknown>>;\n\ntype RetryTelemetry = {\n pipelineDuration: number;\n retryDelayDuration: number;\n attempts: NonNullable<ExecutionResult<unknown>['execution']['attempts']>;\n};\n\ntype TimingGuardAdmission = {\n reason?: 'Debounced execution' | 'Throttled execution';\n aborted: boolean;\n};\n\ntype GuardPhaseResult<T> = {\n allowed: boolean;\n payload: T;\n aborted: boolean;\n abortReason: string | undefined;\n error: Error | undefined;\n errors: HandlerError[];\n outcomes: HandlerExecutionOutcome<unknown>[];\n executedHandlers: HandlerRegistration<any, any>[];\n duration: number;\n};\n\n/** Immutable handler selection and scheduling decisions for one dispatch. */\ntype DispatchPlan = {\n pipelineSnapshot: readonly HandlerRegistration<any, any>[];\n /** Selected registrations, retained for admission metrics and compatibility. */\n eligibleHandlers: readonly HandlerRegistration<any, any>[];\n guards: readonly HandlerRegistration<any, any>[];\n results: readonly HandlerRegistration<any, any>[];\n observers: readonly HandlerRegistration<any, any>[];\n debounceMs?: number;\n throttleMs?: number;\n executionMode: ExecutionMode;\n};\n\nconst RESERVED_PROXY_KEYS = new Set<ReservedActionKey>([\n 'then',\n 'catch',\n 'finally',\n 'toJSON',\n 'constructor',\n '__proto__',\n 'prototype',\n]);\nconst ATTEMPT_SIGNAL_CLEANUP = Symbol('attemptSignalCleanup');\ntype AttemptDispatchOptions = DispatchOptions & {\n [ATTEMPT_SIGNAL_CLEANUP]?: () => void;\n};\n\nfunction snapshotHandlerOutcome<R>(outcome: HandlerExecutionOutcome<R>): HandlerExecutionOutcome<R> {\n return {\n ...outcome,\n metadata: outcome.metadata ? { ...outcome.metadata } : undefined,\n };\n}\n\nfunction normalizePositiveLimit(\n value: number | undefined,\n fallback: number,\n label: string,\n): number {\n const limit = value ?? fallback;\n if (limit === Infinity) return limit;\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new RangeError(`${label} must be a positive safe integer or Infinity.`);\n }\n return limit;\n}\n\n/**\n * Action Register for managing action handlers with priority-based execution\n * \n * Central action registration and dispatch system providing type-safe action pipeline management.\n * Supports sequential, parallel, and race execution modes with advanced handler filtering,\n * throttling, debouncing, and comprehensive result collection.\n * \n * @template TActionMap - Action payload mapping interface extending ActionPayloadMap\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/\n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/register-delegation\n * \n * @public\n */\n\nexport class ActionRegister<\n T extends ActionPayloadMap = Record<string, unknown>,\n TResultMap extends ActionResultMap<T> = {},\n> {\n private pipelines = new Map<keyof T, Array<HandlerRegistration<any, any>>>();\n /** Observer callbacks are intentionally stored outside the executable\n * pipeline so they cannot participate in result arbitration. */\n private readonly observerHandlers = new Map<\n HandlerRegistration<any, any>,\n { handler: ActionObserverHandler<any, any>; when: 'success' | 'failure' | 'always' }\n >();\n /** A once handler is removed from the registry before its callback starts.\n * Keep its claim separately so resource cleanup can still run on settlement. */\n private readonly claimedOnceHandlers = new WeakSet<HandlerRegistration<any, any>>();\n private readonly actionGuard: ActionGuard;\n private executionMode: ExecutionMode = 'sequential';\n private actionExecutionModes = new Map<keyof T, ExecutionMode>();\n \n // ๐ Advanced unregister function management system\n private unregisterFunctions = new Map<keyof T, Map<string, UnregisterFunction>>();\n\n // ๐ง Fix: Track last registration timestamps for getActionStats\n private lastRegisteredTimestamps = new Map<keyof T, Date>();\n \n public readonly name: string;\n private readonly registryConfig: ActionRegisterConfig['registry'];\n\n // ๐ Performance optimizations\n private readonly isDebugMode: boolean;\n private readonly maxHandlersPerAction: number;\n private readonly maxJumps: number;\n\n // ๐ ๋์์ฑ ๋ฌธ์ ํด๊ฒฐ์ ์ํ ํ ์์คํ
(conditional)\n private dispatchQueue?: OperationQueue;\n\n // ๐ง Performance optimization: Fast handler ID generation counter\n private handlerIdCounter = 0;\n\n // ๐ง Performance optimization: PipelineController pool for object reuse\n\n private lifecycleState: 'active' | 'closing' | 'destroyed' = 'active';\n private readonly lifecycleController = new AbortController();\n private readonly activeDispatches = new Set<Promise<unknown>>();\n private readonly activeHandlerPromises = new Set<Promise<unknown>>();\n private destroyAsyncPromise: Promise<void> | undefined;\n private dispatchConstructionDepth = 0;\n\n // ๐ง Performance optimization: Cached Proxy instances for actions getters\n private _actionsProxy?: {\n [K in ProxyActionKey<T>]: (...args: DispatchArgs<T[K]>) => Promise<void>\n };\n private _actionsWithResultProxy?: {\n [K in ProxyActionKey<T>]: (...args: DispatchArgs<T[K]>) => Promise<ExecutionResult<ActionResult<TResultMap, K>>>\n };\n private readonly actionDispatchers = new Map<\n PropertyKey,\n (...args: any[]) => Promise<unknown>\n >();\n private readonly actionResultDispatchers = new Map<\n PropertyKey,\n (...args: any[]) => Promise<unknown>\n >();\n\n constructor(config: ActionRegisterConfig = {}) {\n this.name = config.name || 'ActionRegister';\n this.registryConfig = config.registry;\n this.maxHandlersPerAction = normalizePositiveLimit(\n config.registry?.maxHandlersPerAction,\n Infinity,\n 'maxHandlersPerAction',\n );\n this.maxJumps = normalizePositiveLimit(\n config.registry?.maxJumps,\n 10,\n 'maxJumps',\n );\n this.isDebugMode = this.registryConfig?.debug === true;\n \n // Guard creation with improved cleanup handling\n this.actionGuard = new ActionGuard(this.registryConfig?.autoCleanup !== false);\n \n // ๐ Conditional queue system initialization\n if (config.registry?.useConcurrencyQueue === true) {\n this.dispatchQueue = new OperationQueue(`${this.name}-Dispatch`);\n }\n \n if (this.registryConfig?.defaultExecutionMode) {\n this.executionMode = this.registryConfig.defaultExecutionMode;\n }\n \n this.log('ActionRegister initialized', {\n defaultExecutionMode: this.executionMode,\n autoCleanup: this.registryConfig?.autoCleanup !== false,\n concurrencyQueue: Boolean(this.dispatchQueue),\n debugMode: this.isDebugMode\n });\n }\n\n /**\n * ๐ Action-based dispatcher\n *\n * Provides function-based access to actions for more convenient dispatching.\n * Each action becomes a callable function that can be invoked directly.\n *\n * @example\n * ```typescript\n * interface MyActions extends ActionPayloadMap {\n * userLogin: { userId: string; email: string };\n * resetApp: void;\n * }\n * \n * const registry = new ActionRegister<MyActions>();\n * \n * // Function-based dispatching\n * await registry.actions.userLogin({ userId: '123', email: 'test@example.com' });\n * await registry.actions.resetApp();\n * await registry.actions.resetApp(undefined, { debounce: 100 });\n * ```\n * \n * @public\n */\n get actions(): {\n [K in ProxyActionKey<T>]: (...args: DispatchArgs<T[K]>) => Promise<void>\n } {\n // ๐ง Performance: Return cached Proxy instance\n if (!this._actionsProxy) {\n this._actionsProxy = new Proxy({} as any, {\n get: (_target, prop: string | symbol) => {\n if (typeof prop !== 'string') return undefined;\n if (RESERVED_PROXY_KEYS.has(prop as ReservedActionKey)) return undefined;\n const actionKey = prop as ProxyActionKey<T>;\n\n let dispatcher = this.actionDispatchers.get(prop);\n if (!dispatcher) {\n dispatcher = (payload?: T[typeof actionKey], options?: DispatchOptions) =>\n this.dispatch(\n actionKey,\n ...( [payload, options] as DispatchArgs<T[typeof actionKey]> )\n );\n this.actionDispatchers.set(prop, dispatcher);\n }\n return dispatcher;\n }\n });\n }\n return this._actionsProxy!;\n }\n\n /**\n * Actions-based dispatching with result collection\n * \n * Provides a function-based interface for dispatching actions with detailed execution results.\n * Each registered action becomes a callable function that returns ExecutionResult.\n * \n * @example\n * ```typescript\n * // Actions with payload\n * const result = await registry.actionsWithResult.userLogin({ userId: '123', email: 'user@example.com' });\n * \n * // Actions without payload\n * const result = await registry.actionsWithResult.userLogout();\n * const debouncedResult = await registry.actionsWithResult.userLogout(\n * undefined,\n * { debounce: 100 }\n * );\n * \n * // With options\n * const result = await registry.actionsWithResult.processData(\n * { data: { name: 'test' }, type: 'json' },\n * { executionMode: 'parallel' }\n * );\n * ```\n * \n * @returns Proxy object with action functions that return ExecutionResult\n */\n get actionsWithResult(): {\n [K in ProxyActionKey<T>]: (...args: DispatchArgs<T[K]>) => Promise<ExecutionResult<ActionResult<TResultMap, K>>>\n } {\n // ๐ง Performance: Return cached Proxy instance\n if (!this._actionsWithResultProxy) {\n this._actionsWithResultProxy = new Proxy({} as any, {\n get: (_target, prop: string | symbol) => {\n if (typeof prop !== 'string') return undefined;\n if (RESERVED_PROXY_KEYS.has(prop as ReservedActionKey)) return undefined;\n const actionKey = prop as ProxyActionKey<T>;\n\n let dispatcher = this.actionResultDispatchers.get(prop);\n if (!dispatcher) {\n const dispatchAction = this.dispatchWithResult.bind(this) as (\n action: ProxyActionKey<T>,\n ...args: DispatchArgs<T[ProxyActionKey<T>]>\n ) => Promise<ExecutionResult<unknown>>;\n dispatcher = (payload?: T[typeof actionKey], options?: DispatchOptions) =>\n dispatchAction(\n actionKey,\n ...( [payload, options] as DispatchArgs<T[typeof actionKey]> )\n );\n this.actionResultDispatchers.set(prop, dispatcher);\n }\n return dispatcher;\n }\n });\n }\n return this._actionsWithResultProxy!;\n }\n\n /**\n * Register an action handler with optional configuration\n * \n * @param action - The action type to register handler for\n * @param handler - The handler function to execute\n * @param config - Optional handler configuration including priority, timing, and lifecycle options.\n * \n * @returns Unregister function to remove this handler\n * \n * @throws {Error} When maximum handlers limit is reached\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n register<K extends ActionNames<T> & keyof TResultMap>(\n action: K,\n handler: ActionResultHandler<T[K], ActionResult<TResultMap, K>>,\n config?: HandlerConfig<T[K]>\n ): UnregisterFunction;\n register<K extends Exclude<ActionNames<T>, keyof TResultMap>, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config?: HandlerConfig<T[K]>\n ): UnregisterFunction;\n register<K extends ActionNames<T>, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config: HandlerConfig<T[K]> = {}\n ): UnregisterFunction {\n return this.registerWithRole(action, handler, config, 'legacy');\n }\n\n /**\n * Register a side-effect-only handler in an explicit guard or observer\n * phase. This is a supported 1.x compatibility convenience for callers\n * that configure the phase dynamically.\n *\n * Prefer `registerGuard()` for admission and `registerObserver()` for a\n * statically known post-result effect. `effectKind` remains required so this\n * API cannot participate in result arbitration implicitly.\n * @public\n */\n registerEffect<K extends ActionNames<T>>(\n action: K,\n handler: ActionGuardHandler<T[K]>,\n config: EffectConfig<T[K]> & { effectKind: 'guard' },\n ): UnregisterFunction;\n registerEffect<K extends ActionNames<T>>(\n action: K,\n handler: ActionEffectHandler<T[K]>,\n config: EffectConfig<T[K]> & { effectKind: 'observer' },\n ): UnregisterFunction;\n registerEffect<K extends ActionNames<T>>(\n action: K,\n handler: ActionEffectHandler<T[K]> | ActionGuardHandler<T[K]>,\n config: EffectConfig<T[K]>,\n ): UnregisterFunction {\n if (config.effectKind === 'guard') {\n return this.registerGuard(action, handler as ActionGuardHandler<T[K]>, config);\n }\n return this.registerObserver(action, event => (handler as ActionEffectHandler<T[K]>)(event.payload as T[K], {\n signal: event.signal,\n getPayload: () => event.payload as T[K],\n }), config);\n }\n\n /** Register an authorization or validation guard that always runs before\n * concurrent result arbitration. */\n registerGuard<K extends ActionNames<T>>(\n action: K,\n handler: ActionGuardHandler<T[K]>,\n config: GuardConfig<T[K]> = {},\n ): UnregisterFunction {\n // Runtime callers can still pass an unsafe cast or plain JavaScript\n // configuration. Admission must never become fail-open as a result.\n return this.registerWithRole(action, handler as ActionHandler<T[K], void>, {\n ...config,\n scheduling: 'await-before-next',\n errorPolicy: 'fatal',\n }, 'guard');\n }\n\n /** Register a terminal observer. It runs after result aggregation and has\n * no controller, result, payload, or winner-selection capabilities. */\n registerObserver<\n K extends ActionNames<T>,\n R = ActionResult<TResultMap, K>,\n H extends (event: ActionObserverEvent<T[K], R>) => unknown = ActionObserverHandler<T[K], R>,\n >(\n action: K,\n handler: H & (ReturnType<H> extends void | Promise<void> ? unknown : never),\n config: ObserverConfig<T[K]> = {},\n ): UnregisterFunction {\n const handlerId = config.id ?? this.generateHandlerId(action);\n const existing = this.pipelines.get(action)?.find(item => item.id === handlerId);\n if (existing && (existing.role ?? 'legacy') !== 'observer') {\n throw new Error(\n `Action handler role conflict for \"${String(action)}\" and id \"${handlerId}\": `\n + `cannot replace ${(existing.role ?? 'legacy')} with observer.`,\n );\n }\n // A duplicate observer must not acquire ownership of another registration\n // (or overwrite its callback) when replacement was explicitly disabled.\n if (existing && config.replaceExisting === false) return () => {};\n const unregister = this.registerWithRole(\n action,\n (() => undefined) as ActionHandler<T[K], void>,\n { ...config, id: handlerId },\n 'observer',\n );\n const registration = this.pipelines.get(action)?.find(item => item.id === handlerId);\n if (!registration) {\n unregister();\n throw new Error(`Observer registration \"${handlerId}\" was not retained.`);\n }\n this.observerHandlers.set(registration, {\n handler: handler as ActionObserverHandler<any, any>,\n when: config.when ?? 'always',\n });\n return () => {\n this.observerHandlers.delete(registration);\n unregister();\n };\n }\n\n /**\n * Register a handler that contributes the result declared for an action.\n *\n * @public\n */\n registerResult<K extends ActionNames<T> & keyof TResultMap>(\n action: K,\n handler: ActionResultHandler<T[K], ActionResult<TResultMap, K>>,\n config?: HandlerConfig<T[K]>,\n ): UnregisterFunction {\n return this.registerWithRole(\n action,\n handler as ActionHandler<T[K], ActionResult<TResultMap, K>>,\n config ?? {},\n 'result',\n );\n }\n\n private registerWithRole<K extends keyof T, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config: HandlerConfig<T[K]>,\n role: HandlerRole,\n ): UnregisterFunction {\n this.assertStringActionKey(action);\n this.assertAcceptingWork();\n const handlerId = config.id || this.generateHandlerId(action);\n return this._performRegistrationSync(action, handler, config, handlerId, role);\n }\n\n /**\n * ๐ Unified logging method with cached debug mode check\n */\n private log(message: string, data?: unknown, level: 'log' | 'warn' | 'error' = 'log') {\n if (this.isDebugMode) {\n const timestamp = new Date().toISOString();\n console[level](`๐ฏ [${timestamp}] [${this.name}] ${message}`, data || '');\n }\n }\n\n private assertAcceptingWork(): void {\n if (this.lifecycleState !== 'active') {\n throw new ActionRegisterDestroyedError(this.name, this.lifecycleState);\n }\n }\n\n private assertStringActionKey(action: PropertyKey): void {\n if (typeof action !== 'string') {\n throw new TypeError('Action keys must be strings.');\n }\n }\n\n private rejectedLifecyclePromise<R>(): Promise<R> {\n const error = new ActionRegisterDestroyedError(\n this.name,\n this.lifecycleState === 'active' ? 'destroyed' : this.lifecycleState\n );\n const rejected = Promise.reject<R>(error);\n void rejected.catch(() => {});\n return rejected;\n }\n\n /**\n * ๐ง Generate unique handler ID using optimized counter-based approach\n */\n private generateHandlerId<K extends keyof T>(action: K): string {\n // ๐ง Performance: Use simple counter instead of crypto.randomUUID()\n // This is safe for single-process apps and ~70% faster\n return `${String(action)}_${this.name}_${++this.handlerIdCounter}`;\n }\n\n /**\n * ๐ง Create and merge AbortSignal instances with proper cleanup\n * \n * @param options Dispatch options containing signal and autoAbort configuration\n * @returns [effectiveSignal, autoAbortController, cleanupFunction]\n */\n private createAbortSignal(options?: DispatchOptions): [\n AbortSignal | undefined, \n AbortController | undefined, \n () => void\n ] {\n const signals: AbortSignal[] = [];\n const cleanups: (() => void)[] = [];\n let autoAbortController: AbortController | undefined;\n\n // Add existing signal if provided\n if (options?.signal) {\n signals.push(options.signal);\n }\n\n // Create auto-abort controller if enabled\n if (options?.autoAbort?.enabled) {\n autoAbortController = new AbortController();\n signals.push(autoAbortController.signal);\n }\n\n // No signals to merge\n if (signals.length === 0) {\n return [undefined, autoAbortController, () => {}];\n }\n\n // Single signal - no merge needed\n if (signals.length === 1) {\n return [signals[0], autoAbortController, () => cleanups.forEach(c => c())];\n }\n\n // Multiple signals - use AbortSignal.any() if available, fallback to manual merge\n let effectiveSignal: AbortSignal;\n \n if (typeof (AbortSignal as any).any === 'function') {\n // Modern browsers with AbortSignal.any()\n effectiveSignal = (AbortSignal as any).any(signals);\n } else {\n // Fallback: Create controller and link all signals\n const mergedController = new AbortController();\n effectiveSignal = mergedController.signal;\n \n signals.forEach(signal => {\n if (signal.aborted) {\n mergedController.abort();\n } else {\n const abortHandler = () => mergedController.abort();\n signal.addEventListener('abort', abortHandler, { once: true });\n cleanups.push(() => signal.removeEventListener('abort', abortHandler));\n }\n });\n }\n\n const cleanup = () => {\n cleanups.forEach(c => {\n try {\n c();\n } catch (error) {\n this.log('Cleanup error during AbortSignal cleanup', error, 'warn');\n }\n });\n };\n\n return [effectiveSignal, autoAbortController, cleanup];\n }\n\n /**\n * ๐ Perform synchronous handler registration\n */\n private _performRegistrationSync<K extends keyof T, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config: HandlerConfig<T[K]>,\n handlerId: string,\n role: HandlerRole = 'legacy',\n ): UnregisterFunction {\n // Create handler registration with defaults\n const registration: HandlerRegistration<T[K], R> = {\n handler,\n config: resolveHandlerConfig(config, handlerId),\n id: handlerId,\n role,\n };\n \n // Initialize pipeline if it doesn't exist\n if (!this.pipelines.has(action)) {\n this.pipelines.set(action, []);\n }\n\n const pipeline = this.pipelines.get(action)!;\n const actionUnregisterFunctions = this.getUnregisterFunctions(action);\n \n const existingIndex = pipeline.findIndex(reg => reg.id === handlerId);\n\n // Replacement keeps the pipeline size stable. Apply a finite limit only\n // when the registration would add a distinct handler.\n if (existingIndex === -1 && pipeline.length >= this.maxHandlersPerAction) {\n throw new RangeError(\n `Handler limit (${this.maxHandlersPerAction}) reached for action \"${String(action)}\".`,\n );\n }\n\n // ๐ Enhanced duplicate ID handling with replaceExisting support and cleanup\n if (existingIndex !== -1) {\n const existing = pipeline[existingIndex];\n const existingUnregister = actionUnregisterFunctions.get(handlerId);\n\n if (existing && (existing.role ?? 'legacy') !== role) {\n throw new Error(\n `Action handler role conflict for \"${String(action)}\" and id \"${handlerId}\": `\n + `cannot replace ${(existing.role ?? 'legacy')} with ${role}.`,\n );\n }\n \n if (registration.config.replaceExisting) {\n // ๐ง Fix: Clean up existing handler properly without removing from pipeline\n\n // Call cleanup if available on the old handler\n if (existing?.config.cleanup && typeof existing.config.cleanup === 'function') {\n try {\n existing.config.cleanup();\n } catch (cleanupError) {\n this.log(`Cleanup error for replaced handler: ${String(action)}`, cleanupError, 'warn');\n }\n }\n if (existing) this.observerHandlers.delete(existing);\n\n // Clean up existing unregister function\n if (existingUnregister) {\n actionUnregisterFunctions.delete(handlerId);\n }\n\n // Replace existing handler directly in pipeline\n pipeline[existingIndex] = registration;\n pipeline.sort((a, b) => b.config.priority - a.config.priority);\n // Cache disabled\n\n // ๐ง Fix: Update last registered timestamp when replacing\n this.lastRegisteredTimestamps.set(action, new Date());\n\n // Create new unregister function and store it\n const newUnregister = this.createUnregisterFunction(action, handlerId, registration);\n actionUnregisterFunctions.set(handlerId, newUnregister);\n \n this.log(`Handler replaced: ${String(action)}`, {\n handlerId,\n priority: config.priority,\n totalHandlers: pipeline.length,\n hadExistingUnregister: Boolean(existingUnregister)\n });\n \n return newUnregister;\n } else {\n // The rejected registration does not own the existing handler. Returning\n // its unregister function would let the rejected caller tear down a\n // registration created by somebody else.\n if (!existing) {\n throw new Error('Internal error: existing handler should be defined in duplicate handler block');\n }\n \n this.log(`Handler duplicate ignored, returning no-op unregister: ${String(action)}`, {\n handlerId,\n existingPriority: existing.config.priority,\n newPriority: config.priority,\n existingBlocking: existing.config.blocking,\n newBlocking: config.blocking,\n note: 'Use replaceExisting:true to replace'\n }, 'warn');\n \n return () => {};\n }\n }\n \n // Add handler to pipeline\n pipeline.push(registration);\n pipeline.sort((a, b) => b.config.priority - a.config.priority);\n // Cache disabled\n\n // ๐ง Fix: Update last registered timestamp\n this.lastRegisteredTimestamps.set(action, new Date());\n\n // Create and store unregister function\n const unregister = this.createUnregisterFunction(action, handlerId, registration);\n actionUnregisterFunctions.set(handlerId, unregister);\n\n this.log(`Handler registered: ${String(action)}`, {\n handlerId,\n priority: config.priority,\n totalHandlers: pipeline.length\n });\n\n return unregister;\n }\n\n\n /**\n * Dispatch an action with optional execution options\n * \n * @param action - The action type to dispatch\n * @param args - The payload/options tuple for the selected action: payload-bearing actions require a payload, while void actions may omit it; dispatch options are optional.\n * \n * @returns Promise that resolves when all handlers complete\n * \n * @throws {Error} When action dispatching fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n // Overload for actions with payload (more specific)\n dispatch<K extends ActionNames<T>>(action: K, ...args: DispatchArgs<T[K]>): Promise<void>;\n \n // Implementation (least specific)\n dispatch<K extends ActionNames<T>>(action: K, ...args: DispatchArgs<T[K]>): Promise<void> {\n this.assertStringActionKey(action);\n const [payload, options] = args as [T[K] | undefined, DispatchOptions | undefined];\n if (this.lifecycleState !== 'active') {\n return this.rejectedLifecyclePromise<void>();\n }\n\n const timeoutScope = this.createTimeoutScope(action, options);\n const dispatchHandlerPromises: DispatchHandlerPromises = new Set();\n const attemptState = { count: 0 };\n const plan = this.resolveDispatchPlan(action, options);\n const hasTimingGuard = plan.debounceMs !== undefined || plan.throttleMs !== undefined;\n const notifiedObservers = new Set<HandlerRegistration<any, any>>();\n const notifiedObserverOutcomes = new Set<ActionObserverEvent<T[K], unknown>['outcome']>();\n let terminalErrorReported = false;\n const reportTerminalError = (error: unknown) => {\n if (terminalErrorReported) return;\n terminalErrorReported = true;\n this.invokeErrorHandler(error, action, payload, options, attemptState.count);\n };\n // Void dispatch still aggregates handler values for terminal observers;\n // only the public dispatch return type is void.\n const notifyObservers = async (event: ActionObserverEvent<T[K], unknown>) => {\n if (notifiedObserverOutcomes.has(event.outcome)) return;\n notifiedObserverOutcomes.add(event.outcome);\n await this.executeObservers(action, plan, event, notifiedObservers);\n };\n const pipelineOperation = async () => {\n const guard = plan.guards.length > 0\n ? await this.executeGuardPhase(\n action, payload as T[K], timeoutScope.options, plan, dispatchHandlerPromises,\n )\n : {\n allowed: true, payload: payload as T[K], aborted: false,\n abortReason: undefined, error: undefined, errors: [], outcomes: [], executedHandlers: [], duration: 0,\n };\n this.cleanupOneTimeHandlers(action, guard.executedHandlers, dispatchHandlerPromises);\n if (!guard.allowed) {\n await notifyObservers({\n action: String(action),\n payload: guard.payload,\n outcome: guard.aborted ? 'cancelled' : 'failed',\n result: undefined,\n errors: guard.errors,\n signal: timeoutScope.options?.signal,\n });\n // An explicit controller abort is an expected cancellation. A thrown\n // guard error remains fatal for dispatch(), matching errorPolicy.\n if (!guard.aborted && guard.errors.length > 0) {\n throw guard.error\n ?? guard.errors[0]?.error\n ?? new Error(`Guard phase failed for \"${String(action)}\"`);\n }\n return;\n }\n const execution = await this.executeWithRetry(async attemptSignal => {\n const executedHandlers: HandlerRegistration<any, any>[] = [];\n try {\n return await this._performDispatchWithResult<K, void>(\n action,\n guard.payload,\n this.withAttemptSignal(timeoutScope.options, attemptSignal),\n undefined,\n plan,\n executedHandlers,\n dispatchHandlerPromises\n );\n } finally {\n this.cleanupOneTimeHandlers(\n action,\n executedHandlers,\n dispatchHandlerPromises\n );\n }\n }, timeoutScope.options, attemptState, result => result.outcome === 'failed', () => (\n this.getAttemptHandlers(action, plan).length > 0\n ), undefined, this.shouldDrainBeforeRetry(plan, timeoutScope.options)\n ? () => this.drainAttemptHandlers(dispatchHandlerPromises)\n : undefined);\n if (timeoutScope.options?.signal?.aborted) {\n // The timeout signal shares the cancellation channel, but its public\n // terminal contract remains a failed ActionTimeoutError.\n if (timeoutScope.options.signal.reason instanceof ActionTimeoutError) {\n throw timeoutScope.options.signal.reason;\n }\n await notifyObservers({\n action: String(action),\n payload: guard.payload,\n outcome: 'cancelled',\n result: undefined,\n errors: execution.errors,\n signal: timeoutScope.options.signal,\n });\n return;\n }\n if (execution.outcome === 'failed') {\n throw execution.errors[execution.errors.length - 1]?.error\n ?? new Error(`Action \"${String(action)}\" failed`);\n }\n const result = this.processResults<unknown>(\n execution.results as unknown[],\n execution.terminated,\n execution.terminated ? execution.result : undefined,\n options?.result,\n );\n await notifyObservers({\n action: String(action),\n payload: guard.payload,\n outcome: execution.outcome,\n result,\n errors: execution.errors,\n signal: timeoutScope.options?.signal,\n });\n };\n const operation = async () => {\n if (timeoutScope.options?.signal?.aborted) {\n await notifyObservers({ action: String(action), payload: payload as T[K], outcome: 'cancelled',\n result: undefined, errors: [], signal: timeoutScope.options?.signal });\n return;\n }\n\n // Strict validation must complete before timing guards mutate admission state.\n this.validatePayload(action, payload);\n this.validateResultOptions(options?.result);\n if (timeoutScope.options?.signal?.aborted) {\n await notifyObservers({ action: String(action), payload: payload as T[K], outcome: 'cancelled',\n result: undefined, errors: [], signal: timeoutScope.options?.signal });\n return;\n }\n\n if (hasTimingGuard) {\n const admission = await this.evaluateTimingGuards(\n String(action),\n plan,\n timeoutScope.options?.signal,\n );\n if (admission.aborted || timeoutScope.options?.signal?.aborted || admission.reason) {\n await notifyObservers({\n action: String(action), payload: payload as T[K],\n outcome: admission.aborted || timeoutScope.options?.signal?.aborted\n ? 'cancelled'\n : admission.reason === 'Debounced execution' ? 'debounced' : 'throttled',\n result: undefined, errors: admission.reason ? [{\n handlerId: 'admission', error: new Error(admission.reason),\n timestamp: Date.now(), severity: 'blocking',\n }] : [],\n signal: timeoutScope.options?.signal,\n });\n return;\n }\n }\n\n if (timeoutScope.options?.signal?.aborted) {\n await notifyObservers({ action: String(action), payload: payload as T[K], outcome: 'cancelled',\n result: undefined, errors: [], signal: timeoutScope.options?.signal });\n return;\n }\n\n if (timeoutScope.options?.immediate || !this.dispatchQueue) {\n return pipelineOperation();\n }\n\n const queued = this.dispatchQueue.enqueueWithHandle(\n pipelineOperation,\n timeoutScope.options?.queuePriority ?? 0\n );\n timeoutScope.onTimeout(error => queued.cancel(error));\n return queued.promise;\n };\n\n let dispatchPromise: Promise<void>;\n let observedDispatchPromise: Promise<void>;\n this.dispatchConstructionDepth += 1;\n try {\n dispatchPromise = operation();\n observedDispatchPromise = dispatchPromise.catch(async error => {\n reportTerminalError(error);\n await notifyObservers({\n action: String(action), payload: payload as T[K], outcome: 'failed', result: undefined,\n errors: [{ handlerId: 'dispatch', error: error instanceof Error ? error : new Error(String(error)),\n timestamp: Date.now(), severity: 'blocking' }], signal: timeoutScope.options?.signal,\n });\n throw error;\n });\n this.trackDispatchPromise(observedDispatchPromise);\n } finally {\n this.dispatchConstructionDepth -= 1;\n }\n const exposedPromise = this.raceWithTimeout(\n observedDispatchPromise!,\n timeoutScope,\n dispatchHandlerPromises\n );\n const observedPromise = exposedPromise.catch(async error => {\n reportTerminalError(error);\n // The public timeout is already terminal. Failure observers remain\n // shutdown-owned best-effort work, but a non-cooperative observer must\n // not hold the timed-out caller open indefinitely.\n const observerNotification = this.trackGlobalHandlerPromise(notifyObservers({\n action: String(action), payload: payload as T[K], outcome: 'failed', result: undefined,\n errors: [{ handlerId: 'dispatch', error: error instanceof Error ? error : new Error(String(error)),\n timestamp: Date.now(), severity: 'blocking' }], signal: timeoutScope.options?.signal,\n }));\n void observerNotification.catch(observerError => {\n this.log(`Failure observer delivery failed for ${String(action)}`, observerError, 'warn');\n });\n throw error;\n });\n\n // Preserve rejection semantics for observers without leaking fire-and-forget\n // dispatches as process-level unhandled rejections.\n void observedPromise.catch(() => {});\n return observedPromise;\n }\n\n /** Execute a dispatch operation with an optional whole-action retry policy. */\n private async executeWithRetry<R>(\n operation: (attemptSignal: AbortSignal) => Promise<R>,\n options: DispatchOptions | undefined,\n attemptState: { count: number },\n shouldRetryResult?: (result: R) => boolean,\n canRetry: () => boolean = () => true,\n telemetry?: RetryTelemetry,\n beforeRetry?: () => Promise<void>,\n ): Promise<R> {\n const configuredAttempts = options?.retryOnError?.maxAttempts ?? 1;\n const maxAttempts = Number.isFinite(configuredAttempts)\n ? Math.max(1, Math.floor(configuredAttempts))\n : 1;\n const retryDelay = Math.max(0, options?.retryOnError?.delay ?? 0);\n\n while (attemptState.count < maxAttempts) {\n attemptState.count += 1;\n const attemptStartedAt = Date.now();\n const attemptController = new AbortController();\n\n try {\n const result = await operation(attemptController.signal);\n const shouldRetry = shouldRetryResult?.(result) ?? false;\n const canRetryAttempt = (\n shouldRetry &&\n attemptState.count < maxAttempts &&\n !options?.signal?.aborted &&\n canRetry()\n );\n const attemptEndedAt = Date.now();\n telemetry?.attempts.push({\n startTime: attemptStartedAt,\n endTime: attemptEndedAt,\n duration: attemptEndedAt - attemptStartedAt,\n outcome: shouldRetry\n ? (canRetryAttempt ? 'retried' : 'failed')\n : 'succeeded',\n });\n if (telemetry) telemetry.pipelineDuration += attemptEndedAt - attemptStartedAt;\n if (!canRetryAttempt) {\n return result;\n }\n attemptController.abort(new ActionAttemptSupersededError(attemptState.count));\n await beforeRetry?.();\n const retryStartedAt = Date.now();\n const shouldContinue = await this.waitForRetry(retryDelay, options?.signal);\n if (telemetry) telemetry.retryDelayDuration += Date.now() - retryStartedAt;\n if (!shouldContinue) {\n telemetry?.attempts.push({\n startTime: Date.now(), endTime: Date.now(), duration: 0, outcome: 'cancelled',\n });\n return result;\n }\n } catch (error) {\n const attemptEndedAt = Date.now();\n const canRetryAttempt = !(\n error instanceof ActionValidationError ||\n attemptState.count >= maxAttempts ||\n options?.signal?.aborted ||\n !canRetry()\n );\n telemetry?.attempts.push({\n startTime: attemptStartedAt,\n endTime: attemptEndedAt,\n duration: attemptEndedAt - attemptStartedAt,\n outcome: canRetryAttempt ? 'retried' : 'failed',\n });\n if (telemetry) telemetry.pipelineDuration += attemptEndedAt - attemptStartedAt;\n if (!canRetryAttempt) {\n throw error;\n }\n attemptController.abort(new ActionAttemptSupersededError(attemptState.count));\n await beforeRetry?.();\n const retryStartedAt = Date.now();\n const shouldContinue = await this.waitForRetry(retryDelay, options?.signal);\n if (telemetry) telemetry.retryDelayDuration += Date.now() - retryStartedAt;\n if (!shouldContinue) throw error;\n }\n }\n\n // The loop always returns or throws. This protects the generic return type\n // if an invalid retry configuration somehow reaches this point.\n const terminalAttempt = new AbortController();\n return operation(terminalAttempt.signal);\n }\n\n private trackDispatchPromise<R>(promise: Promise<R>): Promise<R> {\n this.activeDispatches.add(promise);\n const remove = () => this.activeDispatches.delete(promise);\n void promise.then(remove, remove);\n return promise;\n }\n\n private trackHandlerPromise<R>(\n promise: Promise<R>,\n dispatchHandlerPromises: DispatchHandlerPromises\n ): Promise<R> {\n this.activeHandlerPromises.add(promise);\n dispatchHandlerPromises.add(promise);\n const remove = () => {\n this.activeHandlerPromises.delete(promise);\n dispatchHandlerPromises.delete(promise);\n };\n void promise.then(remove, remove);\n return promise;\n }\n\n private withAttemptSignal(\n options: DispatchOptions | undefined,\n attemptSignal: AbortSignal,\n ): AttemptDispatchOptions {\n const outerSignal = options?.signal;\n if (!outerSignal) return { ...options, signal: attemptSignal };\n if (typeof AbortSignal.any === 'function') {\n return { ...options, signal: AbortSignal.any([outerSignal, attemptSignal]) };\n }\n const controller = new AbortController();\n const forwardOuter = () => controller.abort(outerSignal.reason);\n const forwardAttempt = () => controller.abort(attemptSignal.reason);\n if (outerSignal.aborted) forwardOuter();\n else outerSignal.addEventListener('abort', forwardOuter, { once: true });\n if (attemptSignal.aborted) forwardAttempt();\n else attemptSignal.addEventListener('abort', forwardAttempt, { once: true });\n const cleanup = () => {\n outerSignal.removeEventListener('abort', forwardOuter);\n attemptSignal.removeEventListener('abort', forwardAttempt);\n };\n controller.signal.addEventListener('abort', cleanup, { once: true });\n return { ...options, signal: controller.signal, [ATTEMPT_SIGNAL_CLEANUP]: cleanup };\n }\n\n private shouldDrainBeforeRetry(\n plan: DispatchPlan,\n options: DispatchOptions | undefined,\n ): boolean {\n const barrier = options?.retryOnError?.attemptBarrier\n ?? (plan.executionMode === 'race' ? 'abort-and-drain' : 'abort-and-overlap');\n return barrier === 'abort-and-drain';\n }\n\n /** Do not begin a whole-action retry while a previous race loser is still\n * running. Handlers should still observe their signal for cancellation. */\n private async drainAttemptHandlers(\n dispatchHandlerPromises: DispatchHandlerPromises,\n ): Promise<void> {\n const pending = [...dispatchHandlerPromises];\n if (pending.length > 0) await Promise.allSettled(pending);\n }\n\n private trackGlobalHandlerPromise<R>(promise: Promise<R>): Promise<R> {\n this.activeHandlerPromises.add(promise);\n const remove = () => this.activeHandlerPromises.delete(promise);\n void promise.then(remove, remove);\n return promise;\n }\n\n /** Abort-aware retry delay so cancellation does not wait for the full backoff. */\n private waitForRetry(delay: number, signal?: AbortSignal): Promise<boolean> {\n if (signal?.aborted) return Promise.resolve(false);\n if (delay <= 0) return Promise.resolve(true);\n\n return new Promise(resolve => {\n const timer = setTimeout(finish, delay);\n const abort = () => finish(false);\n\n function finish(shouldContinue = true) {\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n resolve(shouldContinue);\n }\n\n signal?.addEventListener('abort', abort, { once: true });\n });\n }\n\n /** Build a wall-clock timeout that also participates in pipeline cancellation. */\n private createTimeoutScope<K extends keyof T>(\n action: K,\n options?: DispatchOptions\n ): {\n options: DispatchOptions | undefined;\n timeoutPromise?: Promise<never>;\n onTimeout: (callback: (error: ActionTimeoutError) => void) => void;\n cleanup: () => void;\n cleanupSignals: () => void;\n } {\n const configuredTimeout = options?.timeout;\n if (\n configuredTimeout !== undefined &&\n (!Number.isFinite(configuredTimeout) || configuredTimeout < 0)\n ) {\n throw new RangeError('timeout must be a non-negative finite number.');\n }\n const hasTimeout = configuredTimeout !== undefined;\n const timeout = configuredTimeout;\n const timeoutController = hasTimeout ? new AbortController() : undefined;\n const signalCleanups: Array<() => void> = [];\n const timeoutCallbacks = new Set<(error: ActionTimeoutError) => void>();\n const signals = [\n this.lifecycleController.signal,\n options?.signal,\n timeoutController?.signal,\n ].filter((candidate): candidate is AbortSignal => Boolean(candidate));\n let signal = signals[0]!;\n\n if (signals.length > 1) {\n if (typeof (AbortSignal as typeof AbortSignal & {\n any?: (signals: AbortSignal[]) => AbortSignal;\n }).any === 'function') {\n signal = (AbortSignal as typeof AbortSignal & {\n any: (signals: AbortSignal[]) => AbortSignal;\n }).any(signals);\n } else {\n const mergedController = new AbortController();\n const forwardAbort = (source: AbortSignal) => {\n if (!mergedController.signal.aborted) mergedController.abort(source.reason);\n };\n\n for (const source of signals) {\n if (source.aborted) {\n forwardAbort(source);\n break;\n }\n const listener = () => forwardAbort(source);\n source.addEventListener('abort', listener, { once: true });\n signalCleanups.push(() => source.removeEventListener('abort', listener));\n }\n signal = mergedController.signal;\n }\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = timeoutController && timeout !== undefined\n ? new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const error = new ActionTimeoutError(String(action), timeout);\n timeoutController.abort(error);\n timeoutCallbacks.forEach(callback => callback(error));\n reject(error);\n }, timeout);\n })\n : undefined;\n\n return {\n options: { ...options, signal },\n timeoutPromise,\n onTimeout: callback => timeoutCallbacks.add(callback),\n cleanup: () => {\n if (timer !== undefined) clearTimeout(timer);\n timeoutCallbacks.clear();\n },\n cleanupSignals: () => signalCleanups.forEach(cleanup => cleanup()),\n };\n }\n\n /** Expose timeout failure while allowing the queued operation to drain safely. */\n private raceWithTimeout<R>(\n operation: Promise<R>,\n scope: {\n timeoutPromise?: Promise<never>;\n cleanup: () => void;\n cleanupSignals: () => void;\n },\n dispatchHandlerPromises: DispatchHandlerPromises\n ): Promise<R> {\n const exposed = scope.timeoutPromise\n ? Promise.race([operation, scope.timeoutPromise])\n : operation;\n const cleanupAfterStartedHandlers = () => {\n // Successful completion must cancel the ref'ed timeout timer immediately.\n // Only fallback signal-forwarding listeners need to outlive race losers.\n scope.cleanup();\n this.cleanupSignalsAfterStartedHandlers(\n scope.cleanupSignals,\n dispatchHandlerPromises\n );\n };\n void exposed.then(cleanupAfterStartedHandlers, cleanupAfterStartedHandlers);\n return exposed;\n }\n\n private cleanupSignalsAfterStartedHandlers(\n cleanup: () => void,\n dispatchHandlerPromises: DispatchHandlerPromises\n ): void {\n const handlersStillRunning = [...dispatchHandlerPromises];\n if (handlersStillRunning.length === 0) {\n cleanup();\n return;\n }\n\n // In AbortSignal.any() fallback environments, this dispatch's signal\n // forwarding listeners must outlive its race-mode losers even though the\n // exposed dispatch resolved. Unrelated dispatches must not delay cleanup.\n void Promise.allSettled(handlersStillRunning).then(cleanup);\n }\n\n /** Invoke the configured error handler without allowing it to replace the dispatch error. */\n private invokeErrorHandler<K extends keyof T>(\n error: unknown,\n action: K,\n payload: T[K] | undefined,\n options: DispatchOptions | undefined,\n attempts: number\n ): void {\n const errorHandler = this.registryConfig?.errorHandler;\n if (!errorHandler) return;\n\n const normalizedError = error instanceof Error ? error : new Error(String(error));\n try {\n const handlerResult = errorHandler(normalizedError, {\n action: String(action),\n payload,\n options,\n attempts,\n phase: normalizedError instanceof ActionTimeoutError\n ? 'timeout'\n : normalizedError instanceof ActionValidationError\n ? 'validation'\n : 'execution',\n });\n if (handlerResult && typeof (handlerResult as PromiseLike<void>).then === 'function') {\n void Promise.resolve(handlerResult).catch(handlerError => {\n this.log('Global async error handler failed', handlerError, 'warn');\n });\n }\n } catch (handlerError) {\n this.log('Global error handler failed', handlerError, 'warn');\n }\n }\n\n /**\n * Validate an action payload against the configured schema.\n * Shared by all dispatch paths so result collection cannot bypass validation.\n */\n private validatePayload<K extends keyof T>(\n action: K,\n payload?: T[K]\n ): ExecutionResult<never>['validation'] {\n if (\n !this.registryConfig?.schema ||\n this.registryConfig.validateOnDispatch === false\n ) {\n return undefined;\n }\n\n const actionName = String(action);\n const actionSchema = this.registryConfig.schema[actionName];\n if (!actionSchema) {\n return undefined;\n }\n\n let result: ReturnType<typeof actionSchema.safeParse>;\n try {\n result = actionSchema.safeParse(payload);\n } catch (error) {\n throw new ActionValidationError(actionName, error);\n }\n if (result.success) {\n return { passed: true, errors: [] };\n }\n\n const mode = this.registryConfig.validationMode ?? 'strict';\n if (mode === 'strict') {\n throw new ActionValidationError(actionName, result.error);\n }\n\n if (mode === 'warn') {\n console.warn(\n `Action \"${actionName}\" payload validation failed:`,\n result.error.message\n );\n this.log(`Validation warning for action '${actionName}'`, {\n issues: result.error.issues,\n }, 'warn');\n }\n\n return {\n passed: false,\n errors: result.error.issues.map(issue => issue.message),\n };\n }\n\n private createAbortedExecutionResult<R>(\n startTime: number,\n skippedRegistrations: readonly HandlerRegistration<any, any>[] = [],\n validation?: ExecutionResult<R>['validation']\n ): ExecutionResult<R> {\n const endTime = Date.now();\n const handlers = skippedRegistrations.map(registration => ({\n id: registration.id,\n status: 'skipped' as const,\n executed: false,\n duration: 0,\n result: undefined,\n error: undefined,\n metadata: registration.config.metadata ? { ...registration.config.metadata } : undefined,\n }));\n\n return {\n success: false,\n aborted: true,\n abortReason: 'Action dispatch aborted by signal',\n terminated: false,\n outcome: 'cancelled',\n validation,\n result: undefined,\n successResults: [],\n results: [],\n failedResults: [],\n execution: {\n duration: endTime - startTime,\n admissionDuration: endTime - startTime,\n queueWaitDuration: 0,\n pipelineDuration: 0,\n handlersExecuted: 0,\n handlersSkipped: handlers.length,\n handlersFailed: 0,\n startTime,\n endTime,\n },\n handlers,\n errors: [],\n };\n }\n\n private resolveDispatchPlan<K extends keyof T>(\n action: K,\n options?: DispatchOptions,\n ): DispatchPlan {\n const pipelineSnapshot = [...(this.pipelines.get(action) ?? [])];\n // Guards are admission controls. Ordinary dispatch filters can select\n // result/observer work, but may never bypass validation or authorization.\n const guards = pipelineSnapshot.filter(handler => handler.role === 'guard');\n const filterableHandlers = pipelineSnapshot.filter(handler => handler.role !== 'guard');\n const filteredHandlers = options?.filter\n ? this.filterHandlers(filterableHandlers, options.filter)\n : filterableHandlers;\n const eligibleHandlers = [...guards, ...filteredHandlers];\n const admissionHandlers = eligibleHandlers.filter(handler => handler.role !== 'observer');\n const debounceMs = options?.debounce\n ?? admissionHandlers.find(handler => handler.config.debounce !== undefined)?.config.debounce;\n const throttleMs = options?.throttle\n ?? admissionHandlers.find(handler => handler.config.throttle !== undefined)?.config.throttle;\n\n return {\n pipelineSnapshot,\n eligibleHandlers,\n guards,\n results: filteredHandlers.filter(handler => handler.role !== 'observer'),\n observers: filteredHandlers.filter(handler => handler.role === 'observer'),\n debounceMs,\n throttleMs,\n executionMode: options?.executionMode\n ?? this.actionExecutionModes.get(action)\n ?? this.executionMode,\n };\n }\n\n private async evaluateTimingGuards(\n actionKey: string,\n plan: DispatchPlan,\n signal?: AbortSignal,\n ): Promise<TimingGuardAdmission> {\n const { debounceMs, throttleMs } = plan;\n\n if (signal?.aborted) return { aborted: true };\n\n if (debounceMs !== undefined && !(await this.actionGuard.debounce(actionKey, debounceMs, signal))) {\n return signal?.aborted\n ? { aborted: true }\n : { aborted: false, reason: 'Debounced execution' };\n }\n if (throttleMs !== undefined && !this.actionGuard.throttle(actionKey, throttleMs, signal)) {\n return signal?.aborted\n ? { aborted: true }\n : { aborted: false, reason: 'Throttled execution' };\n }\n return { aborted: false };\n }\n\n /**\n * Keep the dispatch plan stable across retries while honoring handlers that\n * were consumed by the `once` lifecycle after an earlier attempt.\n */\n private getAttemptHandlers<K extends keyof T>(\n action: K,\n plan: DispatchPlan,\n ): HandlerRegistration<any, any>[] {\n const activePipeline = this.pipelines.get(action) ?? [];\n return plan.results.filter(\n handler => !handler.config.once || activePipeline.includes(handler),\n );\n }\n\n private getObservers<K extends keyof T>(\n action: K,\n plan: DispatchPlan,\n ): Array<[\n HandlerRegistration<any, any>,\n { handler: ActionObserverHandler<any, any>; when: 'success' | 'failure' | 'always' }\n ]> {\n const activePipeline = this.pipelines.get(action) ?? [];\n return plan.observers.flatMap(registration => {\n const observer = this.observerHandlers.get(registration);\n return registration.role === 'observer'\n && activePipeline.includes(registration)\n && observer\n ? [[registration, observer] as [\n HandlerRegistration<any, any>,\n { handler: ActionObserverHandler<any, any>; when: 'success' | 'failure' | 'always' }\n ]]\n : [];\n });\n }\n\n /** Observers run after the canonical result has been constructed. Their\n * failures are isolated from that immutable result; detached observers are\n * still tracked for registry shutdown. */\n private async executeObservers<K extends keyof T, R>(\n action: K,\n plan: DispatchPlan,\n event: ActionObserverEvent<T[K], R>,\n notifiedObservers = new Set<HandlerRegistration<any, any>>(),\n ): Promise<void> {\n const observerEvent = this.safeSnapshotObserverEvent(event);\n const selectedObservers: Array<[\n HandlerRegistration<any, any>,\n { handler: ActionObserverHandler<any, any>; when: 'success' | 'failure' | 'always' },\n ]> = [];\n\n // Assign every terminal-path-eligible observer to this immutable event\n // before awaiting any callback. Conditions are deliberately evaluated in\n // the invocation loop below: a lower-priority observer must see state\n // changes made by an awaited higher-priority observer, while remaining\n // reserved to this canonical event if a timeout races that observer chain.\n for (const [registration, observerEntry] of this.getObservers(action, plan)) {\n if (notifiedObservers.has(registration)) continue;\n const successful = observerEvent.outcome === 'completed' || observerEvent.outcome === 'completed_with_errors';\n if (observerEntry.when === 'success' && !successful) continue;\n if (observerEntry.when === 'failure' && successful) continue;\n notifiedObservers.add(registration);\n selectedObservers.push([registration, observerEntry]);\n }\n\n for (const [registration, observerEntry] of selectedObservers) {\n let shouldRun = true;\n try {\n shouldRun = registration.config.condition?.(observerEvent.payload as T[K]) ?? true;\n } catch (error) {\n this.log(`Observer condition failed for ${String(action)}`, error, 'warn');\n continue;\n }\n if (!shouldRun) continue;\n // Detach before invocation so a concurrent dispatch cannot observe and\n // invoke the same once observer. Cleanup remains tied to settlement.\n const detachedOnce = registration.config.once\n && this.removeRegistration(action, registration, false);\n const cleanupOnce = () => {\n if (detachedOnce) this.runRegistrationCleanup(action, registration);\n };\n const invocation = Promise.resolve().then(() => observerEntry.handler(observerEvent));\n if (registration.config.scheduling === 'start-and-continue') {\n void this.trackGlobalHandlerPromise(invocation).then(cleanupOnce, error => {\n this.log(`Observer failed for ${String(action)}`, error, 'warn');\n cleanupOnce();\n });\n } else {\n try {\n await invocation;\n } catch (error) {\n this.log(`Observer failed for ${String(action)}`, error, 'warn');\n } finally {\n cleanupOnce();\n }\n }\n }\n }\n\n /** Give JavaScript observers an isolated, shallowly immutable terminal view.\n * Result payloads are intentionally not deep-cloned: arbitrary result values\n * may be class instances, streams, or identity-bearing domain objects. */\n private snapshotObserverEvent<TPayload, R>(\n event: ActionObserverEvent<TPayload, R>,\n ): ActionObserverEvent<TPayload, R> {\n const freezeValue = <V>(value: V): V => {\n if (Array.isArray(value)) return Object.freeze([...value]) as V;\n if (value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {\n return Object.freeze({ ...(value as Record<string, unknown>) }) as V;\n }\n return value;\n };\n return Object.freeze({\n ...event,\n payload: freezeValue(event.payload),\n result: freezeValue(event.result),\n errors: Object.freeze(event.errors.map(error => Object.freeze({ ...error }))),\n });\n }\n\n /** A diagnostic observer must never make an already constructed canonical\n * result reject, including when shallow-copying a Proxy/getter throws. */\n private safeSnapshotObserverEvent<TPayload, R>(\n event: ActionObserverEvent<TPayload, R>,\n ): ActionObserverEvent<TPayload, R> {\n try {\n return this.snapshotObserverEvent(event);\n } catch (error) {\n this.log('Observer snapshot failed', error, 'warn');\n return Object.freeze({\n action: event.action,\n payload: event.payload,\n outcome: event.outcome,\n result: undefined,\n errors: Object.freeze([]),\n ...(event.signal === undefined ? {} : { signal: event.signal }),\n });\n }\n }\n\n /** Execute the selected guard snapshot once for the whole dispatch. Guards\n * are deliberately outside the retry loop: authorization and normalization\n * belong to admission, not to each provider attempt. */\n private async executeGuardPhase<K extends keyof T>(\n action: K,\n payload: T[K],\n options: DispatchOptions | undefined,\n plan: DispatchPlan,\n dispatchHandlerPromises: DispatchHandlerPromises,\n ): Promise<GuardPhaseResult<T[K]>> {\n if (plan.guards.length === 0) {\n return {\n allowed: true, payload, aborted: false, abortReason: undefined,\n error: undefined, errors: [], outcomes: [], executedHandlers: [], duration: 0,\n };\n }\n const [signal, autoAbortController, cleanup] = this.createAbortSignal(options);\n const context: PipelineContext<T[K], unknown> = {\n action: String(action),\n payload,\n handlers: [...plan.guards] as HandlerRegistration<T[K], unknown>[],\n executedHandlers: [],\n handlerOutcomes: [],\n claimOnce: registration => this.claimOnceRegistration(action, registration),\n signal: signal ?? this.lifecycleController.signal,\n trackHandlerPromise: promise => this.trackHandlerPromise(promise, dispatchHandlerPromises),\n aborted: false,\n abortReason: undefined,\n currentIndex: 0,\n jumpToPriority: undefined,\n jumpCount: 0,\n maxJumps: this.maxJumps,\n executionMode: 'sequential',\n results: [],\n terminated: false,\n terminationResult: undefined,\n };\n const abortHandler = signal ? () => {\n context.aborted = true;\n context.abortReason = typeof signal.reason === 'string'\n ? signal.reason\n : 'Action dispatch aborted by signal';\n } : undefined;\n signal?.addEventListener('abort', abortHandler!, { once: true });\n let error: Error | undefined;\n try {\n await executeSequential(context, (registration, _index) => {\n const controller = this.createController(\n context,\n autoAbortController,\n options?.autoAbort,\n undefined,\n false,\n );\n return {\n signal: controller.signal,\n getPayload: controller.getPayload,\n modifyPayload: controller.modifyPayload,\n abort: controller.abort,\n } as PipelineController<T[K], unknown>;\n });\n } catch (caught) {\n error = caught instanceof Error ? caught : new Error(String(caught));\n } finally {\n if (signal && abortHandler) signal.removeEventListener('abort', abortHandler);\n this.cleanupSignalsAfterStartedHandlers(() => {\n cleanup();\n (options as AttemptDispatchOptions | undefined)?.[ATTEMPT_SIGNAL_CLEANUP]?.();\n }, dispatchHandlerPromises);\n }\n const errors = [...(context.collectedErrors ?? [])];\n if (error && !errors.some(entry => entry.error === error)) {\n errors.push({\n handlerId: 'guard', error, timestamp: Date.now(), severity: 'blocking',\n });\n }\n return {\n allowed: !context.aborted && error === undefined && errors.length === 0,\n payload: context.payload,\n aborted: context.aborted,\n abortReason: context.abortReason,\n error,\n errors,\n outcomes: (context.handlerOutcomes ?? []).map(snapshotHandlerOutcome),\n executedHandlers: context.executedHandlers ?? [],\n duration: (context.handlerOutcomes ?? []).reduce((total, outcome) => total + (outcome.duration ?? 0), 0),\n };\n }\n\n private createGuardRejectedResult<R>(\n startTime: number,\n validation: ExecutionResult<R>['validation'],\n guard: GuardPhaseResult<unknown>,\n selectedHandlers: readonly HandlerRegistration<any, any>[],\n ): ExecutionResult<R> {\n const endTime = Date.now();\n const outcomeById = new Map(guard.outcomes.map(outcome => [outcome.id, outcome]));\n const handlers = selectedHandlers.map(registration => {\n const outcome = outcomeById.get(registration.id);\n return outcome ? { ...snapshotHandlerOutcome(outcome), result: undefined } : {\n id: registration.id, status: 'skipped' as const, executed: false,\n duration: 0, result: undefined, error: undefined,\n metadata: registration.config.metadata ? { ...registration.config.metadata } : undefined,\n };\n });\n return {\n success: false,\n aborted: guard.aborted,\n abortReason: guard.abortReason ?? guard.error?.message,\n terminated: false,\n outcome: guard.aborted ? 'cancelled' : 'failed',\n validation,\n result: undefined,\n successResults: [],\n results: [],\n failedResults: guard.errors.map(error => ({\n handlerId: error.handlerId, error: error.error, expectedType: 'unknown',\n })),\n execution: {\n duration: endTime - startTime, admissionDuration: 0, queueWaitDuration: 0,\n pipelineDuration: endTime - startTime,\n handlersExecuted: handlers.filter(handler => handler.executed).length,\n handlersSkipped: handlers.filter(handler => !handler.executed).length,\n handlersFailed: handlers.filter(handler => handler.status === 'failed').length,\n startTime, endTime,\n },\n handlers,\n errors: guard.errors,\n };\n }\n\n private createTimingGuardResult<R>(\n reason: string,\n startTime: number,\n handlers: readonly HandlerRegistration<any, any>[],\n validation?: ExecutionResult<R>['validation'],\n ): ExecutionResult<R> {\n const endTime = Date.now();\n return {\n success: false,\n // A timing guard rejects admission; it does not cancel an in-flight\n // dispatch or consume a caller AbortSignal.\n aborted: false,\n abortReason: reason,\n terminated: false,\n outcome: reason === 'Debounced execution' ? 'debounced' : 'throttled',\n validation,\n result: undefined,\n successResults: [],\n results: [],\n failedResults: [],\n execution: {\n duration: endTime - startTime,\n admissionDuration: endTime - startTime,\n queueWaitDuration: 0,\n pipelineDuration: 0,\n handlersExecuted: 0,\n handlersSkipped: handlers.length,\n handlersFailed: 0,\n startTime,\n endTime,\n },\n handlers: handlers.map(handler => ({\n id: handler.id,\n status: 'skipped' as const,\n executed: false,\n duration: 0,\n result: undefined,\n error: undefined,\n metadata: handler.config.metadata ? { ...handler.config.metadata } : undefined,\n })),\n errors: [],\n };\n }\n\n /**\n * Dispatch an action and return detailed execution results\n * \n * @param action - The action type to dispatch\n * @param args - The payload/options tuple for the selected action: payload-bearing actions require a payload, while void actions may omit it; dispatch options, including result collection, are optional.\n * \n * @returns Promise resolving to comprehensive execution results\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n dispatchWithResult<K extends ActionNames<T> & keyof TResultMap>(\n action: K,\n ...args: DispatchArgs<T[K]>\n ): Promise<ExecutionResult<ActionResult<TResultMap, K>>>;\n dispatchWithResult<K extends Exclude<ActionNames<T>, keyof TResultMap>, R = void>(\n action: K,\n ...args: DispatchArgs<T[K]>\n ): Promise<ExecutionResult<R>>;\n dispatchWithResult<K extends ActionNames<T>, R = ActionResult<TResultMap, K>>(\n action: K,\n ...args: DispatchArgs<T[K]>\n ): Promise<ExecutionResult<R>> {\n this.assertStringActionKey(action);\n const [payload, options] = args as [T[K] | undefined, DispatchOptions | undefined];\n if (this.lifecycleState !== 'active') {\n return this.rejectedLifecyclePromise<ExecutionResult<R>>();\n }\n\n const timeoutScope = this.createTimeoutScope(action, options);\n const dispatchStartTime = Date.now();\n const dispatchHandlerPromises: DispatchHandlerPromises = new Set();\n const attemptState = { count: 0 };\n let validation: ExecutionResult<R>['validation'];\n let observerPayload = payload as T[K];\n let admissionEndedAt = dispatchStartTime;\n let pipelineStartedAt: number | undefined;\n const retryTelemetry: RetryTelemetry = {\n pipelineDuration: 0,\n retryDelayDuration: 0,\n attempts: [],\n };\n const plan = this.resolveDispatchPlan(action, options);\n const hasTimingGuard = plan.debounceMs !== undefined || plan.throttleMs !== undefined;\n\n const pipelineOperation = async () => {\n pipelineStartedAt = Date.now();\n const guard = plan.guards.length > 0\n ? await this.executeGuardPhase(\n action, payload as T[K], timeoutScope.options, plan, dispatchHandlerPromises,\n )\n : {\n allowed: true, payload: payload as T[K], aborted: false,\n abortReason: undefined, error: undefined, errors: [], outcomes: [], executedHandlers: [], duration: 0,\n };\n this.cleanupOneTimeHandlers(action, guard.executedHandlers, dispatchHandlerPromises);\n observerPayload = guard.payload;\n if (!guard.allowed) {\n return this.createGuardRejectedResult<R>(\n pipelineStartedAt,\n validation,\n guard,\n [...plan.guards, ...plan.results],\n );\n }\n const rawExecution = await this.executeWithRetry(async attemptSignal => {\n const executedHandlers: HandlerRegistration<any, any>[] = [];\n try {\n return await this._performDispatchWithResult<K, R>(\n action,\n guard.payload,\n this.withAttemptSignal(timeoutScope.options, attemptSignal),\n validation,\n plan,\n executedHandlers,\n dispatchHandlerPromises\n );\n } finally {\n this.cleanupOneTimeHandlers(\n action,\n executedHandlers,\n dispatchHandlerPromises\n );\n }\n }, timeoutScope.options, attemptState, result => (\n result.outcome === 'failed'\n ), () => this.getAttemptHandlers(action, plan).length > 0, retryTelemetry,\n this.shouldDrainBeforeRetry(plan, timeoutScope.options)\n ? () => this.drainAttemptHandlers(dispatchHandlerPromises)\n : undefined);\n\n // A caller/lifecycle cancellation during retry backoff is terminal for\n // the dispatch, while the timeout channel remains a failed dispatch.\n if (timeoutScope.options?.signal?.aborted) {\n if (timeoutScope.options.signal.reason instanceof ActionTimeoutError) {\n throw timeoutScope.options.signal.reason;\n }\n return {\n ...rawExecution,\n success: false,\n aborted: true,\n abortReason: typeof timeoutScope.options.signal.reason === 'string'\n ? timeoutScope.options.signal.reason\n : 'Action dispatch aborted by signal',\n outcome: 'cancelled' as const,\n };\n }\n\n const executionWithGuards: ExecutionResult<R> = {\n ...rawExecution,\n handlers: [\n ...guard.outcomes.map(outcome => ({ ...outcome, result: undefined })),\n ...rawExecution.handlers,\n ] as ExecutionResult<R>['handlers'],\n execution: {\n ...rawExecution.execution,\n handlersExecuted: guard.outcomes.filter(outcome => outcome.executed).length\n + rawExecution.execution.handlersExecuted,\n handlersSkipped: guard.outcomes.filter(outcome => !outcome.executed).length\n + rawExecution.execution.handlersSkipped,\n handlersFailed: guard.outcomes.filter(outcome => outcome.status === 'failed').length\n + rawExecution.execution.handlersFailed,\n },\n };\n const resultProcessingStartedAt = Date.now();\n const result = this.processResults(\n executionWithGuards.results,\n executionWithGuards.terminated,\n executionWithGuards.terminated ? executionWithGuards.result : undefined,\n options?.result,\n );\n const resultProcessingDuration = Date.now() - resultProcessingStartedAt;\n const completed = {\n ...executionWithGuards,\n result,\n execution: {\n ...executionWithGuards.execution,\n pipelineDuration: guard.duration + retryTelemetry.pipelineDuration,\n retryDelayDuration: retryTelemetry.retryDelayDuration,\n resultProcessingDuration,\n attempts: retryTelemetry.attempts,\n },\n };\n return completed;\n };\n\n const operation = async () => {\n if (timeoutScope.options?.signal?.aborted) {\n admissionEndedAt = Date.now();\n return this.createAbortedExecutionResult<R>(\n dispatchStartTime,\n [...plan.guards, ...plan.results],\n );\n }\n\n // Strict validation must complete before timing guards mutate admission state.\n validation = this.validatePayload(action, payload);\n if (timeoutScope.options?.signal?.aborted) {\n admissionEndedAt = Date.now();\n return this.createAbortedExecutionResult<R>(\n dispatchStartTime,\n [...plan.guards, ...plan.results],\n validation,\n );\n }\n\n this.validateResultOptions(options?.result);\n if (hasTimingGuard) {\n const admission = await this.evaluateTimingGuards(\n String(action),\n plan,\n timeoutScope.options?.signal,\n );\n if (admission.aborted || timeoutScope.options?.signal?.aborted) {\n admissionEndedAt = Date.now();\n return this.createAbortedExecutionResult<R>(\n dispatchStartTime,\n [...plan.guards, ...plan.results],\n validation,\n );\n }\n if (admission.reason) {\n admissionEndedAt = Date.now();\n return this.createTimingGuardResult<R>(\n admission.reason,\n dispatchStartTime,\n [...plan.guards, ...plan.results],\n validation,\n );\n }\n }\n\n if (timeoutScope.options?.signal?.aborted) {\n admissionEndedAt = Date.now();\n return this.createAbortedExecutionResult<R>(\n dispatchStartTime,\n [...plan.guards, ...plan.results],\n validation,\n );\n }\n\n admissionEndedAt = Date.now();\n\n if (timeoutScope.options?.immediate || !this.dispatchQueue) {\n return pipelineOperation();\n }\n\n const queued = this.dispatchQueue.enqueueWithHandle(\n pipelineOperation,\n timeoutScope.options?.queuePriority ?? 0\n );\n timeoutScope.onTimeout(error => queued.cancel(error));\n return queued.promise;\n };\n\n const notifiedObservers = new Set<HandlerRegistration<any, any>>();\n const notifiedObserverOutcomes = new Set<ActionObserverEvent<T[K], R>['outcome']>();\n let terminalErrorReported = false;\n const reportTerminalError = (error: unknown) => {\n if (terminalErrorReported) return;\n terminalErrorReported = true;\n this.invokeErrorHandler(error, action, payload, options, attemptState.count);\n };\n const notifyObservers = async (event: ActionObserverEvent<T[K], R>) => {\n if (notifiedObserverOutcomes.has(event.outcome)) return;\n notifiedObserverOutcomes.add(event.outcome);\n await this.executeObservers(action, plan, event, notifiedObservers);\n };\n let dispatchPromise: Promise<ExecutionResult<R>>;\n let observedDispatchPromise: Promise<ExecutionResult<R>>;\n this.dispatchConstructionDepth += 1;\n try {\n dispatchPromise = operation();\n observedDispatchPromise = dispatchPromise.then(async result => {\n const dispatchEndedAt = Date.now();\n const pipelineDuration = pipelineStartedAt === undefined\n ? 0\n : result.execution.pipelineDuration;\n const completedResult: ExecutionResult<R> = {\n ...result,\n execution: {\n ...result.execution,\n duration: dispatchEndedAt - dispatchStartTime,\n admissionDuration: Math.max(0, admissionEndedAt - dispatchStartTime),\n queueWaitDuration: pipelineStartedAt === undefined\n ? 0\n : Math.max(0, pipelineStartedAt - admissionEndedAt),\n pipelineDuration,\n startTime: dispatchStartTime,\n endTime: dispatchEndedAt,\n },\n };\n if (completedResult.outcome === 'failed') {\n const terminalError = completedResult.errors[completedResult.errors.length - 1]?.error\n ?? new Error(`Action \"${String(action)}\" failed`);\n reportTerminalError(terminalError);\n }\n await notifyObservers({\n action: String(action), payload: observerPayload,\n outcome: completedResult.outcome, result: completedResult.result,\n errors: completedResult.errors, signal: timeoutScope.options?.signal,\n });\n return completedResult;\n }, async error => {\n reportTerminalError(error);\n await notifyObservers({\n action: String(action), payload: observerPayload, outcome: 'failed', result: undefined,\n errors: [{\n handlerId: 'dispatch',\n error: error instanceof Error ? error : new Error(String(error)),\n timestamp: Date.now(), severity: 'blocking',\n }],\n signal: timeoutScope.options?.signal,\n });\n throw error;\n });\n this.trackDispatchPromise(observedDispatchPromise);\n } finally {\n this.dispatchConstructionDepth -= 1;\n }\n const exposedPromise = this.raceWithTimeout(\n observedDispatchPromise!,\n timeoutScope,\n dispatchHandlerPromises\n );\n const observedPromise = exposedPromise.catch(async error => {\n // A timeout rejects the exposed promise before the canonical operation\n // settles. Notify once and track that observer work for shutdown.\n reportTerminalError(error);\n const observerNotification = this.trackGlobalHandlerPromise(notifyObservers({\n action: String(action), payload: observerPayload, outcome: 'failed', result: undefined,\n errors: [{\n handlerId: 'dispatch',\n error: error instanceof Error ? error : new Error(String(error)),\n timestamp: Date.now(), severity: 'blocking',\n }],\n signal: timeoutScope.options?.signal,\n }));\n void observerNotification.catch(observerError => {\n this.log(`Failure observer delivery failed for ${String(action)}`, observerError, 'warn');\n });\n throw error;\n });\n\n void observedPromise.catch(() => {});\n return observedPromise;\n }\n\n private async _performDispatchWithResult<K extends keyof T, R = void>(\n action: K,\n payload: T[K] | undefined,\n options: DispatchOptions | undefined,\n validation: ExecutionResult<R>['validation'],\n plan: DispatchPlan,\n executedHandlers: HandlerRegistration<any, any>[],\n dispatchHandlerPromises: DispatchHandlerPromises\n ): Promise<ExecutionResult<R>> {\n const _startTime = Date.now();\n \n // ๐ง Improved AbortSignal handling with cleaner merge logic (same as dispatch)\n const [effectiveSignal, autoAbortController, cleanup] = this.createAbortSignal(options);\n \n if (options?.autoAbort?.onControllerCreated && autoAbortController) {\n options.autoAbort.onControllerCreated(autoAbortController);\n }\n \n // Check if dispatch is aborted before starting\n if (effectiveSignal?.aborted) {\n cleanup();\n return this.createAbortedExecutionResult<R>(_startTime, plan.results, validation);\n }\n \n const pipeline = plan.pipelineSnapshot;\n \n if (!pipeline || pipeline.length === 0) {\n this.log(`Pipeline lookup for '${String(action)}'`, {\n pipelineExists: false,\n handlersCount: 0,\n allRegisteredActions: Array.from(this.pipelines.keys()),\n });\n // ๐จ ๊ฒฝ๊ณ : ํธ๋ค๋ฌ๊ฐ ๋ฑ๋ก๋์ง ์์ ์ก์
์คํ\n const warningMessage = `โ ๏ธ Action '${String(action)}' has no registered handlers. This action will be ignored.`;\n \n if (this.isDebugMode) {\n console.warn(warningMessage);\n console.warn('๐ก Tip: Register a handler using registry.register() before dispatching this action.');\n console.warn('๐ Available actions:', Array.from(this.pipelines.keys()));\n }\n this.log(`No handlers found for action '${String(action)}', dispatch cancelled`, {}, 'warn');\n \n cleanup();\n return {\n success: true,\n aborted: false,\n abortReason: undefined as string | undefined,\n terminated: false,\n outcome: 'completed',\n validation,\n result: undefined as any,\n successResults: [] as any,\n results: [],\n failedResults: [],\n execution: {\n duration: 0,\n admissionDuration: 0,\n queueWaitDuration: 0,\n pipelineDuration: 0,\n handlersExecuted: 0,\n handlersSkipped: 0,\n handlersFailed: 0,\n startTime: _startTime,\n endTime: _startTime,\n },\n handlers: [],\n errors: [],\n };\n }\n\n const filteredHandlers = this.getAttemptHandlers(action, plan);\n\n // Create pipeline execution context\n const context: PipelineContext<T[K], R> = {\n action: String(action),\n payload: payload as T[K],\n handlers: [...filteredHandlers],\n executedHandlers: [],\n handlerOutcomes: [],\n deferOnceCleanup: true,\n claimOnce: registration => this.claimOnceRegistration(action, registration),\n signal: effectiveSignal ?? this.lifecycleController.signal,\n trackHandlerPromise: promise => this.trackHandlerPromise(\n promise,\n dispatchHandlerPromises\n ),\n aborted: false,\n abortReason: undefined as string | undefined,\n currentIndex: 0,\n jumpToPriority: undefined as number | undefined,\n jumpCount: 0,\n maxJumps: this.maxJumps,\n executionMode: plan.executionMode,\n \n // Result collection fields\n results: [],\n terminated: false,\n terminationResult: undefined as R | undefined,\n };\n\n let executionError: Error | undefined;\n // Add abort listener if signal provided (use effectiveSignal for auto-abort)\n const abortHandler = effectiveSignal ? () => {\n context.aborted = true;\n context.abortReason = typeof effectiveSignal.reason === 'string'\n ? effectiveSignal.reason\n : 'Action dispatch aborted by signal';\n } : undefined;\n \n if (effectiveSignal && abortHandler) {\n effectiveSignal.addEventListener('abort', abortHandler, { once: true });\n }\n \n // ๐ง Initialize errors array (will be updated after pipeline execution)\n let errors: HandlerError[] = [];\n \n try {\n await this.executePipeline(\n context,\n dispatchHandlerPromises,\n autoAbortController,\n options?.autoAbort\n );\n \n // ๐ง Collect errors from execution context after pipeline execution\n const contextWithErrors = context as PipelineContext<any, any> & { collectedErrors?: HandlerError[] };\n errors = contextWithErrors.collectedErrors || [];\n \n } catch (error) {\n // ๐ง Collect errors from execution context before adding pipeline error\n const contextWithErrors = context as PipelineContext<any, any> & { collectedErrors?: HandlerError[] };\n errors = contextWithErrors.collectedErrors || [];\n \n executionError = error instanceof Error ? error : new Error(String(error));\n errors.push({\n handlerId: 'pipeline',\n error: executionError,\n timestamp: Date.now(),\n severity: 'blocking'\n });\n \n } finally {\n executedHandlers.push(...(context.executedHandlers ?? []));\n if (effectiveSignal && abortHandler) {\n effectiveSignal.removeEventListener('abort', abortHandler);\n }\n this.cleanupSignalsAfterStartedHandlers(() => {\n cleanup();\n (options as AttemptDispatchOptions | undefined)?.[ATTEMPT_SIGNAL_CLEANUP]?.();\n }, dispatchHandlerPromises);\n }\n\n const endTime = Date.now();\n \n const recordedOutcomes = context.handlerOutcomes ?? [];\n const outcomesById = new Map(recordedOutcomes.map(outcome => [outcome.id, outcome]));\n const handlerResults: HandlerExecutionOutcome<R>[] = filteredHandlers.map(handler => {\n const outcome = outcomesById.get(handler.id);\n return outcome\n ? snapshotHandlerOutcome(outcome)\n : {\n id: handler.id,\n status: 'skipped' as const,\n executed: false,\n duration: 0,\n result: undefined,\n error: undefined,\n metadata: handler.config.metadata ? { ...handler.config.metadata } : undefined,\n };\n });\n const handlerErrors = errors.filter(error => error.handlerId !== 'pipeline');\n // Keep the public terminal-error view backward compatible: fatal pipeline\n // failures are represented by the pipeline error, while per-handler\n // diagnostics remain available through `handlers` and `failedResults`.\n const reportedErrors = executionError\n ? errors.filter(error => error.handlerId === 'pipeline')\n : errors;\n const executionHandlersCount = handlerResults.filter(handler => handler.executed).length;\n\n // ๐ง Type safety: Separate successful results from failed ones\n const successResults = context.results.filter((result): result is R => result !== undefined);\n const failedResults = handlerErrors.map(err => ({\n handlerId: err.handlerId,\n error: err.error,\n expectedType: 'unknown'\n }));\n\n // Build execution result with improved type safety\n const executionResult: ExecutionResult<R> = {\n success: !executionError && !context.aborted,\n aborted: context.aborted,\n abortReason: context.abortReason,\n terminated: context.terminated,\n outcome: context.aborted\n ? 'cancelled'\n : executionError\n ? 'failed'\n : handlerErrors.length > 0\n ? 'completed_with_errors'\n : 'completed',\n validation,\n // Result aggregation happens after the retry boundary in dispatchWithResult.\n // Preserve controller.return() here so the post-processing step can retain it.\n result: context.terminated ? context.terminationResult : undefined,\n successResults: successResults,\n results: context.results,\n failedResults,\n execution: {\n duration: endTime - _startTime,\n admissionDuration: 0,\n queueWaitDuration: 0,\n pipelineDuration: endTime - _startTime,\n handlersExecuted: executionHandlersCount,\n handlersSkipped: Math.max(0, filteredHandlers.length - executionHandlersCount),\n handlersFailed: context.executionMode === 'race'\n ? (context.raceWinnerId && outcomesById.get(context.raceWinnerId)?.status === 'failed' ? 1 : 0)\n : handlerResults.filter(handler => handler.status === 'failed').length,\n startTime: _startTime,\n endTime,\n },\n handlers: handlerResults,\n ...(context.executionMode !== 'race' ? {} : {\n raceDiagnostics: {\n ...(context.raceWinnerId === undefined ? {} : { winnerId: context.raceWinnerId }),\n ...(context.raceWinnerId === undefined\n ? {}\n : { winner: snapshotHandlerOutcome(outcomesById.get(context.raceWinnerId)!) }),\n loserSnapshots: (context.raceLoserOutcomes ?? []).map(snapshotHandlerOutcome),\n pendingLosersAtReturn: (context.raceLoserOutcomes ?? [])\n .filter(outcome => outcome.status === 'running').length,\n observedLoserFailures: (context.raceLoserOutcomes ?? [])\n .filter(outcome => outcome.status === 'failed').length,\n },\n }),\n errors: reportedErrors.map(err => ({\n handlerId: err.handlerId,\n error: err.error,\n timestamp: err.timestamp,\n severity: err.severity\n })),\n };\n\n return executionResult;\n }\n\n /** Create a pipeline controller for one handler execution. */\n private createController<K extends keyof T>(\n context: PipelineContext<T[K], any>, \n autoAbortController?: AbortController,\n autoAbortOptions?: { allowHandlerAbort?: boolean },\n isolatedState?: PipelineControllerState<T[K], any>,\n collectResults = true,\n ): PipelineController<T[K], any> {\n const controller = {} as PipelineController<T[K], any>;\n\n // Configure/reset the controller for current context\n (controller as { signal: AbortSignal }).signal =\n context.signal ?? this.lifecycleController.signal;\n\n const state = isolatedState ?? context;\n\n controller.abort = (reason?: string) => {\n state.aborted = true;\n state.abortReason = reason;\n const propagateAbort = !isolatedState || context.executionMode !== 'race';\n if (propagateAbort) {\n context.aborted = true;\n context.abortReason = reason;\n }\n \n // Auto-abort: Handler can trigger pipeline abort if enabled\n if (propagateAbort && autoAbortController && autoAbortOptions?.allowHandlerAbort) {\n autoAbortController.abort(reason);\n }\n };\n\n controller.modifyPayload = (modifier: (payload: T[K]) => T[K]) => {\n state.payload = modifier(state.payload);\n };\n\n controller.getPayload = () => state.payload;\n\n controller.jumpToPriority = (priority: number) => {\n state.jumpToPriority = priority;\n };\n\n controller.return = (result: any) => {\n state.terminated = true;\n state.terminationResult = collectResults ? result : undefined;\n if (!isolatedState) {\n context.terminated = true;\n context.terminationResult = collectResults ? result : undefined;\n }\n return result;\n };\n\n controller.setResult = (result: any) => {\n if (collectResults) state.results.push(result);\n };\n\n controller.getResults = () => {\n return [...state.results];\n };\n\n controller.mergeResult = (merger: (previousResults: any[], currentResult: any) => any) => {\n if (!collectResults) return;\n const currentResult = state.results[state.results.length - 1];\n const previousResults = state.results.slice(0, -1);\n const mergedResult = merger(previousResults, currentResult);\n state.results[state.results.length - 1] = mergedResult;\n };\n\n return controller;\n }\n\n private filterHandlers(\n handlers: HandlerRegistration<any, any>[],\n filterOptions?: DispatchOptions['filter']\n ): HandlerRegistration<any, any>[] {\n if (!filterOptions) {\n return handlers;\n }\n\n // Cache disabled for memory stability\n\n // Cache disabled - using direct filtering for memory stability\n\n // Create Sets for fast lookup if arrays are provided\n const handlerIdSet = filterOptions.handlerIds ? new Set(filterOptions.handlerIds) : null;\n const excludeIdSet = filterOptions.excludeHandlerIds ? new Set(filterOptions.excludeHandlerIds) : null;\n\n // Filter handlers with optimized checks\n const filtered = handlers.filter(registration => {\n const config = registration.config;\n\n // Fast Set-based inclusion check\n if (handlerIdSet && !handlerIdSet.has(config.id)) {\n return false;\n }\n\n // Fast Set-based exclusion check\n if (excludeIdSet?.has(config.id)) {\n return false;\n }\n\n // Priority range check\n if (filterOptions.priority) {\n const priority = config.priority;\n if (filterOptions.priority.min !== undefined && priority < filterOptions.priority.min) {\n return false;\n }\n if (filterOptions.priority.max !== undefined && priority > filterOptions.priority.max) {\n return false;\n }\n }\n\n // Evaluate user code against a frozen snapshot. This prevents a custom\n // filter from changing the registration that the current plan executes.\n if (filterOptions.custom) {\n const configSnapshot = Object.freeze({\n ...config,\n metadata: config.metadata\n ? Object.freeze({ ...config.metadata })\n : undefined,\n });\n if (!filterOptions.custom(configSnapshot)) {\n return false;\n }\n }\n\n return true;\n });\n\n // Cache disabled for memory stability\n\n return filtered;\n }\n\n private validateResultOptions(resultOptions?: DispatchOptions['result']): void {\n if (!resultOptions) return;\n\n if (resultOptions.strategy === 'custom' && typeof resultOptions.merger !== 'function') {\n throw new ActionResultProcessingError(\n 'Custom result strategy requires a merger function',\n );\n }\n\n if (\n resultOptions.maxResults !== undefined &&\n (!Number.isSafeInteger(resultOptions.maxResults) || resultOptions.maxResults < 0)\n ) {\n throw new RangeError('maxResults must be a non-negative safe integer.');\n }\n }\n\n private processResults<R>(\n results: Array<R | undefined>,\n terminated: boolean,\n terminationResult: R | R[] | undefined,\n resultOptions?: DispatchOptions['result']\n ): R | R[] | undefined {\n // controller.return() is authoritative even when its explicit value is undefined.\n if (terminated) {\n return terminationResult;\n }\n\n // ๐ง Fix: Return undefined only if no results options specified AND no results available\n if (!resultOptions) {\n // If no result options specified but we have results, return the last one\n return results.length > 0 ? results[results.length - 1] : undefined;\n }\n\n // ๐ง Fix: Process results even when collect is false if we have a strategy specified\n if (!resultOptions.collect && !resultOptions.strategy) {\n return undefined;\n }\n\n // Apply maxResults limit\n const collectedResults = results.filter((result): result is R => result !== undefined);\n const limitedResults = resultOptions.maxResults !== undefined\n ? collectedResults.slice(0, resultOptions.maxResults)\n : collectedResults;\n\n if (limitedResults.length === 0) {\n if (resultOptions.strategy === 'all' || (resultOptions.collect && !resultOptions.strategy)) {\n return [];\n }\n if (resultOptions.strategy === 'custom' || (resultOptions.strategy === 'merge' && resultOptions.merger)) {\n return resultOptions.merger!(limitedResults);\n }\n return undefined;\n }\n\n // Process results based on strategy with improved type handling\n switch (resultOptions.strategy) {\n case 'first':\n return limitedResults[0];\n case 'last':\n return limitedResults[limitedResults.length - 1];\n case 'all':\n return limitedResults;\n case 'merge':\n if (resultOptions.merger) {\n return resultOptions.merger(limitedResults);\n }\n // Default merge: return last result\n return limitedResults[limitedResults.length - 1];\n case 'custom':\n if (resultOptions.merger) {\n return resultOptions.merger(limitedResults);\n }\n throw new Error('Custom result strategy requires a merger function');\n default:\n // ๐ง Fix: If collect is true but no strategy specified, return all results\n if (resultOptions.collect) {\n return limitedResults;\n }\n // Default: return last result if no strategy specified\n return limitedResults[limitedResults.length - 1];\n }\n }\n\n private async executePipeline<K extends keyof T>(\n context: PipelineContext<T[K], any>,\n dispatchHandlerPromises: DispatchHandlerPromises,\n autoAbortController?: AbortController,\n autoAbortOptions?: { allowHandlerAbort?: boolean }\n ): Promise<void> {\n const createController = (\n registration: HandlerRegistration<T[K], any>,\n _index: number,\n state?: PipelineControllerState<T[K], any>,\n ): PipelineController<T[K], any> => {\n const controller = this.createController(\n context,\n autoAbortController,\n autoAbortOptions,\n state,\n registration.role !== 'guard',\n );\n // Runtime mirrors the narrow public controller contracts. This also\n // prevents JavaScript consumers from accidentally publishing guard\n // results through an API that would be ignored.\n if (registration.role === 'guard') {\n return {\n signal: controller.signal,\n getPayload: controller.getPayload,\n modifyPayload: controller.modifyPayload,\n abort: controller.abort,\n } as PipelineController<T[K], any>;\n }\n if (registration.role === 'result') {\n return {\n signal: controller.signal,\n getPayload: controller.getPayload,\n abort: controller.abort,\n return: controller.return,\n setResult: controller.setResult,\n getResults: controller.getResults,\n mergeResult: controller.mergeResult,\n } as PipelineController<T[K], any>;\n }\n return controller;\n };\n\n // Guards are a preflight phase in every mode, before result arbitration.\n const originalHandlers = context.handlers;\n const preflightHandlers = originalHandlers.filter(handler => handler.role === 'guard');\n if (preflightHandlers.length > 0) {\n context.handlers = preflightHandlers;\n await executeSequential<T[K], any>(context, createController);\n if (context.aborted || context.terminated) {\n context.handlers = originalHandlers;\n return;\n }\n }\n context.handlers = originalHandlers.filter(handler => (\n !preflightHandlers.includes(handler) && handler.role !== 'observer'\n ));\n\n switch (context.executionMode) {\n case 'sequential':\n await executeSequential<T[K], any>(context, createController);\n break;\n case 'parallel':\n await executeParallel<T[K], any>(context, createController);\n break;\n case 'race':\n await executeRace<T[K], any>(context, createController);\n break;\n default:\n throw new Error(`Unknown execution mode: ${context.executionMode}`);\n }\n context.handlers = originalHandlers;\n\n if (!context.deferOnceCleanup) {\n this.cleanupOneTimeHandlers(\n context.action as K,\n context.executedHandlers ?? [],\n dispatchHandlerPromises\n );\n }\n }\n\n private cleanupOneTimeHandlers<K extends keyof T>(\n action: K,\n executedHandlers: HandlerRegistration<any, any>[],\n dispatchHandlerPromises: DispatchHandlerPromises\n ): void {\n const oneTimeHandlers = executedHandlers.filter(reg => reg.config.once);\n if (oneTimeHandlers.length === 0) return;\n\n // Race mode returns its winner while loser handlers can still be active.\n // Detach every invoked once-handler immediately so retries cannot invoke it\n // again, but defer resource cleanup until this dispatch's started handler\n // work drains. Unrelated dispatches must not delay cleanup.\n const handlersStillRunning = [...dispatchHandlerPromises];\n const shouldDeferCleanup = handlersStillRunning.length > 0;\n\n oneTimeHandlers.forEach(registration => {\n const claimed = this.claimedOnceHandlers.delete(registration);\n const removed = claimed || this.removeRegistration(action, registration, !shouldDeferCleanup);\n if (removed) {\n if (claimed && !shouldDeferCleanup) {\n this.runRegistrationCleanup(action, registration);\n }\n if (\n shouldDeferCleanup &&\n typeof registration.config.cleanup === 'function'\n ) {\n const cleanupPromise = Promise.allSettled(handlersStillRunning).then(() => {\n this.runRegistrationCleanup(action, registration);\n });\n void this.trackGlobalHandlerPromise(cleanupPromise).catch(() => {});\n }\n\n this.log(`One-time handler removed: ${String(action)}`, {\n handlerId: registration.id,\n remainingHandlers: this.pipelines.get(action)?.length ?? 0\n });\n }\n });\n }\n\n /** Reserve a once registration before user code starts. This is synchronous,\n * so independent dispatches cannot both invoke the same registration. */\n private claimOnceRegistration<K extends keyof T>(\n action: K,\n registration: HandlerRegistration<any, any>,\n ): boolean {\n if (!registration.config.once) return true;\n if (this.claimedOnceHandlers.has(registration)) return false;\n if (!this.removeRegistration(action, registration, false)) return false;\n this.claimedOnceHandlers.add(registration);\n return true;\n }\n\n\n /**\n * Get the number of registered handlers for an action\n * \n * @param action - The action type to count handlers for\n * \n * @returns Number of registered handlers\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getHandlerCount<K extends ActionNames<T>>(action: K): number {\n const pipeline = this.pipelines.get(action);\n return pipeline ? pipeline.length : 0;\n }\n\n /**\n * Check if an action has any registered handlers\n * \n * @param action - The action type to check\n * \n * @returns True if action has handlers, false otherwise\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n hasHandlers<K extends ActionNames<T>>(action: K): boolean {\n return this.getHandlerCount(action) > 0;\n }\n\n /**\n * Get all registered action types\n * \n * @returns Array of all registered action types\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getRegisteredActions(): (keyof T)[] {\n return Array.from(this.pipelines.keys());\n }\n\n /**\n * Remove all handlers for a specific action\n * \n * @param action - The action type to clear handlers for\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n clearAction<K extends ActionNames<T>>(action: K): void {\n const pipeline = this.pipelines.get(action);\n if (pipeline) {\n [...pipeline].forEach(registration => {\n this.removeRegistration(action, registration);\n });\n }\n\n this.pipelines.delete(action);\n this.lastRegisteredTimestamps.delete(action);\n this.actionGuard.clearGuards(String(action));\n }\n\n /**\n * Remove all handlers for all actions\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n clearAll(): void {\n [...this.pipelines.keys()].forEach(action => {\n this.clearAction(action as ActionNames<T>);\n });\n\n this.pipelines.clear();\n this.lastRegisteredTimestamps.clear();\n this.unregisterFunctions.forEach(unregisters => unregisters.clear());\n this.unregisterFunctions.clear();\n this.actionGuard.clearAll();\n this.observerHandlers.clear();\n }\n\n /**\n * Get the name of this action register\n * \n * @returns The register name\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getName(): string {\n return this.name;\n }\n\n /**\n * Get comprehensive registry information (similar to DeclarativeStoreRegistry pattern)\n * \n * @returns Registry information including actions, handlers, and execution modes\n */\n getRegistryInfo(): ActionRegistryInfo<T> {\n const totalHandlers = Array.from(this.pipelines.values()).reduce(\n (total, pipeline) => total + pipeline.length, \n 0\n );\n \n return {\n name: this.name,\n totalActions: this.pipelines.size,\n totalHandlers,\n registeredActions: Array.from(this.pipelines.keys()),\n actionExecutionModes: new Map(this.actionExecutionModes),\n defaultExecutionMode: this.executionMode,\n };\n }\n\n /**\n * Get detailed statistics for a specific action\n * \n * @param action Action name to get statistics for\n * @returns Detailed handler statistics\n */\n getActionStats<K extends ActionNames<T>>(action: K): ActionHandlerStats<T> | null {\n const pipeline = this.pipelines.get(action);\n if (!pipeline) {\n return null;\n }\n\n // Group handlers by priority\n const priorityMap = new Map<number, typeof pipeline>();\n pipeline.forEach(handler => {\n if (!priorityMap.has(handler.config.priority)) {\n priorityMap.set(handler.config.priority, []);\n }\n priorityMap.get(handler.config.priority)!.push(handler);\n });\n\n const handlersByPriority = Array.from(priorityMap.entries())\n .sort(([a], [b]) => b - a) // Sort by priority (highest first)\n .map(([priority, handlers]) => ({\n priority,\n handlers: handlers.map(h => ({\n id: h.config.id,\n }))\n }));\n\n // Execution statistics are no longer tracked\n const executionStats = undefined;\n\n return {\n action,\n handlerCount: pipeline.length,\n totalHandlers: pipeline.length,\n handlersByPriority,\n executionStats,\n lastRegistered: this.lastRegisteredTimestamps.get(action),\n };\n }\n\n /**\n * Get statistics for all registered actions\n * \n * @returns Array of statistics for all actions\n */\n getAllActionStats(): Array<ActionHandlerStats<T>> {\n return Array.from(this.pipelines.keys())\n .map(action => this.getActionStats(action as ActionNames<T>))\n .filter((stats): stats is ActionHandlerStats<T> => stats !== null);\n }\n\n\n /**\n * Set global execution mode for all actions\n * \n * @param mode Execution mode to set\n */\n setExecutionMode(mode: ExecutionMode): void {\n this.executionMode = mode;\n \n if (this.isDebugMode) {\n console.log(`๐ฏ Global execution mode set to: ${mode}`);\n }\n }\n\n /**\n * Set execution mode for a specific action\n * \n * @param action Action name\n * @param mode Execution mode to set\n */\n setActionExecutionMode<K extends ActionNames<T>>(action: K, mode: ExecutionMode): void {\n this.actionExecutionModes.set(action, mode);\n \n if (this.isDebugMode) {\n console.log(`๐ฏ Execution mode set for action '${String(action)}': ${mode}`);\n }\n }\n\n /**\n * Get execution mode for a specific action\n * \n * @param action Action name\n * @returns Execution mode for the action, or default if not set\n */\n getActionExecutionMode<K extends ActionNames<T>>(action: K): ExecutionMode {\n return this.actionExecutionModes.get(action) || this.executionMode;\n }\n\n /**\n * Remove execution mode override for a specific action\n * \n * @param action Action name\n */\n removeActionExecutionMode<K extends ActionNames<T>>(action: K): void {\n this.actionExecutionModes.delete(action);\n \n if (this.isDebugMode) {\n console.log(`๐ฏ Execution mode reset for action '${String(action)}' to default: ${this.executionMode}`);\n }\n }\n\n\n /**\n * Get registry configuration (for debugging and inspection)\n * \n * @returns Current registry configuration\n */\n getRegistryConfig(): ActionRegisterConfig['registry'] {\n return this.registryConfig;\n }\n\n /**\n * Check if registry has debug mode enabled\n * \n * @returns Whether debug mode is enabled\n */\n isDebugEnabled(): boolean {\n return this.isDebugMode;\n }\n\n /**\n * Creates a consistent unregister function for a handler\n * \n * @param action - Action key\n * @param handlerId - Handler identifier\n * @param registration - Handler registration object\n * @returns Unregister function\n * @private\n */\n private createUnregisterFunction<K extends keyof T>(\n action: K,\n handlerId: string,\n registration: HandlerRegistration<any, any>\n ): UnregisterFunction {\n return () => {\n if (this.removeRegistration(action, registration)) {\n this.log(`Handler unregistered: ${String(action)}`, {\n handlerId,\n remainingHandlers: this.pipelines.get(action)?.length ?? 0,\n actionRemoved: !this.pipelines.has(action)\n });\n }\n };\n }\n\n private getUnregisterFunctions<K extends keyof T>(action: K): Map<string, UnregisterFunction> {\n let unregisters = this.unregisterFunctions.get(action);\n if (!unregisters) {\n unregisters = new Map();\n this.unregisterFunctions.set(action, unregisters);\n }\n return unregisters;\n }\n\n /** Remove a registration and release every resource owned by it exactly once. */\n private removeRegistration<K extends keyof T>(\n action: K,\n registration: HandlerRegistration<any, any>,\n runCleanup = true\n ): boolean {\n const pipeline = this.pipelines.get(action);\n if (!pipeline) return false;\n\n const index = pipeline.indexOf(registration);\n if (index === -1) return false;\n\n pipeline.splice(index, 1);\n this.observerHandlers.delete(registration);\n const actionUnregisterFunctions = this.unregisterFunctions.get(action);\n actionUnregisterFunctions?.delete(registration.id);\n\n if (runCleanup) {\n this.runRegistrationCleanup(action, registration);\n }\n\n if (pipeline.length === 0) {\n this.pipelines.delete(action);\n this.lastRegisteredTimestamps.delete(action);\n this.unregisterFunctions.delete(action);\n }\n\n return true;\n }\n\n private runRegistrationCleanup<K extends keyof T>(\n action: K,\n registration: HandlerRegistration<any, any>\n ): void {\n if (!registration.config.cleanup) return;\n\n try {\n registration.config.cleanup();\n } catch (cleanupError) {\n this.log(`Cleanup error while removing handler: ${String(action)}`, cleanupError, 'warn');\n }\n }\n\n /**\n * Gets the total count of registered unregister functions\n * \n * @returns Number of unregister functions\n * @public\n */\n getUnregisterFunctionCount(): number {\n let count = 0;\n this.unregisterFunctions.forEach(unregisters => {\n count += unregisters.size;\n });\n return count;\n }\n \n /**\n * Checks if an unregister function exists for the given handler ID\n * \n * @param handlerId - Handler identifier to check\n * @returns True if unregister function exists\n * @public\n */\n hasUnregisterFunction(handlerId: string): boolean {\n for (const unregisters of this.unregisterFunctions.values()) {\n if (unregisters.has(handlerId)) return true;\n }\n return false;\n }\n\n /** Reject queued dispatches without releasing registered handlers. */\n cancelPendingDispatches(): void {\n this.dispatchQueue?.clear({ rejectPending: true });\n }\n\n private beginShutdown(deferCleanup = false): Promise<void> {\n if (this.destroyAsyncPromise) return this.destroyAsyncPromise;\n\n if (this.lifecycleState === 'destroyed') {\n this.destroyAsyncPromise = Promise.resolve();\n return this.destroyAsyncPromise;\n }\n\n this.lifecycleState = 'closing';\n const shutdownError = new ActionRegisterDestroyedError(this.name, 'closing');\n\n // Store the stable shutdown promise before aborting signals: abort listeners\n // run synchronously and may re-enter destroyAsync().\n let resolveShutdown!: () => void;\n let rejectShutdown!: (error: unknown) => void;\n this.destroyAsyncPromise = new Promise<void>((resolve, reject) => {\n resolveShutdown = resolve;\n rejectShutdown = reject;\n });\n\n if (!this.lifecycleController.signal.aborted) {\n this.lifecycleController.abort(shutdownError);\n }\n\n // Stop guard timers immediately and reject operations that have not begun.\n // Registered handler cleanup is deferred until every started handler settles.\n this.actionGuard.destroy();\n this.dispatchQueue?.clear({ rejectPending: true, reason: shutdownError });\n\n const canFinalizeSynchronously = (\n !deferCleanup &&\n this.dispatchConstructionDepth === 0 &&\n this.activeDispatches.size === 0 &&\n this.activeHandlerPromises.size === 0\n );\n\n if (canFinalizeSynchronously) {\n this.finalizeDestroy();\n resolveShutdown();\n return this.destroyAsyncPromise;\n }\n\n const drainAndFinalize = async () => {\n // Handler promises can be created by a dispatch that was already starting\n // when shutdown began, so drain until both dynamic sets stay empty.\n while (this.activeDispatches.size > 0 || this.activeHandlerPromises.size > 0) {\n await Promise.allSettled([\n ...this.activeDispatches,\n ...this.activeHandlerPromises,\n ]);\n }\n\n this.finalizeDestroy();\n };\n // Dispatch and queue construction call handlers synchronously before their\n // promises can be inserted into the active sets. Start draining on the next\n // microtask so handler-initiated shutdown cannot finalize through that gap.\n void Promise.resolve()\n .then(drainAndFinalize)\n .then(resolveShutdown, rejectShutdown);\n\n // destroy() is intentionally fire-and-forget; keep its internal promise\n // observed while destroyAsync() remains available to callers that need proof.\n void this.destroyAsyncPromise.catch(error => {\n this.log('ActionRegister async destroy failed', error, 'warn');\n });\n return this.destroyAsyncPromise;\n }\n\n private finalizeDestroy(): void {\n if (this.lifecycleState === 'destroyed') return;\n\n this.clearAll();\n this.actionExecutionModes.clear();\n this.lifecycleState = 'destroyed';\n this.log('ActionRegister destroyed');\n }\n\n /**\n * ๐ Destroy method for comprehensive cleanup\n *\n * Begins terminal cleanup of pipelines, guards, queues, and statistics. Cleanup\n * remains synchronous when no work has started; otherwise active handlers drain\n * in the background. Use destroyAsync() when completion must be observed.\n *\n * @public\n */\n destroy(): void {\n void this.beginShutdown();\n }\n\n /**\n * Begin terminal shutdown and resolve after all started handlers have settled\n * and their registered cleanup functions have run.\n *\n * `deferCleanup` closes the register synchronously while deferring final\n * registered cleanup until the next microtask. This is useful for React\n * commit phases that must invalidate stale dispatchers immediately without\n * invoking user cleanup code inside the commit hook itself.\n *\n * Repeated calls return the same promise. New registrations and dispatches are\n * rejected as soon as shutdown begins.\n *\n * @public\n */\n destroyAsync(options: { deferCleanup?: boolean } = {}): Promise<void> {\n return this.beginShutdown(options.deferCleanup ?? false);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,IAAa,cAAb,MAAyB;CAOvB,YAAY,cAAuB,MAAM;EANzC,KAAQ,yBAAS,IAAI,IAAwB;EAG7C,KAAiB,cAAsB;EACvC,KAAiB,oBAA4B;EAG3C,KAAK,qBAAqB;CAC5B;;CAGA,AAAQ,oBAA0B;EAChC,IAAI,KAAK,sBAAsB,CAAC,KAAK,iBACnC,KAAK,iBAAiB;CAE1B;;;;;;CAOA,AAAQ,mBAAyB;EAC/B,IAAI,KAAK,iBAAiB;EAE1B,KAAK,kBAAkB,kBAAkB;GACvC,KAAK,eAAe;EAC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