@but212/atom-effect 0.1.0 → 0.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/constants.ts","../src/errors/errors.ts","../src/errors/messages.ts","../src/scheduler/scheduler.ts","../src/scheduler/batch.ts","../src/tracking/context.ts","../src/tracking/dependency-manager.ts","../src/tracking/untracked.ts","../src/utils/debug.ts","../src/core/atom/atom.ts","../src/utils/subscriber-manager.ts","../src/core/computed/index.ts","../src/utils/type-guards.ts","../src/core/effect/effect.ts"],"sourcesContent":["/**\n * @fileoverview Constants and configuration for atom-effect library\n * @description Centralized constants for async states, bit flags, and performance tuning\n */\n\n/**\n * Async computation states for computed atoms\n */\nexport const AsyncState = {\n IDLE: 'idle' as const,\n PENDING: 'pending' as const,\n RESOLVED: 'resolved' as const,\n REJECTED: 'rejected' as const,\n};\n\n/**\n * Bit flags for effect state management\n * Using bit flags for efficient state checks (O(1) operations)\n */\nexport const EFFECT_STATE_FLAGS = {\n DISPOSED: 1 << 0, // 0001 - Effect has been disposed\n EXECUTING: 1 << 1, // 0010 - Effect is currently executing\n} as const;\n\n/**\n * Bit flags for computed atom state management\n * Enables fast state transitions and checks without multiple boolean fields\n */\nexport const COMPUTED_STATE_FLAGS = {\n DIRTY: 1 << 0, // 0001 - Needs recomputation\n IDLE: 1 << 1, // 0010 - Initial state, not computed yet\n PENDING: 1 << 2, // 0100 - Async computation in progress\n RESOLVED: 1 << 3, // 1000 - Successfully computed\n REJECTED: 1 << 4, // 10000 - Computation failed\n RECOMPUTING: 1 << 5, // 100000 - Currently recomputing\n HAS_ERROR: 1 << 6, // 1000000 - Has error state\n} as const;\n\n/**\n * Object pool configuration\n * Controls memory management and GC pressure reduction\n */\nexport const POOL_CONFIG = {\n /** Maximum number of pooled objects to prevent memory bloat */\n MAX_SIZE: 1000,\n /** Number of objects to pre-allocate for performance-critical paths */\n WARMUP_SIZE: 100,\n} as const;\n\n/**\n * Scheduler configuration\n * Controls batching behavior and performance limits\n */\nexport const SCHEDULER_CONFIG = {\n /** Maximum effect executions per second to detect infinite loops */\n MAX_EXECUTIONS_PER_SECOND: 100,\n /** Threshold for cleaning up old execution timestamps */\n CLEANUP_THRESHOLD: 100,\n} as const;\n\n/**\n * Debug configuration defaults\n */\nexport const DEBUG_CONFIG = {\n /** Maximum dependencies before warning about large dependency graphs */\n MAX_DEPENDENCIES: 1000,\n /** Enable infinite loop detection warnings */\n WARN_INFINITE_LOOP: true,\n} as const;\n","/**\n * @fileoverview Error class hierarchy for atom-effect library\n * @description Structured error classes with cause tracking and recoverability flags\n */\n\n/**\n * Base error class for all atom-effect errors\n *\n * Provides enhanced error information including:\n * - Original cause tracking for error chains\n * - Recoverability flag for error handling strategies\n * - Timestamp for debugging and logging\n *\n * @example\n * ```ts\n * throw new AtomError('Invalid state', originalError, false);\n * ```\n */\nexport class AtomError extends Error {\n /** Original error that caused this error, if any */\n cause: Error | null;\n /** Whether this error can be recovered from */\n recoverable: boolean;\n /** When this error occurred */\n timestamp: Date;\n\n /**\n * Creates a new AtomError\n * @param message - Error message describing what went wrong\n * @param cause - Original error that caused this error\n * @param recoverable - Whether the operation can be retried\n */\n constructor(message: string, cause: Error | null = null, recoverable: boolean = true) {\n super(message);\n this.name = 'AtomError';\n this.cause = cause;\n this.recoverable = recoverable;\n this.timestamp = new Date();\n }\n}\n\n/**\n * Error thrown during computed value computation\n *\n * Computed errors are considered recoverable by default since they typically\n * result from transient data issues rather than programming errors.\n */\nexport class ComputedError extends AtomError {\n /**\n * Creates a new ComputedError\n * @param message - Error message\n * @param cause - Original error\n */\n constructor(message: string, cause: Error | null = null) {\n super(message, cause, true);\n this.name = 'ComputedError';\n }\n}\n\n/**\n * Error thrown during effect execution\n *\n * Effect errors are considered non-recoverable by default since effects\n * typically represent critical side effects that shouldn't fail silently.\n */\nexport class EffectError extends AtomError {\n /**\n * Creates a new EffectError\n * @param message - Error message\n * @param cause - Original error\n */\n constructor(message: string, cause: Error | null = null) {\n super(message, cause, false);\n this.name = 'EffectError';\n }\n}\n\n/**\n * Error thrown by the scheduler system\n *\n * Scheduler errors indicate fundamental issues with the batching/scheduling\n * mechanism and are considered non-recoverable.\n */\nexport class SchedulerError extends AtomError {\n /**\n * Creates a new SchedulerError\n * @param message - Error message\n * @param cause - Original error\n */\n constructor(message: string, cause: Error | null = null) {\n super(message, cause, false);\n this.name = 'SchedulerError';\n }\n}\n\n/**\n * Wraps an unknown error in the appropriate AtomError subclass\n *\n * Provides consistent error handling by:\n * - Preserving original error information in the cause field\n * - Adding contextual information about where the error occurred\n * - Returning existing AtomErrors unchanged\n * - Handling various error types (TypeError, ReferenceError, etc.)\n *\n * @param error - Unknown error to wrap\n * @param ErrorClass - AtomError subclass to use for wrapping\n * @param context - Context string describing where the error occurred\n * @returns Wrapped error with contextual information\n *\n * @example\n * ```ts\n * try {\n * computeFn();\n * } catch (err) {\n * throw wrapError(err, ComputedError, 'computation phase');\n * }\n * ```\n */\nexport function wrapError(\n error: unknown,\n ErrorClass: typeof AtomError,\n context: string\n): AtomError {\n if (error instanceof TypeError) {\n return new ErrorClass(`Type error (${context}): ${error.message}`, error);\n }\n if (error instanceof ReferenceError) {\n return new ErrorClass(`Reference error (${context}): ${error.message}`, error);\n }\n if (error instanceof AtomError) {\n return error;\n }\n\n // Handle other error types\n const errorMessage = error instanceof Error ? error.message : String(error);\n const cause = error instanceof Error ? error : null;\n return new ErrorClass(`Unexpected error (${context}): ${errorMessage}`, cause);\n}\n\n/**\n * Type guard to check if a value is a Promise\n *\n * Uses duck-typing to detect Promise-like objects by checking for\n * the presence of a `then` method.\n *\n * @template T - The type the Promise resolves to\n * @param value - Value to check\n * @returns True if value has a `then` method (is Promise-like)\n *\n * @example\n * ```ts\n * const result = computeFn();\n * if (isPromise(result)) {\n * await result;\n * }\n * ```\n */\nexport function isPromise<T>(value: unknown): value is Promise<T> {\n return (\n value !== null &&\n value !== undefined &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n","/**\n * @fileoverview Centralized error messages for better maintainability\n * @description All error messages in English for international accessibility\n */\n\nexport const ERROR_MESSAGES = {\n // Computed errors\n COMPUTED_MUST_BE_FUNCTION: 'Computed function must be a function',\n COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION: 'Subscriber listener must be a function',\n COMPUTED_ASYNC_PENDING_NO_DEFAULT: 'Async computation is pending. No default value provided',\n COMPUTED_COMPUTATION_FAILED: 'Computed computation failed',\n COMPUTED_ASYNC_COMPUTATION_FAILED: 'Async computed computation failed',\n COMPUTED_DEPENDENCY_SUBSCRIPTION_FAILED: 'Failed to subscribe to dependency',\n\n // Atom errors\n ATOM_SUBSCRIBER_MUST_BE_FUNCTION: 'Subscription listener must be a function',\n ATOM_SUBSCRIBER_EXECUTION_FAILED: 'Error occurred while executing atom subscribers',\n ATOM_INDIVIDUAL_SUBSCRIBER_FAILED: 'Error during individual atom subscriber execution',\n\n // Effect errors\n EFFECT_MUST_BE_FUNCTION: 'Effect function must be a function',\n EFFECT_EXECUTION_FAILED: 'Effect execution failed',\n EFFECT_CLEANUP_FAILED: 'Effect cleanup function execution failed',\n\n // Debug warnings\n LARGE_DEPENDENCY_GRAPH: (count: number) =>\n `Large dependency graph detected: ${count} dependencies`,\n UNSUBSCRIBE_NON_EXISTENT: 'Attempted to unsubscribe a non-existent listener',\n CALLBACK_ERROR_IN_ERROR_HANDLER: 'Error occurred during onError callback execution',\n} as const;\n","import { SchedulerError } from '../errors/errors';\n\nclass Scheduler {\n private queue: Set<() => void> = new Set();\n private isProcessing: boolean = false;\n public isBatching: boolean = false;\n private batchDepth: number = 0;\n private batchQueue: Array<() => void> = [];\n private batchQueueSize = 0;\n private isFlushingSync: boolean = false;\n private maxFlushIterations: number = 1000;\n\n schedule(callback: () => void): void {\n if (typeof callback !== 'function') {\n throw new SchedulerError('Scheduler callback must be a function');\n }\n\n if (this.isBatching || this.isFlushingSync) {\n this.batchQueue[this.batchQueueSize++] = callback;\n } else {\n this.queue.add(callback);\n if (!this.isProcessing) {\n this.flush();\n }\n }\n }\n\n private flush(): void {\n if (this.isProcessing || this.queue.size === 0) return;\n\n this.isProcessing = true;\n const callbacks = Array.from(this.queue);\n this.queue.clear();\n\n queueMicrotask(() => {\n for (let i = 0; i < callbacks.length; i++) {\n try {\n callbacks[i]?.();\n } catch (error) {\n console.error(\n new SchedulerError('Error occurred during scheduler execution', error as Error)\n );\n }\n }\n\n this.isProcessing = false;\n\n if (this.queue.size > 0 && !this.isBatching) {\n this.flush();\n }\n });\n }\n\n private flushSync(): void {\n this.isFlushingSync = true;\n\n try {\n if (this.batchQueueSize > 0) {\n for (let i = 0; i < this.batchQueueSize; i++) {\n this.queue.add(this.batchQueue[i]!);\n }\n this.batchQueueSize = 0;\n }\n\n let iterations = 0;\n\n while (this.queue.size > 0) {\n if (++iterations > this.maxFlushIterations) {\n console.error(\n new SchedulerError(\n `Maximum flush iterations (${this.maxFlushIterations}) exceeded. ` +\n `Possible infinite loop in reactive dependencies. ` +\n `Consider increasing the limit with scheduler.setMaxFlushIterations()`\n )\n );\n this.queue.clear();\n this.batchQueueSize = 0;\n break;\n }\n\n const callbacks = Array.from(this.queue);\n this.queue.clear();\n\n for (let i = 0; i < callbacks.length; i++) {\n try {\n callbacks[i]?.();\n } catch (error) {\n console.error(\n new SchedulerError('Error occurred during batch execution', error as Error)\n );\n }\n }\n\n if (this.batchQueueSize > 0) {\n for (let i = 0; i < this.batchQueueSize; i++) {\n this.queue.add(this.batchQueue[i]!);\n }\n this.batchQueueSize = 0;\n }\n }\n } finally {\n this.isFlushingSync = false;\n }\n }\n\n startBatch(): void {\n this.batchDepth++;\n this.isBatching = true;\n }\n\n endBatch(): void {\n this.batchDepth = Math.max(0, this.batchDepth - 1);\n\n if (this.batchDepth === 0) {\n this.flushSync();\n this.isBatching = false;\n }\n }\n\n setMaxFlushIterations(max: number): void {\n if (max < 10) {\n throw new SchedulerError('Max flush iterations must be at least 10');\n }\n this.maxFlushIterations = max;\n }\n}\n\nexport const scheduler = new Scheduler();\n","import { AtomError } from '../errors/errors';\nimport { scheduler } from './scheduler';\n\nexport function batch<T>(callback: () => T): T {\n if (typeof callback !== 'function') {\n throw new AtomError('Batch callback must be a function');\n }\n\n scheduler.startBatch();\n\n try {\n return callback();\n } catch (error) {\n throw new AtomError('Error occurred during batch execution', error as Error);\n } finally {\n scheduler.endBatch();\n }\n}\n","import type { Listener } from './tracking.types';\n\nexport interface TrackingContext {\n current: Listener | null;\n run<T>(listener: Listener, fn: () => T): T;\n getCurrent(): Listener | null;\n}\n\nexport const trackingContext: TrackingContext = {\n current: null,\n\n run<T>(listener: Listener, fn: () => T): T {\n const prev = this.current;\n this.current = listener;\n try {\n return fn();\n } finally {\n this.current = prev;\n }\n },\n\n getCurrent(): Listener | null {\n return this.current;\n },\n};\n","import type { Dependency } from '../types';\n\nexport class DependencyManager {\n private depMap = new WeakMap<Dependency, () => void>();\n private depRefs: WeakRef<Dependency>[] = [];\n private cleanupThreshold = 100;\n private addCount = 0;\n\n addDependency(dep: Dependency, unsubscribe: () => void): void {\n if (this.depMap.has(dep)) {\n unsubscribe();\n return;\n }\n\n this.depMap.set(dep, unsubscribe);\n this.depRefs.push(new WeakRef(dep));\n\n if (++this.addCount >= this.cleanupThreshold) {\n this.cleanup();\n this.addCount = 0;\n }\n }\n\n removeDependency(dep: Dependency): boolean {\n const unsubscribe = this.depMap.get(dep);\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch (error) {\n console.warn('[DependencyManager] Error during unsubscribe:', error);\n }\n this.depMap.delete(dep);\n return true;\n }\n return false;\n }\n\n hasDependency(dep: Dependency): boolean {\n return this.depMap.has(dep);\n }\n\n unsubscribeAll(): void {\n for (let i = 0; i < this.depRefs.length; i++) {\n const dep = this.depRefs[i]!.deref();\n if (dep) {\n const unsubscribe = this.depMap.get(dep);\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch (error) {\n console.warn('[DependencyManager] Error during unsubscribe:', error);\n }\n this.depMap.delete(dep);\n }\n }\n }\n this.depRefs.length = 0;\n this.addCount = 0;\n }\n\n cleanup(): void {\n this.depRefs = this.depRefs.filter((ref) => ref.deref() !== undefined);\n }\n\n get count(): number {\n this.cleanup();\n return this.depRefs.length;\n }\n\n getDependencies(): Dependency[] {\n const liveDeps: Dependency[] = [];\n for (let i = 0; i < this.depRefs.length; i++) {\n const dep = this.depRefs[i]!.deref();\n if (dep !== undefined) {\n liveDeps.push(dep);\n }\n }\n return liveDeps;\n }\n\n getDepMap(): WeakMap<Dependency, () => void> {\n return this.depMap;\n }\n\n setCleanupThreshold(threshold: number): void {\n this.cleanupThreshold = Math.max(1, threshold);\n }\n}\n","import { AtomError } from '../errors/errors';\nimport { trackingContext } from './context';\n\nexport function untracked<T>(fn: () => T): T {\n if (typeof fn !== 'function') {\n throw new AtomError('Untracked callback must be a function');\n }\n\n const prev = trackingContext.current;\n trackingContext.current = null;\n\n try {\n return fn();\n } catch (error) {\n throw new AtomError('Error occurred during untracked execution', error as Error);\n } finally {\n trackingContext.current = prev;\n }\n}\n","/**\n * @fileoverview Debug configuration and utilities\n * @description Development-time debugging tools for dependency tracking and circular reference detection\n */\n\nimport { DEBUG_CONFIG } from '../constants';\nimport { ComputedError } from '../errors/errors';\nimport type { DebugConfig } from '../types';\n\n/**\n * Symbols for debug metadata to avoid property name collisions\n */\nexport const DEBUG_NAME = Symbol('debugName');\nexport const DEBUG_ID = Symbol('id');\nexport const DEBUG_TYPE = Symbol('type');\n\n/**\n * Sentinel value to distinguish \"no default value\" from undefined\n */\nexport const NO_DEFAULT_VALUE = Symbol('noDefaultValue');\n\nexport const debug: DebugConfig = {\n enabled:\n typeof process !== 'undefined' && (process as NodeJS.Process).env?.NODE_ENV === 'development',\n maxDependencies: DEBUG_CONFIG.MAX_DEPENDENCIES,\n warnInfiniteLoop: DEBUG_CONFIG.WARN_INFINITE_LOOP,\n\n warn(condition: boolean, message: string): void {\n if (this.enabled && condition) {\n console.warn(`[Atom Effect] ${message}`);\n }\n },\n\n checkCircular(dep: unknown, current: unknown, visited = new Set<unknown>()): void {\n // Direct circular reference check (A→A) - Always checked even in production\n if (dep === current) {\n throw new ComputedError('Direct circular dependency detected');\n }\n\n // Indirect circular reference check only in development mode (for performance)\n if (!this.enabled) return;\n\n // Indirect circular reference check (A→B→C→A)\n if (visited.has(dep)) {\n throw new ComputedError('Indirect circular dependency detected');\n }\n\n visited.add(dep);\n\n // Recursively check nested dependencies\n if (dep && typeof dep === 'object' && 'dependencies' in dep) {\n const dependencies = (dep as { dependencies: Set<unknown> }).dependencies;\n for (const nestedDep of dependencies) {\n this.checkCircular(nestedDep, current, visited);\n }\n }\n },\n\n attachDebugInfo(obj: object, type: string, id: number): void {\n if (!this.enabled) return;\n const target = obj as Record<symbol, unknown>;\n target[DEBUG_NAME] = `${type}_${id}`;\n target[DEBUG_ID] = id;\n target[DEBUG_TYPE] = type;\n },\n\n getDebugName(obj: unknown): string | undefined {\n if (obj && typeof obj === 'object' && DEBUG_NAME in obj) {\n return (obj as Record<symbol, unknown>)[DEBUG_NAME] as string | undefined;\n }\n return undefined;\n },\n\n getDebugType(obj: unknown): string | undefined {\n if (obj && typeof obj === 'object' && DEBUG_TYPE in obj) {\n return (obj as Record<symbol, unknown>)[DEBUG_TYPE] as string | undefined;\n }\n return undefined;\n },\n};\n\nlet nextId = 1;\nexport const generateId = (): number => nextId++;\n","/**\n * @fileoverview atom: Core reactive state primitive\n *\n * Atoms are the fundamental building blocks of the reactive system.\n * They hold mutable state and automatically notify subscribers when their value changes.\n *\n * @example\n * ```ts\n * const count = atom(0);\n * count.value = 1; // Triggers subscribers\n * console.log(count.peek()); // 1 (without tracking)\n * ```\n */\n\nimport { AtomError } from '../../errors/errors';\nimport { ERROR_MESSAGES } from '../../errors/messages';\nimport { scheduler } from '../../scheduler';\nimport { trackingContext } from '../../tracking';\nimport type { AtomOptions, WritableAtom } from '../../types';\nimport { debug, generateId } from '../../utils/debug';\n\n/**\n * Internal implementation of the WritableAtom interface.\n *\n * @template T - The type of value stored in the atom\n *\n * @remarks\n * This class manages reactive state with optimized subscriber management.\n * It supports both function-based and object-based subscribers, and handles\n * synchronous or batched notifications based on configuration.\n */\nclass AtomImpl<T> implements WritableAtom<T> {\n /** Current value stored in the atom */\n private _value: T;\n\n /** Version counter for change detection and stale notification prevention */\n private _version: number;\n\n /** Array of function-based subscribers */\n private _fnSubs: Array<(newValue?: T, oldValue?: T) => void>;\n\n /** Count of active function subscribers (may differ from array length due to sparse removal) */\n private _fnSubCount: number;\n\n /** Array of object-based subscribers with execute method */\n private _objSubs: Array<{ execute: () => void }>;\n\n /** Count of active object subscribers */\n private _objSubCount: number;\n\n /** Whether notifications should be synchronous (bypass scheduler batching) */\n private readonly _sync: boolean;\n\n /** Unique identifier for debugging purposes */\n private readonly _id: string;\n\n /**\n * Creates a new AtomImpl instance.\n *\n * @param initialValue - The initial value of the atom\n * @param sync - Whether to notify subscribers synchronously\n */\n constructor(initialValue: T, sync: boolean) {\n this._value = initialValue;\n this._version = 0;\n this._fnSubs = [];\n this._fnSubCount = 0;\n this._objSubs = [];\n this._objSubCount = 0;\n this._sync = sync;\n this._id = generateId().toString();\n\n debug.attachDebugInfo(this, 'atom', generateId());\n }\n\n /**\n * Gets the current value and registers the atom as a dependency\n * in the current tracking context.\n *\n * @returns The current value\n *\n * @remarks\n * This getter automatically tracks dependencies when accessed within\n * a computed or effect context.\n */\n get value(): T {\n const current = trackingContext.getCurrent();\n if (current !== null && current !== undefined) {\n this._track(current);\n }\n return this._value;\n }\n\n /**\n * Sets a new value and notifies all subscribers if the value changed.\n *\n * @param newValue - The new value to set\n *\n * @remarks\n * Uses Object.is for equality comparison. If the value is unchanged,\n * no notifications are sent. Notifications may be batched unless\n * sync mode is enabled.\n */\n set value(newValue: T) {\n if (Object.is(this._value, newValue)) return;\n\n const oldValue = this._value;\n const currentVersion = ++this._version;\n this._value = newValue;\n\n if ((this._fnSubCount | this._objSubCount) === 0) return;\n\n this._notify(newValue, oldValue, currentVersion);\n }\n\n /**\n * Tracks the current context as a dependency of this atom.\n *\n * @param current - The current tracking context (function or object)\n *\n * @remarks\n * Handles both function-based trackers (with optional addDependency method)\n * and object-based trackers (with execute or addDependency methods).\n */\n private _track(current: unknown): void {\n if (typeof current === 'function') {\n const fnWithDep = current as { addDependency?: (dep: unknown) => void };\n if (fnWithDep.addDependency !== undefined) {\n fnWithDep.addDependency(this);\n } else {\n this._addFnSub(current as (newValue?: T, oldValue?: T) => void);\n }\n } else {\n const tracker = current as { execute?: () => void; addDependency?: (dep: unknown) => void };\n if (tracker.addDependency !== undefined) {\n tracker.addDependency(this);\n } else if (tracker.execute !== undefined) {\n this._addObjSub(tracker as { execute: () => void });\n }\n }\n }\n\n /**\n * Adds a function-based subscriber.\n *\n * @param sub - The subscriber function to add\n * @returns An unsubscribe function\n *\n * @remarks\n * Prevents duplicate subscriptions by checking existing subscribers.\n */\n private _addFnSub(sub: (newValue?: T, oldValue?: T) => void): () => void {\n const subs = this._fnSubs;\n const idx = this._fnSubCount;\n\n for (let i = 0; i < idx; i++) {\n if (subs[i] === sub) return this._createUnsub(i, true);\n }\n\n subs[idx] = sub;\n this._fnSubCount = idx + 1;\n\n return this._createUnsub(idx, true);\n }\n\n /**\n * Adds an object-based subscriber.\n *\n * @param sub - The subscriber object with an execute method\n *\n * @remarks\n * Prevents duplicate subscriptions by checking existing subscribers.\n */\n private _addObjSub(sub: { execute: () => void }): void {\n const subs = this._objSubs;\n const count = this._objSubCount;\n\n for (let i = 0; i < count; i++) {\n if (subs[i] === sub) return;\n }\n\n subs[count] = sub;\n this._objSubCount = count + 1;\n }\n\n /**\n * Creates an unsubscribe function for a subscriber at the given index.\n *\n * @param idx - The index of the subscriber\n * @param isFn - Whether this is a function subscriber (true) or object subscriber (false)\n * @returns An unsubscribe function\n */\n private _createUnsub(idx: number, isFn: boolean): () => void {\n return () => {\n if (isFn) {\n this._removeFnSub(idx);\n } else {\n this._removeObjSub(idx);\n }\n };\n }\n\n /**\n * Removes a function subscriber at the given index.\n *\n * @param idx - The index of the subscriber to remove\n *\n * @remarks\n * Uses swap-and-pop removal for O(1) performance.\n */\n private _removeFnSub(idx: number): void {\n const count = this._fnSubCount;\n if (idx >= count) return;\n\n const lastIdx = count - 1;\n const subs = this._fnSubs;\n\n subs[idx] = subs[lastIdx] as (newValue?: T, oldValue?: T) => void;\n subs[lastIdx] = undefined as any;\n this._fnSubCount = lastIdx;\n }\n\n /**\n * Removes an object subscriber at the given index.\n *\n * @param idx - The index of the subscriber to remove\n *\n * @remarks\n * Uses swap-and-pop removal for O(1) performance.\n */\n private _removeObjSub(idx: number): void {\n const count = this._objSubCount;\n if (idx >= count) return;\n\n const lastIdx = count - 1;\n const subs = this._objSubs;\n\n subs[idx] = subs[lastIdx] as { execute: () => void };\n subs[lastIdx] = undefined as any;\n this._objSubCount = lastIdx;\n }\n\n /**\n * Notifies all subscribers of a value change.\n *\n * @param newValue - The new value\n * @param oldValue - The previous value\n * @param currentVersion - The version at the time of change\n *\n * @remarks\n * Notifications are skipped if the version has changed (stale update).\n * Errors from individual subscribers are caught and logged without\n * interrupting other subscribers.\n */\n private _notify(newValue: T, oldValue: T, currentVersion: number): void {\n const doNotify = (): void => {\n if (this._version !== currentVersion) return;\n\n const fnSubs = this._fnSubs;\n const fnCount = this._fnSubCount;\n const objSubs = this._objSubs;\n const objCount = this._objSubCount;\n\n for (let i = 0; i < fnCount; i++) {\n try {\n const fn = fnSubs[i];\n if (fn) {\n fn(newValue, oldValue);\n }\n } catch (e) {\n console.error(\n new AtomError(ERROR_MESSAGES.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED, e as Error)\n );\n }\n }\n\n for (let i = 0; i < objCount; i++) {\n try {\n const sub = objSubs[i];\n if (sub) {\n sub.execute();\n }\n } catch (e) {\n console.error(\n new AtomError(ERROR_MESSAGES.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED, e as Error)\n );\n }\n }\n };\n\n if (this._sync && !scheduler.isBatching) {\n doNotify();\n } else {\n scheduler.schedule(doNotify);\n }\n }\n\n /**\n * Subscribes a listener function to value changes.\n *\n * @param listener - Function to call when the value changes\n * @returns An unsubscribe function\n * @throws {AtomError} If listener is not a function\n *\n * @example\n * ```ts\n * const unsub = myAtom.subscribe((newVal, oldVal) => {\n * console.log(`Changed from ${oldVal} to ${newVal}`);\n * });\n * // Later: unsub();\n * ```\n */\n subscribe(listener: (newValue?: T, oldValue?: T) => void): () => void {\n if (typeof listener !== 'function') {\n throw new AtomError(ERROR_MESSAGES.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);\n }\n return this._addFnSub(listener);\n }\n\n /**\n * Gets the current value without registering as a dependency.\n *\n * @returns The current value\n *\n * @remarks\n * Use this method when you need to read the value without\n * creating a reactive dependency (e.g., in event handlers).\n */\n peek(): T {\n return this._value;\n }\n\n /**\n * Disposes the atom, clearing all subscribers and releasing resources.\n *\n * @remarks\n * After disposal, the atom should not be used. The value is set to\n * undefined to help with garbage collection.\n */\n dispose(): void {\n this._fnSubs.length = 0;\n this._objSubs.length = 0;\n this._fnSubCount = 0;\n this._objSubCount = 0;\n this._value = undefined as T;\n }\n\n /**\n * Gets the total number of active subscribers.\n *\n * @returns The count of function and object subscribers combined\n */\n subscriberCount(): number {\n return this._fnSubCount + this._objSubCount;\n }\n}\n\n/**\n * Creates a new atom with the given initial value.\n *\n * @template T - The type of value stored in the atom\n * @param initialValue - The initial value of the atom\n * @param options - Optional configuration options\n * @returns A writable atom instance\n *\n * @example\n * ```ts\n * // Basic usage\n * const count = atom(0);\n *\n * // With sync option for immediate notifications\n * const syncCount = atom(0, { sync: true });\n *\n * // Reading and writing\n * console.log(count.value); // 0\n * count.value = 5;\n * console.log(count.peek()); // 5 (non-tracking read)\n * ```\n */\nexport function atom<T>(initialValue: T, options: AtomOptions = {}): WritableAtom<T> {\n return new AtomImpl(initialValue, options.sync ?? false);\n}\n","/**\n * @fileoverview Subscriber management utility\n * @description Manages subscribers with O(1) add/remove operations using Array + WeakMap\n */\n\n/**\n * Manages subscribers with optimized O(1) operations\n *\n * Uses a combination of Array (for iteration) and WeakMap (for O(1) lookup)\n * to provide both fast iteration and fast add/remove operations.\n *\n * Key optimizations:\n * - Array for cache-friendly sequential iteration\n * - WeakMap for O(1) lookup and automatic GC\n * - Swap-and-pop for O(1) removal\n * - Lazy initialization to save memory\n *\n * @template T - Subscriber type (any object type for WeakMap compatibility)\n *\n * @example\n * ```ts\n * const manager = new SubscriberManager<(value: number) => void>();\n *\n * // Add subscriber\n * const unsub = manager.add((val) => console.log(val));\n *\n * // Notify all\n * manager.notify(42);\n *\n * // Remove subscriber\n * unsub();\n * ```\n */\nexport class SubscriberManager<T extends object> {\n private subscribers: T[] | null = null;\n private subscriberIndex: WeakMap<T, number> | null = null;\n\n /**\n * Adds a subscriber and returns an unsubscribe function\n *\n * Performs lazy initialization on first subscriber.\n * Duplicate subscribers are ignored (idempotent).\n *\n * @param subscriber - Function to add as subscriber\n * @returns Unsubscribe function (O(1) removal)\n *\n * @example\n * ```ts\n * const unsub = manager.add((value) => console.log(value));\n * // Later...\n * unsub(); // Remove this subscriber\n * ```\n */\n add(subscriber: T): () => void {\n // Lazy initialization\n if (!this.subscribers) {\n this.subscribers = [];\n this.subscriberIndex = new WeakMap();\n }\n\n // Check for duplicates (O(1))\n if (this.subscriberIndex!.has(subscriber)) {\n // Already subscribed, return no-op unsubscribe\n return () => {};\n }\n\n // Add subscriber (O(1))\n const index = this.subscribers.length;\n this.subscribers.push(subscriber);\n this.subscriberIndex!.set(subscriber, index);\n\n // Return unsubscribe function with duplicate protection\n let isUnsubscribed = false;\n return () => {\n if (isUnsubscribed) return;\n isUnsubscribed = true;\n this.remove(subscriber);\n };\n }\n\n /**\n * Removes a subscriber using swap-and-pop optimization\n *\n * Time complexity: O(1)\n * - Swaps target with last element\n * - Pops last element\n * - Updates index mapping\n *\n * @param subscriber - Subscriber to remove\n * @returns True if removed, false if not found\n */\n remove(subscriber: T): boolean {\n if (!this.subscribers || !this.subscriberIndex) {\n return false;\n }\n\n const idx = this.subscriberIndex.get(subscriber);\n if (idx === undefined) {\n return false; // Not found\n }\n\n const lastIndex = this.subscribers.length - 1;\n\n // Swap with last element (O(1))\n if (idx !== lastIndex) {\n const lastSubscriber = this.subscribers[lastIndex]!;\n this.subscribers[idx] = lastSubscriber;\n this.subscriberIndex.set(lastSubscriber, idx);\n }\n\n // Pop last element (O(1))\n this.subscribers.pop();\n this.subscriberIndex.delete(subscriber);\n\n return true;\n }\n\n /**\n * Checks if a subscriber is registered\n *\n * @param subscriber - Subscriber to check\n * @returns True if registered\n */\n has(subscriber: T): boolean {\n return this.subscriberIndex?.has(subscriber) ?? false;\n }\n\n /**\n * Iterates over all subscribers with a callback\n *\n * Optimized for cache-friendly sequential access.\n * Errors in callbacks are propagated to the caller.\n *\n * @param fn - Callback to execute for each subscriber\n *\n * @example\n * ```ts\n * manager.forEach((subscriber) => {\n * subscriber(newValue, oldValue);\n * });\n * ```\n */\n forEach(fn: (subscriber: T, index: number) => void): void {\n if (!this.subscribers) return;\n\n for (let i = 0; i < this.subscribers.length; i++) {\n fn(this.subscribers[i]!, i);\n }\n }\n\n /**\n * Safely iterates over subscribers with error handling\n *\n * Catches and logs errors from individual callbacks to prevent\n * one failing subscriber from breaking the entire notification chain.\n *\n * @param fn - Callback to execute for each subscriber\n * @param onError - Optional error handler for each callback error\n */\n forEachSafe(fn: (subscriber: T, index: number) => void, onError?: (error: Error) => void): void {\n if (!this.subscribers) return;\n\n for (let i = 0; i < this.subscribers.length; i++) {\n try {\n fn(this.subscribers[i]!, i);\n } catch (error) {\n if (onError) {\n onError(error as Error);\n } else {\n console.error('[SubscriberManager] Error in subscriber callback:', error);\n }\n }\n }\n }\n\n /**\n * Gets the current number of subscribers\n *\n * @returns Number of active subscribers\n */\n get size(): number {\n return this.subscribers?.length ?? 0;\n }\n\n /**\n * Checks if there are any subscribers\n *\n * @returns True if at least one subscriber exists\n */\n get hasSubscribers(): boolean {\n return this.size > 0;\n }\n\n /**\n * Clears all subscribers\n *\n * Removes all subscribers and releases memory.\n * Subsequent operations will re-initialize lazily.\n */\n clear(): void {\n if (this.subscribers) {\n this.subscribers.length = 0;\n }\n this.subscriberIndex = null;\n this.subscribers = null;\n }\n\n /**\n * Gets a copy of all subscribers as an array\n *\n * Useful for debugging or manual iteration.\n * Returns empty array if no subscribers.\n *\n * @returns Array of all subscribers\n */\n toArray(): T[] {\n return this.subscribers ? [...this.subscribers] : [];\n }\n}\n","/**\n * @fileoverview computed: Derived reactive state with automatic dependency tracking\n * @description Creates computed values that automatically update when dependencies change (sync/async support)\n * @optimized Class-based architecture with cache locality and branchless patterns\n */\n\nimport { AsyncState, COMPUTED_STATE_FLAGS } from '../../constants';\nimport type { AtomError } from '../../errors/errors';\nimport { ComputedError, isPromise, wrapError } from '../../errors/errors';\nimport { ERROR_MESSAGES } from '../../errors/messages';\nimport { scheduler } from '../../scheduler';\nimport { trackingContext } from '../../tracking';\nimport { DependencyManager } from '../../tracking/dependency-manager';\nimport type {\n AsyncStateType,\n ComputedAtom,\n ComputedOptions,\n Dependency,\n Subscriber,\n} from '../../types';\nimport { debug, generateId, NO_DEFAULT_VALUE } from '../../utils/debug';\nimport { SubscriberManager } from '../../utils/subscriber-manager';\n\n/**\n * Optimized ComputedAtom implementation with class-based architecture\n *\n * Key optimizations:\n * - Cache-friendly field layout (hot fields first)\n * - Inline bit flags (no separate class instance)\n * - Branchless fast path for value access\n * - Reduced indirection and closure overhead\n *\n * @template T - The type of the computed value\n */\nclass ComputedAtomImpl<T> implements ComputedAtom<T> {\n // === HOT PATH: Most frequently accessed fields (cache line 1) ===\n private _value: T;\n private _stateFlags: number;\n\n // === WARM PATH: Frequently accessed fields (cache line 2) ===\n private _error: AtomError | null = null;\n private _promiseId = 0;\n private readonly _equal: (a: T, b: T) => boolean;\n\n // === COLD PATH: Infrequently accessed fields ===\n private readonly _fn: () => T | Promise<T>;\n private readonly _defaultValue: T;\n private readonly _hasDefaultValue: boolean;\n private readonly _onError: ((error: Error) => void) | null;\n private readonly _functionSubscribers: SubscriberManager<() => void>;\n private readonly _objectSubscribers: SubscriberManager<Subscriber>;\n private readonly _dependencyManager: DependencyManager;\n private readonly _id: number;\n private readonly MAX_PROMISE_ID = Number.MAX_SAFE_INTEGER - 1;\n\n constructor(fn: () => T | Promise<T>, options: ComputedOptions<T> = {}) {\n if (typeof fn !== 'function') {\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_MUST_BE_FUNCTION);\n }\n\n this._fn = fn;\n this._stateFlags = COMPUTED_STATE_FLAGS.DIRTY | COMPUTED_STATE_FLAGS.IDLE;\n this._value = undefined as T;\n\n const {\n equal = Object.is,\n defaultValue = NO_DEFAULT_VALUE as T,\n lazy = true,\n onError = null,\n } = options;\n\n this._equal = equal;\n this._defaultValue = defaultValue;\n this._hasDefaultValue = defaultValue !== NO_DEFAULT_VALUE;\n this._onError = onError;\n this._functionSubscribers = new SubscriberManager<() => void>();\n this._objectSubscribers = new SubscriberManager<Subscriber>();\n this._dependencyManager = new DependencyManager();\n this._id = generateId();\n\n debug.attachDebugInfo(this as unknown as ComputedAtom<T>, 'computed', this._id);\n\n if (debug.enabled) {\n const debugObj = this as unknown as ComputedAtom<T> & {\n subscriberCount: () => number;\n isDirty: () => boolean;\n dependencies: ReturnType<DependencyManager['getDependencies']>;\n stateFlags: string;\n };\n debugObj.subscriberCount = () =>\n this._functionSubscribers.size + this._objectSubscribers.size;\n debugObj.isDirty = () => this._isDirty();\n debugObj.dependencies = this._dependencyManager.getDependencies();\n debugObj.stateFlags = this._getFlagsAsString();\n }\n\n if (!lazy) {\n try {\n this._recompute();\n } catch {\n // Ignore initial computation failure for non-lazy computed\n }\n }\n }\n\n // === PUBLIC API ===\n\n get value(): T {\n // Branchless fast path: single bitwise check for (resolved AND not dirty)\n const isFastPath =\n (this._stateFlags & (COMPUTED_STATE_FLAGS.RESOLVED | COMPUTED_STATE_FLAGS.DIRTY)) ===\n COMPUTED_STATE_FLAGS.RESOLVED;\n\n if (isFastPath) {\n this._registerTracking();\n return this._value;\n }\n\n // Slow path: state transition required\n const result = this._computeValue();\n this._registerTracking();\n return result;\n }\n\n subscribe(listener: () => void): () => void {\n if (typeof listener !== 'function') {\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION);\n }\n return this._functionSubscribers.add(listener);\n }\n\n peek(): T {\n return this._value;\n }\n\n get state(): AsyncStateType {\n return this._getAsyncState();\n }\n\n get hasError(): boolean {\n return this._isRejected();\n }\n\n get lastError(): Error | null {\n return this._error;\n }\n\n get isPending(): boolean {\n return this._isPending();\n }\n\n get isResolved(): boolean {\n return this._isResolved();\n }\n\n invalidate(): void {\n this._markDirty();\n }\n\n dispose(): void {\n this._dependencyManager.unsubscribeAll();\n this._functionSubscribers.clear();\n this._objectSubscribers.clear();\n this._stateFlags = COMPUTED_STATE_FLAGS.DIRTY | COMPUTED_STATE_FLAGS.IDLE;\n this._error = null;\n this._value = undefined as T;\n this._promiseId = (this._promiseId + 1) % this.MAX_PROMISE_ID;\n }\n\n // === PRIVATE: State Flag Operations (inlined for performance) ===\n\n private _isDirty(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.DIRTY) !== 0;\n }\n\n private _setDirty(): void {\n this._stateFlags |= COMPUTED_STATE_FLAGS.DIRTY;\n }\n\n private _clearDirty(): void {\n this._stateFlags &= ~COMPUTED_STATE_FLAGS.DIRTY;\n }\n\n private _isIdle(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.IDLE) !== 0;\n }\n\n private _setIdle(): void {\n this._stateFlags |= COMPUTED_STATE_FLAGS.IDLE;\n this._stateFlags &= ~(\n COMPUTED_STATE_FLAGS.PENDING |\n COMPUTED_STATE_FLAGS.RESOLVED |\n COMPUTED_STATE_FLAGS.REJECTED\n );\n }\n\n private _isPending(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.PENDING) !== 0;\n }\n\n private _setPending(): void {\n this._stateFlags |= COMPUTED_STATE_FLAGS.PENDING;\n this._stateFlags &= ~(\n COMPUTED_STATE_FLAGS.IDLE |\n COMPUTED_STATE_FLAGS.RESOLVED |\n COMPUTED_STATE_FLAGS.REJECTED\n );\n }\n\n private _isResolved(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.RESOLVED) !== 0;\n }\n\n private _setResolved(): void {\n this._stateFlags |= COMPUTED_STATE_FLAGS.RESOLVED;\n this._stateFlags &= ~(\n COMPUTED_STATE_FLAGS.IDLE |\n COMPUTED_STATE_FLAGS.PENDING |\n COMPUTED_STATE_FLAGS.REJECTED |\n COMPUTED_STATE_FLAGS.HAS_ERROR\n );\n }\n\n private _isRejected(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.REJECTED) !== 0;\n }\n\n private _setRejected(): void {\n this._stateFlags |= COMPUTED_STATE_FLAGS.REJECTED | COMPUTED_STATE_FLAGS.HAS_ERROR;\n this._stateFlags &= ~(\n COMPUTED_STATE_FLAGS.IDLE |\n COMPUTED_STATE_FLAGS.PENDING |\n COMPUTED_STATE_FLAGS.RESOLVED\n );\n }\n\n private _isRecomputing(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.RECOMPUTING) !== 0;\n }\n\n private _setRecomputing(value: boolean): void {\n if (value) {\n this._stateFlags |= COMPUTED_STATE_FLAGS.RECOMPUTING;\n } else {\n this._stateFlags &= ~COMPUTED_STATE_FLAGS.RECOMPUTING;\n }\n }\n\n private _getAsyncState(): AsyncStateType {\n if (this._isPending()) return AsyncState.PENDING;\n if (this._isResolved()) return AsyncState.RESOLVED;\n if (this._isRejected()) return AsyncState.REJECTED;\n return AsyncState.IDLE;\n }\n\n private _getFlagsAsString(): string {\n const states: string[] = [];\n if (this._isDirty()) states.push('DIRTY');\n if (this._isIdle()) states.push('IDLE');\n if (this._isPending()) states.push('PENDING');\n if (this._isResolved()) states.push('RESOLVED');\n if (this._isRejected()) states.push('REJECTED');\n if (this._isRecomputing()) states.push('RECOMPUTING');\n return states.join(' | ');\n }\n\n // === PRIVATE: Core Computation Logic ===\n\n private _computeValue(): T {\n if (this._isRecomputing()) return this._value;\n if (this._isPending()) return this._handlePending();\n if (this._isRejected()) return this._handleRejected();\n\n if (this._isDirty() || this._isIdle()) {\n this._recompute();\n if (this._isPending()) {\n return this._handlePending();\n }\n }\n\n return this._value;\n }\n\n private _recompute(): void {\n if (!this._isDirty() && this._isResolved()) {\n return;\n }\n\n this._setRecomputing(true);\n\n // Track dependencies during computation\n const newDependencies = new Set<unknown>();\n const tempMarkDirty = Object.assign(() => this._markDirty(), {\n addDependency: (dep: unknown) => newDependencies.add(dep),\n });\n\n try {\n const result = trackingContext.run(tempMarkDirty, this._fn);\n\n if (isPromise(result)) {\n // Update dependencies before async handling\n this._updateDependencies(newDependencies);\n this._handleAsyncComputation(result);\n this._setRecomputing(false);\n return;\n }\n\n // Update dependencies for sync result\n this._updateDependencies(newDependencies);\n this._handleSyncResult(result);\n } catch (err) {\n // Update dependencies even on error for recovery support\n this._updateDependencies(newDependencies);\n this._handleComputationError(err);\n }\n }\n\n private _handleSyncResult(result: T): void {\n const shouldUpdate = !this._isResolved() || !this._equal(this._value, result);\n\n this._value = result;\n this._clearDirty();\n this._setResolved();\n this._error = null;\n this._setRecomputing(false);\n\n if (shouldUpdate) {\n this._notifySubscribers();\n }\n }\n\n private _handleAsyncComputation(promise: Promise<T>): void {\n this._setPending();\n\n // Branchless promise ID increment with overflow protection\n this._promiseId = this._promiseId >= this.MAX_PROMISE_ID ? 1 : this._promiseId + 1;\n const promiseId = this._promiseId;\n\n promise\n .then((resolvedValue) => {\n // Race condition check: ignore if superseded\n if (promiseId !== this._promiseId) return;\n\n this._handleAsyncResolution(resolvedValue);\n })\n .catch((err) => {\n // Race condition check: ignore if superseded\n if (promiseId !== this._promiseId) return;\n\n this._handleAsyncRejection(err);\n });\n }\n\n private _handleAsyncResolution(resolvedValue: T): void {\n const shouldUpdate = !this._isResolved() || !this._equal(this._value, resolvedValue);\n\n this._value = resolvedValue;\n this._clearDirty();\n this._setResolved();\n this._error = null;\n this._setRecomputing(false);\n\n if (shouldUpdate) {\n this._notifySubscribers();\n }\n }\n\n private _handleAsyncRejection(err: unknown): void {\n const error = wrapError(err, ComputedError, ERROR_MESSAGES.COMPUTED_ASYNC_COMPUTATION_FAILED);\n\n this._error = error;\n this._setRejected();\n this._clearDirty();\n this._setRecomputing(false);\n\n if (this._onError && typeof this._onError === 'function') {\n try {\n this._onError(error);\n } catch (callbackError) {\n console.error(ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER, callbackError);\n }\n }\n\n this._notifySubscribers();\n }\n\n private _handleComputationError(err: unknown): never {\n const error = wrapError(err, ComputedError, ERROR_MESSAGES.COMPUTED_COMPUTATION_FAILED);\n\n this._error = error;\n this._setRejected();\n this._clearDirty();\n this._setRecomputing(false);\n\n if (this._onError && typeof this._onError === 'function') {\n try {\n this._onError(error);\n } catch (callbackError) {\n console.error(ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER, callbackError);\n }\n }\n\n throw error;\n }\n\n private _handlePending(): T {\n if (this._hasDefaultValue) {\n return this._defaultValue;\n }\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_ASYNC_PENDING_NO_DEFAULT);\n }\n\n private _handleRejected(): T {\n if (this._error?.recoverable && this._hasDefaultValue) {\n return this._defaultValue;\n }\n throw this._error;\n }\n\n // === PRIVATE: Dependency Management ===\n\n private _updateDependencies(newDeps: Set<unknown>): void {\n const dependencies = this._dependencyManager.getDependencies();\n\n // Fast path: No dependency changes (O(1) check)\n if (this._hasSameDependencies(dependencies, newDeps)) {\n return;\n }\n\n // Slow path: Delta Sync\n this._performDeltaSync(dependencies, newDeps);\n }\n\n private _hasSameDependencies(current: Dependency[], newDeps: Set<unknown>): boolean {\n if (current.length !== newDeps.size) {\n return false;\n }\n\n for (let i = 0; i < current.length; i++) {\n if (!newDeps.has(current[i]!)) {\n return false;\n }\n }\n\n return true;\n }\n\n private _performDeltaSync(current: Dependency[], newDeps: Set<unknown>): void {\n const existingSet = new Set(current);\n const toRemove: Dependency[] = [];\n const toAdd: Dependency[] = [];\n\n // Find dependencies to remove\n for (let i = 0; i < current.length; i++) {\n const dep = current[i]!;\n if (!newDeps.has(dep)) {\n toRemove.push(dep);\n }\n }\n\n // Find dependencies to add\n newDeps.forEach((dep) => {\n if (!existingSet.has(dep as Dependency)) {\n toAdd.push(dep as Dependency);\n }\n });\n\n // Unsubscribe removed dependencies\n for (let i = 0; i < toRemove.length; i++) {\n this._dependencyManager.removeDependency(toRemove[i]!);\n }\n\n // Subscribe to new dependencies\n for (let i = 0; i < toAdd.length; i++) {\n this._addDependency(toAdd[i]!);\n }\n\n // Update dependencies array in place\n current.length = 0;\n newDeps.forEach((dep) => {\n current.push(dep as Dependency);\n });\n }\n\n private _addDependency(dep: Dependency): void {\n debug.checkCircular(dep, this as unknown as ComputedAtom<T>);\n\n const count = this._dependencyManager.count;\n debug.warn(count > debug.maxDependencies, ERROR_MESSAGES.LARGE_DEPENDENCY_GRAPH(count));\n\n try {\n const unsubscribe = dep.subscribe(() => this._markDirty());\n this._dependencyManager.addDependency(dep, unsubscribe);\n } catch (error) {\n throw wrapError(error, ComputedError, 'dependency subscription');\n }\n }\n\n // === PRIVATE: Subscriber Management ===\n\n private _markDirty(): void {\n if (this._isRecomputing() || this._isDirty()) return;\n\n this._setDirty();\n this._setIdle();\n\n if (this._functionSubscribers.hasSubscribers || this._objectSubscribers.hasSubscribers) {\n scheduler.schedule(() => {\n if (this._isDirty()) {\n try {\n this._recompute();\n } catch {\n // Error already handled\n }\n }\n });\n }\n }\n\n private _notifySubscribers(): void {\n if (!this._functionSubscribers.hasSubscribers && !this._objectSubscribers.hasSubscribers) {\n return;\n }\n\n scheduler.schedule(() => {\n this._functionSubscribers.forEachSafe(\n (subscriber) => subscriber(),\n (err) => console.error(err)\n );\n\n this._objectSubscribers.forEachSafe(\n (subscriber) => subscriber.execute(),\n (err) => console.error(err)\n );\n });\n }\n\n private _registerTracking(): void {\n const current = trackingContext.getCurrent();\n if (!current) return;\n\n if (typeof current === 'function') {\n this._functionSubscribers.add(current);\n } else if (current.addDependency) {\n current.addDependency(this as unknown as ComputedAtom<T>);\n } else if (current.execute) {\n this._objectSubscribers.add(current as Subscriber);\n }\n }\n}\n\n/**\n * Creates a computed value that automatically tracks and reacts to dependencies\n *\n * Computed atoms are derived reactive state that:\n * - Automatically track dependencies accessed during computation\n * - Lazily recompute only when dependencies change (dirty checking)\n * - Support both synchronous and asynchronous computations\n * - Cache results until dependencies change (memoization)\n * - Use bit flags for efficient state management\n * - Provide async state tracking (idle/pending/resolved/rejected)\n *\n * @template T - The type of the computed value\n * @param fn - Computation function (can return T or Promise<T>)\n * @param options - Configuration options\n * @returns A readonly computed atom with automatic dependency tracking\n *\n * @example\n * ```ts\n * // Synchronous computed\n * const count = atom(0);\n * const doubled = computed(() => count.value * 2);\n *\n * // Asynchronous computed with default value\n * const userData = computed(\n * async () => fetch(`/api/user/${userId.value}`).then(r => r.json()),\n * { defaultValue: null }\n * );\n * ```\n */\nexport function computed<T>(fn: () => T, options?: ComputedOptions<T>): ComputedAtom<T>;\nexport function computed<T>(\n fn: () => Promise<T>,\n options: ComputedOptions<T> & { defaultValue: T }\n): ComputedAtom<T>;\nexport function computed<T>(\n fn: () => T | Promise<T>,\n options: ComputedOptions<T> = {}\n): ComputedAtom<T> {\n return new ComputedAtomImpl(fn, options) as unknown as ComputedAtom<T>;\n}\n","import type { ComputedAtom, EffectObject, ReadonlyAtom } from '../types';\nimport { debug } from './debug';\n\nexport function isAtom(obj: unknown): obj is ReadonlyAtom {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n 'value' in obj &&\n 'subscribe' in obj &&\n typeof (obj as Record<string, unknown>).subscribe === 'function'\n );\n}\n\nexport function isComputed(obj: unknown): obj is ComputedAtom {\n if (debug.enabled) {\n const debugType = debug.getDebugType(obj);\n if (debugType) {\n return debugType === 'computed';\n }\n }\n return (\n isAtom(obj) &&\n 'invalidate' in obj &&\n typeof (obj as Record<string, unknown>).invalidate === 'function'\n );\n}\n\nexport function isEffect(obj: unknown): obj is EffectObject {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n 'dispose' in obj &&\n 'run' in obj &&\n typeof (obj as Record<string, unknown>).dispose === 'function' &&\n typeof (obj as Record<string, unknown>).run === 'function'\n );\n}\n","/**\n * @fileoverview effect: Side effect management\n */\n\nimport { EFFECT_STATE_FLAGS, SCHEDULER_CONFIG } from '../../constants';\nimport { EffectError, isPromise, wrapError } from '../../errors/errors';\nimport { ERROR_MESSAGES } from '../../errors/messages';\nimport { scheduler } from '../../scheduler';\nimport { type DependencyTracker, trackingContext } from '../../tracking';\nimport { DependencyManager } from '../../tracking/dependency-manager';\nimport type { Dependency, EffectFunction, EffectObject, EffectOptions } from '../../types';\nimport { debug, generateId } from '../../utils/debug';\nimport { isAtom } from '../../utils/type-guards';\n\nclass EffectImpl implements EffectObject, DependencyTracker {\n private readonly _fn: EffectFunction;\n private readonly _sync: boolean;\n private readonly _maxExecutions: number;\n private readonly _trackModifications: boolean;\n private readonly _id: number;\n\n private _flags: number;\n private _cleanup: (() => void) | null;\n\n private readonly _depManager: DependencyManager;\n private readonly _modifiedDeps: Set<unknown>;\n private readonly _originalDescriptors: WeakMap<Dependency, PropertyDescriptor>;\n private readonly _trackedDeps: Set<Dependency>;\n\n private readonly _history: Float64Array;\n private _historyIdx: number;\n private _historyCount: number;\n private _executionCount: number;\n private readonly _historyCapacity: number;\n\n constructor(fn: EffectFunction, options: EffectOptions = {}) {\n this._fn = fn;\n this._sync = options.sync ?? false;\n this._maxExecutions =\n options.maxExecutionsPerSecond ?? SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_SECOND;\n this._trackModifications = options.trackModifications ?? false;\n this._id = generateId();\n\n this._flags = 0;\n this._cleanup = null;\n\n this._depManager = new DependencyManager();\n this._modifiedDeps = new Set();\n this._originalDescriptors = new WeakMap();\n this._trackedDeps = new Set();\n\n this._historyCapacity = this._maxExecutions + 5;\n this._history = new Float64Array(this._historyCapacity);\n this._historyIdx = 0;\n this._historyCount = 0;\n this._executionCount = 0;\n\n debug.attachDebugInfo(this, 'effect', this._id);\n }\n\n public run = (): void => {\n if (this.isDisposed) {\n throw new EffectError(ERROR_MESSAGES.EFFECT_MUST_BE_FUNCTION);\n }\n this.execute();\n };\n\n public dispose = (): void => {\n if (this.isDisposed) return;\n\n this._setDisposed();\n this._safeCleanup();\n this._depManager.unsubscribeAll();\n\n if (this._trackedDeps.size > 0) {\n this._trackedDeps.forEach((dep) => {\n const descriptor = this._originalDescriptors.get(dep);\n if (descriptor) {\n try {\n Object.defineProperty(dep, 'value', descriptor);\n } catch (_error) {\n debug.warn(true, 'Failed to restore original descriptor');\n }\n }\n });\n this._trackedDeps.clear();\n }\n };\n\n public addDependency = (dep: unknown): void => {\n try {\n const unsubscribe = (dep as Dependency).subscribe(() => {\n if (this._sync) {\n this.execute();\n } else {\n scheduler.schedule(this.execute);\n }\n });\n this._depManager.addDependency(dep as Dependency, unsubscribe);\n\n if (this._trackModifications && isAtom(dep)) {\n this._trackModificationsForDep(dep);\n }\n } catch (error) {\n throw wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_EXECUTION_FAILED);\n }\n };\n\n public execute = (): void => {\n if (this.isDisposed || this.isExecuting) return;\n\n const now = Date.now();\n this._recordExecution(now);\n\n this._setExecuting(true);\n this._safeCleanup();\n this._depManager.unsubscribeAll();\n this._modifiedDeps.clear();\n\n try {\n const result = trackingContext.run(this, this._fn);\n\n this._checkLoopWarnings();\n\n if (isPromise(result)) {\n result\n .then((asyncCleanup) => {\n if (!this.isDisposed && typeof asyncCleanup === 'function') {\n this._cleanup = asyncCleanup;\n }\n })\n .catch((error) => {\n console.error(wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_EXECUTION_FAILED));\n });\n } else {\n this._cleanup = typeof result === 'function' ? result : null;\n }\n } catch (error) {\n console.error(wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_EXECUTION_FAILED));\n this._cleanup = null;\n } finally {\n this._setExecuting(false);\n }\n };\n\n get isDisposed(): boolean {\n return (this._flags & EFFECT_STATE_FLAGS.DISPOSED) !== 0;\n }\n\n get executionCount(): number {\n return this._executionCount;\n }\n\n get isExecuting(): boolean {\n return (this._flags & EFFECT_STATE_FLAGS.EXECUTING) !== 0;\n }\n\n private _setDisposed(): void {\n this._flags |= EFFECT_STATE_FLAGS.DISPOSED;\n }\n\n private _setExecuting(value: boolean): void {\n if (value) this._flags |= EFFECT_STATE_FLAGS.EXECUTING;\n else this._flags &= ~EFFECT_STATE_FLAGS.EXECUTING;\n }\n\n private _safeCleanup(): void {\n if (this._cleanup && typeof this._cleanup === 'function') {\n try {\n this._cleanup();\n } catch (error) {\n console.error(wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_CLEANUP_FAILED));\n }\n this._cleanup = null;\n }\n }\n\n private _recordExecution(now: number): void {\n if (this._maxExecutions <= 0) return;\n\n const oneSecondAgo = now - 1000;\n\n this._history[this._historyIdx] = now;\n this._historyIdx = (this._historyIdx + 1) % this._historyCapacity;\n if (this._historyCount < this._historyCapacity) {\n this._historyCount++;\n }\n this._executionCount++;\n\n let count = 0;\n let idx = (this._historyIdx - 1 + this._historyCapacity) % this._historyCapacity;\n\n for (let i = 0; i < this._historyCount; i++) {\n if (this._history[idx]! < oneSecondAgo) {\n break;\n }\n count++;\n idx = (idx - 1 + this._historyCapacity) % this._historyCapacity;\n }\n\n if (count > this._maxExecutions) {\n const message = `Effect executed ${count} times within 1 second. Infinite loop suspected`;\n const error = new EffectError(message);\n\n this.dispose();\n console.error(error);\n\n if (debug.enabled) {\n throw error;\n }\n }\n }\n\n private _trackModificationsForDep(dep: any): void {\n const proto = Object.getPrototypeOf(dep);\n const originalDescriptor = Object.getOwnPropertyDescriptor(proto, 'value');\n if (originalDescriptor?.set && !this._originalDescriptors.has(dep)) {\n this._originalDescriptors.set(dep, originalDescriptor);\n this._trackedDeps.add(dep);\n\n const self = this;\n\n Object.defineProperty(dep, 'value', {\n set(newValue: unknown) {\n self._modifiedDeps.add(dep);\n originalDescriptor.set?.call(dep, newValue);\n },\n get() {\n return dep.peek();\n },\n configurable: true,\n enumerable: true,\n });\n }\n }\n\n private _checkLoopWarnings(): void {\n if (this._trackModifications && debug.enabled) {\n const dependencies = this._depManager.getDependencies();\n for (let i = 0; i < dependencies.length; i++) {\n const dep = dependencies[i]!;\n if (this._modifiedDeps.has(dep)) {\n debug.warn(\n true,\n `Effect is reading a dependency (${\n debug.getDebugName(dep) || 'unknown'\n }) that it just modified. Infinite loop may occur`\n );\n }\n }\n }\n }\n}\n\nexport function effect(fn: EffectFunction, options: EffectOptions = {}): EffectObject {\n if (typeof fn !== 'function') {\n throw new EffectError(ERROR_MESSAGES.EFFECT_MUST_BE_FUNCTION);\n }\n\n const effectInstance = new EffectImpl(fn, options);\n\n effectInstance.execute();\n\n return effectInstance;\n}\n"],"names":["AsyncState","EFFECT_STATE_FLAGS","COMPUTED_STATE_FLAGS","POOL_CONFIG","SCHEDULER_CONFIG","DEBUG_CONFIG","AtomError","message","cause","recoverable","ComputedError","EffectError","SchedulerError","wrapError","error","ErrorClass","context","errorMessage","isPromise","value","ERROR_MESSAGES","count","Scheduler","callback","callbacks","i","iterations","max","scheduler","batch","trackingContext","listener","fn","prev","DependencyManager","dep","unsubscribe","ref","liveDeps","threshold","untracked","DEBUG_NAME","DEBUG_ID","DEBUG_TYPE","NO_DEFAULT_VALUE","debug","condition","current","visited","dependencies","nestedDep","obj","type","id","target","nextId","generateId","AtomImpl","initialValue","sync","newValue","oldValue","currentVersion","fnWithDep","tracker","sub","subs","idx","isFn","lastIdx","doNotify","fnSubs","fnCount","objSubs","objCount","e","atom","options","SubscriberManager","subscriber","index","isUnsubscribed","lastIndex","lastSubscriber","onError","ComputedAtomImpl","equal","defaultValue","lazy","debugObj","result","states","newDependencies","tempMarkDirty","err","shouldUpdate","promise","promiseId","resolvedValue","callbackError","newDeps","existingSet","toRemove","toAdd","computed","isAtom","isComputed","debugType","isEffect","EffectImpl","descriptor","now","asyncCleanup","oneSecondAgo","proto","originalDescriptor","self","effect","effectInstance"],"mappings":"AAQO,MAAMA,IAAa;AAAA,EACxB,MAAM;AAAA,EACN,SAAS;AAAA,EACT,UAAU;AAAA,EACV,UAAU;AACZ,GAMaC,IAAqB;AAAA,EAChC,UAAU;AAAA;AAAA,EACV,WAAW;AAAA;AACb,GAMaC,IAAuB;AAAA,EAClC,OAAO;AAAA;AAAA,EACP,MAAM;AAAA;AAAA,EACN,SAAS;AAAA;AAAA,EACT,UAAU;AAAA;AAAA,EACV,UAAU;AAAA;AAAA,EACV,aAAa;AAAA;AAAA,EACb,WAAW;AAAA;AACb,GAMaC,IAAc;AAAA;AAAA,EAEzB,UAAU;AAAA;AAAA,EAEV,aAAa;AACf,GAMaC,IAAmB;AAAA;AAAA,EAE9B,2BAA2B;AAAA;AAAA,EAE3B,mBAAmB;AACrB,GAKaC,IAAe;AAAA;AAAA,EAE1B,kBAAkB;AAAA;AAAA,EAElB,oBAAoB;AACtB;AClDO,MAAMC,UAAkB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcnC,YAAYC,GAAiBC,IAAsB,MAAMC,IAAuB,IAAM;AACpF,UAAMF,CAAO,GACb,KAAK,OAAO,aACZ,KAAK,QAAQC,GACb,KAAK,cAAcC,GACnB,KAAK,gCAAgB,KAAA;AAAA,EACvB;AACF;AAQO,MAAMC,UAAsBJ,EAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM3C,YAAYC,GAAiBC,IAAsB,MAAM;AACvD,UAAMD,GAASC,GAAO,EAAI,GAC1B,KAAK,OAAO;AAAA,EACd;AACF;AAQO,MAAMG,UAAoBL,EAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMzC,YAAYC,GAAiBC,IAAsB,MAAM;AACvD,UAAMD,GAASC,GAAO,EAAK,GAC3B,KAAK,OA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UACA,mCACEA,EAAM,aAAaV,CAAG,KAAK,SAC7B;AAAA,QAAA;AAAA,MAGN;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAASkF,EAAOrF,GAAoB6C,IAAyB,IAAkB;AACpF,MAAI,OAAO7C,KAAO;AAChB,UAAM,IAAIrB,EAAYS,EAAe,uBAAuB;AAG9D,QAAMkG,IAAiB,IAAIT,EAAW7E,GAAI6C,CAAO;AAEjD,SAAAyC,EAAe,QAAA,GAERA;AACT;"}
1
+ {"version":3,"file":"index.mjs","sources":["../src/constants.ts","../src/errors/errors.ts","../src/errors/messages.ts","../src/scheduler/scheduler.ts","../src/scheduler/batch.ts","../src/tracking/context.ts","../src/tracking/dependency-manager.ts","../src/tracking/untracked.ts","../src/utils/debug.ts","../src/core/atom/atom.ts","../src/utils/subscriber-manager.ts","../src/core/computed/index.ts","../src/utils/type-guards.ts","../src/core/effect/effect.ts"],"sourcesContent":["/**\n * @fileoverview Constants and configuration for atom-effect library\n * @description Centralized constants for async states, bit flags, and performance tuning\n */\n\n/**\n * Async computation states for computed atoms\n */\nexport const AsyncState = {\n IDLE: 'idle' as const,\n PENDING: 'pending' as const,\n RESOLVED: 'resolved' as const,\n REJECTED: 'rejected' as const,\n};\n\n/**\n * Bit flags for effect state management\n * Using bit flags for efficient state checks (O(1) operations)\n */\nexport const EFFECT_STATE_FLAGS = {\n DISPOSED: 1 << 0, // 0001 - Effect has been disposed\n EXECUTING: 1 << 1, // 0010 - Effect is currently executing\n} as const;\n\n/**\n * Bit flags for computed atom state management\n * Enables fast state transitions and checks without multiple boolean fields\n */\nexport const COMPUTED_STATE_FLAGS = {\n DIRTY: 1 << 0, // 0001 - Needs recomputation\n IDLE: 1 << 1, // 0010 - Initial state, not computed yet\n PENDING: 1 << 2, // 0100 - Async computation in progress\n RESOLVED: 1 << 3, // 1000 - Successfully computed\n REJECTED: 1 << 4, // 10000 - Computation failed\n RECOMPUTING: 1 << 5, // 100000 - Currently recomputing\n HAS_ERROR: 1 << 6, // 1000000 - Has error state\n} as const;\n\n/**\n * Object pool configuration\n * Controls memory management and GC pressure reduction\n */\nexport const POOL_CONFIG = {\n /** Maximum number of pooled objects to prevent memory bloat */\n MAX_SIZE: 1000,\n /** Number of objects to pre-allocate for performance-critical paths */\n WARMUP_SIZE: 100,\n} as const;\n\n/**\n * Scheduler configuration\n * Controls batching behavior and performance limits\n */\nexport const SCHEDULER_CONFIG = {\n /** Maximum effect executions per second to detect infinite loops */\n MAX_EXECUTIONS_PER_SECOND: 100,\n /** Threshold for cleaning up old execution timestamps */\n CLEANUP_THRESHOLD: 100,\n} as const;\n\n/**\n * Debug configuration defaults\n */\nexport const DEBUG_CONFIG = {\n /** Maximum dependencies before warning about large dependency graphs */\n MAX_DEPENDENCIES: 1000,\n /** Enable infinite loop detection warnings */\n WARN_INFINITE_LOOP: true,\n} as const;\n","/**\n * @fileoverview Error class hierarchy for atom-effect library\n * @description Structured error classes with cause tracking and recoverability flags\n */\n\n/**\n * Base error class for all atom-effect errors\n *\n * Provides enhanced error information including:\n * - Original cause tracking for error chains\n * - Recoverability flag for error handling strategies\n * - Timestamp for debugging and logging\n *\n * @example\n * ```ts\n * throw new AtomError('Invalid state', originalError, false);\n * ```\n */\nexport class AtomError extends Error {\n /** Original error that caused this error, if any */\n cause: Error | null;\n /** Whether this error can be recovered from */\n recoverable: boolean;\n /** When this error occurred */\n timestamp: Date;\n\n /**\n * Creates a new AtomError\n * @param message - Error message describing what went wrong\n * @param cause - Original error that caused this error\n * @param recoverable - Whether the operation can be retried\n */\n constructor(message: string, cause: Error | null = null, recoverable: boolean = true) {\n super(message);\n this.name = 'AtomError';\n this.cause = cause;\n this.recoverable = recoverable;\n this.timestamp = new Date();\n }\n}\n\n/**\n * Error thrown during computed value computation\n *\n * Computed errors are considered recoverable by default since they typically\n * result from transient data issues rather than programming errors.\n */\nexport class ComputedError extends AtomError {\n /**\n * Creates a new ComputedError\n * @param message - Error message\n * @param cause - Original error\n */\n constructor(message: string, cause: Error | null = null) {\n super(message, cause, true);\n this.name = 'ComputedError';\n }\n}\n\n/**\n * Error thrown during effect execution\n *\n * Effect errors are considered non-recoverable by default since effects\n * typically represent critical side effects that shouldn't fail silently.\n */\nexport class EffectError extends AtomError {\n /**\n * Creates a new EffectError\n * @param message - Error message\n * @param cause - Original error\n */\n constructor(message: string, cause: Error | null = null) {\n super(message, cause, false);\n this.name = 'EffectError';\n }\n}\n\n/**\n * Error thrown by the scheduler system\n *\n * Scheduler errors indicate fundamental issues with the batching/scheduling\n * mechanism and are considered non-recoverable.\n */\nexport class SchedulerError extends AtomError {\n /**\n * Creates a new SchedulerError\n * @param message - Error message\n * @param cause - Original error\n */\n constructor(message: string, cause: Error | null = null) {\n super(message, cause, false);\n this.name = 'SchedulerError';\n }\n}\n\n/**\n * Wraps an unknown error in the appropriate AtomError subclass\n *\n * Provides consistent error handling by:\n * - Preserving original error information in the cause field\n * - Adding contextual information about where the error occurred\n * - Returning existing AtomErrors unchanged\n * - Handling various error types (TypeError, ReferenceError, etc.)\n *\n * @param error - Unknown error to wrap\n * @param ErrorClass - AtomError subclass to use for wrapping\n * @param context - Context string describing where the error occurred\n * @returns Wrapped error with contextual information\n *\n * @example\n * ```ts\n * try {\n * computeFn();\n * } catch (err) {\n * throw wrapError(err, ComputedError, 'computation phase');\n * }\n * ```\n */\nexport function wrapError(\n error: unknown,\n ErrorClass: typeof AtomError,\n context: string\n): AtomError {\n if (error instanceof TypeError) {\n return new ErrorClass(`Type error (${context}): ${error.message}`, error);\n }\n if (error instanceof ReferenceError) {\n return new ErrorClass(`Reference error (${context}): ${error.message}`, error);\n }\n if (error instanceof AtomError) {\n return error;\n }\n\n // Handle other error types\n const errorMessage = error instanceof Error ? error.message : String(error);\n const cause = error instanceof Error ? error : null;\n return new ErrorClass(`Unexpected error (${context}): ${errorMessage}`, cause);\n}\n\n/**\n * Type guard to check if a value is a Promise\n *\n * Uses duck-typing to detect Promise-like objects by checking for\n * the presence of a `then` method.\n *\n * @template T - The type the Promise resolves to\n * @param value - Value to check\n * @returns True if value has a `then` method (is Promise-like)\n *\n * @example\n * ```ts\n * const result = computeFn();\n * if (isPromise(result)) {\n * await result;\n * }\n * ```\n */\nexport function isPromise<T>(value: unknown): value is Promise<T> {\n return (\n value !== null &&\n value !== undefined &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n","/**\n * @fileoverview Centralized error messages for better maintainability\n * @description All error messages in English for international accessibility\n * @module errors/messages\n */\n\n/**\n * Centralized error message constants for the atom-effect library.\n *\n * @description\n * Provides consistent, maintainable error messages across the library.\n * All messages are in English for international accessibility.\n *\n * @remarks\n * - Computed errors: Related to computed atom creation and execution\n * - Atom errors: Related to atom subscription and notification\n * - Effect errors: Related to effect lifecycle and cleanup\n * - Debug warnings: Non-critical warnings for debugging\n *\n * @example\n * ```ts\n * import { ERROR_MESSAGES } from './messages';\n *\n * if (typeof fn !== 'function') {\n * throw new Error(ERROR_MESSAGES.COMPUTED_MUST_BE_FUNCTION);\n * }\n * ```\n */\nexport const ERROR_MESSAGES = {\n // ─────────────────────────────────────────────────────────────────\n // Computed errors\n // ─────────────────────────────────────────────────────────────────\n\n /**\n * Error thrown when computed() receives a non-function argument.\n */\n COMPUTED_MUST_BE_FUNCTION: 'Computed function must be a function',\n\n /**\n * Error thrown when subscribe() receives a non-function listener.\n */\n COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION: 'Subscriber listener must be a function',\n\n /**\n * Error thrown when accessing a pending async computed without a default value.\n */\n COMPUTED_ASYNC_PENDING_NO_DEFAULT: 'Async computation is pending. No default value provided',\n\n /**\n * Error thrown when a synchronous computed computation fails.\n */\n COMPUTED_COMPUTATION_FAILED: 'Computed computation failed',\n\n /**\n * Error thrown when an asynchronous computed computation fails.\n */\n COMPUTED_ASYNC_COMPUTATION_FAILED: 'Async computed computation failed',\n\n /**\n * Error thrown when subscribing to a dependency fails.\n */\n COMPUTED_DEPENDENCY_SUBSCRIPTION_FAILED: 'Failed to subscribe to dependency',\n\n // ─────────────────────────────────────────────────────────────────\n // Atom errors\n // ─────────────────────────────────────────────────────────────────\n\n /**\n * Error thrown when atom.subscribe() receives a non-function listener.\n */\n ATOM_SUBSCRIBER_MUST_BE_FUNCTION: 'Subscription listener must be a function',\n\n /**\n * Error thrown when the atom subscriber notification process fails.\n */\n ATOM_SUBSCRIBER_EXECUTION_FAILED: 'Error occurred while executing atom subscribers',\n\n /**\n * Error logged when an individual subscriber throws during notification.\n * @remarks This error is caught and logged to prevent cascading failures.\n */\n ATOM_INDIVIDUAL_SUBSCRIBER_FAILED: 'Error during individual atom subscriber execution',\n\n // ─────────────────────────────────────────────────────────────────\n // Effect errors\n // ─────────────────────────────────────────────────────────────────\n\n /**\n * Error thrown when effect() receives a non-function argument.\n */\n EFFECT_MUST_BE_FUNCTION: 'Effect function must be a function',\n\n /**\n * Error thrown when an effect's execution fails.\n */\n EFFECT_EXECUTION_FAILED: 'Effect execution failed',\n\n /**\n * Error thrown when an effect's cleanup function fails.\n */\n EFFECT_CLEANUP_FAILED: 'Effect cleanup function execution failed',\n\n // ─────────────────────────────────────────────────────────────────\n // Debug warnings\n // ─────────────────────────────────────────────────────────────────\n\n /**\n * Warning message for large dependency graphs.\n *\n * @param count - The number of dependencies detected\n * @returns Formatted warning message with dependency count\n *\n * @example\n * ```ts\n * console.warn(ERROR_MESSAGES.LARGE_DEPENDENCY_GRAPH(150));\n * // Output: \"Large dependency graph detected: 150 dependencies\"\n * ```\n */\n LARGE_DEPENDENCY_GRAPH: (count: number): string =>\n `Large dependency graph detected: ${count} dependencies`,\n\n /**\n * Warning logged when attempting to unsubscribe a non-existent listener.\n */\n UNSUBSCRIBE_NON_EXISTENT: 'Attempted to unsubscribe a non-existent listener',\n\n /**\n * Error logged when the onError callback itself throws an error.\n * @remarks This prevents cascading failures from masking the original error.\n */\n CALLBACK_ERROR_IN_ERROR_HANDLER: 'Error occurred during onError callback execution',\n} as const;\n","import { SchedulerError } from '../errors/errors';\n\n/**\n * Scheduler for managing reactive updates and batching operations.\n *\n * The Scheduler is responsible for coordinating when reactive computations\n * are executed. It supports both immediate (microtask) execution and\n * batched synchronous execution for optimal performance.\n *\n * Key features:\n * - Deduplication of callbacks via Set\n * - Nested batch support with depth tracking\n * - Infinite loop protection with configurable iteration limit\n * - Error isolation to prevent one callback from breaking others\n *\n * @example\n * ```typescript\n * // Schedule a callback for microtask execution\n * scheduler.schedule(() => console.log('Updated!'));\n *\n * // Batch multiple updates\n * scheduler.startBatch();\n * scheduler.schedule(() => console.log('Update 1'));\n * scheduler.schedule(() => console.log('Update 2'));\n * scheduler.endBatch(); // Both execute synchronously here\n * ```\n */\nclass Scheduler {\n /** Queue of callbacks waiting for microtask execution */\n private queue: Set<() => void> = new Set();\n\n /** Whether the scheduler is currently processing the queue */\n private isProcessing: boolean = false;\n\n /** Whether batching is currently active */\n public isBatching: boolean = false;\n\n /** Current nesting depth of batch operations */\n private batchDepth: number = 0;\n\n /** Array of callbacks queued during batching */\n private batchQueue: Array<() => void> = [];\n\n /** Current size of the batch queue (for array reuse) */\n private batchQueueSize = 0;\n\n /** Whether synchronous flush is in progress */\n private isFlushingSync: boolean = false;\n\n /** Maximum iterations allowed during flush to prevent infinite loops */\n private maxFlushIterations: number = 1000;\n\n /**\n * Schedules a callback for execution.\n *\n * If batching is active or a sync flush is in progress, the callback\n * is added to the batch queue. Otherwise, it's added to the main queue\n * and a flush is triggered via microtask.\n *\n * @param callback - The function to schedule for execution\n * @throws {SchedulerError} If callback is not a function\n *\n * @example\n * ```typescript\n * scheduler.schedule(() => {\n * // This runs in the next microtask (or sync if batching)\n * updateUI();\n * });\n * ```\n */\n schedule(callback: () => void): void {\n if (typeof callback !== 'function') {\n throw new SchedulerError('Scheduler callback must be a function');\n }\n\n if (this.isBatching || this.isFlushingSync) {\n this.batchQueue[this.batchQueueSize++] = callback;\n } else {\n this.queue.add(callback);\n if (!this.isProcessing) {\n this.flush();\n }\n }\n }\n\n /**\n * Flushes the queue asynchronously via microtask.\n *\n * Executes all queued callbacks in a microtask, allowing the current\n * synchronous execution to complete first. Errors in individual\n * callbacks are caught and logged without interrupting others.\n *\n * @private\n * @remarks\n * This method is idempotent - calling it multiple times while\n * processing is active has no effect.\n */\n private flush(): void {\n if (this.isProcessing || this.queue.size === 0) return;\n\n this.isProcessing = true;\n const callbacks = Array.from(this.queue);\n this.queue.clear();\n\n queueMicrotask(() => {\n for (let i = 0; i < callbacks.length; i++) {\n try {\n callbacks[i]?.();\n } catch (error) {\n console.error(\n new SchedulerError('Error occurred during scheduler execution', error as Error)\n );\n }\n }\n\n this.isProcessing = false;\n\n if (this.queue.size > 0 && !this.isBatching) {\n this.flush();\n }\n });\n }\n\n /**\n * Flushes all queued callbacks synchronously.\n *\n * This method is called when a batch ends. It processes all callbacks\n * in the batch queue and main queue synchronously, allowing callbacks\n * to schedule additional callbacks that are processed in the same flush.\n *\n * @private\n * @remarks\n * - Includes infinite loop protection via maxFlushIterations\n * - Errors in callbacks are caught and logged individually\n * - The isFlushingSync flag prevents re-entrancy issues\n */\n private flushSync(): void {\n this.isFlushingSync = true;\n\n try {\n if (this.batchQueueSize > 0) {\n for (let i = 0; i < this.batchQueueSize; i++) {\n this.queue.add(this.batchQueue[i]!);\n }\n this.batchQueueSize = 0;\n }\n\n let iterations = 0;\n\n while (this.queue.size > 0) {\n if (++iterations > this.maxFlushIterations) {\n console.error(\n new SchedulerError(\n `Maximum flush iterations (${this.maxFlushIterations}) exceeded. ` +\n `Possible infinite loop in reactive dependencies. ` +\n `Consider increasing the limit with scheduler.setMaxFlushIterations()`\n )\n );\n this.queue.clear();\n this.batchQueueSize = 0;\n break;\n }\n\n const callbacks = Array.from(this.queue);\n this.queue.clear();\n\n for (let i = 0; i < callbacks.length; i++) {\n try {\n callbacks[i]?.();\n } catch (error) {\n console.error(\n new SchedulerError('Error occurred during batch execution', error as Error)\n );\n }\n }\n\n if (this.batchQueueSize > 0) {\n for (let i = 0; i < this.batchQueueSize; i++) {\n this.queue.add(this.batchQueue[i]!);\n }\n this.batchQueueSize = 0;\n }\n }\n } finally {\n this.isFlushingSync = false;\n }\n }\n\n /**\n * Starts a new batch operation.\n *\n * While batching is active, all scheduled callbacks are deferred\n * until endBatch() is called. Batches can be nested - only the\n * outermost endBatch() triggers execution.\n *\n * @example\n * ```typescript\n * scheduler.startBatch();\n * // All updates here are deferred\n * atom1.value = 'a';\n * atom2.value = 'b';\n * scheduler.endBatch(); // Both updates processed together\n * ```\n */\n startBatch(): void {\n this.batchDepth++;\n this.isBatching = true;\n }\n\n /**\n * Ends a batch operation.\n *\n * Decrements the batch depth counter. When depth reaches zero,\n * all queued callbacks are flushed synchronously and batching\n * is disabled.\n *\n * @remarks\n * Safe to call even if startBatch() wasn't called - depth is\n * clamped to zero minimum.\n *\n * @example\n * ```typescript\n * scheduler.startBatch();\n * try {\n * // ... batched operations\n * } finally {\n * scheduler.endBatch(); // Always end batch, even on error\n * }\n * ```\n */\n endBatch(): void {\n this.batchDepth = Math.max(0, this.batchDepth - 1);\n\n if (this.batchDepth === 0) {\n this.flushSync();\n this.isBatching = false;\n }\n }\n\n /**\n * Sets the maximum number of flush iterations allowed.\n *\n * This limit prevents infinite loops when reactive dependencies\n * form cycles. If exceeded, the queue is cleared and an error\n * is logged.\n *\n * @param max - Maximum iterations (must be at least 10)\n * @throws {SchedulerError} If max is less than 10\n *\n * @example\n * ```typescript\n * // Increase limit for complex dependency graphs\n * scheduler.setMaxFlushIterations(5000);\n * ```\n */\n setMaxFlushIterations(max: number): void {\n if (max < 10) {\n throw new SchedulerError('Max flush iterations must be at least 10');\n }\n this.maxFlushIterations = max;\n }\n}\n\n/** Global scheduler instance for reactive updates */\nexport const scheduler = new Scheduler();\n","import { AtomError } from '../errors/errors';\nimport { scheduler } from './scheduler';\n\n/**\n * Executes multiple reactive updates in a single batch.\n *\n * Batching groups multiple state changes together, deferring notifications\n * until all updates are complete. This prevents intermediate states from\n * triggering unnecessary recomputations and improves performance.\n *\n * @template T - The return type of the callback function\n * @param callback - The function containing batched updates\n * @returns The result of the callback function\n * @throws {AtomError} If the callback is not a function\n * @throws {AtomError} If an error occurs during batch execution\n *\n * @example\n * ```typescript\n * const firstName = atom('John');\n * const lastName = atom('Doe');\n *\n * // Without batching: triggers 2 separate updates\n * firstName.value = 'Jane';\n * lastName.value = 'Smith';\n *\n * // With batching: triggers 1 combined update\n * batch(() => {\n * firstName.value = 'Jane';\n * lastName.value = 'Smith';\n * });\n * ```\n */\nexport function batch<T>(callback: () => T): T {\n if (typeof callback !== 'function') {\n throw new AtomError('Batch callback must be a function');\n }\n\n scheduler.startBatch();\n\n try {\n return callback();\n } catch (error) {\n throw new AtomError('Error occurred during batch execution', error as Error);\n } finally {\n scheduler.endBatch();\n }\n}\n","import type { Listener } from './tracking.types';\n\n/**\n * Interface for the tracking context that manages dependency tracking.\n *\n * The tracking context is responsible for maintaining the current listener\n * during reactive computations, enabling automatic dependency collection.\n *\n * @interface TrackingContext\n */\nexport interface TrackingContext {\n /**\n * The currently active listener being tracked.\n * `null` when no tracking is in progress.\n */\n current: Listener | null;\n\n /**\n * Executes a function within a tracking context.\n *\n * Sets the provided listener as the current tracking target,\n * executes the function, and restores the previous context.\n *\n * @template T - The return type of the function\n * @param listener - The listener to set as current during execution\n * @param fn - The function to execute within the tracking context\n * @returns The result of the executed function\n *\n * @example\n * ```typescript\n * const result = trackingContext.run(myListener, () => {\n * // Any atom access here will be tracked\n * return someAtom.value + otherAtom.value;\n * });\n * ```\n */\n run<T>(listener: Listener, fn: () => T): T;\n\n /**\n * Gets the currently active listener.\n *\n * @returns The current listener or `null` if no tracking is active\n *\n * @example\n * ```typescript\n * const current = trackingContext.getCurrent();\n * if (current) {\n * // Dependency tracking is active\n * }\n * ```\n */\n getCurrent(): Listener | null;\n}\n\n/**\n * Global tracking context singleton for dependency tracking.\n *\n * This object manages the current listener during reactive computations,\n * enabling atoms and computed values to automatically track their dependencies.\n *\n * @remarks\n * - The context uses a stack-like behavior via the `run` method\n * - Nested `run` calls properly restore the previous context\n * - Thread-safe within a single JavaScript execution context\n *\n * @example\n * ```typescript\n * // Setting up tracking for a computed value\n * const value = trackingContext.run(computedListener, () => {\n * return atom1.value + atom2.value; // Both atoms are tracked\n * });\n *\n * // Checking if tracking is active\n * if (trackingContext.getCurrent()) {\n * // Register this atom as a dependency\n * }\n * ```\n */\nexport const trackingContext: TrackingContext = {\n /** @inheritdoc */\n current: null,\n\n /**\n * @inheritdoc\n * @throws Re-throws any error from the executed function after restoring context\n */\n run<T>(listener: Listener, fn: () => T): T {\n const prev = this.current;\n this.current = listener;\n try {\n return fn();\n } finally {\n this.current = prev;\n }\n },\n\n /** @inheritdoc */\n getCurrent(): Listener | null {\n return this.current;\n },\n};\n","import type { Dependency } from '../types';\n\n/**\n * Manages reactive dependencies with automatic cleanup and memory-efficient tracking.\n *\n * This class provides a centralized way to track dependencies between reactive\n * primitives (atoms, computed values) and their subscribers. It uses WeakRef\n * and WeakMap for memory-efficient storage that allows garbage collection\n * of unused dependencies.\n *\n * @remarks\n * - Uses WeakMap for O(1) lookup and automatic GC of unreferenced dependencies\n * - Uses WeakRef array for iteration while allowing GC\n * - Periodic cleanup removes stale WeakRefs to prevent memory leaks\n * - Thread-safe for single-threaded JavaScript execution\n *\n * @example\n * ```typescript\n * const manager = new DependencyManager();\n *\n * // Add a dependency with its unsubscribe callback\n * const unsubscribe = atom.subscribe(() => recompute());\n * manager.addDependency(atom, unsubscribe);\n *\n * // Check if dependency exists\n * if (manager.hasDependency(atom)) {\n * console.log('Dependency tracked');\n * }\n *\n * // Remove specific dependency\n * manager.removeDependency(atom);\n *\n * // Clean up all dependencies\n * manager.unsubscribeAll();\n * ```\n */\nexport class DependencyManager {\n /**\n * WeakMap storing dependency -> unsubscribe function mappings.\n * Allows O(1) lookup and automatic garbage collection.\n */\n private depMap = new WeakMap<Dependency, () => void>();\n\n /**\n * Array of WeakRefs for iteration over live dependencies.\n * WeakRefs allow the referenced objects to be garbage collected.\n */\n private depRefs: WeakRef<Dependency>[] = [];\n\n /**\n * Number of additions before triggering automatic cleanup.\n * @defaultValue 100\n */\n private cleanupThreshold = 100;\n\n /**\n * Counter tracking additions since last cleanup.\n */\n private addCount = 0;\n\n /**\n * Adds a dependency with its associated unsubscribe callback.\n *\n * If the dependency already exists, the new unsubscribe callback is\n * immediately called to prevent duplicate subscriptions.\n *\n * @param dep - The dependency to track (atom, computed, etc.)\n * @param unsubscribe - Callback to invoke when removing the dependency\n *\n * @remarks\n * - Duplicate dependencies are rejected with immediate unsubscribe\n * - Automatic cleanup is triggered every `cleanupThreshold` additions\n * - Time complexity: O(1) for add, O(n) when cleanup triggers\n *\n * @example\n * ```typescript\n * const unsubscribe = atom.subscribe(() => markDirty());\n * manager.addDependency(atom, unsubscribe);\n * ```\n */\n addDependency(dep: Dependency, unsubscribe: () => void): void {\n if (this.depMap.has(dep)) {\n unsubscribe();\n return;\n }\n\n this.depMap.set(dep, unsubscribe);\n this.depRefs.push(new WeakRef(dep));\n\n if (++this.addCount >= this.cleanupThreshold) {\n this.cleanup();\n this.addCount = 0;\n }\n }\n\n /**\n * Removes a dependency and calls its unsubscribe callback.\n *\n * @param dep - The dependency to remove\n * @returns `true` if the dependency was found and removed, `false` otherwise\n *\n * @remarks\n * - Unsubscribe errors are caught and logged to prevent cascading failures\n * - The WeakRef entry is not immediately removed (cleaned up lazily)\n * - Time complexity: O(1)\n *\n * @example\n * ```typescript\n * const wasRemoved = manager.removeDependency(atom);\n * if (wasRemoved) {\n * console.log('Dependency successfully removed');\n * }\n * ```\n */\n removeDependency(dep: Dependency): boolean {\n const unsubscribe = this.depMap.get(dep);\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch (error) {\n console.warn('[DependencyManager] Error during unsubscribe:', error);\n }\n this.depMap.delete(dep);\n return true;\n }\n return false;\n }\n\n /**\n * Checks if a dependency is currently being tracked.\n *\n * @param dep - The dependency to check\n * @returns `true` if the dependency exists in the manager\n *\n * @remarks\n * Time complexity: O(1)\n *\n * @example\n * ```typescript\n * if (manager.hasDependency(atom)) {\n * // Dependency is already tracked\n * }\n * ```\n */\n hasDependency(dep: Dependency): boolean {\n return this.depMap.has(dep);\n }\n\n /**\n * Removes all dependencies and calls their unsubscribe callbacks.\n *\n * This method iterates through all tracked dependencies, calls their\n * unsubscribe callbacks, and clears internal storage.\n *\n * @remarks\n * - Errors during unsubscribe are caught and logged individually\n * - Safe to call multiple times (idempotent after first call)\n * - Time complexity: O(n) where n is the number of dependencies\n *\n * @example\n * ```typescript\n * // Clean up when disposing a computed value\n * manager.unsubscribeAll();\n * ```\n */\n unsubscribeAll(): void {\n for (let i = 0; i < this.depRefs.length; i++) {\n const dep = this.depRefs[i]!.deref();\n if (dep) {\n const unsubscribe = this.depMap.get(dep);\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch (error) {\n console.warn('[DependencyManager] Error during unsubscribe:', error);\n }\n this.depMap.delete(dep);\n }\n }\n }\n this.depRefs.length = 0;\n this.addCount = 0;\n }\n\n /**\n * Removes stale WeakRefs from the internal array.\n *\n * WeakRefs whose targets have been garbage collected are filtered out\n * to prevent unbounded growth of the depRefs array.\n *\n * @remarks\n * - Called automatically every `cleanupThreshold` additions\n * - Can be called manually for immediate cleanup\n * - Time complexity: O(n) where n is the number of WeakRefs\n *\n * @example\n * ```typescript\n * // Force immediate cleanup\n * manager.cleanup();\n * ```\n */\n cleanup(): void {\n this.depRefs = this.depRefs.filter((ref) => ref.deref() !== undefined);\n }\n\n /**\n * Gets the current number of live dependencies.\n *\n * @returns The count of dependencies that haven't been garbage collected\n *\n * @remarks\n * - Triggers cleanup before counting for accurate results\n * - Time complexity: O(n) due to cleanup\n *\n * @example\n * ```typescript\n * console.log(`Tracking ${manager.count} dependencies`);\n * ```\n */\n get count(): number {\n this.cleanup();\n return this.depRefs.length;\n }\n\n /**\n * Gets an array of all live dependencies.\n *\n * @returns Array of dependencies that haven't been garbage collected\n *\n * @remarks\n * - Returns a new array (safe to modify)\n * - Does not trigger cleanup (may include some stale refs)\n * - Time complexity: O(n)\n *\n * @example\n * ```typescript\n * const deps = manager.getDependencies();\n * deps.forEach(dep => console.log(dep));\n * ```\n */\n getDependencies(): Dependency[] {\n const liveDeps: Dependency[] = [];\n for (let i = 0; i < this.depRefs.length; i++) {\n const dep = this.depRefs[i]!.deref();\n if (dep !== undefined) {\n liveDeps.push(dep);\n }\n }\n return liveDeps;\n }\n\n /**\n * Gets the internal WeakMap for advanced use cases.\n *\n * @returns The internal dependency -> unsubscribe WeakMap\n *\n * @remarks\n * - Returns the actual internal map (not a copy)\n * - Modifications will affect the manager's state\n * - Use with caution in production code\n *\n * @example\n * ```typescript\n * const map = manager.getDepMap();\n * const unsubscribe = map.get(someDependency);\n * ```\n */\n getDepMap(): WeakMap<Dependency, () => void> {\n return this.depMap;\n }\n\n /**\n * Sets the threshold for automatic cleanup triggering.\n *\n * @param threshold - Number of additions before cleanup (minimum 1)\n *\n * @remarks\n * - Lower values mean more frequent cleanup (less memory, more CPU)\n * - Higher values mean less frequent cleanup (more memory, less CPU)\n * - Default is 100, suitable for most use cases\n *\n * @example\n * ```typescript\n * // More aggressive cleanup for memory-constrained environments\n * manager.setCleanupThreshold(50);\n *\n * // Less frequent cleanup for performance-critical paths\n * manager.setCleanupThreshold(500);\n * ```\n */\n setCleanupThreshold(threshold: number): void {\n this.cleanupThreshold = Math.max(1, threshold);\n }\n}\n","import { AtomError } from '../errors/errors';\nimport { trackingContext } from './context';\n\n/**\n * Executes a function without tracking any reactive dependencies.\n *\n * This utility allows reading atom values without establishing\n * a dependency relationship, useful for accessing values that\n * shouldn't trigger recomputation when they change.\n *\n * @template T - The return type of the function\n * @param fn - The function to execute without tracking\n * @returns The result of the executed function\n * @throws {AtomError} If the callback is not a function\n * @throws {AtomError} If an error occurs during execution\n *\n * @example\n * ```typescript\n * const count = atom(0);\n * const doubled = computed(() => {\n * // This read will NOT be tracked as a dependency\n * const untrackedValue = untracked(() => count.value);\n * return untrackedValue * 2;\n * });\n * ```\n */\nexport function untracked<T>(fn: () => T): T {\n if (typeof fn !== 'function') {\n throw new AtomError('Untracked callback must be a function');\n }\n\n const prev = trackingContext.current;\n trackingContext.current = null;\n\n try {\n return fn();\n } catch (error) {\n throw new AtomError('Error occurred during untracked execution', error as Error);\n } finally {\n trackingContext.current = prev;\n }\n}\n","/**\n * @fileoverview Debug configuration and utilities\n *\n * This module provides development-time debugging tools for dependency tracking\n * and circular reference detection in the reactive state management system.\n *\n * @module utils/debug\n * @see {@link DebugConfig} for the configuration interface\n */\n\nimport { DEBUG_CONFIG } from '../constants';\nimport { ComputedError } from '../errors/errors';\nimport type { DebugConfig } from '../types';\n\n/**\n * Symbol key for storing debug display name on reactive objects.\n *\n * @remarks\n * Using symbols prevents property name collisions with user-defined properties.\n *\n * @example\n * ```typescript\n * const atom = createAtom(0);\n * console.log(atom[DEBUG_NAME]); // \"atom_1\"\n * ```\n */\nexport const DEBUG_NAME: unique symbol = Symbol('debugName');\n\n/**\n * Symbol key for storing unique identifier on reactive objects.\n *\n * @remarks\n * Each reactive object (atom, computed, effect) receives a unique numeric ID\n * for debugging and tracking purposes.\n */\nexport const DEBUG_ID: unique symbol = Symbol('id');\n\n/**\n * Symbol key for storing the type discriminator on reactive objects.\n *\n * @remarks\n * Possible values: 'atom' | 'computed' | 'effect'\n */\nexport const DEBUG_TYPE: unique symbol = Symbol('type');\n\n/**\n * Sentinel value to distinguish \"no default value provided\" from `undefined`.\n *\n * @remarks\n * This allows computed values to differentiate between:\n * - User explicitly passing `undefined` as default\n * - User not providing any default value\n *\n * @example\n * ```typescript\n * const hasDefault = options.defaultValue !== NO_DEFAULT_VALUE;\n * ```\n */\nexport const NO_DEFAULT_VALUE: unique symbol = Symbol('noDefaultValue');\n\n/**\n * Type guard for objects with a dependencies property.\n *\n * @param obj - The object to check\n * @returns True if the object has a Set-typed dependencies property\n *\n * @internal\n */\nfunction hasDependencies(obj: unknown): obj is { dependencies: Set<unknown> } {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n 'dependencies' in obj &&\n (obj as { dependencies: unknown }).dependencies instanceof Set\n );\n}\n\n/**\n * Debug configuration instance with runtime utilities.\n *\n * Provides development-time features including:\n * - Circular dependency detection (direct and indirect)\n * - Large dependency graph warnings\n * - Debug metadata attachment for inspection\n *\n * @remarks\n * Most features are only active when `NODE_ENV === 'development'`\n * to avoid performance overhead in production builds.\n *\n * @example\n * ```typescript\n * // Check for circular dependencies\n * debug.checkCircular(dependencyAtom, computedAtom);\n *\n * // Warn about potential issues\n * debug.warn(count > 100, 'Large dependency count detected');\n *\n * // Attach debug info to a reactive object\n * debug.attachDebugInfo(atom, 'atom', 42);\n * ```\n */\nexport const debug: DebugConfig = {\n /**\n * Whether debug mode is enabled.\n *\n * @remarks\n * Automatically set based on `NODE_ENV` environment variable.\n * Only `'development'` enables debug features.\n */\n enabled:\n typeof process !== 'undefined' && (process as NodeJS.Process).env?.NODE_ENV === 'development',\n\n /**\n * Maximum number of dependencies before warning.\n *\n * @see {@link DEBUG_CONFIG.MAX_DEPENDENCIES}\n */\n maxDependencies: DEBUG_CONFIG.MAX_DEPENDENCIES,\n\n /**\n * Whether to warn about potential infinite loops.\n *\n * @see {@link DEBUG_CONFIG.WARN_INFINITE_LOOP}\n */\n warnInfiniteLoop: DEBUG_CONFIG.WARN_INFINITE_LOOP,\n\n /**\n * Logs a warning message when condition is true and debug is enabled.\n *\n * @param condition - When true, the warning is logged\n * @param message - The warning message to display\n *\n * @example\n * ```typescript\n * debug.warn(deps.length > 100, 'Large dependency graph detected');\n * ```\n */\n warn(condition: boolean, message: string): void {\n if (this.enabled && condition) {\n console.warn(`[Atom Effect] ${message}`);\n }\n },\n\n /**\n * Checks for circular dependencies in the dependency graph.\n *\n * Detects two types of circular references:\n * 1. **Direct**: A depends on itself (A → A)\n * 2. **Indirect**: A depends on B which depends on A (A → B → A)\n *\n * @param dep - The dependency being added\n * @param current - The current reactive object adding the dependency\n * @param visited - Set of already visited nodes (for recursion)\n *\n * @throws {ComputedError} When a circular dependency is detected\n *\n * @remarks\n * - Direct circular detection runs in all environments\n * - Indirect circular detection only runs in development mode\n * - Uses depth-first traversal with O(n) time complexity\n *\n * @example\n * ```typescript\n * // This will throw for direct circular reference\n * debug.checkCircular(computedA, computedA);\n *\n * // This will throw for indirect circular reference (dev only)\n * // Given: A → B → C → A\n * debug.checkCircular(computedC, computedA);\n * ```\n */\n checkCircular(dep: unknown, current: unknown, visited = new Set<unknown>()): void {\n // Direct circular reference check (A→A) - Always checked even in production\n if (dep === current) {\n throw new ComputedError('Direct circular dependency detected');\n }\n\n // Indirect circular reference check only in development mode (for performance)\n if (!this.enabled) {\n return;\n }\n\n // Indirect circular reference check (A→B→C→A)\n if (visited.has(dep)) {\n throw new ComputedError('Indirect circular dependency detected');\n }\n\n visited.add(dep);\n\n // Recursively check nested dependencies using type guard\n if (hasDependencies(dep)) {\n for (const nestedDep of dep.dependencies) {\n this.checkCircular(nestedDep, current, visited);\n }\n }\n },\n\n /**\n * Attaches debug metadata to a reactive object.\n *\n * @param obj - The object to attach metadata to\n * @param type - The type of reactive object ('atom' | 'computed' | 'effect')\n * @param id - The unique identifier for this object\n *\n * @remarks\n * Only attaches metadata when debug mode is enabled.\n * Uses symbol keys to avoid property name collisions.\n *\n * @example\n * ```typescript\n * const atom = createAtomInternal(0);\n * debug.attachDebugInfo(atom, 'atom', 1);\n * // atom[DEBUG_NAME] === 'atom_1'\n * // atom[DEBUG_ID] === 1\n * // atom[DEBUG_TYPE] === 'atom'\n * ```\n */\n attachDebugInfo(obj: object, type: string, id: number): void {\n if (!this.enabled) {\n return;\n }\n\n const target = obj as Record<symbol, unknown>;\n target[DEBUG_NAME] = `${type}_${id}`;\n target[DEBUG_ID] = id;\n target[DEBUG_TYPE] = type;\n },\n\n /**\n * Retrieves the debug display name from a reactive object.\n *\n * @param obj - The object to get the name from\n * @returns The debug name (e.g., 'atom_1') or undefined if not set\n *\n * @example\n * ```typescript\n * const name = debug.getDebugName(myAtom);\n * console.log(`Updating ${name ?? 'unknown'}`);\n * ```\n */\n getDebugName(obj: unknown): string | undefined {\n if (obj !== null && typeof obj === 'object' && DEBUG_NAME in obj) {\n return (obj as Record<symbol, unknown>)[DEBUG_NAME] as string | undefined;\n }\n return undefined;\n },\n\n /**\n * Retrieves the debug type from a reactive object.\n *\n * @param obj - The object to get the type from\n * @returns The type ('atom' | 'computed' | 'effect') or undefined if not set\n *\n * @example\n * ```typescript\n * const type = debug.getDebugType(reactiveObj);\n * if (type === 'computed') {\n * // Handle computed-specific logic\n * }\n * ```\n */\n getDebugType(obj: unknown): string | undefined {\n if (obj !== null && typeof obj === 'object' && DEBUG_TYPE in obj) {\n return (obj as Record<symbol, unknown>)[DEBUG_TYPE] as string | undefined;\n }\n return undefined;\n },\n};\n\n/**\n * Counter for generating unique IDs.\n *\n * @internal\n */\nlet nextId = 1;\n\n/**\n * Generates a unique numeric identifier for reactive objects.\n *\n * @returns A unique positive integer, incrementing with each call\n *\n * @remarks\n * IDs are globally unique within a single runtime session.\n * The counter resets when the module is reloaded.\n *\n * @example\n * ```typescript\n * const atomId = generateId(); // 1\n * const computedId = generateId(); // 2\n * ```\n */\nexport const generateId = (): number => nextId++;\n","/**\n * @fileoverview atom: Core reactive state primitive\n *\n * Atoms are the fundamental building blocks of the reactive system.\n * They hold mutable state and automatically notify subscribers when their value changes.\n *\n * @example\n * ```ts\n * const count = atom(0);\n * count.value = 1; // Triggers subscribers\n * console.log(count.peek()); // 1 (without tracking)\n * ```\n */\n\nimport { AtomError } from '../../errors/errors';\nimport { ERROR_MESSAGES } from '../../errors/messages';\nimport { scheduler } from '../../scheduler';\nimport { trackingContext } from '../../tracking';\nimport type { AtomOptions, WritableAtom } from '../../types';\nimport { debug, generateId } from '../../utils/debug';\n\n/**\n * Internal implementation of the WritableAtom interface.\n *\n * @template T - The type of value stored in the atom\n *\n * @remarks\n * This class manages reactive state with optimized subscriber management.\n * It supports both function-based and object-based subscribers, and handles\n * synchronous or batched notifications based on configuration.\n */\nclass AtomImpl<T> implements WritableAtom<T> {\n /** Current value stored in the atom */\n private _value: T;\n\n /** Version counter for change detection and stale notification prevention */\n private _version: number;\n\n /** Array of function-based subscribers */\n private _fnSubs: Array<(newValue?: T, oldValue?: T) => void>;\n\n /** Count of active function subscribers (may differ from array length due to sparse removal) */\n private _fnSubCount: number;\n\n /** Array of object-based subscribers with execute method */\n private _objSubs: Array<{ execute: () => void }>;\n\n /** Count of active object subscribers */\n private _objSubCount: number;\n\n /** Whether notifications should be synchronous (bypass scheduler batching) */\n private readonly _sync: boolean;\n\n /** Unique identifier for debugging purposes */\n private readonly _id: string;\n\n /**\n * Creates a new AtomImpl instance.\n *\n * @param initialValue - The initial value of the atom\n * @param sync - Whether to notify subscribers synchronously\n */\n constructor(initialValue: T, sync: boolean) {\n this._value = initialValue;\n this._version = 0;\n this._fnSubs = [];\n this._fnSubCount = 0;\n this._objSubs = [];\n this._objSubCount = 0;\n this._sync = sync;\n this._id = generateId().toString();\n\n debug.attachDebugInfo(this, 'atom', generateId());\n }\n\n /**\n * Gets the current value and registers the atom as a dependency\n * in the current tracking context.\n *\n * @returns The current value\n *\n * @remarks\n * This getter automatically tracks dependencies when accessed within\n * a computed or effect context.\n */\n get value(): T {\n const current = trackingContext.getCurrent();\n if (current !== null && current !== undefined) {\n this._track(current);\n }\n return this._value;\n }\n\n /**\n * Sets a new value and notifies all subscribers if the value changed.\n *\n * @param newValue - The new value to set\n *\n * @remarks\n * Uses Object.is for equality comparison. If the value is unchanged,\n * no notifications are sent. Notifications may be batched unless\n * sync mode is enabled.\n */\n set value(newValue: T) {\n if (Object.is(this._value, newValue)) return;\n\n const oldValue = this._value;\n const currentVersion = ++this._version;\n this._value = newValue;\n\n if ((this._fnSubCount | this._objSubCount) === 0) return;\n\n this._notify(newValue, oldValue, currentVersion);\n }\n\n /**\n * Tracks the current context as a dependency of this atom.\n *\n * @param current - The current tracking context (function or object)\n *\n * @remarks\n * Handles both function-based trackers (with optional addDependency method)\n * and object-based trackers (with execute or addDependency methods).\n */\n private _track(current: unknown): void {\n if (typeof current === 'function') {\n const fnWithDep = current as { addDependency?: (dep: unknown) => void };\n if (fnWithDep.addDependency !== undefined) {\n fnWithDep.addDependency(this);\n } else {\n this._addFnSub(current as (newValue?: T, oldValue?: T) => void);\n }\n } else {\n const tracker = current as { execute?: () => void; addDependency?: (dep: unknown) => void };\n if (tracker.addDependency !== undefined) {\n tracker.addDependency(this);\n } else if (tracker.execute !== undefined) {\n this._addObjSub(tracker as { execute: () => void });\n }\n }\n }\n\n /**\n * Adds a function-based subscriber.\n *\n * @param sub - The subscriber function to add\n * @returns An unsubscribe function\n *\n * @remarks\n * Prevents duplicate subscriptions by checking existing subscribers.\n */\n private _addFnSub(sub: (newValue?: T, oldValue?: T) => void): () => void {\n const subs = this._fnSubs;\n const idx = this._fnSubCount;\n\n for (let i = 0; i < idx; i++) {\n if (subs[i] === sub) return this._createUnsub(i, true);\n }\n\n subs[idx] = sub;\n this._fnSubCount = idx + 1;\n\n return this._createUnsub(idx, true);\n }\n\n /**\n * Adds an object-based subscriber.\n *\n * @param sub - The subscriber object with an execute method\n *\n * @remarks\n * Prevents duplicate subscriptions by checking existing subscribers.\n */\n private _addObjSub(sub: { execute: () => void }): void {\n const subs = this._objSubs;\n const count = this._objSubCount;\n\n for (let i = 0; i < count; i++) {\n if (subs[i] === sub) return;\n }\n\n subs[count] = sub;\n this._objSubCount = count + 1;\n }\n\n /**\n * Creates an unsubscribe function for a subscriber at the given index.\n *\n * @param idx - The index of the subscriber\n * @param isFn - Whether this is a function subscriber (true) or object subscriber (false)\n * @returns An unsubscribe function\n */\n private _createUnsub(idx: number, isFn: boolean): () => void {\n return () => {\n if (isFn) {\n this._removeFnSub(idx);\n } else {\n this._removeObjSub(idx);\n }\n };\n }\n\n /**\n * Removes a function subscriber at the given index.\n *\n * @param idx - The index of the subscriber to remove\n *\n * @remarks\n * Uses swap-and-pop removal for O(1) performance.\n */\n private _removeFnSub(idx: number): void {\n const count = this._fnSubCount;\n if (idx >= count) return;\n\n const lastIdx = count - 1;\n const subs = this._fnSubs;\n\n subs[idx] = subs[lastIdx] as (newValue?: T, oldValue?: T) => void;\n subs[lastIdx] = undefined as any;\n this._fnSubCount = lastIdx;\n }\n\n /**\n * Removes an object subscriber at the given index.\n *\n * @param idx - The index of the subscriber to remove\n *\n * @remarks\n * Uses swap-and-pop removal for O(1) performance.\n */\n private _removeObjSub(idx: number): void {\n const count = this._objSubCount;\n if (idx >= count) return;\n\n const lastIdx = count - 1;\n const subs = this._objSubs;\n\n subs[idx] = subs[lastIdx] as { execute: () => void };\n subs[lastIdx] = undefined as any;\n this._objSubCount = lastIdx;\n }\n\n /**\n * Notifies all subscribers of a value change.\n *\n * @param newValue - The new value\n * @param oldValue - The previous value\n * @param currentVersion - The version at the time of change\n *\n * @remarks\n * Notifications are skipped if the version has changed (stale update).\n * Errors from individual subscribers are caught and logged without\n * interrupting other subscribers.\n */\n private _notify(newValue: T, oldValue: T, currentVersion: number): void {\n const doNotify = (): void => {\n if (this._version !== currentVersion) return;\n\n const fnSubs = this._fnSubs;\n const fnCount = this._fnSubCount;\n const objSubs = this._objSubs;\n const objCount = this._objSubCount;\n\n for (let i = 0; i < fnCount; i++) {\n try {\n const fn = fnSubs[i];\n if (fn) {\n fn(newValue, oldValue);\n }\n } catch (e) {\n console.error(\n new AtomError(ERROR_MESSAGES.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED, e as Error)\n );\n }\n }\n\n for (let i = 0; i < objCount; i++) {\n try {\n const sub = objSubs[i];\n if (sub) {\n sub.execute();\n }\n } catch (e) {\n console.error(\n new AtomError(ERROR_MESSAGES.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED, e as Error)\n );\n }\n }\n };\n\n if (this._sync && !scheduler.isBatching) {\n doNotify();\n } else {\n scheduler.schedule(doNotify);\n }\n }\n\n /**\n * Subscribes a listener function to value changes.\n *\n * @param listener - Function to call when the value changes\n * @returns An unsubscribe function\n * @throws {AtomError} If listener is not a function\n *\n * @example\n * ```ts\n * const unsub = myAtom.subscribe((newVal, oldVal) => {\n * console.log(`Changed from ${oldVal} to ${newVal}`);\n * });\n * // Later: unsub();\n * ```\n */\n subscribe(listener: (newValue?: T, oldValue?: T) => void): () => void {\n if (typeof listener !== 'function') {\n throw new AtomError(ERROR_MESSAGES.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);\n }\n return this._addFnSub(listener);\n }\n\n /**\n * Gets the current value without registering as a dependency.\n *\n * @returns The current value\n *\n * @remarks\n * Use this method when you need to read the value without\n * creating a reactive dependency (e.g., in event handlers).\n */\n peek(): T {\n return this._value;\n }\n\n /**\n * Disposes the atom, clearing all subscribers and releasing resources.\n *\n * @remarks\n * After disposal, the atom should not be used. The value is set to\n * undefined to help with garbage collection.\n */\n dispose(): void {\n this._fnSubs.length = 0;\n this._objSubs.length = 0;\n this._fnSubCount = 0;\n this._objSubCount = 0;\n this._value = undefined as T;\n }\n\n /**\n * Gets the total number of active subscribers.\n *\n * @returns The count of function and object subscribers combined\n */\n subscriberCount(): number {\n return this._fnSubCount + this._objSubCount;\n }\n}\n\n/**\n * Creates a new atom with the given initial value.\n *\n * @template T - The type of value stored in the atom\n * @param initialValue - The initial value of the atom\n * @param options - Optional configuration options\n * @returns A writable atom instance\n *\n * @example\n * ```ts\n * // Basic usage\n * const count = atom(0);\n *\n * // With sync option for immediate notifications\n * const syncCount = atom(0, { sync: true });\n *\n * // Reading and writing\n * console.log(count.value); // 0\n * count.value = 5;\n * console.log(count.peek()); // 5 (non-tracking read)\n * ```\n */\nexport function atom<T>(initialValue: T, options: AtomOptions = {}): WritableAtom<T> {\n return new AtomImpl(initialValue, options.sync ?? false);\n}\n","/**\n * @fileoverview Subscriber management utility\n * @description Manages subscribers with O(1) add/remove operations using Array + WeakMap\n */\n\n/**\n * Manages subscribers with optimized O(1) operations\n *\n * Uses a combination of Array (for iteration) and WeakMap (for O(1) lookup)\n * to provide both fast iteration and fast add/remove operations.\n *\n * Key optimizations:\n * - Array for cache-friendly sequential iteration\n * - WeakMap for O(1) lookup and automatic GC\n * - Swap-and-pop for O(1) removal\n * - Lazy initialization to save memory\n *\n * @template T - Subscriber type (any object type for WeakMap compatibility)\n *\n * @example\n * ```ts\n * const manager = new SubscriberManager<(value: number) => void>();\n *\n * // Add subscriber\n * const unsub = manager.add((val) => console.log(val));\n *\n * // Notify all\n * manager.notify(42);\n *\n * // Remove subscriber\n * unsub();\n * ```\n */\nexport class SubscriberManager<T extends object> {\n private subscribers: T[] | null = null;\n private subscriberIndex: WeakMap<T, number> | null = null;\n\n /**\n * Adds a subscriber and returns an unsubscribe function\n *\n * Performs lazy initialization on first subscriber.\n * Duplicate subscribers are ignored (idempotent).\n *\n * @param subscriber - Function to add as subscriber\n * @returns Unsubscribe function (O(1) removal)\n *\n * @example\n * ```ts\n * const unsub = manager.add((value) => console.log(value));\n * // Later...\n * unsub(); // Remove this subscriber\n * ```\n */\n add(subscriber: T): () => void {\n // Lazy initialization\n if (!this.subscribers) {\n this.subscribers = [];\n this.subscriberIndex = new WeakMap();\n }\n\n // Check for duplicates (O(1))\n if (this.subscriberIndex!.has(subscriber)) {\n // Already subscribed, return no-op unsubscribe\n return () => {};\n }\n\n // Add subscriber (O(1))\n const index = this.subscribers.length;\n this.subscribers.push(subscriber);\n this.subscriberIndex!.set(subscriber, index);\n\n // Return unsubscribe function with duplicate protection\n let isUnsubscribed = false;\n return () => {\n if (isUnsubscribed) return;\n isUnsubscribed = true;\n this.remove(subscriber);\n };\n }\n\n /**\n * Removes a subscriber using swap-and-pop optimization\n *\n * Time complexity: O(1)\n * - Swaps target with last element\n * - Pops last element\n * - Updates index mapping\n *\n * @param subscriber - Subscriber to remove\n * @returns True if removed, false if not found\n */\n remove(subscriber: T): boolean {\n if (!this.subscribers || !this.subscriberIndex) {\n return false;\n }\n\n const idx = this.subscriberIndex.get(subscriber);\n if (idx === undefined) {\n return false; // Not found\n }\n\n const lastIndex = this.subscribers.length - 1;\n\n // Swap with last element (O(1))\n if (idx !== lastIndex) {\n const lastSubscriber = this.subscribers[lastIndex]!;\n this.subscribers[idx] = lastSubscriber;\n this.subscriberIndex.set(lastSubscriber, idx);\n }\n\n // Pop last element (O(1))\n this.subscribers.pop();\n this.subscriberIndex.delete(subscriber);\n\n return true;\n }\n\n /**\n * Checks if a subscriber is registered\n *\n * @param subscriber - Subscriber to check\n * @returns True if registered\n */\n has(subscriber: T): boolean {\n return this.subscriberIndex?.has(subscriber) ?? false;\n }\n\n /**\n * Iterates over all subscribers with a callback\n *\n * Optimized for cache-friendly sequential access.\n * Errors in callbacks are propagated to the caller.\n *\n * @param fn - Callback to execute for each subscriber\n *\n * @example\n * ```ts\n * manager.forEach((subscriber) => {\n * subscriber(newValue, oldValue);\n * });\n * ```\n */\n forEach(fn: (subscriber: T, index: number) => void): void {\n if (!this.subscribers) return;\n\n for (let i = 0; i < this.subscribers.length; i++) {\n fn(this.subscribers[i]!, i);\n }\n }\n\n /**\n * Safely iterates over subscribers with error handling\n *\n * Catches and logs errors from individual callbacks to prevent\n * one failing subscriber from breaking the entire notification chain.\n *\n * @param fn - Callback to execute for each subscriber\n * @param onError - Optional error handler for each callback error\n */\n forEachSafe(fn: (subscriber: T, index: number) => void, onError?: (error: Error) => void): void {\n if (!this.subscribers) return;\n\n for (let i = 0; i < this.subscribers.length; i++) {\n try {\n fn(this.subscribers[i]!, i);\n } catch (error) {\n if (onError) {\n onError(error as Error);\n } else {\n console.error('[SubscriberManager] Error in subscriber callback:', error);\n }\n }\n }\n }\n\n /**\n * Gets the current number of subscribers\n *\n * @returns Number of active subscribers\n */\n get size(): number {\n return this.subscribers?.length ?? 0;\n }\n\n /**\n * Checks if there are any subscribers\n *\n * @returns True if at least one subscriber exists\n */\n get hasSubscribers(): boolean {\n return this.size > 0;\n }\n\n /**\n * Clears all subscribers\n *\n * Removes all subscribers and releases memory.\n * Subsequent operations will re-initialize lazily.\n */\n clear(): void {\n if (this.subscribers) {\n this.subscribers.length = 0;\n }\n this.subscriberIndex = null;\n this.subscribers = null;\n }\n\n /**\n * Gets a copy of all subscribers as an array\n *\n * Useful for debugging or manual iteration.\n * Returns empty array if no subscribers.\n *\n * @returns Array of all subscribers\n */\n toArray(): T[] {\n return this.subscribers ? [...this.subscribers] : [];\n }\n}\n","/**\n * @fileoverview computed: Derived reactive state with automatic dependency tracking\n * @description Creates computed values that automatically update when dependencies change (sync/async support)\n * @optimized Class-based architecture with cache locality and branchless patterns\n */\n\nimport { AsyncState, COMPUTED_STATE_FLAGS } from '../../constants';\nimport type { AtomError } from '../../errors/errors';\nimport { ComputedError, isPromise, wrapError } from '../../errors/errors';\nimport { ERROR_MESSAGES } from '../../errors/messages';\nimport { scheduler } from '../../scheduler';\nimport { trackingContext } from '../../tracking';\nimport { DependencyManager } from '../../tracking/dependency-manager';\nimport type {\n AsyncStateType,\n ComputedAtom,\n ComputedOptions,\n Dependency,\n Subscriber,\n} from '../../types';\nimport { debug, generateId, NO_DEFAULT_VALUE } from '../../utils/debug';\nimport { SubscriberManager } from '../../utils/subscriber-manager';\n\n/**\n * Optimized ComputedAtom implementation with class-based architecture\n *\n * Key optimizations:\n * - Cache-friendly field layout (hot fields first)\n * - Inline bit flags (no separate class instance)\n * - Branchless fast path for value access\n * - Reduced indirection and closure overhead\n *\n * @template T - The type of the computed value\n */\nclass ComputedAtomImpl<T> implements ComputedAtom<T> {\n // === HOT PATH: Most frequently accessed fields (cache line 1) ===\n private _value: T;\n private _stateFlags: number;\n\n // === WARM PATH: Frequently accessed fields (cache line 2) ===\n private _error: AtomError | null = null;\n private _promiseId = 0;\n private readonly _equal: (a: T, b: T) => boolean;\n\n // === COLD PATH: Infrequently accessed fields ===\n private readonly _fn: () => T | Promise<T>;\n private readonly _defaultValue: T;\n private readonly _hasDefaultValue: boolean;\n private readonly _onError: ((error: Error) => void) | null;\n private readonly _functionSubscribers: SubscriberManager<() => void>;\n private readonly _objectSubscribers: SubscriberManager<Subscriber>;\n private readonly _dependencyManager: DependencyManager;\n private readonly _id: number;\n private readonly MAX_PROMISE_ID = Number.MAX_SAFE_INTEGER - 1;\n\n constructor(fn: () => T | Promise<T>, options: ComputedOptions<T> = {}) {\n if (typeof fn !== 'function') {\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_MUST_BE_FUNCTION);\n }\n\n this._fn = fn;\n this._stateFlags = COMPUTED_STATE_FLAGS.DIRTY | COMPUTED_STATE_FLAGS.IDLE;\n this._value = undefined as T;\n\n const {\n equal = Object.is,\n defaultValue = NO_DEFAULT_VALUE as T,\n lazy = true,\n onError = null,\n } = options;\n\n this._equal = equal;\n this._defaultValue = defaultValue;\n this._hasDefaultValue = defaultValue !== NO_DEFAULT_VALUE;\n this._onError = onError;\n this._functionSubscribers = new SubscriberManager<() => void>();\n this._objectSubscribers = new SubscriberManager<Subscriber>();\n this._dependencyManager = new DependencyManager();\n this._id = generateId();\n\n debug.attachDebugInfo(this as unknown as ComputedAtom<T>, 'computed', this._id);\n\n if (debug.enabled) {\n const debugObj = this as unknown as ComputedAtom<T> & {\n subscriberCount: () => number;\n isDirty: () => boolean;\n dependencies: ReturnType<DependencyManager['getDependencies']>;\n stateFlags: string;\n };\n debugObj.subscriberCount = () =>\n this._functionSubscribers.size + this._objectSubscribers.size;\n debugObj.isDirty = () => this._isDirty();\n debugObj.dependencies = this._dependencyManager.getDependencies();\n debugObj.stateFlags = this._getFlagsAsString();\n }\n\n if (!lazy) {\n try {\n this._recompute();\n } catch {\n // Ignore initial computation failure for non-lazy computed\n }\n }\n }\n\n // === PUBLIC API ===\n\n get value(): T {\n // Branchless fast path: single bitwise check for (resolved AND not dirty)\n const isFastPath =\n (this._stateFlags & (COMPUTED_STATE_FLAGS.RESOLVED | COMPUTED_STATE_FLAGS.DIRTY)) ===\n COMPUTED_STATE_FLAGS.RESOLVED;\n\n if (isFastPath) {\n this._registerTracking();\n return this._value;\n }\n\n // Slow path: state transition required\n const result = this._computeValue();\n this._registerTracking();\n return result;\n }\n\n subscribe(listener: () => void): () => void {\n if (typeof listener !== 'function') {\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION);\n }\n return this._functionSubscribers.add(listener);\n }\n\n peek(): T {\n return this._value;\n }\n\n get state(): AsyncStateType {\n return this._getAsyncState();\n }\n\n get hasError(): boolean {\n return this._isRejected();\n }\n\n get lastError(): Error | null {\n return this._error;\n }\n\n get isPending(): boolean {\n return this._isPending();\n }\n\n get isResolved(): boolean {\n return this._isResolved();\n }\n\n invalidate(): void {\n this._markDirty();\n }\n\n dispose(): void {\n this._dependencyManager.unsubscribeAll();\n this._functionSubscribers.clear();\n this._objectSubscribers.clear();\n this._stateFlags = COMPUTED_STATE_FLAGS.DIRTY | COMPUTED_STATE_FLAGS.IDLE;\n this._error = null;\n this._value = undefined as T;\n this._promiseId = (this._promiseId + 1) % this.MAX_PROMISE_ID;\n }\n\n // === PRIVATE: State Flag Operations (inlined for performance) ===\n\n private _isDirty(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.DIRTY) !== 0;\n }\n\n private _setDirty(): void {\n this._stateFlags |= COMPUTED_STATE_FLAGS.DIRTY;\n }\n\n private _clearDirty(): void {\n this._stateFlags &= ~COMPUTED_STATE_FLAGS.DIRTY;\n }\n\n private _isIdle(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.IDLE) !== 0;\n }\n\n private _setIdle(): void {\n this._stateFlags |= COMPUTED_STATE_FLAGS.IDLE;\n this._stateFlags &= ~(\n COMPUTED_STATE_FLAGS.PENDING |\n COMPUTED_STATE_FLAGS.RESOLVED |\n COMPUTED_STATE_FLAGS.REJECTED\n );\n }\n\n private _isPending(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.PENDING) !== 0;\n }\n\n private _setPending(): void {\n this._stateFlags |= COMPUTED_STATE_FLAGS.PENDING;\n this._stateFlags &= ~(\n COMPUTED_STATE_FLAGS.IDLE |\n COMPUTED_STATE_FLAGS.RESOLVED |\n COMPUTED_STATE_FLAGS.REJECTED\n );\n }\n\n private _isResolved(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.RESOLVED) !== 0;\n }\n\n private _setResolved(): void {\n this._stateFlags |= COMPUTED_STATE_FLAGS.RESOLVED;\n this._stateFlags &= ~(\n COMPUTED_STATE_FLAGS.IDLE |\n COMPUTED_STATE_FLAGS.PENDING |\n COMPUTED_STATE_FLAGS.REJECTED |\n COMPUTED_STATE_FLAGS.HAS_ERROR\n );\n }\n\n private _isRejected(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.REJECTED) !== 0;\n }\n\n private _setRejected(): void {\n this._stateFlags |= COMPUTED_STATE_FLAGS.REJECTED | COMPUTED_STATE_FLAGS.HAS_ERROR;\n this._stateFlags &= ~(\n COMPUTED_STATE_FLAGS.IDLE |\n COMPUTED_STATE_FLAGS.PENDING |\n COMPUTED_STATE_FLAGS.RESOLVED\n );\n }\n\n private _isRecomputing(): boolean {\n return (this._stateFlags & COMPUTED_STATE_FLAGS.RECOMPUTING) !== 0;\n }\n\n private _setRecomputing(value: boolean): void {\n if (value) {\n this._stateFlags |= COMPUTED_STATE_FLAGS.RECOMPUTING;\n } else {\n this._stateFlags &= ~COMPUTED_STATE_FLAGS.RECOMPUTING;\n }\n }\n\n private _getAsyncState(): AsyncStateType {\n if (this._isPending()) return AsyncState.PENDING;\n if (this._isResolved()) return AsyncState.RESOLVED;\n if (this._isRejected()) return AsyncState.REJECTED;\n return AsyncState.IDLE;\n }\n\n private _getFlagsAsString(): string {\n const states: string[] = [];\n if (this._isDirty()) states.push('DIRTY');\n if (this._isIdle()) states.push('IDLE');\n if (this._isPending()) states.push('PENDING');\n if (this._isResolved()) states.push('RESOLVED');\n if (this._isRejected()) states.push('REJECTED');\n if (this._isRecomputing()) states.push('RECOMPUTING');\n return states.join(' | ');\n }\n\n // === PRIVATE: Core Computation Logic ===\n\n private _computeValue(): T {\n if (this._isRecomputing()) return this._value;\n if (this._isPending()) return this._handlePending();\n if (this._isRejected()) return this._handleRejected();\n\n if (this._isDirty() || this._isIdle()) {\n this._recompute();\n if (this._isPending()) {\n return this._handlePending();\n }\n }\n\n return this._value;\n }\n\n private _recompute(): void {\n if (!this._isDirty() && this._isResolved()) {\n return;\n }\n\n this._setRecomputing(true);\n\n // Track dependencies during computation\n const newDependencies = new Set<unknown>();\n const tempMarkDirty = Object.assign(() => this._markDirty(), {\n addDependency: (dep: unknown) => newDependencies.add(dep),\n });\n\n try {\n const result = trackingContext.run(tempMarkDirty, this._fn);\n\n if (isPromise(result)) {\n // Update dependencies before async handling\n this._updateDependencies(newDependencies);\n this._handleAsyncComputation(result);\n this._setRecomputing(false);\n return;\n }\n\n // Update dependencies for sync result\n this._updateDependencies(newDependencies);\n this._handleSyncResult(result);\n } catch (err) {\n // Update dependencies even on error for recovery support\n this._updateDependencies(newDependencies);\n this._handleComputationError(err);\n }\n }\n\n private _handleSyncResult(result: T): void {\n const shouldUpdate = !this._isResolved() || !this._equal(this._value, result);\n\n this._value = result;\n this._clearDirty();\n this._setResolved();\n this._error = null;\n this._setRecomputing(false);\n\n if (shouldUpdate) {\n this._notifySubscribers();\n }\n }\n\n private _handleAsyncComputation(promise: Promise<T>): void {\n this._setPending();\n\n // Branchless promise ID increment with overflow protection\n this._promiseId = this._promiseId >= this.MAX_PROMISE_ID ? 1 : this._promiseId + 1;\n const promiseId = this._promiseId;\n\n promise\n .then((resolvedValue) => {\n // Race condition check: ignore if superseded\n if (promiseId !== this._promiseId) return;\n\n this._handleAsyncResolution(resolvedValue);\n })\n .catch((err) => {\n // Race condition check: ignore if superseded\n if (promiseId !== this._promiseId) return;\n\n this._handleAsyncRejection(err);\n });\n }\n\n private _handleAsyncResolution(resolvedValue: T): void {\n const shouldUpdate = !this._isResolved() || !this._equal(this._value, resolvedValue);\n\n this._value = resolvedValue;\n this._clearDirty();\n this._setResolved();\n this._error = null;\n this._setRecomputing(false);\n\n if (shouldUpdate) {\n this._notifySubscribers();\n }\n }\n\n private _handleAsyncRejection(err: unknown): void {\n const error = wrapError(err, ComputedError, ERROR_MESSAGES.COMPUTED_ASYNC_COMPUTATION_FAILED);\n\n this._error = error;\n this._setRejected();\n this._clearDirty();\n this._setRecomputing(false);\n\n if (this._onError && typeof this._onError === 'function') {\n try {\n this._onError(error);\n } catch (callbackError) {\n console.error(ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER, callbackError);\n }\n }\n\n this._notifySubscribers();\n }\n\n private _handleComputationError(err: unknown): never {\n const error = wrapError(err, ComputedError, ERROR_MESSAGES.COMPUTED_COMPUTATION_FAILED);\n\n this._error = error;\n this._setRejected();\n this._clearDirty();\n this._setRecomputing(false);\n\n if (this._onError && typeof this._onError === 'function') {\n try {\n this._onError(error);\n } catch (callbackError) {\n console.error(ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER, callbackError);\n }\n }\n\n throw error;\n }\n\n private _handlePending(): T {\n if (this._hasDefaultValue) {\n return this._defaultValue;\n }\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_ASYNC_PENDING_NO_DEFAULT);\n }\n\n private _handleRejected(): T {\n if (this._error?.recoverable && this._hasDefaultValue) {\n return this._defaultValue;\n }\n throw this._error;\n }\n\n // === PRIVATE: Dependency Management ===\n\n private _updateDependencies(newDeps: Set<unknown>): void {\n const dependencies = this._dependencyManager.getDependencies();\n\n // Fast path: No dependency changes (O(1) check)\n if (this._hasSameDependencies(dependencies, newDeps)) {\n return;\n }\n\n // Slow path: Delta Sync\n this._performDeltaSync(dependencies, newDeps);\n }\n\n private _hasSameDependencies(current: Dependency[], newDeps: Set<unknown>): boolean {\n if (current.length !== newDeps.size) {\n return false;\n }\n\n for (let i = 0; i < current.length; i++) {\n if (!newDeps.has(current[i]!)) {\n return false;\n }\n }\n\n return true;\n }\n\n private _performDeltaSync(current: Dependency[], newDeps: Set<unknown>): void {\n const existingSet = new Set(current);\n const toRemove: Dependency[] = [];\n const toAdd: Dependency[] = [];\n\n // Find dependencies to remove\n for (let i = 0; i < current.length; i++) {\n const dep = current[i]!;\n if (!newDeps.has(dep)) {\n toRemove.push(dep);\n }\n }\n\n // Find dependencies to add\n newDeps.forEach((dep) => {\n if (!existingSet.has(dep as Dependency)) {\n toAdd.push(dep as Dependency);\n }\n });\n\n // Unsubscribe removed dependencies\n for (let i = 0; i < toRemove.length; i++) {\n this._dependencyManager.removeDependency(toRemove[i]!);\n }\n\n // Subscribe to new dependencies\n for (let i = 0; i < toAdd.length; i++) {\n this._addDependency(toAdd[i]!);\n }\n\n // Update dependencies array in place\n current.length = 0;\n newDeps.forEach((dep) => {\n current.push(dep as Dependency);\n });\n }\n\n private _addDependency(dep: Dependency): void {\n debug.checkCircular(dep, this as unknown as ComputedAtom<T>);\n\n const count = this._dependencyManager.count;\n debug.warn(count > debug.maxDependencies, ERROR_MESSAGES.LARGE_DEPENDENCY_GRAPH(count));\n\n try {\n const unsubscribe = dep.subscribe(() => this._markDirty());\n this._dependencyManager.addDependency(dep, unsubscribe);\n } catch (error) {\n throw wrapError(error, ComputedError, 'dependency subscription');\n }\n }\n\n // === PRIVATE: Subscriber Management ===\n\n private _markDirty(): void {\n if (this._isRecomputing() || this._isDirty()) return;\n\n this._setDirty();\n this._setIdle();\n\n if (this._functionSubscribers.hasSubscribers || this._objectSubscribers.hasSubscribers) {\n scheduler.schedule(() => {\n if (this._isDirty()) {\n try {\n this._recompute();\n } catch {\n // Error already handled\n }\n }\n });\n }\n }\n\n private _notifySubscribers(): void {\n if (!this._functionSubscribers.hasSubscribers && !this._objectSubscribers.hasSubscribers) {\n return;\n }\n\n scheduler.schedule(() => {\n this._functionSubscribers.forEachSafe(\n (subscriber) => subscriber(),\n (err) => console.error(err)\n );\n\n this._objectSubscribers.forEachSafe(\n (subscriber) => subscriber.execute(),\n (err) => console.error(err)\n );\n });\n }\n\n private _registerTracking(): void {\n const current = trackingContext.getCurrent();\n if (!current) return;\n\n if (typeof current === 'function') {\n this._functionSubscribers.add(current);\n } else if (current.addDependency) {\n current.addDependency(this as unknown as ComputedAtom<T>);\n } else if (current.execute) {\n this._objectSubscribers.add(current as Subscriber);\n }\n }\n}\n\n/**\n * Creates a computed value that automatically tracks and reacts to dependencies\n *\n * Computed atoms are derived reactive state that:\n * - Automatically track dependencies accessed during computation\n * - Lazily recompute only when dependencies change (dirty checking)\n * - Support both synchronous and asynchronous computations\n * - Cache results until dependencies change (memoization)\n * - Use bit flags for efficient state management\n * - Provide async state tracking (idle/pending/resolved/rejected)\n *\n * @template T - The type of the computed value\n * @param fn - Computation function (can return T or Promise<T>)\n * @param options - Configuration options\n * @returns A readonly computed atom with automatic dependency tracking\n *\n * @example\n * ```ts\n * // Synchronous computed\n * const count = atom(0);\n * const doubled = computed(() => count.value * 2);\n *\n * // Asynchronous computed with default value\n * const userData = computed(\n * async () => fetch(`/api/user/${userId.value}`).then(r => r.json()),\n * { defaultValue: null }\n * );\n * ```\n */\nexport function computed<T>(fn: () => T, options?: ComputedOptions<T>): ComputedAtom<T>;\nexport function computed<T>(\n fn: () => Promise<T>,\n options: ComputedOptions<T> & { defaultValue: T }\n): ComputedAtom<T>;\nexport function computed<T>(\n fn: () => T | Promise<T>,\n options: ComputedOptions<T> = {}\n): ComputedAtom<T> {\n return new ComputedAtomImpl(fn, options) as unknown as ComputedAtom<T>;\n}\n","import type { ComputedAtom, EffectObject, ReadonlyAtom } from '../types';\nimport { debug } from './debug';\n\nexport function isAtom(obj: unknown): obj is ReadonlyAtom {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n 'value' in obj &&\n 'subscribe' in obj &&\n typeof (obj as Record<string, unknown>).subscribe === 'function'\n );\n}\n\nexport function isComputed(obj: unknown): obj is ComputedAtom {\n if (debug.enabled) {\n const debugType = debug.getDebugType(obj);\n if (debugType) {\n return debugType === 'computed';\n }\n }\n return (\n isAtom(obj) &&\n 'invalidate' in obj &&\n typeof (obj as Record<string, unknown>).invalidate === 'function'\n );\n}\n\nexport function isEffect(obj: unknown): obj is EffectObject {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n 'dispose' in obj &&\n 'run' in obj &&\n typeof (obj as Record<string, unknown>).dispose === 'function' &&\n typeof (obj as Record<string, unknown>).run === 'function'\n );\n}\n","/**\n * @fileoverview Effect module for managing reactive side effects.\n *\n * This module provides a mechanism for creating and managing side effects\n * that automatically re-execute when their dependencies change. Effects\n * support cleanup functions, async operations, and infinite loop detection.\n */\n\nimport { EFFECT_STATE_FLAGS, SCHEDULER_CONFIG } from '../../constants';\nimport { EffectError, isPromise, wrapError } from '../../errors/errors';\nimport { ERROR_MESSAGES } from '../../errors/messages';\nimport { scheduler } from '../../scheduler';\nimport { type DependencyTracker, trackingContext } from '../../tracking';\nimport { DependencyManager } from '../../tracking/dependency-manager';\nimport type { Dependency, EffectFunction, EffectObject, EffectOptions } from '../../types';\nimport { debug, generateId } from '../../utils/debug';\nimport { isAtom } from '../../utils/type-guards';\n\n/**\n * Internal implementation of the EffectObject interface.\n *\n * @remarks\n * This class manages reactive side effects with automatic dependency tracking,\n * cleanup handling, and infinite loop detection. It implements both EffectObject\n * for public API and DependencyTracker for integration with the tracking system.\n *\n * Key features:\n * - Automatic dependency tracking during execution\n * - Support for synchronous and scheduled (batched) execution\n * - Cleanup function support for resource management\n * - Infinite loop detection with configurable threshold\n * - Optional modification tracking for debugging\n *\n * @implements {EffectObject}\n * @implements {DependencyTracker}\n */\nclass EffectImpl implements EffectObject, DependencyTracker {\n /**\n * The effect function to execute.\n * @readonly\n */\n private readonly _fn: EffectFunction;\n\n /**\n * Whether the effect should execute synchronously when dependencies change.\n * When false, execution is scheduled through the scheduler for batching.\n * @readonly\n */\n private readonly _sync: boolean;\n\n /**\n * Maximum number of executions allowed per second before triggering\n * infinite loop detection.\n * @readonly\n */\n private readonly _maxExecutions: number;\n\n /**\n * Whether to track modifications to dependencies for debugging purposes.\n * When enabled, warns if an effect modifies a dependency it reads.\n * @readonly\n */\n private readonly _trackModifications: boolean;\n\n /**\n * Unique identifier for this effect instance, used for debugging.\n * @readonly\n */\n private readonly _id: number;\n\n /**\n * Bit flags representing the current state of the effect.\n * Uses EFFECT_STATE_FLAGS constants for DISPOSED and EXECUTING states.\n */\n private _flags: number;\n\n /**\n * The cleanup function returned by the last effect execution.\n * Called before re-execution or disposal.\n */\n private _cleanup: (() => void) | null;\n\n /**\n * Manages dependency subscriptions for automatic re-execution.\n * @readonly\n */\n private readonly _depManager: DependencyManager;\n\n /**\n * Set of dependencies that were modified during the current execution.\n * Used for detecting potential infinite loops.\n * @readonly\n */\n private readonly _modifiedDeps: Set<unknown>;\n\n /**\n * Stores original property descriptors for dependencies when modification\n * tracking is enabled, allowing restoration on disposal.\n * @readonly\n */\n private readonly _originalDescriptors: WeakMap<Dependency, PropertyDescriptor>;\n\n /**\n * Set of dependencies that have modification tracking applied.\n * @readonly\n */\n private readonly _trackedDeps: Set<Dependency>;\n\n /**\n * Circular buffer storing timestamps of recent executions for\n * infinite loop detection.\n * @readonly\n */\n private readonly _history: Float64Array;\n\n /**\n * Current write index in the execution history circular buffer.\n */\n private _historyIdx: number;\n\n /**\n * Number of entries currently stored in the execution history.\n */\n private _historyCount: number;\n\n /**\n * Total number of times this effect has been executed.\n */\n private _executionCount: number;\n\n /**\n * Maximum capacity of the execution history buffer.\n * @readonly\n */\n private readonly _historyCapacity: number;\n\n /**\n * Creates a new EffectImpl instance.\n *\n * @param fn - The effect function to execute. May return a cleanup function\n * or a Promise that resolves to a cleanup function.\n * @param options - Configuration options for the effect\n * @param options.sync - If true, re-executes synchronously on dependency changes.\n * Defaults to false (scheduled execution).\n * @param options.maxExecutionsPerSecond - Maximum executions per second before\n * infinite loop detection triggers.\n * Defaults to SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_SECOND.\n * @param options.trackModifications - If true, tracks and warns about dependencies\n * that are both read and modified. Defaults to false.\n *\n * @example\n * ```typescript\n * const impl = new EffectImpl(\n * () => {\n * console.log(counter.value);\n * return () => console.log('cleanup');\n * },\n * { sync: true }\n * );\n * ```\n */\n constructor(fn: EffectFunction, options: EffectOptions = {}) {\n this._fn = fn;\n this._sync = options.sync ?? false;\n this._maxExecutions =\n options.maxExecutionsPerSecond ?? SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_SECOND;\n this._trackModifications = options.trackModifications ?? false;\n this._id = generateId();\n\n this._flags = 0;\n this._cleanup = null;\n\n this._depManager = new DependencyManager();\n this._modifiedDeps = new Set();\n this._originalDescriptors = new WeakMap();\n this._trackedDeps = new Set();\n\n this._historyCapacity = this._maxExecutions + 5;\n this._history = new Float64Array(this._historyCapacity);\n this._historyIdx = 0;\n this._historyCount = 0;\n this._executionCount = 0;\n\n debug.attachDebugInfo(this, 'effect', this._id);\n }\n\n /**\n * Manually triggers the effect to run.\n *\n * @throws {EffectError} If the effect has been disposed\n *\n * @remarks\n * This method is typically used when you need to force an effect to\n * re-execute outside of its normal dependency-triggered execution cycle.\n *\n * @example\n * ```typescript\n * const fx = effect(() => console.log(counter.value));\n * // Later, force re-execution:\n * fx.run();\n * ```\n */\n public run = (): void => {\n if (this.isDisposed) {\n throw new EffectError(ERROR_MESSAGES.EFFECT_MUST_BE_FUNCTION);\n }\n this.execute();\n };\n\n /**\n * Disposes of the effect, cleaning up all resources and subscriptions.\n *\n * @remarks\n * After disposal:\n * - The cleanup function is called (if any)\n * - All dependency subscriptions are removed\n * - Modification tracking descriptors are restored to their original state\n * - The effect will no longer execute\n *\n * This method is idempotent - calling it multiple times has no additional effect.\n *\n * @example\n * ```typescript\n * const fx = effect(() => console.log(counter.value));\n * // Later, when the effect is no longer needed:\n * fx.dispose();\n * ```\n */\n public dispose = (): void => {\n if (this.isDisposed) return;\n\n this._setDisposed();\n this._safeCleanup();\n this._depManager.unsubscribeAll();\n\n if (this._trackedDeps.size > 0) {\n this._trackedDeps.forEach((dep) => {\n const descriptor = this._originalDescriptors.get(dep);\n if (descriptor) {\n try {\n Object.defineProperty(dep, 'value', descriptor);\n } catch (_error) {\n debug.warn(true, 'Failed to restore original descriptor');\n }\n }\n });\n this._trackedDeps.clear();\n }\n };\n\n /**\n * Adds a dependency to this effect's tracking list.\n *\n * @param dep - The dependency to track (must implement Dependency interface)\n *\n * @throws {EffectError} If subscription to the dependency fails\n *\n * @remarks\n * This method is called automatically by the tracking context when\n * a reactive value is accessed during effect execution. It sets up\n * a subscription so the effect re-executes when the dependency changes.\n *\n * If modification tracking is enabled and the dependency is an atom,\n * additional tracking is set up to detect read-after-write patterns.\n *\n * @internal\n */\n public addDependency = (dep: unknown): void => {\n try {\n const unsubscribe = (dep as Dependency).subscribe(() => {\n if (this._sync) {\n this.execute();\n } else {\n scheduler.schedule(this.execute);\n }\n });\n this._depManager.addDependency(dep as Dependency, unsubscribe);\n\n if (this._trackModifications && isAtom(dep)) {\n this._trackModificationsForDep(dep);\n }\n } catch (error) {\n throw wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_EXECUTION_FAILED);\n }\n };\n\n /**\n * Executes the effect function, tracking dependencies and managing cleanup.\n *\n * @remarks\n * This method performs the following steps:\n * 1. Checks if the effect is disposed or already executing (guards against re-entrancy)\n * 2. Records the execution timestamp for infinite loop detection\n * 3. Runs any existing cleanup function\n * 4. Clears previous dependency subscriptions\n * 5. Executes the effect function within a tracking context\n * 6. Handles both sync and async cleanup functions\n *\n * If the effect function returns a Promise, the cleanup function is extracted\n * from the resolved value. Errors during execution are caught and logged.\n *\n * @example\n * ```typescript\n * const fx = effect(() => {\n * console.log(counter.value);\n * return () => console.log('cleanup');\n * });\n * fx.execute(); // Manually trigger execution\n * ```\n */\n public execute = (): void => {\n if (this.isDisposed || this.isExecuting) return;\n\n const now = Date.now();\n this._recordExecution(now);\n\n this._setExecuting(true);\n this._safeCleanup();\n this._depManager.unsubscribeAll();\n this._modifiedDeps.clear();\n\n try {\n const result = trackingContext.run(this, this._fn);\n\n this._checkLoopWarnings();\n\n if (isPromise(result)) {\n result\n .then((asyncCleanup) => {\n if (!this.isDisposed && typeof asyncCleanup === 'function') {\n this._cleanup = asyncCleanup;\n }\n })\n .catch((error) => {\n console.error(wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_EXECUTION_FAILED));\n });\n } else {\n this._cleanup = typeof result === 'function' ? result : null;\n }\n } catch (error) {\n console.error(wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_EXECUTION_FAILED));\n this._cleanup = null;\n } finally {\n this._setExecuting(false);\n }\n };\n\n /**\n * Indicates whether this effect has been disposed.\n *\n * @returns `true` if the effect has been disposed, `false` otherwise\n *\n * @remarks\n * A disposed effect will not execute and cannot be reactivated.\n * Use this property to check if the effect is still active before\n * performing operations that depend on it.\n *\n * @example\n * ```typescript\n * const fx = effect(() => console.log(counter.value));\n * console.log(fx.isDisposed); // false\n * fx.dispose();\n * console.log(fx.isDisposed); // true\n * ```\n */\n get isDisposed(): boolean {\n return (this._flags & EFFECT_STATE_FLAGS.DISPOSED) !== 0;\n }\n\n /**\n * Returns the total number of times this effect has been executed.\n *\n * @returns The cumulative execution count since the effect was created\n *\n * @remarks\n * This counter is useful for debugging, testing, and monitoring\n * effect behavior. It increments on every execution, regardless\n * of whether the execution succeeds or fails.\n *\n * @example\n * ```typescript\n * const fx = effect(() => console.log(counter.value));\n * console.log(fx.executionCount); // 1 (initial execution)\n * counter.value = 10;\n * console.log(fx.executionCount); // 2\n * ```\n */\n get executionCount(): number {\n return this._executionCount;\n }\n\n /**\n * Indicates whether this effect is currently executing.\n *\n * @returns `true` if the effect is mid-execution, `false` otherwise\n *\n * @remarks\n * This property is used internally to prevent re-entrant execution\n * (an effect triggering itself during its own execution). It can\n * also be useful for debugging to understand the effect's state.\n *\n * @example\n * ```typescript\n * const fx = effect(() => {\n * console.log('executing:', fx.isExecuting); // true\n * });\n * console.log(fx.isExecuting); // false (after execution completes)\n * ```\n */\n get isExecuting(): boolean {\n return (this._flags & EFFECT_STATE_FLAGS.EXECUTING) !== 0;\n }\n\n /**\n * Sets the disposed flag on this effect.\n *\n * @remarks\n * This is a low-level method that only sets the bit flag.\n * Use the public `dispose()` method for proper cleanup.\n *\n * @internal\n */\n private _setDisposed(): void {\n this._flags |= EFFECT_STATE_FLAGS.DISPOSED;\n }\n\n /**\n * Sets or clears the executing flag on this effect.\n *\n * @param value - `true` to mark as executing, `false` to clear\n *\n * @remarks\n * Uses bitwise operations for efficient flag manipulation.\n * This flag prevents re-entrant execution of the effect.\n *\n * @internal\n */\n private _setExecuting(value: boolean): void {\n if (value) this._flags |= EFFECT_STATE_FLAGS.EXECUTING;\n else this._flags &= ~EFFECT_STATE_FLAGS.EXECUTING;\n }\n\n /**\n * Safely executes the cleanup function if one exists.\n *\n * @remarks\n * This method:\n * - Checks if a cleanup function exists and is callable\n * - Wraps the cleanup call in a try-catch to prevent cleanup errors\n * from breaking the effect lifecycle\n * - Logs any cleanup errors to the console\n * - Clears the cleanup reference after execution\n *\n * @internal\n */\n private _safeCleanup(): void {\n if (this._cleanup && typeof this._cleanup === 'function') {\n try {\n this._cleanup();\n } catch (error) {\n console.error(wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_CLEANUP_FAILED));\n }\n this._cleanup = null;\n }\n }\n\n /**\n * Records an execution timestamp and checks for infinite loop conditions.\n *\n * @param now - The current timestamp in milliseconds (from `Date.now()`)\n *\n * @remarks\n * This method implements a circular buffer to track recent execution\n * timestamps. If the number of executions within the last second exceeds\n * `_maxExecutions`, the effect is disposed and an error is thrown (in debug mode)\n * or logged (in production mode).\n *\n * The circular buffer approach provides O(1) insertion and efficient\n * memory usage for tracking execution history.\n *\n * @throws {EffectError} In debug mode, throws when infinite loop is detected\n *\n * @internal\n */\n private _recordExecution(now: number): void {\n if (this._maxExecutions <= 0) return;\n\n const oneSecondAgo = now - 1000;\n\n this._history[this._historyIdx] = now;\n this._historyIdx = (this._historyIdx + 1) % this._historyCapacity;\n if (this._historyCount < this._historyCapacity) {\n this._historyCount++;\n }\n this._executionCount++;\n\n let count = 0;\n let idx = (this._historyIdx - 1 + this._historyCapacity) % this._historyCapacity;\n\n for (let i = 0; i < this._historyCount; i++) {\n if (this._history[idx]! < oneSecondAgo) {\n break;\n }\n count++;\n idx = (idx - 1 + this._historyCapacity) % this._historyCapacity;\n }\n\n if (count > this._maxExecutions) {\n const message = `Effect executed ${count} times within 1 second. Infinite loop suspected`;\n const error = new EffectError(message);\n\n this.dispose();\n console.error(error);\n\n if (debug.enabled) {\n throw error;\n }\n }\n }\n\n /**\n * Sets up modification tracking for a dependency.\n *\n * @param dep - The dependency (atom) to track modifications on\n *\n * @remarks\n * This method intercepts the `value` setter on the dependency to detect\n * when the effect modifies a dependency it also reads. This pattern\n * (read-after-write within the same effect) often indicates an infinite loop.\n *\n * The original property descriptor is preserved and can be restored\n * when the effect is disposed.\n *\n * @internal\n */\n private _trackModificationsForDep(dep: any): void {\n const proto = Object.getPrototypeOf(dep);\n const originalDescriptor = Object.getOwnPropertyDescriptor(proto, 'value');\n if (originalDescriptor?.set && !this._originalDescriptors.has(dep)) {\n this._originalDescriptors.set(dep, originalDescriptor);\n this._trackedDeps.add(dep);\n\n const self = this;\n\n Object.defineProperty(dep, 'value', {\n set(newValue: unknown) {\n self._modifiedDeps.add(dep);\n originalDescriptor.set?.call(dep, newValue);\n },\n get() {\n return dep.peek();\n },\n configurable: true,\n enumerable: true,\n });\n }\n }\n\n /**\n * Checks for and warns about potential infinite loop patterns.\n *\n * @remarks\n * When modification tracking is enabled and debug mode is active,\n * this method checks if any dependencies were both read and modified\n * during the effect execution. Such patterns often lead to infinite loops.\n *\n * Warnings are only emitted in debug mode to avoid performance overhead\n * in production.\n *\n * @internal\n */\n private _checkLoopWarnings(): void {\n if (this._trackModifications && debug.enabled) {\n const dependencies = this._depManager.getDependencies();\n for (let i = 0; i < dependencies.length; i++) {\n const dep = dependencies[i]!;\n if (this._modifiedDeps.has(dep)) {\n debug.warn(\n true,\n `Effect is reading a dependency (${\n debug.getDebugName(dep) || 'unknown'\n }) that it just modified. Infinite loop may occur`\n );\n }\n }\n }\n }\n}\n\n/**\n * Creates a reactive effect that automatically re-executes when its dependencies change.\n *\n * @param fn - The effect function to execute. May return a cleanup function\n * or a Promise that resolves to a cleanup function.\n * @param options - Configuration options for the effect\n * @param options.sync - If true, re-executes synchronously on dependency changes.\n * Defaults to false (scheduled/batched execution).\n * @param options.maxExecutionsPerSecond - Maximum executions per second before\n * infinite loop detection triggers.\n * Defaults to `SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_SECOND`.\n * @param options.trackModifications - If true, tracks and warns about dependencies\n * that are both read and modified. Defaults to false.\n *\n * @returns An {@link EffectObject} with `run()`, `dispose()`, and state properties\n *\n * @throws {EffectError} If `fn` is not a function\n *\n * @remarks\n * Effects are the primary way to perform side effects in response to reactive\n * state changes. They automatically track which reactive values (atoms, computed)\n * are accessed during execution and re-run when those values change.\n *\n * The effect function may return a cleanup function that will be called before\n * the next execution or when the effect is disposed. This is useful for\n * cleaning up subscriptions, timers, or other resources.\n *\n * @example\n * Basic usage:\n * ```typescript\n * const counter = atom(0);\n *\n * const fx = effect(() => {\n * console.log('Counter:', counter.value);\n * });\n * // Logs: \"Counter: 0\"\n *\n * counter.value = 1;\n * // Logs: \"Counter: 1\"\n *\n * fx.dispose(); // Stop the effect\n * ```\n *\n * @example\n * With cleanup function:\n * ```typescript\n * const fx = effect(() => {\n * const timer = setInterval(() => console.log('tick'), 1000);\n * return () => clearInterval(timer); // Cleanup\n * });\n * ```\n *\n * @example\n * Synchronous execution:\n * ```typescript\n * const fx = effect(\n * () => console.log(counter.value),\n * { sync: true }\n * );\n * ```\n */\nexport function effect(fn: EffectFunction, options: EffectOptions = {}): EffectObject {\n if (typeof fn !== 'function') {\n throw new EffectError(ERROR_MESSAGES.EFFECT_MUST_BE_FUNCTION);\n }\n\n const effectInstance = new EffectImpl(fn, options);\n\n effectInstance.execute();\n\n return effectInstance;\n}\n"],"names":["AsyncState","EFFECT_STATE_FLAGS","COMPUTED_STATE_FLAGS","POOL_CONFIG","SCHEDULER_CONFIG","DEBUG_CONFIG","AtomError","message","cause","recoverable","ComputedError","EffectError","SchedulerError","wrapError","error","ErrorClass","context","errorMessage","isPromise","value","ERROR_MESSAGES","count","Scheduler","callback","callbacks","i","iterations","max","scheduler","batch","trackingContext","listener","fn","prev","DependencyManager","dep","unsubscribe","ref","liveDeps","threshold","untracked","DEBUG_NAME","DEBUG_ID","DEBUG_TYPE","NO_DEFAULT_VALUE","hasDependencies","obj","debug","condition","current","visited","nestedDep","type","id","target","nextId","generateId","AtomImpl","initialValue","sync","newValue","oldValue","currentVersion","fnWithDep","tracker","sub","subs","idx","isFn","lastIdx","doNotify","fnSubs","fnCount","objSubs","objCount","e","atom","options","SubscriberManager","subscriber","index","isUnsubscribed","lastIndex","lastSubscriber","onError","ComputedAtomImpl","equal","defaultValue","lazy","debugObj","result","states","newDependencies","tempMarkDirty","err","shouldUpdate","promise","promiseId","resolvedValue","callbackError","newDeps","dependencies","existingSet","toRemove","toAdd","computed","isAtom","isComputed","debugType","isEffect","EffectImpl","descriptor","now","asyncCleanup","oneSecondAgo","proto","originalDescriptor","self","effect","effectInstance"],"mappings":"AAQO,MAAMA,IAAa;AAAA,EACxB,MAAM;AAAA,EACN,SAAS;AAAA,EACT,UAAU;AAAA,EACV,UAAU;AACZ,GAMaC,IAAqB;AAAA,EAChC,UAAU;AAAA;AAAA,EACV,WAAW;AAAA;AACb,GAMaC,IAAuB;AAAA,EAClC,OAAO;AAAA;AAAA,EACP,MAAM;AAAA;AAAA,EACN,SAAS;AAAA;AAAA,EACT,UAAU;AAAA;AAAA,EACV,UAAU;AAAA;AAAA,EACV,aAAa;AAAA;AAAA,EACb,WAAW;AAAA;AACb,GAMaC,IAAc;AAAA;AAAA,EAEzB,UAAU;AAAA;AAAA,EAEV,aAAa;AACf,GAMaC,IAAmB;AAAA;AAAA,EAE9B,2BAA2B;AAAA;AAAA,EAE3B,mBAAmB;AACrB,GAKaC,IAAe;AAAA;AAAA,EAE1B,kBAAkB;AAAA;AAAA,EAElB,oBAAoB;AACtB;AClDO,MAAMC,UAAkB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcnC,YAAYC,GAAiBC,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A,CACb;AAAA,IACH;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeQ,qBAA2B;AACjC,QAAI,KAAK,uBAAuBY,EAAM,SAAS;AAC7C,YAAMsD,IAAe,KAAK,YAAY,gBAAA;AACtC,eAAS5E,IAAI,GAAGA,IAAI4E,EAAa,QAAQ5E,KAAK;AAC5C,cAAMU,IAAMkE,EAAa5E,CAAC;AAC1B,QAAI,KAAK,cAAc,IAAIU,CAAG,KAC5BY,EAAM;AAAA,UACJ;AAAA,UACA,mCACEA,EAAM,aAAaZ,CAAG,KAAK,SAC7B;AAAA,QAAA;AAAA,MAGN;AAAA,IACF;AAAA,EACF;AACF;AA+DO,SAASmF,EAAOtF,GAAoB6C,IAAyB,IAAkB;AACpF,MAAI,OAAO7C,KAAO;AAChB,UAAM,IAAIrB,EAAYS,EAAe,uBAAuB;AAG9D,QAAMmG,IAAiB,IAAIT,EAAW9E,GAAI6C,CAAO;AAEjD,SAAA0C,EAAe,QAAA,GAERA;AACT;"}
@@ -1,2 +1,31 @@
1
+ /**
2
+ * Executes multiple reactive updates in a single batch.
3
+ *
4
+ * Batching groups multiple state changes together, deferring notifications
5
+ * until all updates are complete. This prevents intermediate states from
6
+ * triggering unnecessary recomputations and improves performance.
7
+ *
8
+ * @template T - The return type of the callback function
9
+ * @param callback - The function containing batched updates
10
+ * @returns The result of the callback function
11
+ * @throws {AtomError} If the callback is not a function
12
+ * @throws {AtomError} If an error occurs during batch execution
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * const firstName = atom('John');
17
+ * const lastName = atom('Doe');
18
+ *
19
+ * // Without batching: triggers 2 separate updates
20
+ * firstName.value = 'Jane';
21
+ * lastName.value = 'Smith';
22
+ *
23
+ * // With batching: triggers 1 combined update
24
+ * batch(() => {
25
+ * firstName.value = 'Jane';
26
+ * lastName.value = 'Smith';
27
+ * });
28
+ * ```
29
+ */
1
30
  export declare function batch<T>(callback: () => T): T;
2
31
  //# sourceMappingURL=batch.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"batch.d.ts","sourceRoot":"","sources":["../../src/scheduler/batch.ts"],"names":[],"mappings":"AAGA,wBAAgB,KAAK,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC,CAc7C"}
1
+ {"version":3,"file":"batch.d.ts","sourceRoot":"","sources":["../../src/scheduler/batch.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,KAAK,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC,CAc7C"}