@but212/atom-effect 0.30.1 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/atom-effect.min.js +1 -1
- package/dist/atom-effect.min.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +24 -46
- package/dist/index.mjs +522 -473
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../src/constants.ts","../src/errors.ts","../src/utils/debug.ts","../src/core/buffers.ts","../src/symbols.ts","../src/utils/type-guards.ts","../src/core/tracking.ts","../src/core/base.ts","../src/core/scheduler.ts","../src/core/atom.ts","../src/core/computed.ts","../src/core/effect.ts","../src/core/lens.ts"],"sourcesContent":["/**\n * Internal State Flags for ReactiveNode.\n *\n * Managed as a 31-bit integer field (V8 SMI optimization).\n *\n * Bit Layout:\n * [0-7] - Shared Core (Disposed, Computed marker, etc.)\n * [8-15] - Computed States (Dirty, Recomputing, etc.)\n * [16-23] - Async Lifecycle (Idle, Pending, Resolved, Rejected)\n * [24-30] - Primitive Specific (Atom Sync, Effect Executing, etc.)\n */\nconst FLAGS = {\n // --- Shared Core (0-7) ---\n DISPOSED: 1 << 0,\n IS_COMPUTED: 1 << 1,\n\n // --- Computed Flags (8-15) ---\n DIRTY: 1 << 8,\n RECOMPUTING: 1 << 9,\n HAS_ERROR: 1 << 10,\n FORCE_COMPUTE: 1 << 11,\n\n // --- Async States (16-23) ---\n IDLE: 1 << 16,\n PENDING: 1 << 17,\n RESOLVED: 1 << 18,\n REJECTED: 1 << 19,\n\n // --- Atom Specific (24-27) ---\n ATOM_SYNC: 1 << 24,\n ATOM_NOTIFICATION_SCHEDULED: 1 << 25,\n\n // --- Effect Specific (28-30) ---\n EFFECT_EXECUTING: 1 << 28,\n} as const;\n\n/**\n * Compound Masks for fast bitwise clearing/checking.\n */\nexport const STATE_MASKS = Object.freeze({\n /** Matches all bits related to async states (Idle, Pending, Resolved, Rejected). */\n ASYNC_STATE: FLAGS.IDLE | FLAGS.PENDING | FLAGS.RESOLVED | FLAGS.REJECTED,\n /** Matches all flags that indicate a computed node is dirty or recomputing. */\n COMPUTED_DIRTY_MASK: FLAGS.DIRTY | FLAGS.RECOMPUTING | FLAGS.FORCE_COMPUTE,\n});\n\n/**\n * Async operation states for public API and high-level checks.\n */\nexport const AsyncState = Object.freeze({\n IDLE: 'idle',\n PENDING: 'pending',\n RESOLVED: 'resolved',\n REJECTED: 'rejected',\n});\n\n/**\n * Effect flags.\n */\nexport const EFFECT_STATE_FLAGS = Object.freeze({\n DISPOSED: FLAGS.DISPOSED,\n EXECUTING: FLAGS.EFFECT_EXECUTING,\n});\n\n/**\n * Computed flags.\n */\nexport const COMPUTED_STATE_FLAGS = Object.freeze({\n DISPOSED: FLAGS.DISPOSED,\n IS_COMPUTED: FLAGS.IS_COMPUTED,\n DIRTY: FLAGS.DIRTY,\n IDLE: FLAGS.IDLE,\n PENDING: FLAGS.PENDING,\n RESOLVED: FLAGS.RESOLVED,\n REJECTED: FLAGS.REJECTED,\n RECOMPUTING: FLAGS.RECOMPUTING,\n HAS_ERROR: FLAGS.HAS_ERROR,\n FORCE_COMPUTE: FLAGS.FORCE_COMPUTE,\n});\n\n/**\n * Writable Atom Flags.\n */\nexport const ATOM_STATE_FLAGS = Object.freeze({\n DISPOSED: FLAGS.DISPOSED,\n SYNC: FLAGS.ATOM_SYNC,\n NOTIFICATION_SCHEDULED: FLAGS.ATOM_NOTIFICATION_SCHEDULED,\n});\n\n/**\n * Scheduler configuration.\n */\nexport const SCHEDULER_CONFIG = Object.freeze({\n // Infinite loop protection\n MAX_EXECUTIONS_PER_SECOND: 1000,\n MAX_EXECUTIONS_PER_EFFECT: 100,\n\n // Batch processing limits to prevent blocking the main thread for too long\n MAX_EXECUTIONS_PER_FLUSH: 10000,\n MAX_FLUSH_ITERATIONS: 1000,\n MIN_FLUSH_ITERATIONS: 10,\n\n // Memory management\n BATCH_QUEUE_SHRINK_THRESHOLD: 1000,\n});\n\n/**\n * V8 Small Integer (SMI) max value.\n */\nexport const SMI_MAX = 0x3fffffff;\n\n/**\n * Debugging thresholds.\n */\nexport const DEBUG_CONFIG = Object.freeze({\n WARN_INFINITE_LOOP: true,\n EFFECT_FREQUENCY_WINDOW: 1000,\n LOOP_THRESHOLD: 100,\n});\n\n/**\n * Computed configuration.\n */\nexport const COMPUTED_CONFIG = Object.freeze({\n MAX_PROMISE_ID: SMI_MAX,\n});\n\n/**\n * Epoch sentinel values.\n */\nexport const EPOCH_CONSTANTS = Object.freeze({\n /** Uninitialized epoch marker. Used as initial value before any flush has occurred. */\n UNINITIALIZED: -1,\n /** Minimum valid epoch value after a counter reset. */\n MIN: 1,\n});\n\nlet runtimeDebug = false;\ntry {\n runtimeDebug = !!(\n (typeof globalThis !== 'undefined' &&\n (globalThis as { __ATOM_DEBUG__?: boolean }).__ATOM_DEBUG__) ||\n (typeof sessionStorage !== 'undefined' && sessionStorage.getItem('__ATOM_DEBUG__') === 'true')\n );\n} catch {}\n\n/**\n * Development environment flag.\n */\nexport const IS_DEV =\n (typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production') ||\n (typeof __DEV__ !== 'undefined' && !!__DEV__) ||\n // @ts-expect-error: import.meta.env is Vite-specific and may not be defined in all environments\n (typeof import.meta !== 'undefined' && import.meta.env && import.meta.env.DEV) ||\n runtimeDebug;\n\n// Fallback declarations for global environment variables\ndeclare const __DEV__: boolean;\n\nexport const EMPTY_ERROR_ARRAY: readonly Error[] = Object.freeze([]);\n","/**\n * Structured JSON representation of an AtomError.\n */\nexport interface AtomErrorJSON {\n name: string;\n message: string;\n code?: string | undefined;\n recoverable: boolean;\n stack?: string | undefined;\n cause?: unknown | undefined;\n}\n\n/**\n * Constructor type for Atom errors.\n */\nexport type AtomErrorConstructor = new (\n message: string,\n cause?: unknown,\n recoverable?: boolean,\n code?: string\n) => AtomError;\n\n/**\n * Base error class for the Atom system.\n * Designed for high performance, traceability, and cycle protection.\n */\nexport class AtomError extends Error {\n override readonly name: string = 'AtomError';\n\n constructor(\n message: string,\n public readonly cause: unknown = null,\n public readonly recoverable: boolean = true,\n public readonly code?: string\n ) {\n super(message);\n\n // Maintain a stable object shape for V8\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Returns the entire error chain as an array.\n * Includes the circular node if a cycle is detected.\n */\n getChain(): Array<AtomError | Error | unknown> {\n // Fast path: no cause\n if (this.cause === null || this.cause === undefined) {\n return [this];\n }\n\n const chain: Array<AtomError | Error | unknown> = [this];\n const seen = new Set<unknown>([this]);\n let current: unknown = this.cause;\n\n while (current !== null && current !== undefined) {\n const alreadySeen = seen.has(current);\n chain.push(current);\n\n if (alreadySeen) break;\n seen.add(current);\n\n if (current instanceof AtomError) {\n current = current.cause;\n } else if (current instanceof Error && 'cause' in current) {\n current = (current as Error & { cause?: unknown }).cause;\n } else {\n break;\n }\n }\n return chain;\n }\n\n /**\n * Serializes the error to a structured object for logging.\n * Protected against circular references.\n */\n toJSON(seen: Set<unknown> = new Set()): AtomErrorJSON {\n if (seen.has(this)) {\n return {\n name: this.name,\n message: '[Circular Reference]',\n recoverable: this.recoverable,\n code: this.code,\n };\n }\n seen.add(this);\n\n let causeJson: unknown = this.cause;\n if (this.cause instanceof AtomError) {\n causeJson = this.cause.toJSON(seen);\n } else if (this.cause instanceof Error) {\n causeJson = {\n name: this.cause.name,\n message: this.cause.message,\n stack: this.cause.stack,\n cause: (this.cause as Error & { cause?: unknown }).cause,\n };\n }\n\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n recoverable: this.recoverable,\n stack: this.stack,\n cause: causeJson,\n };\n }\n\n /**\n * Internal helper to format wrapped messages consistently.\n */\n static format(source: string, context: string, message: string): string {\n return `${source} (${context}): ${message}`;\n }\n}\n\n/** Thrown when a computation fails. */\nexport class ComputedError extends AtomError {\n override readonly name = 'ComputedError';\n}\n\n/** Thrown when an effect execution or cleanup fails. */\nexport class EffectError extends AtomError {\n override readonly name = 'EffectError';\n constructor(message: string, cause: unknown = null, recoverable = false, code?: string) {\n super(message, cause, recoverable, code);\n }\n}\n\n/** Thrown by the execution engine or scheduler. */\nexport class SchedulerError extends AtomError {\n override readonly name = 'SchedulerError';\n constructor(message: string, cause: unknown = null, recoverable = false, code?: string) {\n super(message, cause, recoverable, code);\n }\n}\n\n/**\n * Registry of standardized error messages.\n */\nexport const ERROR_MESSAGES = {\n // Computed Errors\n COMPUTED_MUST_BE_FUNCTION: 'Computed target must be a function',\n COMPUTED_ASYNC_PENDING_NO_DEFAULT: 'Async computation pending with no default value',\n COMPUTED_COMPUTATION_FAILED: 'Computation execution failed',\n COMPUTED_ASYNC_COMPUTATION_FAILED: 'Async computation execution failed',\n COMPUTED_CIRCULAR_DEPENDENCY: 'Circular dependency detected',\n COMPUTED_DISPOSED: 'Attempted to access disposed computed',\n\n // Atom Errors\n ATOM_SUBSCRIBER_MUST_BE_FUNCTION: 'Subscriber must be a function or Subscriber object',\n ATOM_INDIVIDUAL_SUBSCRIBER_FAILED: 'Subscriber execution failed',\n\n // Effect Errors\n EFFECT_MUST_BE_FUNCTION: 'Effect target must be a function',\n EFFECT_EXECUTION_FAILED: 'Effect execution failed',\n EFFECT_CLEANUP_FAILED: 'Effect cleanup failed',\n EFFECT_DISPOSED: 'Attempted to run disposed effect',\n\n // Scheduler Errors\n SCHEDULER_FLUSH_OVERFLOW: (max: number, dropped: number): string =>\n `Maximum flush iterations (${max}) exceeded. ${dropped} jobs dropped. Possible infinite loop.`,\n\n // System / Debug\n CALLBACK_ERROR_IN_ERROR_HANDLER: 'Exception encountered in onError handler',\n EFFECT_FREQUENCY_LIMIT_EXCEEDED:\n 'Effect executed too frequently within 1 second. Suspected infinite loop.',\n SCHEDULER_CALLBACK_MUST_BE_FUNCTION: 'Scheduler callback must be a function',\n SCHEDULER_END_BATCH_WITHOUT_START: 'endBatch() called without matching startBatch(). Ignoring.',\n BATCH_CALLBACK_MUST_BE_FUNCTION: 'Batch callback must be a function',\n} as const;\n\n/**\n * Wraps any value into the Atom error hierarchy, preserving the trace and context.\n *\n * @param error - The raw error or object thrown.\n * @param ErrorClass - The specific AtomError subclass to use.\n * @param context - Human-readable description of where the error occurred.\n */\nexport function wrapError(\n error: unknown,\n ErrorClass: AtomErrorConstructor,\n context: string\n): AtomError {\n // 1. AtomError (Chainable Trace)\n if (error instanceof AtomError) {\n return new ErrorClass(\n AtomError.format(error.name, context, error.message),\n error,\n error.recoverable,\n error.code\n );\n }\n\n // 2. Native Error\n if (error instanceof Error) {\n const type = error.name || error.constructor.name || 'Error';\n return new ErrorClass(AtomError.format(type, context, error.message), error);\n }\n\n // 3. Unknown Types (Raw Preservation)\n return new ErrorClass(AtomError.format('Unexpected error', context, String(error)), error);\n}\n","import { DEBUG_CONFIG, IS_DEV } from '@/constants';\nimport type { DebugConfig, DependencyId } from '@/types';\n\n/**\n * Debug symbols used to store metadata on objects without interfering with their normal properties.\n * These are exported to allow external inspection or custom debugging tools.\n */\n\n/** Symbol used to store and retrieve a human-readable name for an atom or effect. */\nexport const DEBUG_NAME = Symbol('AtomEffect.DebugName');\n/** Symbol used to store and retrieve the unique internal ID. */\nexport const DEBUG_ID = Symbol('AtomEffect.Id');\n/** Symbol used to store and retrieve the type identifier (e.g., 'atom', 'effect'). */\nexport const DEBUG_TYPE = Symbol('AtomEffect.Type');\n/** Symbol used as a sentinel value to indicate that no default value was provided. */\nexport const NO_DEFAULT_VALUE = Symbol('AtomEffect.NoDefaultValue');\n\n/** Log prefix for Atom Effect console messages. */\nconst PREFIX = '[Atom Effect]';\n\n/**\n * Optimized Debug controller implementation for development environments.\n * Provides active monitoring, logging, and inspection capabilities.\n *\n * @internal\n * @implements {DebugConfig}\n */\nclass DevDebugController implements DebugConfig {\n /** Whether debugging features are currently active. */\n public enabled = true;\n\n /** Whether to warn when a potential infinite loop is detected. */\n public warnInfiniteLoop = DEBUG_CONFIG.WARN_INFINITE_LOOP;\n\n /** Tracks the number of updates per dependency within a single execution scope. */\n private _updateCounts = new Map<DependencyId, number>();\n\n /**\n * Weakly references registered nodes to allow garbage collection while maintaining\n * a list for graph dumping.\n */\n private _nodeRegistry = new Map<DependencyId, WeakRef<object>>();\n\n /** Threshold for triggering an infinite loop warning. */\n private _threshold = DEBUG_CONFIG.LOOP_THRESHOLD;\n\n /** Prevents redundant cleanup scheduling. */\n private _cleanupScheduled = false;\n\n /**\n * Logs a warning message if the condition is met and debugging is enabled.\n *\n * @param cond - The condition to check.\n * @param msg - The message to log if the condition is true.\n */\n public warn = (cond: boolean, msg: string): void => {\n if (this.enabled && cond) console.warn(`${PREFIX} ${msg}`);\n };\n\n /**\n * Registers a node in the internal registry for tracking and graph generation.\n * Uses WeakRef to prevent memory leaks.\n *\n * @param node - The object/node to register, must have a unique DependencyId.\n */\n public registerNode = (node: object & { id: DependencyId }): void => {\n this._nodeRegistry.set(node.id, new WeakRef(node));\n };\n\n /**\n * Attaches debug metadata to a runtime object.\n *\n * @param obj - The object to attach info to.\n * @param type - The type of the node (e.g., 'atom', 'selector', 'effect').\n * @param id - The unique internal identifier.\n * @param customName - Optional user-defined name for easier identification.\n */\n public attachDebugInfo = (\n obj: object,\n type: string,\n id: DependencyId,\n customName?: string\n ): void => {\n if (!this.enabled) return;\n\n Object.defineProperties(obj, {\n [DEBUG_NAME]: { value: customName ?? `${type}_${id}`, configurable: true },\n [DEBUG_ID]: { value: id, configurable: true },\n [DEBUG_TYPE]: { value: type, configurable: true },\n });\n\n this.registerNode(obj as { id: DependencyId });\n };\n\n /**\n * Tracks an update to a dependency and checks for infinite loops.\n * Counts are automatically reset at the end of the current microtask.\n *\n * @param id - The unique identifier of the dependency being updated.\n * @param name - An optional display name for the warning message.\n */\n public trackUpdate = (id: DependencyId, name?: string): void => {\n if (!this.enabled || !this.warnInfiniteLoop) return;\n\n const counts = this._updateCounts;\n const count = (counts.get(id) ?? 0) + 1;\n\n if (count > this._threshold) {\n this.warn(\n true,\n `Infinite loop detected for ${name ?? `dependency ${id}`}. Over ${this._threshold} updates in a single execution scope.`\n );\n } else {\n counts.set(id, count);\n }\n\n if (!this._cleanupScheduled) {\n this._cleanupScheduled = true;\n // Reset counts at the end of the current microtask to prevent memory leaks\n // and false positives across different execution cycles.\n Promise.resolve().then(() => {\n this._updateCounts.clear();\n this._cleanupScheduled = false;\n });\n }\n };\n\n /**\n * Generates a snapshot of the current reactive graph.\n * Automatically prunes dead references from the registry.\n *\n * @returns An array of debug info objects for all currently alive nodes.\n */\n public dumpGraph = (): Record<string, unknown>[] => {\n const result: Record<string, unknown>[] = [];\n for (const [id, ref] of this._nodeRegistry) {\n const node = ref.deref();\n if (node) {\n result.push({\n id,\n name: this.getDebugName(node),\n type: this.getDebugType(node),\n updateCount: this._updateCounts.get(id) ?? 0,\n });\n } else {\n this._nodeRegistry.delete(id);\n this._updateCounts.delete(id);\n }\n }\n return result;\n };\n\n /**\n * Retrieves the debug name from an object if it exists.\n *\n * @param obj - the object to inspect.\n * @returns The human-readable name or undefined.\n */\n public getDebugName = (obj: object | null | undefined): string | undefined => {\n if (!obj) return undefined;\n return (obj as Record<symbol, unknown>)[DEBUG_NAME] as string | undefined;\n };\n\n /**\n * Retrieves the debug type from an object if it exists.\n *\n * @param obj - the object to inspect.\n * @returns The type identifier or undefined.\n */\n public getDebugType = (obj: object | null | undefined): string | undefined => {\n if (!obj) return undefined;\n return (obj as Record<symbol, unknown>)[DEBUG_TYPE] as string | undefined;\n };\n}\n\n/**\n * Inert implementation of the Debug controller for production environments.\n * All operations are no-ops to ensure maximum performance and minimal bundle size.\n *\n * @internal\n * @implements {DebugConfig}\n */\nconst ProdDebugController: DebugConfig = {\n enabled: false,\n warnInfiniteLoop: false,\n warn: () => {},\n registerNode: () => {},\n attachDebugInfo: () => {},\n trackUpdate: () => {},\n dumpGraph: () => [],\n getDebugName: () => undefined,\n getDebugType: () => undefined,\n};\n\n/**\n * The global debug singleton instance.\n * Automatically switches between development and production implementations\n * based on the environment configuration (IS_DEV).\n *\n * In production, this becomes a lightweight object with empty methods,\n * allowing engines to inline or ignore calls, effectively providing zero overhead.\n *\n * @public\n */\nexport const debug: DebugConfig = IS_DEV ? new DevDebugController() : ProdDebugController;\n\n/**\n * Internal counter for generating unique DependencyIds.\n * @private\n */\nlet nextId = 1;\n\n/**\n * Generates a unique, monotonically increasing integer ID.\n * Casts to DependencyId type for internal type safety.\n *\n * @returns A fresh DependencyId.\n * @public\n */\nexport const generateId = (): DependencyId => (nextId++ | 0) as DependencyId;\n","// ── SlotBuffer ──────────────────────────────────────────────────────────\n\n/**\n * A ultra-high-performance, allocation-optimized container for reactive subscribers.\n *\n * Design Philosophy:\n * 1. Inline Storage: Uses 4 object properties (_s0.._s3) to store items directly.\n * Since >90% of reactive nodes have 1-4 subscribers, this avoids array creation entirely.\n * 2. Spill-over Model: Shifts to a lazy-allocated overflow array only when necessary.\n * 3. Size Duality: Distinguishes between Physical Boundary (_count) and Logical Size (_actualCount)\n * to support fast iteration while maintaining hole-reuse capabilities.\n */\nexport class SlotBuffer<T> {\n // Direct property slots for ultra-fast access and zero allocation.\n _s0: T | null = null;\n _s1: T | null = null;\n _s2: T | null = null;\n _s3: T | null = null;\n\n // Bookkeeping fields\n /** Physical high-water mark. Indicates the highest index ever occupied + 1. */\n _count = 0;\n /** Logical element count. Number of non-null items currently in the buffer. */\n _actualCount = 0;\n /** Lazy overflow container for index >= 4. */\n _overflow: (T | null)[] | null = null;\n /** LIFO reuse-stack of freed overflow indices to maintain O(1) addition. */\n _freeIndices: number[] | null = null;\n\n // ── Internal Physical Primitives ──────────────────────────────────────\n\n /**\n * Low-level atomic write.\n * Does NOT update bookkeeping counters. Used as a building block for higher APIs.\n */\n protected _rawWrite(index: number, item: T | null): void {\n if (index < 4) {\n if (index === 0) this._s0 = item;\n else if (index === 1) this._s1 = item;\n else if (index === 2) this._s2 = item;\n else this._s3 = item;\n } else {\n if (this._overflow === null) {\n this._overflow = [];\n }\n const ov = this._overflow;\n const ovIdx = index - 4;\n // Growth-on-demand for sparse writes via setAt()\n ov[ovIdx] = item;\n }\n }\n\n /**\n * Finds the first available hole or appends to the tail.\n * Returns the assigned physical index.\n */\n protected _rawAdd(item: T): number {\n if (this._s0 === null) {\n this._s0 = item;\n return 0;\n }\n if (this._s1 === null) {\n this._s1 = item;\n return 1;\n }\n if (this._s2 === null) {\n this._s2 = item;\n return 2;\n }\n if (this._s3 === null) {\n this._s3 = item;\n return 3;\n }\n\n if (this._overflow === null) {\n this._overflow = [];\n }\n const ov = this._overflow;\n const free = this._freeIndices;\n if (free !== null && free.length > 0) {\n const idx = free.pop()!;\n ov[idx] = item;\n return idx + 4;\n }\n ov.push(item);\n return 4 + ov.length - 1;\n }\n\n /** Atomic swap of two physical slots. Essential for dependency relocation. */\n protected _rawSwap(idxA: number, idxB: number): void {\n if (idxA === idxB) return;\n const valA = this.getAt(idxA);\n const valB = this.getAt(idxB);\n this._rawWrite(idxA, valB);\n this._rawWrite(idxB, valA);\n }\n\n // ── Public API ────────────────────────────────────────────────────────\n\n /** Number of active (non-null) elements. */\n get size(): number {\n return this._actualCount;\n }\n /** Highest physical index + 1. */\n get physicalSize(): number {\n return this._count;\n }\n\n /** Retrieves item at the specified index. O(1). */\n getAt(index: number): T | null {\n if (index < 4) {\n if (index === 0) return this._s0;\n if (index === 1) return this._s1;\n if (index === 2) return this._s2;\n return this._s3;\n }\n const ov = this._overflow;\n return ov?.[index - 4] ?? null;\n }\n\n /**\n * Sets item at index.\n * Forces recalculation of logic size and high-water mark reduction on nullification.\n */\n setAt(index: number, item: T | null): void {\n const old = this.getAt(index);\n if (old === item) return;\n\n this._rawWrite(index, item);\n\n // Sync logical count (Active items tracking)\n if (old === null) this._actualCount++;\n else if (item === null) this._actualCount--;\n\n // Sync physical high-water mark (Iteration boundary tracking)\n if (item !== null && index >= this._count) {\n this._count = index + 1;\n } else if (item === null) {\n this._shrinkPhysicalSizeFrom(index);\n }\n }\n\n /** Shrinks high-water mark recursively from the tail. */\n private _shrinkPhysicalSizeFrom(index: number): void {\n if (index === this._count - 1) {\n this._count--;\n while (this._count > 0 && this.getAt(this._count - 1) == null) {\n this._count--;\n }\n }\n }\n\n /**\n * Truncates the buffer to a specific size.\n * Normalizes the high-water mark even if the current count is 0.\n */\n truncateFrom(index: number): void {\n // 1. Cleanup inline slots\n if (index <= 3) {\n if (index <= 0 && this._s0 !== null) {\n this._onItemRemoved(this._s0);\n this._s0 = null;\n this._actualCount--;\n }\n if (index <= 1 && this._s1 !== null) {\n this._onItemRemoved(this._s1);\n this._s1 = null;\n this._actualCount--;\n }\n if (index <= 2 && this._s2 !== null) {\n this._onItemRemoved(this._s2);\n this._s2 = null;\n this._actualCount--;\n }\n if (index <= 3 && this._s3 !== null) {\n this._onItemRemoved(this._s3);\n this._s3 = null;\n this._actualCount--;\n }\n }\n\n // 2. Cleanup overflow array\n const ov = this._overflow;\n if (ov !== null) {\n const ovStart = index > 4 ? index - 4 : 0;\n const len = ov.length;\n for (let i = ovStart; i < len; i++) {\n const item = ov[i];\n if (item != null) {\n this._onItemRemoved(item);\n ov[i] = null;\n this._actualCount--;\n }\n }\n if (index <= 4) {\n this._overflow = null;\n } else {\n ov.length = index - 4;\n }\n }\n\n this._count = index; // Normalize high-water mark as requested by tracking cycles.\n if (this._actualCount < 0) this._actualCount = 0;\n this._freeIndices = null; // Reset reuse pool during truncation.\n }\n\n /**\n * Internal hook for resource cleanup (e.g. unsubscriptions).\n * @internal For use in DepSlotBuffer only.\n */\n protected _onItemRemoved(_item: T): void {}\n\n /** Appends an item to the buffer. Returns assigned index. O(1). */\n add(item: T): number {\n const idx = this._rawAdd(item);\n if (idx >= this._count) this._count = idx + 1;\n this._actualCount++;\n return idx;\n }\n\n /** Removes an item by reference. O(N). */\n remove(item: T): boolean {\n // Search in priority order: inline first.\n let idx = -1;\n if (this._s0 === item) {\n idx = 0;\n } else if (this._s1 === item) {\n idx = 1;\n } else if (this._s2 === item) {\n idx = 2;\n } else if (this._s3 === item) {\n idx = 3;\n } else {\n const ov = this._overflow;\n if (ov !== null) {\n idx = ov.indexOf(item);\n if (idx !== -1) idx += 4;\n }\n }\n\n if (idx !== -1) {\n this._rawWrite(idx, null);\n this._shrinkPhysicalSizeFrom(idx);\n this._actualCount--;\n if (idx >= 4) {\n if (this._freeIndices === null) {\n this._freeIndices = [];\n }\n this._freeIndices.push(idx - 4);\n }\n return true;\n }\n return false;\n }\n\n /** O(N) presence check. */\n has(item: T): boolean {\n if (this._actualCount === 0) return false;\n if (this._s0 === item || this._s1 === item || this._s2 === item || this._s3 === item)\n return true;\n const ov = this._overflow;\n if (ov !== null) return ov.indexOf(item) !== -1;\n return false;\n }\n\n /** Optimized iteration. Fast-path triggers when buffer is dense (no holes). */\n forEach(fn: (item: T) => void): void {\n const actual = this._actualCount;\n if (actual === 0) return;\n\n if (actual === this._count) {\n if (this._s0 != null) fn(this._s0);\n if (this._s1 != null) fn(this._s1);\n if (this._s2 != null) fn(this._s2);\n if (this._s3 != null) fn(this._s3);\n const ov = this._overflow;\n if (ov !== null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const item = ov[i];\n if (item != null) fn(item);\n }\n }\n return;\n }\n\n let count = 0;\n const limit = this._count;\n for (let i = 0; i < limit; i++) {\n const item = this.getAt(i);\n if (item != null) {\n fn(item);\n if (++count >= actual) break;\n }\n }\n }\n\n /** Elimination of all holes via in-place shifting. Zero-allocation. */\n compact(): void {\n if (this._actualCount === this._count) return;\n\n let writeIdx = 0;\n const limit = this._count;\n for (let readIdx = 0; readIdx < limit; readIdx++) {\n const item = this.getAt(readIdx);\n if (item != null) {\n if (readIdx !== writeIdx) {\n this._rawWrite(writeIdx, item);\n this._rawWrite(readIdx, null);\n }\n writeIdx++;\n }\n }\n\n this._count = this._actualCount;\n if (this._overflow !== null) {\n if (writeIdx <= 4) this._overflow = null;\n else this._overflow.length = writeIdx - 4;\n }\n this._freeIndices = null;\n }\n\n /** Complete reset and memory release. */\n clear(): void {\n this._s0 = this._s1 = this._s2 = this._s3 = null;\n this._count = 0;\n this._actualCount = 0;\n this._overflow = null;\n this._freeIndices = null;\n }\n\n dispose(): void {\n this.clear();\n }\n}\n\n// ── DepSlotBuffer ───────────────────────────────────────────────────────\n\nimport type { Dependency } from '@/types';\nimport type { DependencyLink } from './tracking';\n\n/**\n * Specialized high-speed buffer for Dependency Tracking Cycles.\n *\n * DESIGN:\n * 1. Ordering: Keeps dependencies in the order of execution to minimize seeks.\n * 2. Relocation: Swaps existing links to current track index to maintain \"Dense-head\" structure.\n * 3. Map Optimization: Switches to Node->Index Map lookup once distance exceeds 32 slots.\n */\nexport class DepSlotBuffer extends SlotBuffer<DependencyLink> {\n private _map: Map<Dependency, number> | null = null;\n private readonly _SCAN_THRESHOLD = 32;\n\n hasComputeds = false;\n prepareTracking(): void {\n this.hasComputeds = false;\n }\n\n protected override _onItemRemoved(link: DependencyLink): void {\n link.unsub?.();\n }\n\n /** Synchronizes the Node->Index Map when setting entries directly. */\n override setAt(index: number, item: DependencyLink | null): void {\n const old = this.getAt(index);\n super.setAt(index, item);\n\n if (this._map !== null) {\n if (old?.unsub) this._map.delete(old.node);\n if (item?.unsub) this._map.set(item.node, index);\n }\n }\n\n /**\n * Finds and reuses a dependency from a previous cycle.\n * If found, it relocates the link to trackIndex via swapping.\n */\n claimExisting(dep: Dependency, trackIndex: number): boolean {\n const length = this._count;\n if (length <= trackIndex) return false;\n\n // 1. Optimistic direct hit check.\n const current = this.getAt(trackIndex);\n if (current && current.node === dep && current.unsub) {\n current.version = dep.version;\n return true;\n }\n\n // 2. High-volume lookup via Map once scope threshold is exceeded.\n if (this._map !== null || length - trackIndex > this._SCAN_THRESHOLD) {\n return this._claimViaMap(dep, trackIndex);\n }\n\n // 3. Sequential search for small scopes (faster than Map hashing).\n for (let i = trackIndex + 1; i < length; i++) {\n const l = this.getAt(i);\n if (l && l.node === dep && l.unsub) {\n l.version = dep.version;\n this._rawSwap(i, trackIndex);\n return true;\n }\n }\n return false;\n }\n\n private _claimViaMap(dep: Dependency, trackIndex: number): boolean {\n if (this._map === null) {\n this._map = this._initMap();\n }\n const map = this._map;\n const existingIndex = map.get(dep);\n if (existingIndex === undefined || existingIndex < trackIndex) return false;\n\n const link = this.getAt(existingIndex);\n // Safety check against external slot corruption.\n if (link == null || !link.unsub) return false;\n\n link.version = dep.version;\n\n if (existingIndex !== trackIndex) {\n const occupant = this.getAt(trackIndex);\n this._rawSwap(existingIndex, trackIndex);\n\n map.set(dep, trackIndex);\n if (occupant?.unsub) map.set(occupant.node, existingIndex);\n }\n return true;\n }\n\n private _initMap(): Map<Dependency, number> {\n const map = new Map<Dependency, number>();\n for (let i = 0; i < this._count; i++) {\n const link = this.getAt(i);\n if (link?.unsub) map.set(link.node, i);\n }\n return map;\n }\n\n /**\n * Inserts a new link at trackIdx.\n * Relocates any current occupant at trackIdx to make room.\n */\n insertNew(trackIdx: number, link: DependencyLink): void {\n const occupant = this.getAt(trackIdx);\n if (occupant !== null) {\n // Moves occupant to the first available hole to preserve its subscription.\n const newIdx = this._rawAdd(occupant);\n if (newIdx >= this._count) this._count = newIdx + 1;\n if (this._map !== null && occupant.unsub) this._map.set(occupant.node, newIdx);\n }\n\n this._rawWrite(trackIdx, link);\n if (trackIdx >= this._count) this._count = trackIdx + 1;\n\n // NET GAIN PRINCIPLE:\n // If occupant was present: occupant moved to null slot (+0) + link added (+1) = +1 total size gain.\n // If occupant was null: link added to null slot (+1) = +1 total size gain.\n this._actualCount++;\n\n if (this._map !== null && link.unsub) this._map.set(link.node, trackIdx);\n }\n\n override add(item: DependencyLink): number {\n const idx = super.add(item);\n if (this._map !== null && item.unsub) this._map.set(item.node, idx);\n return idx;\n }\n\n override remove(_item: DependencyLink): boolean {\n throw new Error('remove() prohibited');\n }\n override compact(): void {}\n\n override truncateFrom(index: number): void {\n super.truncateFrom(index);\n if (this._map !== null) {\n this._map = null; // Clear map cache to avoid memory leaks.\n }\n }\n\n disposeAll(): void {\n this.truncateFrom(0);\n this.hasComputeds = false;\n }\n}\n","/**\n * Global brand symbol for all reactive primitives.\n * Uses a bitwise mask for high-performance type identification.\n */\nexport const BRAND: unique symbol = Symbol.for('atom-effect/brand');\n\n/**\n * Bitwise flags for brand identification.\n */\nexport const BrandFlags = {\n Atom: 1 << 0,\n Writable: 1 << 1,\n Computed: 1 << 2,\n Effect: 1 << 3,\n} as const;\n","import { BRAND, BrandFlags } from '@/symbols';\nimport type { ComputedAtom, EffectObject, ReadonlyAtom, WritableAtom } from '@/types';\n\n/**\n * Internal helper to check for a brand flag on objects or functions.\n * Optimized for high-performance bitwise identification.\n */\nfunction isBranded<T>(obj: unknown, flag: number): obj is T {\n if (!obj) return false;\n const type = typeof obj;\n return (\n (type === 'object' || type === 'function') &&\n // Bitwise AND check on the consolidated BRAND symbol\n !!(((obj as Record<symbol, number>)[BRAND] ?? 0) & flag)\n );\n}\n\n/**\n * Readonly atom check.\n */\nexport function isAtom(obj: unknown): obj is ReadonlyAtom {\n return isBranded(obj, BrandFlags.Atom);\n}\n\n/**\n * Writable atom check.\n */\nexport function isWritable(obj: unknown): obj is WritableAtom {\n return isBranded(obj, BrandFlags.Writable);\n}\n\n/**\n * Computed atom check.\n */\nexport function isComputed(obj: unknown): obj is ComputedAtom {\n return isBranded(obj, BrandFlags.Computed);\n}\n\n/**\n * Effect object check.\n */\nexport function isEffect(obj: unknown): obj is EffectObject {\n return isBranded(obj, BrandFlags.Effect);\n}\n\n/**\n * Promise check.\n * Includes a fast-path for native Promises and supports duck-typed thenables.\n */\nexport function isPromise<T>(value: unknown): value is Promise<T> {\n if (value instanceof Promise) return true;\n if (!value) return false;\n const type = typeof value;\n return (\n (type === 'object' || type === 'function') &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n","import { IS_DEV } from '@/constants';\nimport type { Dependency, Subscriber } from '@/types';\nimport { debug } from '@/utils/debug';\nimport { isPromise } from '@/utils/type-guards';\n\n// ── Tracking Types ──────────────────────────────────────────────────────\n\n/**\n * Dependency consumer.\n * Objects implementing this can be registered as the current tracking target.\n */\nexport interface DependencySubscriber {\n /**\n * Registers a dependency to this subscriber.\n */\n addDependency(dep: Dependency): void;\n}\n\n/**\n * Executable unit.\n * Represents a reactive node or effect that can be re-run.\n */\nexport interface ExecutableSubscriber {\n execute(): void;\n}\n\n/**\n * Dependency tracker.\n * Combines dependency collection and execution capabilities.\n */\nexport interface DependencyTracker extends DependencySubscriber, ExecutableSubscriber {}\n\n/**\n * Trackable function.\n * A function that is also recognized as a dependency consumer.\n */\nexport type TrackableFunction = (() => void) & DependencySubscriber;\n\n// ── Dependency Link & Subscription ───────────────────────────────────────\n\n/**\n * Dependency graph edge.\n * Maintains the link between a subscriber and its dependency.\n */\nexport class DependencyLink {\n constructor(\n public node: Dependency,\n public version: number,\n /**\n * Unsubscribe cleanup function.\n * Default value ensures consistent V8 hidden class shape.\n */\n public unsub: (() => void) | undefined = undefined\n ) {}\n}\n\n/**\n * Subscription entry.\n * Encapsulates the notification logic for a dependency change.\n */\nexport class Subscription<T> {\n constructor(\n /**\n * Optional callback. Always initialized to maintain hidden class.\n */\n public fn: ((newValue?: T, oldValue?: T) => void) | undefined = undefined,\n /**\n * Optional subscriber. Always initialized to maintain hidden class.\n */\n public sub: Subscriber | undefined = undefined\n ) {}\n\n /**\n * Notifies the subscriber of a value change.\n *\n * @remarks\n * Execution is wrapped in `untracked` to prevent context leakage.\n */\n notify(newValue?: T, oldValue?: T): void {\n untracked(() => {\n const fn = this.fn;\n if (fn !== undefined) {\n fn(newValue, oldValue);\n }\n\n const sub = this.sub;\n if (sub !== undefined) {\n sub.execute();\n }\n });\n }\n}\n\n// ── Tracking Context ────────────────────────────────────────────────────\n\n/**\n * Tracking context implementation.\n * Manages the global stack of active dependency collectors.\n */\nclass TrackingContext {\n /** Active subscriber at the top of the stack. */\n public current: DependencySubscriber | null = null;\n\n /**\n * Executes a function within the scope of a specific subscriber.\n *\n * @param subscriber - The subscriber to collect dependencies for.\n * @param fn - The logic to execute.\n * @returns The result of `fn`.\n */\n public run<T>(subscriber: DependencySubscriber, fn: () => T): T {\n // Fast path: already in the correct context\n if (this.current === subscriber) {\n return fn();\n }\n\n const prev = this.current;\n this.current = subscriber;\n\n try {\n const result = fn();\n\n // Async detection: check if the function returned a Promise\n if (IS_DEV) {\n debug.warn(\n isPromise(result),\n 'Detected Promise returned within tracking context. ' +\n 'Dependencies accessed after \"await\" will NOT be tracked. ' +\n 'Consider using synchronous tracking before the async boundary.'\n );\n }\n\n return result;\n } finally {\n // Synchronous restoration is required for safety in multi-tasking environments\n this.current = prev;\n }\n }\n}\n\n/**\n * Global tracking context singleton.\n */\nexport const trackingContext = new TrackingContext();\n\n/**\n * Tracking context type.\n */\nexport type { TrackingContext };\n\n// ── Untracked ───────────────────────────────────────────────────────────\n\n/**\n * Executes a function without dependency tracking.\n *\n * @param fn - Function to execute.\n * @returns Result of `fn`.\n */\nexport function untracked<T>(fn: () => T): T {\n const ctx = trackingContext;\n const prev = ctx.current;\n\n // Optimized: Skip context switching if already untracked\n if (prev === null) {\n return fn();\n }\n\n ctx.current = null;\n try {\n return fn();\n } finally {\n ctx.current = prev;\n }\n}\n","import { COMPUTED_STATE_FLAGS, EPOCH_CONSTANTS, IS_DEV, SMI_MAX } from '@/constants';\nimport { AtomError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport type { DependencyId, Subscriber } from '@/types';\nimport { generateId } from '@/utils/debug';\nimport { type DepSlotBuffer, SlotBuffer } from './buffers';\nimport { Subscription } from './tracking';\n\n/**\n * Unified base class for all reactive nodes (Atoms, Computeds, Effects).\n *\n * Optimized for V8 Hidden Class Monomorphism by having a single, consistent\n * object shape for all reactive logic.\n *\n * @template T - The type of value produced by this node (used for subscriptions).\n */\nexport abstract class ReactiveNode<T> {\n /** [Producer/Consumer] State flags */\n flags: number;\n /** [Producer/Consumer] Version counter */\n version: number;\n /** [Producer/Consumer] Last access epoch */\n _lastSeenEpoch: number;\n /** [Context] Scheduler epoch tag */\n _nextEpoch: number | undefined;\n /** [Debug] Unique ID for identify node in tracking maps */\n readonly id: DependencyId;\n\n /**\n * [Producer] Managed subscribers.\n */\n _slots: SlotBuffer<Subscription<T>> | null;\n\n /** [Producer] Re-entry guard for notification loop. */\n _notifying: number;\n\n /**\n * [Consumer] Managed dependencies.\n */\n _deps: DepSlotBuffer | null;\n /** [Consumer] O(1) Hot-path dependency index for rapid dirty checks. */\n _hotIndex: number;\n\n constructor() {\n this.flags = 0;\n this.version = 0;\n this._lastSeenEpoch = EPOCH_CONSTANTS.UNINITIALIZED;\n this._nextEpoch = undefined;\n this._notifying = 0;\n this._hotIndex = -1;\n this._slots = null;\n this._deps = null;\n this.id = generateId() & SMI_MAX;\n }\n\n /**\n * Whether the node has been disposed.\n * @internal\n */\n get isDisposed(): boolean {\n return (this.flags & COMPUTED_STATE_FLAGS.DISPOSED) !== 0; // Bit 0: DISPOSED\n }\n\n /**\n * Whether the node is a computed atom.\n * @internal\n */\n get isComputed(): boolean {\n return (this.flags & COMPUTED_STATE_FLAGS.IS_COMPUTED) !== 0; // Bit 1: IS_COMPUTED\n }\n\n /**\n * Whether the node currently has an error.\n * @internal\n */\n get hasError(): boolean {\n return false;\n }\n\n // ============================================================================\n // Producer Logic (Subscriber Management)\n // ============================================================================\n\n /**\n * Adds subscriber for notifications.\n */\n subscribe(listener: ((newValue?: T, oldValue?: T) => void) | Subscriber): () => void {\n const isFn = typeof listener === 'function';\n if (!isFn && (!listener || typeof (listener as Subscriber).execute !== 'function')) {\n throw wrapError(\n new TypeError('Invalid subscriber'),\n AtomError,\n ERROR_MESSAGES.ATOM_SUBSCRIBER_MUST_BE_FUNCTION\n );\n }\n\n let slots = this._slots;\n if (!slots) {\n slots = new SlotBuffer<Subscription<T>>();\n this._slots = slots;\n }\n\n // Duplicate check: Unrolled for performance + early exit\n let duplicate = false;\n if (slots._s0 != null && (isFn ? slots._s0.fn === listener : slots._s0.sub === listener)) {\n duplicate = true;\n } else if (\n slots._s1 != null &&\n (isFn ? slots._s1.fn === listener : slots._s1.sub === listener)\n ) {\n duplicate = true;\n } else if (\n slots._s2 != null &&\n (isFn ? slots._s2.fn === listener : slots._s2.sub === listener)\n ) {\n duplicate = true;\n } else if (\n slots._s3 != null &&\n (isFn ? slots._s3.fn === listener : slots._s3.sub === listener)\n ) {\n duplicate = true;\n } else {\n const ov = slots._overflow;\n if (ov != null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const s = ov[i];\n if (s != null && (isFn ? s.fn === listener : s.sub === listener)) {\n duplicate = true;\n break;\n }\n }\n }\n }\n\n if (duplicate) {\n if (IS_DEV) console.warn(`[atom-effect] Duplicate subscription ignored on node ${this.id}`);\n return () => {};\n }\n\n const link = new Subscription<T>(\n isFn ? (listener as (newValue?: T, oldValue?: T) => void) : undefined,\n !isFn ? (listener as Subscriber) : undefined\n );\n\n slots.add(link);\n return () => this._unsubscribe(link);\n }\n\n protected _unsubscribe(link: Subscription<T>): void {\n const slots = this._slots;\n if (!slots) return;\n\n slots.remove(link);\n if (this._notifying === 0) {\n slots.compact();\n }\n }\n\n /**\n * Returns current subscriber count.\n */\n subscriberCount(): number {\n const slots = this._slots;\n return slots === null ? 0 : slots.size;\n }\n\n /**\n * Notifies all subscribers about a value update.\n */\n protected _notifySubscribers(newValue: T | undefined, oldValue: T | undefined): void {\n const slots = this._slots;\n if (slots === null || slots.size === 0) return;\n\n this._notifying++;\n try {\n // 1. Inline slots: Manual unroll to avoid closure allocation\n let s = slots._s0;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n s = slots._s1;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n s = slots._s2;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n s = slots._s3;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n\n // 2. Overflow scan: Standard loop for performance\n const ov = slots._overflow;\n if (ov != null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const sub = ov[i];\n if (sub != null) {\n try {\n sub.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n }\n }\n } finally {\n if (--this._notifying === 0) {\n slots.compact();\n }\n }\n }\n\n private _logNotifyError(err: unknown): void {\n console.error(wrapError(err, AtomError, ERROR_MESSAGES.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED));\n }\n\n // ============================================================================\n // Consumer Logic (Dependency Validation)\n // ============================================================================\n\n /**\n * Determines if the node is dirty by checking its dependency chain.\n * Optimized with O(1) hot-path check.\n */\n protected _isDirty(): boolean {\n const deps = this._deps;\n if (deps === null || deps.size === 0) return false;\n\n // Phase 1: Hot-path Check - O(1)\n const hotIndex = this._hotIndex;\n if (hotIndex !== -1) {\n const hotLink = deps.getAt(hotIndex);\n if (hotLink != null && hotLink.node.version !== hotLink.version) {\n return true;\n }\n }\n\n // Phase 2: Standard Validation - O(N)\n return this._deepDirtyCheck();\n }\n\n /**\n * Deeply validates dependency versions.\n */\n protected abstract _deepDirtyCheck(): boolean;\n}\n","import { IS_DEV, SCHEDULER_CONFIG, SMI_MAX } from '@/constants';\nimport { ERROR_MESSAGES, SchedulerError } from '@/errors';\n\n// ── Epoch & Version Management ──────────────────────────────────────────\n\n/**\n * Global epoch counter used for job deduplication and tracking state consistency.\n */\nlet collectorEpoch = 0;\n\n/**\n * Returns the next tracking epoch.\n * Wraps around using SMI_MAX and reserves 0 for uninitialized state.\n */\nexport function nextEpoch(): number {\n const next = (collectorEpoch + 1) & SMI_MAX;\n collectorEpoch = next === 0 ? 1 : next;\n return collectorEpoch;\n}\n\n/**\n * Returns the current global tracking epoch.\n */\nexport function currentEpoch(): number {\n return collectorEpoch;\n}\n\n/**\n * Increments a version counter within SMI range.\n * Reservations: Avoids 0 to allow it as a 'never updated' marker.\n */\nexport function nextVersion(v: number): number {\n const next = (v + 1) & SMI_MAX;\n return next === 0 ? 1 : next;\n}\n\n/** Current number of executions in the active flush cycle. */\nexport let flushExecutionCount = 0;\nlet isFlushing = false;\nlet _flushEpoch = 0;\n\n/** Returns the epoch associated with the current flush cycle. */\nexport function currentFlushEpoch(): number {\n return _flushEpoch;\n}\n\n/**\n * Starts a new flush cycle.\n * @returns true if the cycle was successfully started, false if already flushing.\n */\nexport function startFlush(): boolean {\n if (isFlushing) {\n if (IS_DEV) {\n console.warn('startFlush() called during flush - ignored');\n }\n return false;\n }\n\n isFlushing = true;\n _flushEpoch = nextEpoch();\n flushExecutionCount = 0;\n return true;\n}\n\n/** Ends the current flush cycle. */\nexport function endFlush(): void {\n isFlushing = false;\n}\n\n/**\n * Runs a function within a managed flush scope.\n * Ensures the flush state is properly incremented and cleaned up.\n *\n * @param fn - The function to execute.\n * @returns The result of the function execution.\n */\nexport function runInFlushScope<T>(fn: () => T): T | undefined {\n const started = startFlush();\n try {\n return fn();\n } finally {\n if (started) endFlush();\n }\n}\n\n/**\n * Track total execution count within a flush.\n * Throws if the count exceeds configured safety limits to prevent hung processes.\n */\nexport function incrementFlushExecutionCount(): number {\n if (!isFlushing) return 0;\n\n const count = ++flushExecutionCount;\n if (count <= SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH) {\n return count;\n }\n\n throw new Error(\n `[atom-effect] Infinite loop detected: flush execution count exceeded ${SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH}`\n );\n}\n\n/** Resets all global flush-related states to their defaults. */\nexport function resetFlushState(): void {\n _flushEpoch = 0;\n flushExecutionCount = 0;\n isFlushing = false;\n}\n\n// ── Scheduler ───────────────────────────────────────────────────────────\n\nexport interface SchedulerJobObject {\n execute(): void;\n /** Internal tracking for deduplication within the same epoch. */\n _nextEpoch?: number | undefined;\n}\n\n/** Represents a job that can be executed by the scheduler via a function interface. */\nexport interface SchedulerJobFunction {\n (): void;\n /** Internal tracking for deduplication within the same epoch. */\n _nextEpoch?: number | undefined;\n}\n\n/** Union type representing any valid schedulable task. */\nexport type SchedulerJob = SchedulerJobFunction | SchedulerJobObject;\n\n/**\n * Core Scheduler that manages asynchronous and synchronous task execution.\n *\n * Features:\n * - Double buffering for stable queue processing.\n * - Automatic job deduplication via Epoch tagging.\n * - Nested batching support with automatic coalescence.\n * - Microsecond-level scheduling via queueMicrotask.\n */\nclass Scheduler {\n /** Double buffer to allow scheduling new jobs while processing the current queue. */\n private _queueBuffer: [(SchedulerJob | undefined)[], (SchedulerJob | undefined)[]] = [[], []];\n /** Pointer to the currently active buffer for ingestion. */\n private _bufferIndex = 0;\n /** Current size of the active ingestion buffer. */\n private _size = 0;\n /** Current internal epoch for job tagging. */\n private _epoch = 0;\n\n /** Flag indicating the scheduler is currently draining a microtask loop. */\n private _isProcessing = false;\n /** Flag indicating a synchronous flush (batch end) is currently active. */\n private _isFlushingSync = false;\n\n /** Number of active nested batch contexts. */\n private _batchDepth = 0;\n /** Temporary holding area for jobs scheduled during an active batch or sync flush. */\n private _batchQueue: (SchedulerJob | undefined)[] = [];\n /** Current number of jobs in the batch holding area. */\n private _batchQueueSize = 0;\n\n /** Maximum allowed internal loop iterations before assuming an infinite loop. */\n private _maxFlushIterations: number = SCHEDULER_CONFIG.MAX_FLUSH_ITERATIONS;\n\n /** Optional callback fired when the scheduler drops jobs due to overflow. */\n onOverflow: ((droppedCount: number) => void) | null = null;\n\n private readonly _boundRunLoop = this._runLoop.bind(this);\n\n /** Returns the total number of pending jobs (active + batched). */\n get queueSize(): number {\n return this._size + this._batchQueueSize;\n }\n\n /** Returns true if the scheduler is currently within a `batch()` scope. */\n get isBatching(): boolean {\n return this._batchDepth > 0;\n }\n\n /**\n * Schedules a job for execution.\n * Jobs are deduplicated based on the current epoch; if the same job is scheduled twice\n * in the same epoch, the second call is ignored.\n *\n * @param callback - The task to be executed.\n */\n schedule(callback: SchedulerJob): void {\n if (IS_DEV) {\n if (\n typeof callback !== 'function' &&\n (!callback || typeof (callback as SchedulerJobObject).execute !== 'function')\n ) {\n throw new SchedulerError(ERROR_MESSAGES.SCHEDULER_CALLBACK_MUST_BE_FUNCTION);\n }\n }\n\n const epoch = this._epoch;\n if (callback._nextEpoch === epoch) return;\n callback._nextEpoch = epoch;\n\n // If batching or sync flushing, move to batch queue to ensure order and coalescence.\n if (this._batchDepth > 0 || this._isFlushingSync) {\n this._batchQueue[this._batchQueueSize++] = callback;\n return;\n }\n\n const buffer = this._queueBuffer[this._bufferIndex]!;\n buffer[this._size++] = callback;\n\n if (!this._isProcessing) {\n this._flush();\n }\n }\n\n /** Initiates an asynchronous flush via microtask. */\n private _flush(): void {\n if (this._isProcessing || this._size === 0) return;\n this._isProcessing = true;\n queueMicrotask(this._boundRunLoop);\n }\n\n /** Internal microtask execution loop. */\n private _runLoop(): void {\n try {\n if (this._size === 0 && this._batchQueueSize === 0) return;\n\n const started = startFlush();\n this._drainQueue();\n if (started) endFlush();\n } finally {\n this._isProcessing = false;\n }\n }\n\n /** Internal synchronous flush typically triggered at the end of a batch. */\n _flushSync(): void {\n if (this._size === 0 && this._batchQueueSize === 0) return;\n\n const prev = this._isFlushingSync;\n this._isFlushingSync = true;\n const started = startFlush();\n try {\n this._mergeBatchQueue();\n this._drainQueue();\n } finally {\n this._isFlushingSync = prev;\n if (started) endFlush();\n }\n }\n\n /**\n * Merges the temporal batch queue into the main active buffer.\n * Increments the epoch to allow previously executed jobs to be re-scheduled if needed.\n */\n private _mergeBatchQueue(): void {\n const queueSize = this._batchQueueSize;\n if (queueSize === 0) return;\n\n this._epoch = (this._epoch + 1) | 0;\n const epoch = this._epoch;\n const bQueue = this._batchQueue;\n const targetBuffer = this._queueBuffer[this._bufferIndex]!;\n let currentSize = this._size;\n\n for (let i = 0; i < queueSize; i++) {\n const job = bQueue[i]!;\n if (job._nextEpoch !== epoch) {\n job._nextEpoch = epoch;\n targetBuffer[currentSize++] = job;\n }\n bQueue[i] = undefined; // Immediate GC hint\n }\n\n this._size = currentSize;\n this._batchQueueSize = 0;\n // Shrink array if it grew significantly, otherwise keep capacity to avoid re-allocs.\n if (bQueue.length > SCHEDULER_CONFIG.BATCH_QUEUE_SHRINK_THRESHOLD) bQueue.length = 0;\n }\n\n /**\n * Continuous loop that drains both main and batch queues.\n * Processes until all queues are empty or max iterations reached.\n */\n private _drainQueue(): void {\n let iterations = 0;\n while (this._size > 0 || this._batchQueueSize > 0) {\n if (++iterations > this._maxFlushIterations) {\n this._handleFlushOverflow();\n return;\n }\n\n if (this._batchQueueSize > 0) this._mergeBatchQueue();\n if (this._size > 0) this._processQueue();\n }\n }\n\n /** Executes all jobs currently in the primary buffer and swaps buffers. */\n private _processQueue(): void {\n const idx = this._bufferIndex;\n const jobs = this._queueBuffer[idx]!;\n const count = this._size;\n\n // Buffer swapping: ingestion now happens in the previously dormant buffer.\n this._bufferIndex = idx ^ 1;\n this._size = 0;\n this._epoch = (this._epoch + 1) | 0;\n\n for (let i = 0; i < count; i++) {\n const job = jobs[i]!;\n jobs[i] = undefined; // Avoid memory leaks by clearing references immediately.\n try {\n if (typeof job === 'function') {\n job();\n } else {\n job.execute();\n }\n } catch (e) {\n console.error(new SchedulerError('Error occurred during scheduler execution', e as Error));\n }\n }\n }\n\n /** Resets the scheduler state on infinite loop detection and notifies via onOverflow. */\n private _handleFlushOverflow(): void {\n const droppedCount = this._size + this._batchQueueSize;\n console.error(\n new SchedulerError(\n ERROR_MESSAGES.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations, droppedCount)\n )\n );\n\n this._size = 0;\n this._queueBuffer[0]!.length = 0;\n this._queueBuffer[1]!.length = 0;\n this._batchQueueSize = 0;\n this._batchQueue.length = 0;\n\n const onOverflow = this.onOverflow;\n if (onOverflow) {\n try {\n onOverflow(droppedCount);\n } catch {}\n }\n }\n\n /** Enters a new batching depth. */\n startBatch(): void {\n this._batchDepth++;\n }\n\n /**\n * Decrements batching depth. If depth reaches 0, triggers a synchronous flush\n * to apply all coherent updates collected during the batch.\n */\n endBatch(): void {\n if (this._batchDepth === 0) {\n if (IS_DEV) console.warn(ERROR_MESSAGES.SCHEDULER_END_BATCH_WITHOUT_START);\n return;\n }\n\n if (--this._batchDepth === 0) {\n if (!this._isFlushingSync) {\n this._flushSync();\n }\n }\n }\n\n /** Configures the maximum safety iterations for the flush loop. */\n setMaxFlushIterations(max: number): void {\n if (max < SCHEDULER_CONFIG.MIN_FLUSH_ITERATIONS)\n throw new SchedulerError(\n `Max iterations must be at least ${SCHEDULER_CONFIG.MIN_FLUSH_ITERATIONS}`\n );\n this._maxFlushIterations = max;\n }\n}\n\n/** Global scheduler instance. */\nexport const scheduler = new Scheduler();\n\n/**\n * Groups multiple state updates into a single batch, delaying effects and computations\n * until the batch is closed.\n *\n * @param fn - The function containing state updates.\n * @returns The result of the function execution.\n * @throws {TypeError} If fn is not a function.\n */\nexport function batch<T>(fn: () => T): T {\n if (IS_DEV && typeof fn !== 'function') {\n throw new TypeError(ERROR_MESSAGES.BATCH_CALLBACK_MUST_BE_FUNCTION);\n }\n\n scheduler.startBatch();\n try {\n return fn();\n } finally {\n scheduler.endBatch();\n }\n}\n","import { ATOM_STATE_FLAGS } from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { BRAND, BrandFlags } from '@/symbols';\nimport type { AtomOptions, WritableAtom } from '@/types';\nimport { debug } from '@/utils/debug';\nimport { nextVersion, scheduler } from './scheduler';\nimport { trackingContext } from './tracking';\n\n/**\n * Internal {@link WritableAtom} implementation.\n */\nclass AtomImpl<T> extends ReactiveNode<T> implements WritableAtom<T> {\n private _value: T;\n /** Old value for notifications */\n private _pendingOldValue: T | undefined;\n /** Equality comparator */\n private _equal: (a: T, b: T) => boolean;\n\n /** @internal */\n readonly [BRAND] = BrandFlags.Atom | BrandFlags.Writable;\n\n constructor(initialValue: T, options: AtomOptions<T>) {\n super();\n this._value = initialValue;\n this._equal = options.equal ?? Object.is;\n\n if (options.sync) {\n this.flags |= ATOM_STATE_FLAGS.SYNC;\n }\n\n debug.attachDebugInfo(this, 'atom', this.id, options.name);\n }\n\n /** @internal */\n get isNotificationScheduled(): boolean {\n return (this.flags & ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED) !== 0;\n }\n\n /** @internal */\n get isSync(): boolean {\n return (this.flags & ATOM_STATE_FLAGS.SYNC) !== 0;\n }\n\n get value(): T {\n const ctx = trackingContext.current;\n if (ctx != null) {\n ctx.addDependency(this);\n }\n return this._value;\n }\n\n set value(newValue: T) {\n const oldValue = this._value;\n if (this._equal(oldValue, newValue)) return;\n\n this._value = newValue;\n this.version = nextVersion(this.version);\n debug.trackUpdate(this.id, debug.getDebugName(this));\n\n // 1. Double check: schedule pending or no slots\n if ((this.flags & ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED) !== 0) return;\n\n const slots = this._slots;\n if (slots == null || slots.size === 0) return;\n\n this._pendingOldValue = oldValue;\n this.flags |= ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED;\n\n // 2. Schedule or flush (inline bitwise)\n if ((this.flags & ATOM_STATE_FLAGS.SYNC) !== 0 && !scheduler.isBatching) {\n // If not already notifying, start the flush loop.\n // If already notifying, the existing loop will pick up the new flag.\n if (this._notifying === 0) {\n this._flushNotifications();\n }\n } else {\n scheduler.schedule(this);\n }\n }\n\n /**\n * Executes scheduled notification.\n * @internal\n */\n execute(): void {\n this._flushNotifications();\n }\n\n /**\n * Triggers subscribers.\n */\n private _flushNotifications(): void {\n const SCHED_BIT = ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED;\n const DISP_BIT = ATOM_STATE_FLAGS.DISPOSED;\n const SYNC_BIT = ATOM_STATE_FLAGS.SYNC;\n\n // Loop to handle re-entrant sync updates in breadth-first order\n while ((this.flags & (SCHED_BIT | DISP_BIT)) === SCHED_BIT) {\n const oldValue = this._pendingOldValue as T;\n this._pendingOldValue = undefined;\n this.flags &= ~SCHED_BIT;\n\n // Net-zero check: if value returned to original during batching, skip notification\n if (!this._equal(this._value, oldValue)) {\n this._notifySubscribers(this._value, oldValue);\n }\n\n // Only continue looping if we are in sync mode and not batching.\n // For async mode, the scheduler handles subsequent executions.\n if ((this.flags & SYNC_BIT) === 0 || scheduler.isBatching) {\n break;\n }\n }\n }\n\n peek(): T {\n return this._value;\n }\n\n dispose(): void {\n const flags = this.flags;\n if ((flags & ATOM_STATE_FLAGS.DISPOSED) !== 0) return;\n\n this._slots?.clear();\n this.flags = flags | ATOM_STATE_FLAGS.DISPOSED;\n // Release references\n this._value = undefined as T;\n this._pendingOldValue = undefined;\n this._equal = Object.is; // Reset to default\n }\n\n protected override _deepDirtyCheck(): boolean {\n return false;\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n}\n\n/**\n * Creates a reactive atom holding mutable state.\n *\n * @param initialValue - The initial value of the atom.\n * @param options - Configuration options (sync: boolean).\n */\nexport function atom<T>(initialValue: T, options: AtomOptions = {}): WritableAtom<T> {\n return new AtomImpl(initialValue, options);\n}\n","import {\n AsyncState,\n COMPUTED_CONFIG,\n COMPUTED_STATE_FLAGS,\n EMPTY_ERROR_ARRAY,\n EPOCH_CONSTANTS,\n IS_DEV,\n} from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { ComputedError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport { BRAND, BrandFlags } from '@/symbols';\nimport type {\n AsyncStateType,\n ComputedAtom,\n ComputedOptions,\n Dependency,\n Subscriber,\n} from '@/types';\nimport { debug, NO_DEFAULT_VALUE } from '@/utils/debug';\nimport { isPromise } from '@/utils/type-guards';\nimport { DepSlotBuffer } from './buffers';\nimport { nextEpoch, nextVersion } from './scheduler';\nimport { DependencyLink, trackingContext, untracked } from './tracking';\n\nconst {\n IDLE,\n DIRTY,\n PENDING,\n RESOLVED,\n REJECTED,\n HAS_ERROR,\n RECOMPUTING,\n DISPOSED,\n IS_COMPUTED,\n FORCE_COMPUTE,\n} = COMPUTED_STATE_FLAGS;\n\n/**\n * Computed atom implementation.\n */\nclass ComputedAtomImpl<T> extends ReactiveNode<T> implements ComputedAtom<T>, Subscriber {\n /** @internal */\n readonly [BRAND] = BrandFlags.Atom | BrandFlags.Computed;\n\n private _value: T;\n private _error: Error | null = null;\n /** Promise tracking ID */\n private _promiseId = 0;\n\n private readonly _equal: (a: T, b: T) => boolean;\n private readonly _fn: () => T | Promise<T>;\n private readonly _defaultValue: T;\n private readonly _onError: ((error: Error) => void) | null;\n\n /** Initialized in constructor. Unified node property. */\n _deps = new DepSlotBuffer();\n\n // Async state\n\n // Dependency collection state\n private _trackEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _trackCount = 0;\n\n constructor(fn: () => T | Promise<T>, options: ComputedOptions<T> = {}) {\n if (typeof fn !== 'function') throw new ComputedError(ERROR_MESSAGES.COMPUTED_MUST_BE_FUNCTION);\n super();\n\n this._value = undefined as T;\n // Start dirty so first access triggers computation\n this.flags = IS_COMPUTED | DIRTY | IDLE;\n this._equal = options.equal ?? Object.is;\n this._fn = fn;\n this._defaultValue = 'defaultValue' in options ? options.defaultValue : (NO_DEFAULT_VALUE as T);\n this._onError = options.onError ?? null;\n\n debug.attachDebugInfo(this, 'computed', this.id, options.name);\n\n // Eager evaluation if not lazy\n if (options.lazy === false) {\n try {\n this._recompute();\n } catch {\n /* _handleError already stored error and called onError */\n }\n }\n }\n\n /** @internal */\n get isDirty(): boolean {\n return (this.flags & DIRTY) !== 0;\n }\n\n /** @internal */\n get isRejected(): boolean {\n return (this.flags & REJECTED) !== 0;\n }\n\n /** @internal */\n get isRecomputing(): boolean {\n return (this.flags & RECOMPUTING) !== 0;\n }\n\n private get _hasErrorInternal(): boolean {\n return (this.flags & HAS_ERROR) !== 0;\n }\n\n private _track(): void {\n trackingContext.current?.addDependency(this);\n }\n\n get value(): T {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n\n let flags = this.flags;\n // 1. Fast path: Stable and Resolved\n if ((flags & (RESOLVED | DIRTY | IDLE)) === RESOLVED) {\n return this._value;\n }\n\n // 2. Exception paths\n if ((flags & DISPOSED) !== 0) throw new ComputedError(ERROR_MESSAGES.COMPUTED_DISPOSED);\n\n if ((flags & RECOMPUTING) !== 0) {\n const def = this._defaultValue;\n if (def !== (NO_DEFAULT_VALUE as T)) return def;\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_CIRCULAR_DEPENDENCY);\n }\n\n // 3. Evaluation path\n if ((flags & (DIRTY | IDLE)) !== 0) {\n const deps = this._deps;\n if (\n (flags & IDLE) === 0 &&\n (flags & FORCE_COMPUTE) === 0 &&\n deps.size > 0 &&\n !this._isDirty()\n ) {\n flags = this.flags &= ~DIRTY;\n } else {\n this._recompute();\n flags = this.flags;\n }\n if ((flags & RESOLVED) !== 0) return this._value;\n }\n\n // 4. Async/Error handling\n const def = this._defaultValue;\n const hasDefault = def !== (NO_DEFAULT_VALUE as T);\n\n if ((flags & PENDING) !== 0) {\n if (hasDefault) return def;\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_ASYNC_PENDING_NO_DEFAULT);\n }\n\n if ((flags & REJECTED) !== 0) {\n if (hasDefault) return def;\n throw this._error;\n }\n\n return this._value;\n }\n\n peek(): T {\n return this._value;\n }\n\n get state(): AsyncStateType {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n const flags = this.flags;\n if ((flags & RESOLVED) !== 0) return AsyncState.RESOLVED;\n if ((flags & PENDING) !== 0) return AsyncState.PENDING;\n if ((flags & REJECTED) !== 0) return AsyncState.REJECTED;\n return AsyncState.IDLE;\n }\n\n get hasError(): boolean {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n\n const flags = this.flags;\n // Inlined checks for REJECTED | HAS_ERROR\n if ((flags & (REJECTED | HAS_ERROR)) !== 0) return true;\n\n const deps = this._deps;\n if (!deps.hasComputeds) return false;\n\n // Isolate tracking to prevent bubbling dependencies from polluting the current context\n return untracked(() => {\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n if (link?.node.hasError) return true;\n }\n return false;\n });\n }\n\n get isValid(): boolean {\n return !this.hasError;\n }\n\n get errors(): readonly Error[] {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n\n const selfErr = this._error;\n const deps = this._deps;\n\n // Early exit: no computed dependencies means no bubbling errors\n if (!deps.hasComputeds) {\n if (selfErr == null) return EMPTY_ERROR_ARRAY;\n return Object.freeze([selfErr]);\n }\n\n const collected: Error[] = [];\n if (selfErr != null) collected.push(selfErr);\n\n // Isolate tracking and accumulate errors recursively\n untracked(() => {\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n const depNode = link?.node;\n if (depNode != null && (depNode.flags & IS_COMPUTED) !== 0) {\n this._accumulateErrors(depNode as unknown as ComputedAtomImpl<unknown>, collected);\n }\n }\n });\n\n return collected.length === 0 ? EMPTY_ERROR_ARRAY : Object.freeze(collected);\n }\n\n /**\n * Internal helper to collect unique errors from a computed dependency.\n */\n private _accumulateErrors(dep: ComputedAtomImpl<unknown>, collected: Error[]): void {\n const err = dep._error;\n if (err != null && !collected.includes(err)) {\n collected.push(err);\n }\n\n const deps = dep._deps;\n if (!deps.hasComputeds) return;\n\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n const node = link?.node;\n if (node != null && (node.flags & IS_COMPUTED) !== 0) {\n this._accumulateErrors(node as unknown as ComputedAtomImpl<unknown>, collected);\n }\n }\n }\n\n get lastError(): Error | null {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n return this._error;\n }\n\n get isPending(): boolean {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n return (this.flags & PENDING) !== 0;\n }\n\n get isResolved(): boolean {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n return (this.flags & RESOLVED) !== 0;\n }\n\n invalidate(): void {\n this.flags |= FORCE_COMPUTE;\n this._markDirty();\n }\n\n dispose(): void {\n const flags = this.flags;\n if ((flags & DISPOSED) !== 0) return;\n\n this._deps.disposeAll();\n\n if (this._slots != null) {\n this._slots.clear();\n }\n this.flags = DISPOSED | DIRTY | IDLE;\n\n // Release Memory\n this._error = null;\n this._value = undefined as T;\n this._hotIndex = -1;\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n addDependency(dep: Dependency): void {\n const trackEpoch = this._trackEpoch;\n if (dep._lastSeenEpoch === trackEpoch) return;\n dep._lastSeenEpoch = trackEpoch;\n\n const trackIndex = this._trackCount++;\n const deps = this._deps;\n const existing = deps.getAt(trackIndex);\n\n // 1. Stable Path: dependency index remains the same\n if (existing != null && existing.node === dep) {\n existing.version = dep.version;\n }\n // 2. Diverged Path: lookup or insert\n else if (deps.claimExisting(dep, trackIndex)) {\n // Version updated inside claimExisting\n }\n // 3. New dependency\n else {\n const link = new DependencyLink(dep, dep.version, dep.subscribe(this));\n deps.insertNew(trackIndex, link);\n }\n\n if ((dep.flags & IS_COMPUTED) !== 0) {\n deps.hasComputeds = true;\n }\n }\n\n private _recompute(): void {\n if (this.isRecomputing) return;\n this.flags = (this.flags | RECOMPUTING) & ~FORCE_COMPUTE;\n\n this._trackEpoch = nextEpoch();\n this._trackCount = 0;\n this._deps.prepareTracking();\n this._hotIndex = -1;\n\n let committed = false;\n try {\n // Execute function\n const result = trackingContext.run(this, this._fn);\n\n // Clean up any remaining trailing dependencies\n this._deps.truncateFrom(this._trackCount);\n\n committed = true;\n\n // Handle Result\n if (isPromise(result)) {\n this._handleAsyncComputation(result);\n } else {\n this._finalizeResolution(result);\n }\n } catch (e) {\n // Commit dependencies on error gracefully\n if (!committed) {\n try {\n this._deps.truncateFrom(this._trackCount);\n } catch (commitErr) {\n if (IS_DEV) {\n console.warn('[atom-effect] _commitDeps failed during error recovery:', commitErr);\n }\n }\n }\n this._handleError(e as Error, ERROR_MESSAGES.COMPUTED_COMPUTATION_FAILED, true);\n } finally {\n // Reset transient state\n this._trackEpoch = EPOCH_CONSTANTS.UNINITIALIZED;\n this._trackCount = 0;\n this.flags &= ~RECOMPUTING;\n }\n }\n\n private _handleAsyncComputation(promise: Promise<T>): void {\n // Set pending, clear idle/dirty/resolved/rejected\n this.flags = (this.flags | PENDING) & ~(IDLE | DIRTY | RESOLVED | REJECTED);\n // Notify pending\n this._notifySubscribers(undefined, undefined);\n\n // Invalidate old promises\n this._promiseId = (this._promiseId + 1) % COMPUTED_CONFIG.MAX_PROMISE_ID;\n const promiseId = this._promiseId;\n\n promise.then(\n (res) => {\n if (promiseId !== this._promiseId) return; // Stale\n\n if (this._isDirty()) {\n return this._markDirty(); // Retry\n }\n\n this._finalizeResolution(res);\n this._notifySubscribers(res, undefined);\n },\n (err) =>\n promiseId === this._promiseId &&\n this._handleError(err, ERROR_MESSAGES.COMPUTED_ASYNC_COMPUTATION_FAILED)\n );\n }\n\n private _handleError(err: unknown, msg: string, throwErr = false): void {\n const error = wrapError(err, ComputedError, msg);\n\n // Always bump version if state changed to rejected or the error instance is different.\n // This ensures bubbling and tracking systems are aware of the transition or change.\n if (!this.isRejected || this._error !== error) {\n this.version = nextVersion(this.version);\n }\n\n this._error = error;\n // Set rejected + has_error, clear idle/dirty/pending/resolved\n this.flags = (this.flags & ~(IDLE | DIRTY | PENDING | RESOLVED)) | REJECTED | HAS_ERROR;\n\n if (this._onError) {\n try {\n this._onError(error);\n } catch (e) {\n console.error(ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER, e);\n }\n }\n\n // Must notify subscribers BEFORE throwing, otherwise the reactivity chain is broken\n // for synchronous failures.\n this._notifySubscribers(undefined, undefined);\n\n if (throwErr) throw error;\n }\n\n private _finalizeResolution(value: T): void {\n const flags = this.flags;\n // Only bump version if value actually changed or first resolve\n if ((flags & RESOLVED) === 0 || !this._equal(this._value, value)) {\n this.version = nextVersion(this.version);\n }\n\n this._value = value;\n this._error = null;\n // Set resolved, clear idle/dirty/pending/rejected/has_error\n this.flags = (flags | RESOLVED) & ~(IDLE | DIRTY | PENDING | REJECTED | HAS_ERROR);\n }\n\n execute(): void {\n // Subscriber implementation\n this._markDirty();\n }\n\n /** @internal */\n _markDirty(): void {\n const flags = this.flags;\n if ((flags & (RECOMPUTING | DIRTY)) !== 0) return;\n this.flags = flags | DIRTY;\n debug.trackUpdate(this.id, debug.getDebugName(this));\n this._notifySubscribers(undefined, undefined);\n }\n\n /**\n * Deep dirty check for computations.\n */\n protected override _deepDirtyCheck(): boolean {\n const deps = this._deps;\n return untracked(() => {\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n if (link == null) continue;\n\n const dep = link.node;\n // Inlined isComputed check\n if ((dep.flags & IS_COMPUTED) !== 0) {\n try {\n // Force computed to re-evaluate so version reflects latest state\n void (dep as { value: unknown }).value;\n } catch {\n if (IS_DEV)\n console.warn(`[atom-effect] Dependency #${dep.id} threw during dirty check`);\n }\n }\n\n if (dep.version !== link.version) {\n this._hotIndex = i;\n return true;\n }\n }\n\n this._hotIndex = -1;\n return false;\n });\n }\n}\n\n/**\n * Creates a computed value.\n * @param fn - Computation function\n * @param options - Options object\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);\n}\n","import {\n DEBUG_CONFIG,\n EFFECT_STATE_FLAGS,\n EPOCH_CONSTANTS,\n IS_DEV,\n SCHEDULER_CONFIG,\n} from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { EffectError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport { BRAND, BrandFlags } from '@/symbols';\nimport type { Dependency, EffectFunction, EffectObject, EffectOptions } from '@/types';\nimport { debug } from '@/utils/debug';\nimport { isPromise } from '@/utils/type-guards';\nimport { DepSlotBuffer } from './buffers';\nimport {\n currentFlushEpoch,\n flushExecutionCount,\n incrementFlushExecutionCount,\n nextEpoch,\n scheduler,\n} from './scheduler';\nimport { DependencyLink, type DependencyTracker, trackingContext } from './tracking';\n\n/**\n * Effect implementation.\n */\nclass EffectImpl extends ReactiveNode<void> implements EffectObject, DependencyTracker {\n /** @internal */\n readonly [BRAND] = BrandFlags.Effect;\n\n private _cleanup: (() => void) | null = null;\n /** Initialized in constructor to maintain God Class object shape */\n _deps = new DepSlotBuffer();\n\n /** Pre-allocated notify callback shared by all subscriptions */\n private readonly _notifyCallback: () => void;\n\n private readonly _onError: ((error: unknown) => void) | null;\n\n // Cycle detection\n private _currentEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _lastFlushEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _executionsInEpoch: number;\n\n private readonly _fn: EffectFunction;\n private readonly _sync: boolean;\n private readonly _maxExecutions: number;\n private readonly _maxExecutionsPerFlush: number;\n // Frequency tracking (Dev)\n private _executionCount: number;\n private _windowStart: number;\n private _windowCount: number;\n private _execId: number;\n private _trackCount: number;\n\n constructor(fn: EffectFunction, options: EffectOptions = {}) {\n super();\n this._fn = fn;\n this._onError = options.onError ?? null;\n this._sync = options.sync ?? false;\n this._maxExecutions =\n options.maxExecutionsPerSecond ?? SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_SECOND;\n this._maxExecutionsPerFlush =\n options.maxExecutionsPerFlush ?? SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_EFFECT;\n\n this._executionsInEpoch = 0;\n this._executionCount = 0;\n this._windowStart = 0;\n this._windowCount = 0;\n this._execId = 0;\n this._trackCount = 0;\n\n // Pre-allocate callbacks once — eliminates per-dependency closure allocation\n if (this._sync) {\n this._notifyCallback = () => this.execute();\n } else {\n this._notifyCallback = () => scheduler.schedule(this);\n }\n\n debug.attachDebugInfo(this, 'effect', this.id, options.name);\n }\n\n public run(): void {\n if (this.isDisposed) {\n throw new EffectError(ERROR_MESSAGES.EFFECT_DISPOSED);\n }\n this.execute(true);\n }\n\n public dispose(): void {\n if (this.isDisposed) return;\n this.flags |= EFFECT_STATE_FLAGS.DISPOSED;\n\n this._execCleanup();\n this._deps?.disposeAll();\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n public addDependency(dep: Dependency): void {\n const flags = this.flags;\n if ((flags & EFFECT_STATE_FLAGS.EXECUTING) === 0) return;\n\n const startEpoch = this._currentEpoch;\n if (dep._lastSeenEpoch === startEpoch) return;\n dep._lastSeenEpoch = startEpoch;\n\n const trackIndex = this._trackCount++;\n const deps = this._deps;\n\n // Optimized: Direct access to inline slots for the hottest 4 dependencies\n let existing: DependencyLink | null;\n switch (trackIndex) {\n case 0:\n existing = deps._s0;\n break;\n case 1:\n existing = deps._s1;\n break;\n case 2:\n existing = deps._s2;\n break;\n case 3:\n existing = deps._s3;\n break;\n default:\n existing = deps.getAt(trackIndex);\n }\n\n // 1. Stable Path: dependency index remains the same\n if (existing != null && existing.node === dep) {\n existing.version = dep.version;\n }\n // 2. Diverged Path: lookup or insert\n else if (deps.claimExisting(dep, trackIndex)) {\n // Version updated in claimExisting\n }\n // 3. New dependency\n else {\n this._insertNewDependency(dep, trackIndex);\n }\n\n if (dep.isComputed) {\n deps.hasComputeds = true;\n }\n }\n\n private _insertNewDependency(dep: Dependency, trackIndex: number): void {\n let link: DependencyLink;\n try {\n const unsubscribe = dep.subscribe(this._notifyCallback);\n link = new DependencyLink(dep, dep.version, unsubscribe);\n } catch (error) {\n const wrapped = wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_EXECUTION_FAILED);\n console.error(wrapped);\n if (this._onError) {\n try {\n this._onError(wrapped);\n } catch {}\n }\n link = new DependencyLink(dep, dep.version, undefined);\n }\n\n this._deps!.insertNew(trackIndex, link);\n }\n\n /**\n * Executes effect with tracking.\n */\n public execute(force = false): void {\n const flags = this.flags;\n // Guard: Combined bitwise check for efficiency\n if ((flags & (EFFECT_STATE_FLAGS.DISPOSED | EFFECT_STATE_FLAGS.EXECUTING)) !== 0) return;\n\n // Skip if not dirty or forced\n const deps = this._deps;\n if (!force && deps.size > 0 && !this._isDirty()) return;\n\n this._checkInfiniteLoops();\n debug.trackUpdate(this.id, debug.getDebugName(this));\n\n this.flags = flags | EFFECT_STATE_FLAGS.EXECUTING;\n this._execCleanup();\n\n this._currentEpoch = nextEpoch();\n this._trackCount = 0;\n deps.prepareTracking();\n this._hotIndex = -1;\n\n let committed = false;\n try {\n const result = trackingContext.run(this, this._fn);\n\n // Clean up any remaining trailing dependencies\n deps.truncateFrom(this._trackCount);\n\n committed = true;\n\n // Handle result\n if (isPromise(result)) {\n this._handleAsyncResult(result);\n } else {\n this._cleanup = typeof result === 'function' ? result : null;\n }\n } catch (error) {\n // Commit on error gracefully to maintain state for recovery\n if (!committed) {\n try {\n deps.truncateFrom(this._trackCount);\n } catch (commitErr) {\n if (IS_DEV) {\n console.warn('[atom-effect] _commitDeps failed during error recovery:', commitErr);\n }\n }\n }\n this._handleExecutionError(error);\n this._cleanup = null;\n } finally {\n this.flags &= ~EFFECT_STATE_FLAGS.EXECUTING;\n }\n }\n\n private _handleAsyncResult(promise: Promise<unknown>): void {\n const execId = ++this._execId;\n promise.then(\n (cleanup) => {\n // Guard against race conditions (new execution or disposal happened)\n if (execId !== this._execId || this.isDisposed) {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (e) {\n this._handleExecutionError(e, ERROR_MESSAGES.EFFECT_CLEANUP_FAILED);\n }\n }\n return;\n }\n if (typeof cleanup === 'function') this._cleanup = cleanup as () => void;\n },\n (err) => execId === this._execId && this._handleExecutionError(err)\n );\n }\n\n protected override _deepDirtyCheck(): boolean {\n const prevContext = trackingContext.current;\n trackingContext.current = null;\n const deps = this._deps!;\n\n try {\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n if (link == null) continue;\n\n const dep = link.node;\n if (dep.isComputed) {\n this._tryPullComputed(dep);\n }\n\n if (dep.version !== link.version) {\n this._hotIndex = i;\n return true;\n }\n }\n return false;\n } finally {\n trackingContext.current = prevContext;\n }\n }\n\n private _tryPullComputed(dep: Dependency): void {\n try {\n // Force computed to re-evaluate so version reflects latest state\n void (dep as { value: unknown }).value;\n } catch {\n if (IS_DEV) {\n console.warn(`[atom-effect] Dependency #${dep.id} threw during dirty check`);\n }\n }\n }\n\n private _execCleanup(): void {\n const cleanup = this._cleanup;\n if (cleanup == null) return;\n this._cleanup = null;\n try {\n cleanup();\n } catch (error) {\n this._handleExecutionError(error, ERROR_MESSAGES.EFFECT_CLEANUP_FAILED);\n }\n }\n\n private _checkInfiniteLoops(): void {\n const epoch = currentFlushEpoch();\n if (this._lastFlushEpoch !== epoch) {\n this._lastFlushEpoch = epoch;\n this._executionsInEpoch = 0;\n }\n\n const executions = ++this._executionsInEpoch;\n if (executions > this._maxExecutionsPerFlush) this._throwInfiniteLoopError('per-effect');\n\n const globalExecutions = incrementFlushExecutionCount();\n if (globalExecutions > SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH) {\n this._throwInfiniteLoopError('global');\n }\n\n this._executionCount++;\n\n if (IS_DEV) this._checkFrequencyLimit();\n }\n\n private _checkFrequencyLimit(): void {\n if (!Number.isFinite(this._maxExecutions)) return;\n\n const now = Date.now();\n if (now - this._windowStart >= DEBUG_CONFIG.EFFECT_FREQUENCY_WINDOW) {\n this._windowStart = now;\n this._windowCount = 1;\n return;\n }\n\n if (++this._windowCount > this._maxExecutions) {\n const err = new EffectError(ERROR_MESSAGES.EFFECT_FREQUENCY_LIMIT_EXCEEDED);\n this.dispose();\n this._handleExecutionError(err);\n throw err;\n }\n }\n\n get executionCount(): number {\n return this._executionCount;\n }\n get isExecuting(): boolean {\n return (this.flags & EFFECT_STATE_FLAGS.EXECUTING) !== 0;\n }\n\n private _throwInfiniteLoopError(type: 'per-effect' | 'global'): never {\n const error = new EffectError(\n `Infinite loop detected (${type}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${flushExecutionCount}`\n );\n this.dispose();\n console.error(error);\n throw error;\n }\n\n private _handleExecutionError(\n error: unknown,\n message: string = ERROR_MESSAGES.EFFECT_EXECUTION_FAILED\n ): void {\n const errorObj = wrapError(error, EffectError, message);\n console.error(errorObj);\n if (this._onError) {\n try {\n this._onError(errorObj);\n } catch (e) {\n console.error(wrapError(e, EffectError, ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER));\n }\n }\n }\n}\n\n/**\n * Creates and starts an effect.\n *\n * @param fn - Effect function.\n * @param options - Configuration options.\n * @returns Effect instance.\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 effectInstance.execute();\n\n return effectInstance;\n}\n","import { BRAND, BrandFlags } from '@/symbols';\nimport type { Paths, PathValue, WritableAtom } from '../types';\n\n/** Blocks prototype pollution and dangerous object member access */\nconst SAFE_KEY_PATTERN = /^(?:__proto__|constructor|prototype)$/;\n\n/**\n * Internal recursive helper for creating deep immutable copies with structural sharing.\n * Only clones nodes along the path where changes occur.\n */\nexport function setDeepValue(obj: unknown, keys: string[], index: number, value: unknown): unknown {\n if (index === keys.length) return value;\n\n const key = keys[index]!;\n if (SAFE_KEY_PATTERN.test(key)) return obj;\n\n const curr = (obj != null && typeof obj === 'object' ? obj : {}) as Record<string, unknown>;\n const oldVal = curr[key];\n const newVal = setDeepValue(oldVal, keys, index + 1, value);\n\n if (Object.is(oldVal, newVal)) return obj;\n\n // Handle Array cloning with index awareness\n if (Array.isArray(curr)) {\n const arr = curr.slice();\n const idx = Number(key);\n if (key.trim() !== '' && Number.isInteger(idx) && idx >= 0) {\n arr[idx] = newVal;\n } else {\n (arr as unknown as Record<string, unknown>)[key] = newVal;\n }\n return arr;\n }\n\n return { ...curr, [key]: newVal };\n}\n\n/**\n * Helper to retrieve a nested value from an object/array at a given path.\n */\nexport function getPathValue(source: unknown, parts: string[]): unknown {\n let res = source;\n const len = parts.length;\n for (let i = 0; i < len; i++) {\n if (res == null) return undefined;\n const key = parts[i]!;\n if (SAFE_KEY_PATTERN.test(key)) return undefined;\n res = (res as Record<string, unknown>)[key];\n }\n return res;\n}\n\n/**\n * Creates a two-way \"lens\" for a specific property path on an object-based atom.\n *\n * @example\n * const store = atom({ user: { name: 'Alice' } });\n * const nameLens = atomLens(store, 'user.name');\n * console.log(nameLens.value); // 'Alice'\n * nameLens.value = 'Bob'; // Updates store.user.name immutably\n */\nexport function atomLens<T extends object, P extends Paths<T>>(\n atom: WritableAtom<T>,\n path: P\n): WritableAtom<PathValue<T, P>> {\n const parts = path.includes('.') ? path.split('.') : [path];\n const unsubs = new Set<() => void>();\n const dispose = () => {\n unsubs.forEach((u) => u());\n unsubs.clear();\n };\n\n return {\n get value() {\n return getPathValue(atom.value, parts) as PathValue<T, P>;\n },\n set value(newVal: PathValue<T, P>) {\n const cur = atom.peek(),\n next = setDeepValue(cur, parts, 0, newVal);\n if (next !== cur) atom.value = next as T;\n },\n peek: () => getPathValue(atom.peek(), parts) as PathValue<T, P>,\n subscribe(listener: (nv: PathValue<T, P>, ov: PathValue<T, P>) => void) {\n const unsub = atom.subscribe((np, op) => {\n const nv = getPathValue(np, parts) as PathValue<T, P>,\n ov = getPathValue(op, parts) as PathValue<T, P>;\n if (!Object.is(nv, ov)) listener(nv, ov);\n });\n unsubs.add(unsub);\n return () => {\n unsub();\n unsubs.delete(unsub);\n };\n },\n subscriberCount: () => unsubs.size,\n dispose,\n [Symbol.dispose]: dispose,\n [BRAND]: BrandFlags.Atom | BrandFlags.Writable,\n } as unknown as WritableAtom<PathValue<T, P>>;\n}\n\n/**\n * Composes an existing lens with a sub-path to create a deeper lens.\n */\nexport const composeLens = <T extends object, P extends Paths<T>>(lens: WritableAtom<T>, path: P) =>\n atomLens(lens, path);\n\n/**\n * Creates a lens factory bound to a specific atom.\n */\nexport const lensFor =\n <T extends object>(atom: WritableAtom<T>) =>\n <P extends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A,EAAU,GACjB,CAAA,EAAQ,EAAW,KAAO,EAAW,UAO1C,IAAa,GAAA,CAAqD,EAAuB,IACvF,GAAS,EAAM,CAAA,EAKJ,GACQ,GACE,GACnB,GAAS,EAAM,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../src/constants.ts","../src/errors.ts","../src/utils/debug.ts","../src/core/buffers.ts","../src/symbols.ts","../src/utils/type-guards.ts","../src/core/tracking.ts","../src/core/base.ts","../src/core/scheduler.ts","../src/core/atom.ts","../src/core/computed.ts","../src/core/effect.ts","../src/core/lens.ts"],"sourcesContent":["/**\n * Internal State Flags for ReactiveNode.\n *\n * Managed as a 31-bit integer field (V8 SMI optimization).\n *\n * Bit Layout:\n * [0-7] - Shared Core (Disposed, Computed marker, etc.)\n * [8-15] - Computed States (Dirty, Recomputing, etc.)\n * [16-23] - Async Lifecycle (Idle, Pending, Resolved, Rejected)\n * [24-30] - Primitive Specific (Atom Sync, Effect Executing, etc.)\n */\nconst FLAGS = {\n // --- Shared Core (0-7) ---\n DISPOSED: 1 << 0,\n IS_COMPUTED: 1 << 1,\n\n // --- Computed Flags (8-15) ---\n DIRTY: 1 << 8,\n RECOMPUTING: 1 << 9,\n HAS_ERROR: 1 << 10,\n FORCE_COMPUTE: 1 << 11,\n\n // --- Async States (16-23) ---\n IDLE: 1 << 16,\n PENDING: 1 << 17,\n RESOLVED: 1 << 18,\n REJECTED: 1 << 19,\n\n // --- Atom Specific (24-27) ---\n ATOM_SYNC: 1 << 24,\n ATOM_NOTIFICATION_SCHEDULED: 1 << 25,\n\n // --- Effect Specific (28-30) ---\n EFFECT_EXECUTING: 1 << 28,\n} as const;\n\n/**\n * Compound Masks for fast bitwise clearing/checking.\n */\nexport const STATE_MASKS = Object.freeze({\n /** Matches all bits related to async states (Idle, Pending, Resolved, Rejected). */\n ASYNC_STATE: FLAGS.IDLE | FLAGS.PENDING | FLAGS.RESOLVED | FLAGS.REJECTED,\n /** Matches all flags that indicate a computed node is dirty or recomputing. */\n COMPUTED_DIRTY_MASK: FLAGS.DIRTY | FLAGS.RECOMPUTING | FLAGS.FORCE_COMPUTE,\n});\n\n/**\n * Async operation states for public API and high-level checks.\n */\nexport const AsyncState = Object.freeze({\n IDLE: 'idle',\n PENDING: 'pending',\n RESOLVED: 'resolved',\n REJECTED: 'rejected',\n});\n\n/**\n * Effect flags.\n */\nexport const EFFECT_STATE_FLAGS = Object.freeze({\n DISPOSED: FLAGS.DISPOSED,\n EXECUTING: FLAGS.EFFECT_EXECUTING,\n});\n\n/**\n * Computed flags.\n */\nexport const COMPUTED_STATE_FLAGS = Object.freeze({\n DISPOSED: FLAGS.DISPOSED,\n IS_COMPUTED: FLAGS.IS_COMPUTED,\n DIRTY: FLAGS.DIRTY,\n IDLE: FLAGS.IDLE,\n PENDING: FLAGS.PENDING,\n RESOLVED: FLAGS.RESOLVED,\n REJECTED: FLAGS.REJECTED,\n RECOMPUTING: FLAGS.RECOMPUTING,\n HAS_ERROR: FLAGS.HAS_ERROR,\n FORCE_COMPUTE: FLAGS.FORCE_COMPUTE,\n});\n\n/**\n * Writable Atom Flags.\n */\nexport const ATOM_STATE_FLAGS = Object.freeze({\n DISPOSED: FLAGS.DISPOSED,\n SYNC: FLAGS.ATOM_SYNC,\n NOTIFICATION_SCHEDULED: FLAGS.ATOM_NOTIFICATION_SCHEDULED,\n});\n\n/**\n * Scheduler configuration.\n */\nexport const SCHEDULER_CONFIG = Object.freeze({\n // Infinite loop protection\n MAX_EXECUTIONS_PER_SECOND: 1000,\n MAX_EXECUTIONS_PER_EFFECT: 100,\n\n // Batch processing limits to prevent blocking the main thread for too long\n MAX_EXECUTIONS_PER_FLUSH: 10000,\n MAX_FLUSH_ITERATIONS: 1000,\n MIN_FLUSH_ITERATIONS: 10,\n\n // Memory management\n BATCH_QUEUE_SHRINK_THRESHOLD: 1000,\n});\n\n/**\n * V8 Small Integer (SMI) max value.\n */\nexport const SMI_MAX = 0x3fffffff;\n\n/**\n * Debugging thresholds.\n */\nexport const DEBUG_CONFIG = Object.freeze({\n WARN_INFINITE_LOOP: true,\n EFFECT_FREQUENCY_WINDOW: 1000,\n LOOP_THRESHOLD: 100,\n});\n\n/**\n * Computed configuration.\n */\nexport const COMPUTED_CONFIG = Object.freeze({\n MAX_PROMISE_ID: SMI_MAX,\n});\n\n/**\n * Epoch sentinel values.\n */\nexport const EPOCH_CONSTANTS = Object.freeze({\n /** Uninitialized epoch marker. Used as initial value before any flush has occurred. */\n UNINITIALIZED: -1,\n /** Minimum valid epoch value after a counter reset. */\n MIN: 1,\n});\n\nlet runtimeDebug = false;\ntry {\n runtimeDebug = !!(\n (typeof globalThis !== 'undefined' &&\n (globalThis as { __ATOM_DEBUG__?: boolean }).__ATOM_DEBUG__) ||\n (typeof sessionStorage !== 'undefined' && sessionStorage.getItem('__ATOM_DEBUG__') === 'true')\n );\n} catch {}\n\n/**\n * Development environment flag.\n */\nexport const IS_DEV =\n (typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production') ||\n (typeof __DEV__ !== 'undefined' && !!__DEV__) ||\n // @ts-expect-error: import.meta.env is Vite-specific and may not be defined in all environments\n (typeof import.meta !== 'undefined' && import.meta.env && import.meta.env.DEV) ||\n runtimeDebug;\n\n// Fallback declarations for global environment variables\ndeclare const __DEV__: boolean;\n\nexport const EMPTY_ERROR_ARRAY: readonly Error[] = Object.freeze([]);\n","/**\n * Structured JSON representation of an AtomError.\n */\nexport interface AtomErrorJSON {\n name: string;\n message: string;\n code?: string | undefined;\n recoverable: boolean;\n stack?: string | undefined;\n cause?: unknown | undefined;\n}\n\n/**\n * Constructor type for Atom errors.\n */\nexport type AtomErrorConstructor = new (\n message: string,\n cause?: unknown,\n recoverable?: boolean,\n code?: string\n) => AtomError;\n\n/**\n * Base error class for the Atom system.\n * Designed for high performance, traceability, and cycle protection.\n */\nexport class AtomError extends Error {\n override readonly name: string = 'AtomError';\n\n constructor(\n message: string,\n public readonly cause: unknown = null,\n public readonly recoverable: boolean = true,\n public readonly code?: string\n ) {\n super(message);\n\n // Maintain a stable object shape for V8\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Returns the entire error chain as an array.\n * Includes the circular node if a cycle is detected.\n */\n getChain(): Array<AtomError | Error | unknown> {\n const cause = this.cause;\n if (cause === null || cause === undefined) return [this];\n\n const chain: Array<AtomError | Error | unknown> = [this];\n let current: unknown = cause;\n let seen: Set<unknown> | null = null;\n\n while (current !== null && current !== undefined) {\n chain.push(current);\n\n // Cycle detection after push to include the circular node in the chain\n if (current === this || seen?.has(current)) break;\n\n if (current instanceof AtomError) {\n current = current.cause;\n } else if (current instanceof Error) {\n current = (current as { cause?: unknown }).cause;\n } else {\n break;\n }\n\n // Initialize deep cycle detection only for long chains to minimize allocations\n if (chain.length > 3) {\n if (seen === null) {\n seen = new Set(chain);\n } else {\n seen.add(current);\n }\n }\n }\n return chain;\n }\n\n /**\n * Serializes the error to a structured object for logging.\n * Protected against circular references.\n */\n toJSON(seen?: Set<unknown>): AtomErrorJSON {\n const s = seen ?? new Set<unknown>();\n if (s.has(this)) {\n return {\n name: this.name,\n message: '[Circular Reference]',\n recoverable: this.recoverable,\n code: this.code,\n };\n }\n s.add(this);\n\n let causeJson: unknown = this.cause;\n if (causeJson instanceof AtomError) {\n causeJson = causeJson.toJSON(s);\n } else if (causeJson instanceof Error) {\n causeJson = {\n name: causeJson.name,\n message: causeJson.message,\n stack: causeJson.stack,\n cause: (causeJson as { cause?: unknown }).cause,\n };\n }\n\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n recoverable: this.recoverable,\n stack: this.stack,\n cause: causeJson,\n };\n }\n\n /**\n * Internal helper to format wrapped messages consistently.\n */\n static format(source: string, context: string, message: string): string {\n return `${source} (${context}): ${message}`;\n }\n}\n\n/** Thrown when a computation fails. */\nexport class ComputedError extends AtomError {\n override readonly name = 'ComputedError';\n}\n\n/** Thrown when an effect execution or cleanup fails. */\nexport class EffectError extends AtomError {\n override readonly name = 'EffectError';\n constructor(message: string, cause: unknown = null, recoverable = false, code?: string) {\n super(message, cause, recoverable, code);\n }\n}\n\n/** Thrown by the execution engine or scheduler. */\nexport class SchedulerError extends AtomError {\n override readonly name = 'SchedulerError';\n constructor(message: string, cause: unknown = null, recoverable = false, code?: string) {\n super(message, cause, recoverable, code);\n }\n}\n\n/**\n * Registry of standardized error messages.\n */\nexport const ERROR_MESSAGES = {\n // Computed Errors\n COMPUTED_MUST_BE_FUNCTION: 'Computed target must be a function',\n COMPUTED_ASYNC_PENDING_NO_DEFAULT: 'Async computation pending with no default value',\n COMPUTED_COMPUTATION_FAILED: 'Computation execution failed',\n COMPUTED_ASYNC_COMPUTATION_FAILED: 'Async computation execution failed',\n COMPUTED_CIRCULAR_DEPENDENCY: 'Circular dependency detected',\n COMPUTED_DISPOSED: 'Attempted to access disposed computed',\n\n // Atom Errors\n ATOM_SUBSCRIBER_MUST_BE_FUNCTION: 'Subscriber must be a function or Subscriber object',\n ATOM_INDIVIDUAL_SUBSCRIBER_FAILED: 'Subscriber execution failed',\n\n // Effect Errors\n EFFECT_MUST_BE_FUNCTION: 'Effect target must be a function',\n EFFECT_EXECUTION_FAILED: 'Effect execution failed',\n EFFECT_CLEANUP_FAILED: 'Effect cleanup failed',\n EFFECT_DISPOSED: 'Attempted to run disposed effect',\n\n // Scheduler Errors\n SCHEDULER_FLUSH_OVERFLOW: (max: number, dropped: number): string =>\n `Maximum flush iterations (${max}) exceeded. ${dropped} jobs dropped. Possible infinite loop.`,\n\n // System / Debug\n CALLBACK_ERROR_IN_ERROR_HANDLER: 'Exception encountered in onError handler',\n EFFECT_FREQUENCY_LIMIT_EXCEEDED:\n 'Effect executed too frequently within 1 second. Suspected infinite loop.',\n SCHEDULER_CALLBACK_MUST_BE_FUNCTION: 'Scheduler callback must be a function',\n SCHEDULER_END_BATCH_WITHOUT_START: 'endBatch() called without matching startBatch(). Ignoring.',\n BATCH_CALLBACK_MUST_BE_FUNCTION: 'Batch callback must be a function',\n} as const;\n\n/**\n * Wraps any value into the Atom error hierarchy, preserving the trace and context.\n *\n * @param error - The raw error or object thrown.\n * @param ErrorClass - The specific AtomError subclass to use.\n * @param context - Human-readable description of where the error occurred.\n */\nexport function wrapError(\n error: unknown,\n ErrorClass: AtomErrorConstructor,\n context: string\n): AtomError {\n // 1. AtomError (Chainable Trace)\n if (error instanceof AtomError) {\n return new ErrorClass(\n `${error.name} (${context}): ${error.message}`,\n error,\n error.recoverable,\n error.code\n );\n }\n\n // 2. Native Error\n if (error instanceof Error) {\n return new ErrorClass(`${error.name || 'Error'} (${context}): ${error.message}`, error);\n }\n\n // 3. Unknown Types (Raw Preservation)\n return new ErrorClass(`Unexpected error (${context}): ${String(error)}`, error);\n}\n","import { DEBUG_CONFIG, IS_DEV } from '@/constants';\nimport type { DebugConfig, DependencyId } from '@/types';\n\n/**\n * Debug symbols used to store metadata on objects without interfering with their normal properties.\n * These are exported to allow external inspection or custom debugging tools.\n */\n\n/** Symbol used to store and retrieve a human-readable name for an atom or effect. */\nexport const DEBUG_NAME = Symbol('AtomEffect.DebugName');\n/** Symbol used to store and retrieve the unique internal ID. */\nexport const DEBUG_ID = Symbol('AtomEffect.Id');\n/** Symbol used to store and retrieve the type identifier (e.g., 'atom', 'effect'). */\nexport const DEBUG_TYPE = Symbol('AtomEffect.Type');\n/** Symbol used as a sentinel value to indicate that no default value was provided. */\nexport const NO_DEFAULT_VALUE = Symbol('AtomEffect.NoDefaultValue');\n\n/** @internal */\ninterface DebugMetadata {\n [DEBUG_NAME]?: string;\n [DEBUG_ID]?: DependencyId;\n [DEBUG_TYPE]?: string;\n}\n\n/** Log prefix for Atom Effect console messages. */\nconst PREFIX = '[Atom Effect]';\n\n/** Shared no-op function to reduce memory footprint and call overhead in production. */\nconst noop = () => {};\n\n/**\n * Optimized Debug controller implementation for development environments.\n * Provides active monitoring, logging, and inspection capabilities.\n *\n * @internal\n * @implements {DebugConfig}\n */\nclass DevDebugController implements DebugConfig {\n /** Whether debugging features are currently active. */\n public enabled = true;\n\n /** Whether to warn when a potential infinite loop is detected. */\n public warnInfiniteLoop = DEBUG_CONFIG.WARN_INFINITE_LOOP;\n\n /** Tracks the number of updates per dependency within a single execution scope. */\n private _updateCounts = new Map<DependencyId, number>();\n\n /**\n * Weakly references registered nodes to allow garbage collection while maintaining\n * a list for graph dumping.\n */\n private _nodeRegistry = new Map<DependencyId, WeakRef<object>>();\n\n /** Threshold for triggering an infinite loop warning. */\n private _threshold = DEBUG_CONFIG.LOOP_THRESHOLD;\n\n /** Prevents redundant cleanup scheduling. */\n private _cleanupScheduled = false;\n\n /**\n * Logs a warning message if the condition is met and debugging is enabled.\n *\n * @param cond - The condition to check.\n * @param msg - The message to log if the condition is true.\n */\n public warn = (cond: boolean, msg: string): void => {\n if (this.enabled && cond) console.warn(`${PREFIX} ${msg}`);\n };\n\n /**\n * Registers a node in the internal registry for tracking and graph generation.\n * Uses WeakRef to prevent memory leaks.\n *\n * @param node - The object/node to register, must have a unique DependencyId.\n */\n public registerNode = (node: object & { id: DependencyId }): void => {\n this._nodeRegistry.set(node.id, new WeakRef(node));\n };\n\n /**\n * Attaches debug metadata to a runtime object.\n *\n * @remarks\n * Optimized with direct property assignment instead of 'Object.defineProperties'\n * for significantly faster node initialization in hot paths.\n *\n * @param obj - The object to attach info to.\n * @param type - The type of the node (e.g., 'atom', 'selector', 'effect').\n * @param id - The unique internal identifier.\n * @param customName - Optional user-defined name for easier identification.\n */\n public attachDebugInfo = (\n obj: object,\n type: string,\n id: DependencyId,\n customName?: string\n ): void => {\n if (!this.enabled) return;\n\n // Use direct symbol access for peak V8 assignment performance\n const meta = obj as DebugMetadata;\n meta[DEBUG_NAME] = customName ?? `${type}_${id}`;\n meta[DEBUG_ID] = id;\n meta[DEBUG_TYPE] = type;\n\n this.registerNode(obj as { id: DependencyId });\n };\n\n /**\n * Tracks an update to a dependency and checks for infinite loops.\n * Counts are automatically reset at the end of the current microtask.\n *\n * @param id - The unique identifier of the dependency being updated.\n * @param name - An optional display name for the warning message.\n */\n public trackUpdate = (id: DependencyId, name?: string): void => {\n if (!this.enabled || !this.warnInfiniteLoop) return;\n\n const counts = this._updateCounts;\n const count = (counts.get(id) ?? 0) + 1;\n\n if (count > this._threshold) {\n this.warn(\n true,\n `Infinite loop detected for ${name ?? `dependency ${id}`}. Over ${this._threshold} updates in a single execution scope.`\n );\n } else {\n counts.set(id, count);\n }\n\n if (!this._cleanupScheduled) {\n this._cleanupScheduled = true;\n // Reset counts at the end of the current microtask using lightweight mechanism\n queueMicrotask(() => {\n this._updateCounts.clear();\n this._cleanupScheduled = false;\n });\n }\n };\n\n /**\n * Generates a snapshot of the current reactive graph.\n * Automatically prunes dead references from the registry.\n *\n * @returns An array of debug info objects for all currently alive nodes.\n */\n public dumpGraph = (): Record<string, unknown>[] => {\n const result: Record<string, unknown>[] = [];\n for (const [id, ref] of this._nodeRegistry) {\n const node = ref.deref();\n if (node) {\n result.push({\n id,\n name: this.getDebugName(node),\n type: this.getDebugType(node),\n updateCount: this._updateCounts.get(id) ?? 0,\n });\n } else {\n this._nodeRegistry.delete(id);\n this._updateCounts.delete(id);\n }\n }\n return result;\n };\n\n /**\n * Retrieves the debug name from an object if it exists.\n *\n * @param obj - the object to inspect.\n * @returns The human-readable name or undefined.\n */\n public getDebugName = (obj: object | null | undefined): string | undefined => {\n if (obj == null) return undefined;\n return (obj as DebugMetadata)[DEBUG_NAME];\n };\n\n /**\n * Retrieves the debug type from an object if it exists.\n *\n * @param obj - the object to inspect.\n * @returns The type identifier or undefined.\n */\n public getDebugType = (obj: object | null | undefined): string | undefined => {\n if (obj == null) return undefined;\n return (obj as DebugMetadata)[DEBUG_TYPE];\n };\n}\n\n/**\n * Inert implementation of the Debug controller for production environments.\n * All operations are no-ops using shared handlers for minimal overhead.\n *\n * @internal\n * @implements {DebugConfig}\n */\nconst ProdDebugController: DebugConfig = {\n enabled: false,\n warnInfiniteLoop: false,\n warn: noop,\n registerNode: noop,\n attachDebugInfo: noop,\n trackUpdate: noop,\n dumpGraph: () => [],\n getDebugName: () => undefined,\n getDebugType: () => undefined,\n};\n\n/**\n * The global debug singleton instance.\n * Automatically switches between development and production implementations.\n *\n * @public\n */\nexport const debug: DebugConfig = IS_DEV ? new DevDebugController() : ProdDebugController;\n\n/**\n * Internal counter for generating unique DependencyIds.\n * @private\n */\nlet nextId = 1;\n\n/**\n * Generates a unique, monotonically increasing integer ID.\n * Performance: Uses SMI bitwise optimization.\n *\n * @returns A fresh DependencyId.\n * @public\n */\nexport const generateId = (): DependencyId => (nextId++ | 0) as DependencyId;\n","// ── SlotBuffer ──────────────────────────────────────────────────────────\n\n/**\n * A ultra-high-performance, allocation-optimized container for reactive subscribers.\n *\n * Design Philosophy:\n * 1. Inline Storage: Uses 4 object properties (_s0.._s3) to store items directly.\n * Since >90% of reactive nodes have 1-4 subscribers, this avoids array creation entirely.\n * 2. Spill-over Model: Shifts to a lazy-allocated overflow array only when necessary.\n * 3. Size Duality: Distinguishes between Physical Boundary (_count) and Logical Size (_actualCount)\n * to support fast iteration while maintaining hole-reuse capabilities.\n */\nexport class SlotBuffer<T> {\n // Physical high-water mark first for better V8 object layout (numbers)\n /** Physical high-water mark. Indicates the highest index ever occupied + 1. */\n _count = 0;\n /** Logical element count. Number of non-null items currently in the buffer. */\n _actualCount = 0;\n\n // Direct property slots for ultra-fast access and zero allocation.\n _s0: T | null = null;\n _s1: T | null = null;\n _s2: T | null = null;\n _s3: T | null = null;\n\n /** Lazy overflow container for index >= 4. */\n _overflow: (T | null)[] | null = null;\n /** LIFO reuse-stack of freed overflow indices to maintain O(1) addition. */\n _freeIndices: number[] | null = null;\n\n // ── Internal Physical Primitives ──────────────────────────────────────\n\n /**\n * Low-level atomic write.\n * Does NOT update bookkeeping counters. Used as a building block for higher APIs.\n */\n protected _rawWrite(index: number, item: T | null): void {\n if (index < 4) {\n if (index === 0) this._s0 = item;\n else if (index === 1) this._s1 = item;\n else if (index === 2) this._s2 = item;\n else this._s3 = item;\n } else {\n if (this._overflow === null) this._overflow = [];\n const ov = this._overflow;\n ov[index - 4] = item;\n }\n }\n\n /**\n * Finds the first available hole or appends to the tail.\n * Returns the assigned physical index.\n */\n protected _rawAdd(item: T): number {\n if (this._s0 === null) {\n this._s0 = item;\n return 0;\n }\n if (this._s1 === null) {\n this._s1 = item;\n return 1;\n }\n if (this._s2 === null) {\n this._s2 = item;\n return 2;\n }\n if (this._s3 === null) {\n this._s3 = item;\n return 3;\n }\n\n if (this._overflow === null) this._overflow = [];\n const ov = this._overflow;\n const free = this._freeIndices;\n if (free !== null && free.length > 0) {\n const idx = free.pop()!;\n ov[idx] = item;\n return idx + 4;\n }\n ov.push(item);\n return 3 + ov.length;\n }\n\n /** Atomic swap of two physical slots. Essential for dependency relocation. */\n protected _rawSwap(idxA: number, idxB: number): void {\n if (idxA === idxB) return;\n const valA = this.getAt(idxA);\n const valB = this.getAt(idxB);\n this._rawWrite(idxA, valB);\n this._rawWrite(idxB, valA);\n }\n\n // ── Public API ────────────────────────────────────────────────────────\n\n /** Number of active (non-null) elements. */\n get size(): number {\n return this._actualCount;\n }\n /** Highest physical index + 1. */\n get physicalSize(): number {\n return this._count;\n }\n\n /** Retrieves item at the specified index. O(1). */\n getAt(index: number): T | null {\n if (index < 4) {\n if (index === 0) return this._s0;\n if (index === 1) return this._s1;\n if (index === 2) return this._s2;\n if (index === 3) return this._s3;\n return null;\n }\n const ov = this._overflow;\n return ov === null ? null : (ov[index - 4] ?? null);\n }\n\n /**\n * Sets item at index.\n * Forces recalculation of logic size and high-water mark reduction on nullification.\n */\n setAt(index: number, item: T | null): void {\n const old = this.getAt(index);\n if (old === item) return;\n\n this._rawWrite(index, item);\n\n // Sync logical count (Active items tracking)\n if (old === null) this._actualCount++;\n else if (item === null) this._actualCount--;\n\n // Sync physical high-water mark (Iteration boundary tracking)\n if (item !== null) {\n if (index >= this._count) this._count = index + 1;\n } else {\n this._shrinkPhysicalSizeFrom(index);\n }\n }\n\n /**\n * Shrinks high-water mark recursively from the tail.\n * Optimized to avoid getAt() overhead in tight loop.\n */\n private _shrinkPhysicalSizeFrom(index: number): void {\n if (index !== this._count - 1) return;\n this._count--;\n\n if (this._count > 4) {\n const ov = this._overflow!;\n while (this._count > 4 && ov[this._count - 5] === null) {\n this._count--;\n }\n }\n\n if (this._count === 4 && this._s3 === null) {\n this._count = 3;\n if (this._s2 === null) {\n this._count = 2;\n if (this._s1 === null) {\n this._count = 1;\n if (this._s0 === null) this._count = 0;\n }\n }\n }\n }\n\n /**\n * Truncates the buffer to a specific size.\n * Normalizes the high-water mark even if the current count is 0.\n */\n truncateFrom(index: number): void {\n // 1. Cleanup inline slots\n if (index <= 3) {\n if (index <= 3 && this._s3 !== null) {\n this._onItemRemoved(this._s3!);\n this._s3 = null;\n this._actualCount--;\n }\n if (index <= 2 && this._s2 !== null) {\n this._onItemRemoved(this._s2!);\n this._s2 = null;\n this._actualCount--;\n }\n if (index <= 1 && this._s1 !== null) {\n this._onItemRemoved(this._s1!);\n this._s1 = null;\n this._actualCount--;\n }\n if (index <= 0 && this._s0 !== null) {\n this._onItemRemoved(this._s0!);\n this._s0 = null;\n this._actualCount--;\n }\n }\n\n // 2. Cleanup overflow array\n const ov = this._overflow;\n if (ov !== null) {\n const ovStart = index > 4 ? index - 4 : 0;\n const len = ov.length;\n for (let i = ovStart; i < len; i++) {\n const item = ov[i];\n if (item !== null && item !== undefined) {\n this._onItemRemoved(item);\n ov[i] = null;\n this._actualCount--;\n }\n }\n if (index <= 4) {\n this._overflow = null;\n } else {\n ov.length = index - 4;\n }\n }\n\n this._count = index;\n if (this._actualCount < 0) this._actualCount = 0;\n this._freeIndices = null;\n }\n\n /**\n * Internal hook for resource cleanup (e.g. unsubscriptions).\n * @internal For use in DepSlotBuffer only.\n */\n protected _onItemRemoved(_item: T): void {}\n\n /** Appends an item to the buffer. Returns assigned index. O(1). */\n add(item: T): number {\n const idx = this._rawAdd(item);\n if (idx >= this._count) this._count = idx + 1;\n this._actualCount++;\n return idx;\n }\n\n /** Removes an item by reference. O(N). */\n remove(item: T): boolean {\n let idx = -1;\n if (this._s0 === item) idx = 0;\n else if (this._s1 === item) idx = 1;\n else if (this._s2 === item) idx = 2;\n else if (this._s3 === item) idx = 3;\n else {\n const ov = this._overflow;\n if (ov !== null) {\n idx = ov.indexOf(item);\n if (idx !== -1) idx += 4;\n }\n }\n\n if (idx !== -1) {\n this._rawWrite(idx, null);\n this._shrinkPhysicalSizeFrom(idx);\n this._actualCount--;\n if (idx >= 4) {\n if (this._freeIndices === null) this._freeIndices = [];\n const free = this._freeIndices;\n free.push(idx - 4);\n }\n return true;\n }\n return false;\n }\n\n /** O(N) presence check. */\n has(item: T): boolean {\n const actual = this._actualCount;\n if (actual === 0) return false;\n if (this._s0 === item || this._s1 === item || this._s2 === item || this._s3 === item)\n return true;\n const ov = this._overflow;\n if (ov !== null) return ov.indexOf(item) !== -1;\n return false;\n }\n\n /** Optimized iteration. Fast-path triggers when buffer is dense (no holes). */\n forEach(fn: (item: T) => void): void {\n const actual = this._actualCount;\n if (actual === 0) return;\n\n if (actual === this._count) {\n // Dense optimization: Avoid all null checks and property lookups\n fn(this._s0!);\n if (actual > 1) {\n fn(this._s1!);\n if (actual > 2) {\n fn(this._s2!);\n if (actual > 3) {\n fn(this._s3!);\n if (actual > 4) {\n const ov = this._overflow!;\n for (let i = 0, len = ov.length; i < len; i++) fn(ov[i]!);\n }\n }\n }\n }\n return;\n }\n\n // Sparse path: Unrolled for the first 4 slots\n let count = 0;\n if (this._s0 !== null) {\n fn(this._s0);\n if (++count >= actual) return;\n }\n if (this._s1 !== null) {\n fn(this._s1);\n if (++count >= actual) return;\n }\n if (this._s2 !== null) {\n fn(this._s2);\n if (++count >= actual) return;\n }\n if (this._s3 !== null) {\n fn(this._s3);\n if (++count >= actual) return;\n }\n\n const ov = this._overflow;\n if (ov !== null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const item = ov[i];\n if (item !== null && item !== undefined) {\n fn(item);\n if (++count >= actual) return;\n }\n }\n }\n }\n\n /** Elimination of all holes via in-place shifting. Zero-allocation. */\n compact(): void {\n const actual = this._actualCount;\n if (actual === this._count) return;\n\n if (actual === 0) {\n this.clear();\n return;\n }\n\n let writeIdx = 0;\n const limit = this._count;\n for (let readIdx = 0; readIdx < limit; readIdx++) {\n const item = this.getAt(readIdx);\n if (item !== null) {\n if (readIdx !== writeIdx) {\n this._rawWrite(writeIdx, item);\n this._rawWrite(readIdx, null);\n }\n writeIdx++;\n if (writeIdx === actual) break;\n }\n }\n\n this._count = actual;\n if (this._overflow !== null) {\n if (writeIdx <= 4) this._overflow = null;\n else this._overflow.length = writeIdx - 4;\n }\n this._freeIndices = null;\n }\n\n /** Complete reset and memory release. */\n clear(): void {\n this._s0 = this._s1 = this._s2 = this._s3 = null;\n this._count = 0;\n this._actualCount = 0;\n this._overflow = null;\n this._freeIndices = null;\n }\n\n dispose(): void {\n this.clear();\n }\n}\n\n// ── DepSlotBuffer ───────────────────────────────────────────────────────\n\nimport type { Dependency } from '@/types';\nimport type { DependencyLink } from './tracking';\n\n/**\n * Specialized high-speed buffer for Dependency Tracking Cycles.\n */\nexport class DepSlotBuffer extends SlotBuffer<DependencyLink> {\n private _map: Map<Dependency, number> | null = null;\n private readonly _SCAN_THRESHOLD = 32;\n\n hasComputeds = false;\n prepareTracking(): void {\n this.hasComputeds = false;\n }\n\n protected override _onItemRemoved(link: DependencyLink): void {\n link.unsub?.();\n }\n\n /** Synchronizes the Node->Index Map when setting entries directly. */\n override setAt(index: number, item: DependencyLink | null): void {\n const old = this.getAt(index);\n super.setAt(index, item);\n\n if (this._map !== null) {\n if (old !== null) this._map.delete(old.node);\n if (item !== null) this._map.set(item.node, index);\n }\n }\n\n /**\n * Finds and reuses a dependency from a previous cycle.\n * Optimized hot-path with unrolled search.\n */\n claimExisting(dep: Dependency, trackIndex: number): boolean {\n const length = this._count;\n if (length <= trackIndex) return false;\n\n // 1. Direct hit check (Unrolled for performance)\n let current: DependencyLink | null = null;\n if (trackIndex < 4) {\n if (trackIndex === 0) current = this._s0;\n else if (trackIndex === 1) current = this._s1;\n else if (trackIndex === 2) current = this._s2;\n else current = this._s3;\n } else {\n current = this._overflow![trackIndex - 4] ?? null;\n }\n\n if (current && current.node === dep && current.unsub) {\n current.version = dep.version;\n return true;\n }\n\n // 2. Map lookup\n if (this._map !== null || length - trackIndex > this._SCAN_THRESHOLD) {\n return this._claimViaMap(dep, trackIndex);\n }\n\n // 3. Sequential search: Unrolled for the first 4 slots\n let foundIdx = -1;\n let foundLink: DependencyLink | null = null;\n\n let i = trackIndex + 1;\n for (; i < 4 && i < length; i++) {\n const l = i === 1 ? this._s1 : i === 2 ? this._s2 : this._s3;\n if (l && l.node === dep && l.unsub) {\n foundIdx = i;\n foundLink = l;\n break;\n }\n }\n if (foundIdx === -1 && i < length) {\n const ov = this._overflow!;\n for (let j = i - 4, len = length - 4; j < len; j++) {\n const l = ov[j];\n if (l && l.node === dep && l.unsub) {\n foundIdx = j + 4;\n foundLink = l;\n break;\n }\n }\n }\n\n if (foundIdx !== -1) {\n foundLink!.version = dep.version;\n // Precise manual swap to avoid repeated index checks in _rawSwap\n this._rawWrite(trackIndex, foundLink);\n this._rawWrite(foundIdx, current);\n return true;\n }\n\n return false;\n }\n\n private _claimViaMap(dep: Dependency, trackIndex: number): boolean {\n if (this._map === null) this._map = this._initMap();\n const map = this._map;\n const existingIndex = map.get(dep);\n if (existingIndex === undefined || existingIndex < trackIndex) return false;\n\n const link = this.getAt(existingIndex);\n if (link === null || !link.unsub) return false;\n\n link.version = dep.version;\n\n if (existingIndex !== trackIndex) {\n const occupant = this.getAt(trackIndex);\n this._rawSwap(existingIndex, trackIndex);\n\n map.set(dep, trackIndex);\n if (occupant?.unsub) map.set(occupant.node, existingIndex);\n }\n return true;\n }\n\n private _initMap(): Map<Dependency, number> {\n const map = new Map<Dependency, number>();\n if (this._s0?.unsub) map.set(this._s0.node, 0);\n if (this._s1?.unsub) map.set(this._s1.node, 1);\n if (this._s2?.unsub) map.set(this._s2.node, 2);\n if (this._s3?.unsub) map.set(this._s3.node, 3);\n\n const ov = this._overflow;\n if (ov !== null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const link = ov[i];\n if (link?.unsub) map.set(link.node, i + 4);\n }\n }\n return map;\n }\n\n /**\n * Inserts a new link at trackIdx.\n * Optimized to avoid getAt/_rawWrite overhead.\n */\n insertNew(trackIdx: number, link: DependencyLink): void {\n let occupant: DependencyLink | null = null;\n if (trackIdx < 4) {\n if (trackIdx === 0) {\n occupant = this._s0;\n this._s0 = link;\n } else if (trackIdx === 1) {\n occupant = this._s1;\n this._s1 = link;\n } else if (trackIdx === 2) {\n occupant = this._s2;\n this._s2 = link;\n } else {\n occupant = this._s3;\n this._s3 = link;\n }\n } else {\n if (this._overflow === null) this._overflow = [];\n const ov = this._overflow;\n occupant = ov[trackIdx - 4] ?? null;\n ov[trackIdx - 4] = link;\n }\n\n if (occupant !== null) {\n const newIdx = this._rawAdd(occupant);\n if (newIdx >= this._count) this._count = newIdx + 1;\n if (this._map !== null && occupant.unsub) this._map.set(occupant.node, newIdx);\n }\n\n if (trackIdx >= this._count) this._count = trackIdx + 1;\n this._actualCount++;\n\n if (this._map !== null && link.unsub) this._map.set(link.node, trackIdx);\n }\n\n override add(item: DependencyLink): number {\n const idx = super.add(item);\n if (this._map !== null && item.unsub) this._map.set(item.node, idx);\n return idx;\n }\n\n override remove(_item: DependencyLink): boolean {\n throw new Error('remove() prohibited');\n }\n override compact(): void {}\n\n override truncateFrom(index: number): void {\n super.truncateFrom(index);\n if (this._map !== null) {\n this._map = null;\n }\n }\n\n disposeAll(): void {\n this.truncateFrom(0);\n this.hasComputeds = false;\n }\n}\n","/**\n * Global brand symbol for all reactive primitives.\n * Uses a bitwise mask for high-performance type identification.\n */\nexport const BRAND: unique symbol = Symbol.for('atom-effect/brand');\n\n/**\n * Bitwise flags for brand identification.\n */\nexport const BrandFlags = {\n Atom: 1 << 0,\n Writable: 1 << 1,\n Computed: 1 << 2,\n Effect: 1 << 3,\n} as const;\n","import { BRAND, BrandFlags } from '@/symbols';\nimport type { ComputedAtom, EffectObject, ReadonlyAtom, WritableAtom } from '@/types';\n\n/** @internal */\ninterface Branded {\n [BRAND]?: number;\n}\n\n/** @internal */\ninterface Thenable {\n then: unknown;\n}\n\n/**\n * Internal helper to check for a brand flag on objects or functions.\n * Optimized for high-performance bitwise identification.\n */\nfunction isBranded<T>(obj: unknown, flag: number): obj is T {\n if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) return false;\n\n // Bitwise AND check on the consolidated BRAND symbol\n return !!((obj as Branded)[BRAND]! & flag);\n}\n\n/**\n * Readonly atom check.\n */\nexport function isAtom(obj: unknown): obj is ReadonlyAtom {\n return isBranded(obj, BrandFlags.Atom);\n}\n\n/**\n * Writable atom check.\n */\nexport function isWritable(obj: unknown): obj is WritableAtom {\n return isBranded(obj, BrandFlags.Writable);\n}\n\n/**\n * Computed atom check.\n */\nexport function isComputed(obj: unknown): obj is ComputedAtom {\n return isBranded(obj, BrandFlags.Computed);\n}\n\n/**\n * Effect object check.\n */\nexport function isEffect(obj: unknown): obj is EffectObject {\n return isBranded(obj, BrandFlags.Effect);\n}\n\n/**\n * Promise check.\n * Includes a fast-path for native Promises and supports duck-typed thenables.\n * Optimized for non-promise dominance by providing an eager-exit for primitives.\n */\nexport function isPromise<T>(value: unknown): value is Promise<T> {\n // 1. Fast-path for native promises\n if (value instanceof Promise) return true;\n\n // 2. Eager-exit for primitives and null to avoid property indexing\n if (value === null || typeof value !== 'object') return false;\n\n // 3. Duck-typed thenable (supports 3rd party libs)\n return typeof (value as Thenable).then === 'function';\n}\n","import { IS_DEV } from '@/constants';\nimport type { Dependency, Subscriber } from '@/types';\nimport { debug } from '@/utils/debug';\nimport { isPromise } from '@/utils/type-guards';\n\n// ── Tracking Types ──────────────────────────────────────────────────────\n\n/**\n * Dependency consumer.\n * Objects implementing this can be registered as the current tracking target.\n */\nexport interface DependencySubscriber {\n /**\n * Registers a dependency to this subscriber.\n */\n addDependency(dep: Dependency): void;\n}\n\n/**\n * Executable unit.\n * Represents a reactive node or effect that can be re-run.\n */\nexport interface ExecutableSubscriber {\n execute(): void;\n}\n\n/**\n * Dependency tracker.\n * Combines dependency collection and execution capabilities.\n */\nexport interface DependencyTracker extends DependencySubscriber, ExecutableSubscriber {}\n\n/**\n * Trackable function.\n * A function that is also recognized as a dependency consumer.\n */\nexport type TrackableFunction = (() => void) & DependencySubscriber;\n\n// ── Dependency Link & Subscription ───────────────────────────────────────\n\n/**\n * Dependency graph edge.\n * Maintains the link between a subscriber and its dependency.\n */\nexport class DependencyLink {\n constructor(\n public node: Dependency,\n public version: number,\n /**\n * Unsubscribe cleanup function.\n * Default value ensures consistent V8 hidden class shape.\n */\n public unsub: (() => void) | undefined = undefined\n ) {}\n}\n\n/**\n * Subscription entry.\n * Encapsulates the notification logic for a dependency change.\n */\nexport class Subscription<T> {\n constructor(\n /**\n * Optional callback. Always initialized to maintain hidden class.\n */\n public fn: ((newValue?: T, oldValue?: T) => void) | undefined = undefined,\n /**\n * Optional subscriber. Always initialized to maintain hidden class.\n */\n public sub: Subscriber | undefined = undefined\n ) {}\n\n /**\n * Notifies the subscriber of a value change.\n *\n * @remarks\n * Optimized with inlined 'untracked' logic to eliminate closure allocation.\n */\n notify(newValue?: T, oldValue?: T): void {\n const fn = this.fn;\n const sub = this.sub;\n\n // Fast path: nothing to notify\n if (fn === undefined && sub === undefined) return;\n\n const ctx = trackingContext;\n const prev = ctx.current;\n\n // If already untracked, bypass context switching logic\n if (prev === null) {\n if (fn !== undefined) fn(newValue, oldValue);\n if (sub !== undefined) sub.execute();\n return;\n }\n\n // Context switch required for notification safety\n ctx.current = null;\n try {\n if (fn !== undefined) fn(newValue, oldValue);\n if (sub !== undefined) sub.execute();\n } finally {\n ctx.current = prev;\n }\n }\n}\n\n// ── Tracking Context ────────────────────────────────────────────────────\n\n/**\n * Tracking context implementation.\n * Manages the global stack of active dependency collectors.\n */\nclass TrackingContext {\n /** Active subscriber at the top of the stack. */\n public current: DependencySubscriber | null = null;\n\n /**\n * Executes a function within the scope of a specific subscriber.\n *\n * @param subscriber - The subscriber to collect dependencies for.\n * @param fn - The logic to execute.\n * @returns The result of `fn`.\n */\n public run<T>(subscriber: DependencySubscriber, fn: () => T): T {\n // Fast path: already in the correct context\n if (this.current === subscriber) {\n return fn();\n }\n\n const prev = this.current;\n this.current = subscriber;\n\n try {\n // Small production optimization: direct return\n if (!IS_DEV) return fn();\n\n const result = fn();\n\n // Async detection: check if the function returned a Promise\n debug.warn(\n isPromise(result),\n 'Detected Promise returned within tracking context. ' +\n 'Dependencies accessed after \"await\" will NOT be tracked. ' +\n 'Consider using synchronous tracking before the async boundary.'\n );\n\n return result;\n } finally {\n // Synchronous restoration is required for safety in multi-tasking environments\n this.current = prev;\n }\n }\n}\n\n/**\n * Global tracking context singleton.\n */\nexport const trackingContext = new TrackingContext();\n\n/**\n * Tracking context type.\n */\nexport type { TrackingContext };\n\n// ── Untracked ───────────────────────────────────────────────────────────\n\n/**\n * Executes a function without dependency tracking.\n *\n * @param fn - Function to execute.\n * @returns Result of `fn`.\n */\nexport function untracked<T>(fn: () => T): T {\n const ctx = trackingContext;\n const prev = ctx.current;\n\n // Optimized: Skip context switching if already untracked\n if (prev === null) {\n return fn();\n }\n\n ctx.current = null;\n try {\n return fn();\n } finally {\n ctx.current = prev;\n }\n}\n","import { COMPUTED_STATE_FLAGS, EPOCH_CONSTANTS, IS_DEV, SMI_MAX } from '@/constants';\nimport { AtomError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport type { DependencyId, Subscriber } from '@/types';\nimport { generateId } from '@/utils/debug';\nimport { type DepSlotBuffer, SlotBuffer } from './buffers';\nimport { Subscription } from './tracking';\n\n/**\n * Unified base class for all reactive nodes (Atoms, Computeds, Effects).\n *\n * Optimized for V8 Hidden Class Monomorphism by having a single, consistent\n * object shape for all reactive logic.\n *\n * @template T - The type of value produced by this node (used for subscriptions).\n */\nexport abstract class ReactiveNode<T> {\n /** [Producer/Consumer] State flags */\n flags: number;\n /** [Producer/Consumer] Version counter */\n version: number;\n /** [Producer/Consumer] Last access epoch */\n _lastSeenEpoch: number;\n /** [Context] Scheduler epoch tag */\n _nextEpoch: number | undefined;\n /** [Debug] Unique ID for identify node in tracking maps */\n readonly id: DependencyId;\n\n /**\n * [Producer] Managed subscribers.\n */\n _slots: SlotBuffer<Subscription<T>> | null;\n\n /** [Producer] Re-entry guard for notification loop. */\n _notifying: number;\n\n /**\n * [Consumer] Managed dependencies.\n */\n _deps: DepSlotBuffer | null;\n /** [Consumer] O(1) Hot-path dependency index for rapid dirty checks. */\n _hotIndex: number;\n\n constructor() {\n // Reordered for V8 Hidden Class (integers/numbers first)\n this.flags = 0;\n this.version = 0;\n this._lastSeenEpoch = EPOCH_CONSTANTS.UNINITIALIZED;\n this._notifying = 0;\n this._hotIndex = -1;\n this.id = generateId() & SMI_MAX;\n\n // References/Nullable last\n this._nextEpoch = undefined;\n this._slots = null;\n this._deps = null;\n }\n\n /**\n * Whether the node has been disposed.\n * @internal\n */\n get isDisposed(): boolean {\n return (this.flags & COMPUTED_STATE_FLAGS.DISPOSED) !== 0; // Bit 0: DISPOSED\n }\n\n /**\n * Whether the node is a computed atom.\n * @internal\n */\n get isComputed(): boolean {\n return (this.flags & COMPUTED_STATE_FLAGS.IS_COMPUTED) !== 0; // Bit 1: IS_COMPUTED\n }\n\n /**\n * Whether the node currently has an error.\n * @internal\n */\n get hasError(): boolean {\n return false;\n }\n\n // ============================================================================\n // Producer Logic (Subscriber Management)\n // ============================================================================\n\n /**\n * Adds subscriber for notifications.\n */\n subscribe(listener: ((newValue?: T, oldValue?: T) => void) | Subscriber): () => void {\n const isFn = typeof listener === 'function';\n // [Guard Clause] 중첩 최소화 및 타입 안전성 확보\n if (!isFn && (listener === null || typeof (listener as Subscriber).execute !== 'function')) {\n throw wrapError(\n new TypeError('Invalid subscriber'),\n AtomError,\n ERROR_MESSAGES.ATOM_SUBSCRIBER_MUST_BE_FUNCTION\n );\n }\n\n let slots = this._slots;\n if (slots === null) {\n slots = new SlotBuffer<Subscription<T>>();\n this._slots = slots;\n }\n\n // Optimization: Skip duplicate check if empty\n if (slots.size > 0) {\n let duplicate = false;\n\n // Unrolled check using unified comparison to reduce branching\n // Since Subscription stores fn/sub and one is always undefined, we can check both\n if (\n (slots._s0 !== null && (slots._s0.fn === listener || slots._s0.sub === listener)) ||\n (slots._s1 !== null && (slots._s1.fn === listener || slots._s1.sub === listener)) ||\n (slots._s2 !== null && (slots._s2.fn === listener || slots._s2.sub === listener)) ||\n (slots._s3 !== null && (slots._s3.fn === listener || slots._s3.sub === listener))\n ) {\n duplicate = true;\n } else {\n const ov = slots._overflow;\n if (ov !== null) {\n const len = ov.length;\n // Hoisted invariant check (isFn) to avoid branching inside the loop\n if (isFn) {\n for (let i = 0; i < len; i++) {\n const s = ov[i];\n if (s !== null && s?.fn === listener) {\n duplicate = true;\n break;\n }\n }\n } else {\n for (let i = 0; i < len; i++) {\n const s = ov[i];\n if (s !== null && s?.sub === listener) {\n duplicate = true;\n break;\n }\n }\n }\n }\n }\n\n if (duplicate) {\n if (IS_DEV) console.warn(`[atom-effect] Duplicate subscription ignored on node ${this.id}`);\n return () => {};\n }\n }\n\n const link = new Subscription<T>(\n isFn ? (listener as (newValue?: T, oldValue?: T) => void) : undefined,\n !isFn ? (listener as Subscriber) : undefined\n );\n\n slots.add(link);\n return () => this._unsubscribe(link);\n }\n\n protected _unsubscribe(link: Subscription<T>): void {\n const slots = this._slots;\n if (slots === null) return;\n\n slots.remove(link);\n if (this._notifying === 0) {\n slots.compact();\n }\n }\n\n /**\n * Returns current subscriber count.\n */\n subscriberCount(): number {\n const slots = this._slots;\n return slots === null ? 0 : slots.size;\n }\n\n /**\n * Notifies all subscribers about a value update.\n */\n protected _notifySubscribers(newValue: T | undefined, oldValue: T | undefined): void {\n const slots = this._slots;\n if (slots === null || slots.size === 0) return;\n\n this._notifying++;\n try {\n // 1. Inline slots: Manual unroll for hot-path performance\n if (slots._s0 !== null) {\n try {\n slots._s0.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n if (slots._s1 !== null) {\n try {\n slots._s1.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n if (slots._s2 !== null) {\n try {\n slots._s2.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n if (slots._s3 !== null) {\n try {\n slots._s3.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n\n // 2. Overflow scan: Standard loop for performance\n const ov = slots._overflow;\n if (ov !== null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const sub = ov[i];\n if (sub !== null) {\n try {\n sub?.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n }\n }\n } finally {\n if (--this._notifying === 0) {\n slots.compact();\n }\n }\n }\n\n private _logNotifyError(err: unknown): void {\n console.error(wrapError(err, AtomError, ERROR_MESSAGES.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED));\n }\n\n // ============================================================================\n // Consumer Logic (Dependency Validation)\n // ============================================================================\n\n /**\n * Determines if the node is dirty by checking its dependency chain.\n * Optimized with O(1) hot-path check.\n */\n protected _isDirty(): boolean {\n const deps = this._deps;\n if (deps === null || deps.size === 0) return false;\n\n // Phase 1: Hot-path Check - O(1)\n const hotIndex = this._hotIndex;\n if (hotIndex !== -1) {\n const hotLink = deps.getAt(hotIndex);\n if (hotLink !== null && hotLink.node.version !== hotLink.version) {\n return true;\n }\n }\n\n // Phase 2: Standard Validation - O(N)\n return this._deepDirtyCheck();\n }\n\n /**\n * Deeply validates dependency versions.\n */\n protected abstract _deepDirtyCheck(): boolean;\n}\n","import { IS_DEV, SCHEDULER_CONFIG, SMI_MAX } from '@/constants';\nimport { ERROR_MESSAGES, SchedulerError } from '@/errors';\n\n// ── Epoch & Version Management ──────────────────────────────────────────\n\n/**\n * Global epoch counter used for job deduplication and tracking state consistency.\n */\nlet collectorEpoch = 0;\n\n/**\n * Returns the next tracking epoch.\n * Wraps around using SMI_MAX and reserves 0 for uninitialized state.\n */\nexport function nextEpoch(): number {\n const next = (collectorEpoch + 1) & SMI_MAX;\n collectorEpoch = next === 0 ? 1 : next;\n return collectorEpoch;\n}\n\n/**\n * Returns the current global tracking epoch.\n */\nexport function currentEpoch(): number {\n return collectorEpoch;\n}\n\n/**\n * Increments a version counter within SMI range.\n * Reservations: Avoids 0 to allow it as a 'never updated' marker.\n */\nexport function nextVersion(v: number): number {\n const next = (v + 1) & SMI_MAX;\n return next === 0 ? 1 : next;\n}\n\n/** Current number of executions in the active flush cycle. */\nexport let flushExecutionCount = 0;\nlet isFlushing = false;\nlet _flushEpoch = 0;\n\n/** Returns the epoch associated with the current flush cycle. */\nexport function currentFlushEpoch(): number {\n return _flushEpoch;\n}\n\n/**\n * Starts a new flush cycle.\n * @returns true if the cycle was successfully started, false if already flushing.\n */\nexport function startFlush(): boolean {\n if (isFlushing) {\n if (IS_DEV) {\n console.warn('startFlush() called during flush - ignored');\n }\n return false;\n }\n\n isFlushing = true;\n _flushEpoch = nextEpoch();\n flushExecutionCount = 0;\n return true;\n}\n\n/** Ends the current flush cycle. */\nexport function endFlush(): void {\n isFlushing = false;\n}\n\n/**\n * Runs a function within a managed flush scope.\n * Ensures the flush state is properly incremented and cleaned up.\n *\n * @param fn - The function to execute.\n * @returns The result of the function execution.\n */\nexport function runInFlushScope<T>(fn: () => T): T | undefined {\n const started = startFlush();\n try {\n return fn();\n } finally {\n if (started) endFlush();\n }\n}\n\n/**\n * Track total execution count within a flush.\n * Throws if the count exceeds configured safety limits to prevent hung processes.\n */\nexport function incrementFlushExecutionCount(): number {\n if (!isFlushing) return 0;\n\n const count = ++flushExecutionCount;\n if (count <= SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH) {\n return count;\n }\n\n throw new Error(\n `[atom-effect] Infinite loop detected: flush execution count exceeded ${SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH}`\n );\n}\n\n/** Resets all global flush-related states to their defaults. */\nexport function resetFlushState(): void {\n _flushEpoch = 0;\n flushExecutionCount = 0;\n isFlushing = false;\n}\n\n// ── Scheduler ───────────────────────────────────────────────────────────\n\nexport interface SchedulerJobObject {\n execute(): void;\n /** Internal tracking for deduplication within the same epoch. */\n _nextEpoch?: number | undefined;\n}\n\n/** Represents a job that can be executed by the scheduler via a function interface. */\nexport interface SchedulerJobFunction {\n (): void;\n /** Internal tracking for deduplication within the same epoch. */\n _nextEpoch?: number | undefined;\n}\n\n/** Union type representing any valid schedulable task. */\nexport type SchedulerJob = SchedulerJobFunction | SchedulerJobObject;\n\n/**\n * Core Scheduler that manages asynchronous and synchronous task execution.\n *\n * Features:\n * - Double buffering for stable queue processing.\n * - Automatic job deduplication via Epoch tagging.\n * - Nested batching support with automatic coalescence.\n * - Microsecond-level scheduling via queueMicrotask.\n */\nclass Scheduler {\n // SMI fields grouped at top for V8 layout optimization\n private _bufferIndex = 0;\n private _size = 0;\n private _epoch = 0;\n private _batchDepth = 0;\n private _batchQueueSize = 0;\n private _maxFlushIterations: number = SCHEDULER_CONFIG.MAX_FLUSH_ITERATIONS;\n\n // Booleans for compact state tracking\n private _isProcessing = false;\n private _isFlushingSync = false;\n\n // Pre-allocated buffers to avoid tuple access overhead\n private _buffer0: (SchedulerJob | undefined)[] = [];\n private _buffer1: (SchedulerJob | undefined)[] = [];\n /** Temporary holding area for jobs scheduled during an active batch or sync flush. */\n private _batchQueue: (SchedulerJob | undefined)[] = [];\n\n /** Optional callback fired when the scheduler drops jobs due to overflow. */\n onOverflow: ((droppedCount: number) => void) | null = null;\n\n private readonly _boundRunLoop = this._runLoop.bind(this);\n\n /** Returns the total number of pending jobs (active + batched). */\n get queueSize(): number {\n return this._size + this._batchQueueSize;\n }\n\n /** Returns true if the scheduler is currently within a `batch()` scope. */\n get isBatching(): boolean {\n return this._batchDepth > 0;\n }\n\n /**\n * Schedules a job for execution.\n * Jobs are deduplicated based on the current epoch.\n *\n * @param callback - The task to be executed.\n */\n schedule(callback: SchedulerJob): void {\n if (IS_DEV) {\n if (\n typeof callback !== 'function' &&\n (!callback || typeof (callback as SchedulerJobObject).execute !== 'function')\n ) {\n throw new SchedulerError(ERROR_MESSAGES.SCHEDULER_CALLBACK_MUST_BE_FUNCTION);\n }\n }\n\n const epoch = this._epoch;\n if (callback._nextEpoch === epoch) return;\n callback._nextEpoch = epoch;\n\n // If batching or sync flushing, move to batch queue to ensure order and coalescence.\n if (this._batchDepth > 0 || this._isFlushingSync) {\n this._batchQueue[this._batchQueueSize++] = callback;\n return;\n }\n\n const buffer = this._bufferIndex === 0 ? this._buffer0 : this._buffer1;\n buffer[this._size++] = callback;\n\n if (!this._isProcessing) {\n this._flush();\n }\n }\n\n /** Initiates an asynchronous flush via microtask. */\n private _flush(): void {\n if (this._isProcessing || (this._size === 0 && this._batchQueueSize === 0)) return;\n this._isProcessing = true;\n queueMicrotask(this._boundRunLoop);\n }\n\n /** Internal microtask execution loop. */\n private _runLoop(): void {\n try {\n if (this._size === 0 && this._batchQueueSize === 0) return;\n\n const started = startFlush();\n this._drainQueue();\n if (started) endFlush();\n } finally {\n this._isProcessing = false;\n }\n }\n\n /** Internal synchronous flush typically triggered at the end of a batch. */\n _flushSync(): void {\n if (this._size === 0 && this._batchQueueSize === 0) return;\n\n const prev = this._isFlushingSync;\n this._isFlushingSync = true;\n const started = startFlush();\n try {\n this._mergeBatchQueue();\n this._drainQueue();\n } finally {\n this._isFlushingSync = prev;\n if (started) endFlush();\n }\n }\n\n /**\n * Merges the temporal batch queue into the main active buffer.\n */\n private _mergeBatchQueue(): void {\n const queueSize = this._batchQueueSize;\n if (queueSize === 0) return;\n\n const epoch = ++this._epoch | 0;\n const bQueue = this._batchQueue;\n const targetBuffer = this._bufferIndex === 0 ? this._buffer0 : this._buffer1;\n let currentSize = this._size;\n\n for (let i = 0; i < queueSize; i++) {\n const job = bQueue[i]!;\n if (job._nextEpoch !== epoch) {\n job._nextEpoch = epoch;\n targetBuffer[currentSize++] = job;\n }\n bQueue[i] = undefined; // Immediate GC hint\n }\n\n this._size = currentSize;\n this._batchQueueSize = 0;\n // Shrink array if it grew significantly\n if (bQueue.length > SCHEDULER_CONFIG.BATCH_QUEUE_SHRINK_THRESHOLD) bQueue.length = 0;\n }\n\n /**\n * Continuous loop that drains both main and batch queues.\n */\n private _drainQueue(): void {\n let iterations = 0;\n while (this._size > 0 || this._batchQueueSize > 0) {\n if (++iterations > this._maxFlushIterations) {\n this._handleFlushOverflow();\n return;\n }\n\n if (this._batchQueueSize > 0) this._mergeBatchQueue();\n if (this._size > 0) this._processQueue();\n }\n }\n\n /** Executes all jobs currently in the primary buffer and swaps buffers. */\n private _processQueue(): void {\n const idx = this._bufferIndex;\n const jobs = idx === 0 ? this._buffer0 : this._buffer1;\n const count = this._size;\n\n // Buffer swapping & Epoch bump\n this._bufferIndex = idx ^ 1;\n this._size = 0;\n this._epoch = (this._epoch + 1) | 0;\n\n for (let i = 0; i < count; i++) {\n const job = jobs[i]!;\n jobs[i] = undefined; // Avoid memory leaks\n try {\n if (typeof job === 'function') {\n job();\n } else {\n job.execute();\n }\n } catch (e) {\n console.error(new SchedulerError('Error occurred during scheduler execution', e as Error));\n }\n }\n }\n\n /** Resets the scheduler state on infinite loop detection. */\n private _handleFlushOverflow(): void {\n const droppedCount = this._size + this._batchQueueSize;\n console.error(\n new SchedulerError(\n ERROR_MESSAGES.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations, droppedCount)\n )\n );\n\n this._size = 0;\n this._buffer0.length = 0;\n this._buffer1.length = 0;\n this._batchQueueSize = 0;\n this._batchQueue.length = 0;\n\n const onOverflow = this.onOverflow;\n if (onOverflow) {\n try {\n onOverflow(droppedCount);\n } catch {}\n }\n }\n\n /** Enters a new batching depth. */\n startBatch(): void {\n this._batchDepth++;\n }\n\n /** Decrements batching depth. */\n endBatch(): void {\n if (this._batchDepth === 0) {\n if (IS_DEV) console.warn(ERROR_MESSAGES.SCHEDULER_END_BATCH_WITHOUT_START);\n return;\n }\n\n if (--this._batchDepth === 0) {\n if (!this._isFlushingSync) {\n this._flushSync();\n }\n }\n }\n\n /** Configures the maximum safety iterations. */\n setMaxFlushIterations(max: number): void {\n if (max < SCHEDULER_CONFIG.MIN_FLUSH_ITERATIONS)\n throw new SchedulerError(\n `Max iterations must be at least ${SCHEDULER_CONFIG.MIN_FLUSH_ITERATIONS}`\n );\n this._maxFlushIterations = max;\n }\n}\n\n/** Global scheduler instance. */\nexport const scheduler = new Scheduler();\n\n/**\n * Groups multiple state updates into a single batch, delaying effects and computations\n * until the batch is closed.\n *\n * @param fn - The function containing state updates.\n * @returns The result of the function execution.\n * @throws {TypeError} If fn is not a function.\n */\nexport function batch<T>(fn: () => T): T {\n if (IS_DEV && typeof fn !== 'function') {\n throw new TypeError(ERROR_MESSAGES.BATCH_CALLBACK_MUST_BE_FUNCTION);\n }\n\n scheduler.startBatch();\n try {\n return fn();\n } finally {\n scheduler.endBatch();\n }\n}\n\nlet sharedNextTickPromise: Promise<void> | null = null;\n\n/**\n * Returns a promise that resolves after the next scheduler flush.\n * This can be used to wait for all asynchronous effects to be processed.\n *\n * @param fn - Optional callback to execute after the flush.\n * @returns A promise that resolves after the flush completes.\n */\nexport function aeNextTick(fn?: () => void): Promise<void> {\n if (fn) {\n return new Promise<void>((resolve, reject) => {\n scheduler.schedule(() => {\n try {\n fn();\n resolve();\n } catch (err) {\n reject(err);\n }\n });\n });\n }\n\n if (sharedNextTickPromise) {\n return sharedNextTickPromise;\n }\n\n sharedNextTickPromise = new Promise<void>((resolve) => {\n scheduler.schedule(() => {\n sharedNextTickPromise = null;\n resolve();\n });\n });\n\n return sharedNextTickPromise;\n}\n","import { ATOM_STATE_FLAGS, IS_DEV } from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { BRAND, BrandFlags } from '@/symbols';\nimport type { AtomOptions, WritableAtom } from '@/types';\nimport { debug } from '@/utils/debug';\nimport { nextVersion, scheduler } from './scheduler';\nimport { trackingContext } from './tracking';\n\n/**\n * Internal {@link WritableAtom} implementation.\n */\nclass AtomImpl<T> extends ReactiveNode<T> implements WritableAtom<T> {\n private _value: T;\n /** Old value for notifications */\n private _pendingOldValue: T | undefined;\n /** Equality comparator */\n private _equal: (a: T, b: T) => boolean;\n\n /** @internal */\n readonly [BRAND] = BrandFlags.Atom | BrandFlags.Writable;\n\n constructor(initialValue: T, options: AtomOptions<T>) {\n super();\n this._value = initialValue;\n this._equal = options.equal ?? Object.is;\n\n if (options.sync) {\n this.flags |= ATOM_STATE_FLAGS.SYNC;\n }\n\n if (IS_DEV) {\n debug.attachDebugInfo(this, 'atom', this.id, options.name);\n }\n }\n\n /** @internal */\n get isNotificationScheduled(): boolean {\n return (this.flags & ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED) !== 0;\n }\n\n /** @internal */\n get isSync(): boolean {\n return (this.flags & ATOM_STATE_FLAGS.SYNC) !== 0;\n }\n\n get value(): T {\n const ctx = trackingContext.current;\n if (ctx != null) {\n ctx.addDependency(this);\n }\n return this._value;\n }\n\n set value(newValue: T) {\n const oldValue = this._value;\n if (this._equal(oldValue, newValue)) return;\n\n this._value = newValue;\n this.version = nextVersion(this.version);\n\n if (IS_DEV) {\n debug.trackUpdate(this.id, debug.getDebugName(this));\n }\n\n const currentFlags = this.flags;\n const SCHED_BIT = ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED;\n\n // 1. Guard: Skip if already scheduled or no subscribers\n if ((currentFlags & SCHED_BIT) !== 0) return;\n const slots = this._slots;\n if (slots === null || slots.size === 0) return;\n\n // 2. Schedule Notification\n this._pendingOldValue = oldValue;\n const nextFlags = currentFlags | SCHED_BIT;\n this.flags = nextFlags;\n\n // 3. Choice: Flush now or Schedule for later\n const SYNC_BIT = ATOM_STATE_FLAGS.SYNC;\n if ((nextFlags & SYNC_BIT) !== 0 && !scheduler.isBatching) {\n if (this._notifying === 0) {\n this._flushNotifications();\n }\n return;\n }\n\n scheduler.schedule(this);\n }\n\n /**\n * Executes scheduled notification.\n * @internal\n */\n execute(): void {\n this._flushNotifications();\n }\n\n /**\n * Triggers subscribers.\n */\n private _flushNotifications(): void {\n const SCHED_BIT = ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED;\n const DISP_BIT = ATOM_STATE_FLAGS.DISPOSED;\n const SYNC_BIT = ATOM_STATE_FLAGS.SYNC;\n const LOOP_MASK = SCHED_BIT | DISP_BIT;\n\n let flags = this.flags;\n // Loop to handle re-entrant sync updates in breadth-first order\n while ((flags & LOOP_MASK) === SCHED_BIT) {\n const oldValue = this._pendingOldValue as T;\n this._pendingOldValue = undefined;\n\n // Update bitwise state\n this.flags = flags &= ~SCHED_BIT;\n\n // Net-zero check: if value returned to original during batching, skip notification\n const currentVal = this._value;\n if (!this._equal(currentVal, oldValue)) {\n this._notifySubscribers(currentVal, oldValue);\n }\n\n flags = this.flags;\n // Only continue looping if we are in sync mode and not batching.\n if ((flags & SYNC_BIT) === 0 || scheduler.isBatching) {\n break;\n }\n }\n }\n\n peek(): T {\n return this._value;\n }\n\n dispose(): void {\n const flags = this.flags;\n const DISP_BIT = ATOM_STATE_FLAGS.DISPOSED;\n if ((flags & DISP_BIT) !== 0) return;\n\n this.flags = flags | DISP_BIT;\n this._slots?.clear();\n\n // Release references\n this._value = undefined as T;\n this._pendingOldValue = undefined;\n this._equal = Object.is; // Reset to default\n }\n\n protected override _deepDirtyCheck(): boolean {\n return false;\n }\n}\n\n/**\n * Creates a reactive atom holding mutable state.\n *\n * @param initialValue - The initial value of the atom.\n * @param options - Configuration options (sync: boolean).\n */\nexport function atom<T>(initialValue: T, options: AtomOptions = {}): WritableAtom<T> {\n return new AtomImpl(initialValue, options);\n}\n","import {\n AsyncState,\n COMPUTED_CONFIG,\n COMPUTED_STATE_FLAGS,\n EMPTY_ERROR_ARRAY,\n EPOCH_CONSTANTS,\n IS_DEV,\n} from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { ComputedError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport { BRAND, BrandFlags } from '@/symbols';\nimport type {\n AsyncStateType,\n ComputedAtom,\n ComputedOptions,\n Dependency,\n Subscriber,\n} from '@/types';\nimport { debug, NO_DEFAULT_VALUE } from '@/utils/debug';\nimport { isPromise } from '@/utils/type-guards';\nimport { DepSlotBuffer } from './buffers';\nimport { nextEpoch, nextVersion } from './scheduler';\nimport { DependencyLink, trackingContext, untracked } from './tracking';\n\nconst {\n IDLE,\n DIRTY,\n PENDING,\n RESOLVED,\n REJECTED,\n HAS_ERROR,\n RECOMPUTING,\n DISPOSED,\n IS_COMPUTED,\n FORCE_COMPUTE,\n} = COMPUTED_STATE_FLAGS;\n\n/**\n * Computed atom implementation.\n */\nclass ComputedAtomImpl<T> extends ReactiveNode<T> implements ComputedAtom<T>, Subscriber {\n /** @internal */\n readonly [BRAND] = BrandFlags.Atom | BrandFlags.Computed;\n\n // Bookkeeping fields grouped at top for V8 SMI/Number optimization\n /** Promise tracking ID */\n private _promiseId = 0;\n private _trackEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _trackCount = 0;\n\n private _value: T;\n private _error: Error | null = null;\n\n /** Initialized in constructor. Unified node property. */\n _deps = new DepSlotBuffer();\n\n private readonly _equal: (a: T, b: T) => boolean;\n private readonly _computation: () => T | Promise<T>;\n private readonly _defaultValue: T;\n private readonly _onError: ((error: Error) => void) | null;\n\n constructor(computation: () => T | Promise<T>, options: ComputedOptions<T> = {}) {\n if (typeof computation !== 'function')\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_MUST_BE_FUNCTION);\n super();\n\n this._value = undefined as T;\n // Start dirty so first access triggers computation\n this.flags = IS_COMPUTED | DIRTY | IDLE;\n this._equal = options.equal ?? Object.is;\n this._computation = computation;\n this._defaultValue = 'defaultValue' in options ? options.defaultValue : (NO_DEFAULT_VALUE as T);\n this._onError = options.onError ?? null;\n\n debug.attachDebugInfo(this, 'computed', this.id, options.name);\n\n // Eager evaluation if not lazy\n if (options.lazy === false) {\n try {\n this._recompute();\n } catch {\n /* _handleError already stored error and called onError */\n }\n }\n }\n\n /** @internal */\n get isDirty(): boolean {\n return (this.flags & DIRTY) !== 0;\n }\n\n /** @internal */\n get isRejected(): boolean {\n return (this.flags & REJECTED) !== 0;\n }\n\n /** @internal */\n get isRecomputing(): boolean {\n return (this.flags & RECOMPUTING) !== 0;\n }\n\n get value(): T {\n const context = trackingContext.current;\n if (context !== null) context.addDependency(this);\n\n const flags = this.flags;\n // 1. Fast path: Stable and Resolved. Masking multiple flags for single-branch optimization.\n if ((flags & (RESOLVED | DIRTY | IDLE | DISPOSED | RECOMPUTING)) === RESOLVED) {\n return this._value;\n }\n\n // 2. Exception paths (Disposed, Cycles)\n if ((flags & DISPOSED) !== 0) throw new ComputedError(ERROR_MESSAGES.COMPUTED_DISPOSED);\n\n if ((flags & RECOMPUTING) !== 0) {\n const defaultValue = this._defaultValue;\n if (defaultValue !== (NO_DEFAULT_VALUE as T)) return defaultValue;\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_CIRCULAR_DEPENDENCY);\n }\n\n // 3. Evaluation path (Lazy Stale Check)\n if ((flags & (DIRTY | IDLE)) !== 0) {\n const dependencies = this._deps;\n // Force computation if idle, forced, has no deps (initial), or deep check failed\n const shouldRecompute =\n (flags & (IDLE | FORCE_COMPUTE)) !== 0 || dependencies.size === 0 || this._isDirty();\n\n if (!shouldRecompute) {\n this.flags &= ~DIRTY;\n } else {\n this._recompute();\n }\n if ((this.flags & RESOLVED) !== 0) return this._value;\n }\n\n // 4. Async/Error handled after recomputation check\n const defaultValue = this._defaultValue;\n const hasDefault = defaultValue !== (NO_DEFAULT_VALUE as T);\n\n if ((this.flags & PENDING) !== 0) {\n if (hasDefault) return defaultValue;\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_ASYNC_PENDING_NO_DEFAULT);\n }\n\n if ((this.flags & REJECTED) !== 0) {\n if (hasDefault) return defaultValue;\n throw this._error;\n }\n\n return this._value;\n }\n\n peek(): T {\n return this._value;\n }\n\n get state(): AsyncStateType {\n const context = trackingContext.current;\n if (context !== null) context.addDependency(this);\n const flags = this.flags;\n if ((flags & RESOLVED) !== 0) return AsyncState.RESOLVED;\n if ((flags & PENDING) !== 0) return AsyncState.PENDING;\n if ((flags & REJECTED) !== 0) return AsyncState.REJECTED;\n return AsyncState.IDLE;\n }\n\n get hasError(): boolean {\n const context = trackingContext.current;\n if (context !== null) context.addDependency(this);\n\n const flags = this.flags;\n if ((flags & (REJECTED | HAS_ERROR)) !== 0) return true;\n\n const dependencies = this._deps;\n if (!dependencies.hasComputeds) return false;\n\n return untracked(() => {\n const size = dependencies.size;\n for (let i = 0; i < size; i++) {\n const link = dependencies.getAt(i);\n if (link?.node.hasError) return true;\n }\n return false;\n });\n }\n\n get isValid(): boolean {\n return !this.hasError;\n }\n\n get errors(): readonly Error[] {\n const context = trackingContext.current;\n if (context !== null) context.addDependency(this);\n\n const selfError = this._error;\n const dependencies = this._deps;\n\n if (!dependencies.hasComputeds) {\n if (selfError === null) return EMPTY_ERROR_ARRAY;\n return Object.freeze([selfError]);\n }\n\n const collected: Error[] = [];\n if (selfError !== null) collected.push(selfError);\n\n untracked(() => {\n const size = dependencies.size;\n for (let i = 0; i < size; i++) {\n const link = dependencies.getAt(i);\n const dependencyNode = link?.node;\n if (dependencyNode !== undefined && (dependencyNode.flags & IS_COMPUTED) !== 0) {\n this._accumulateErrors(dependencyNode as unknown as ComputedAtomImpl<unknown>, collected);\n }\n }\n });\n\n return collected.length === 0 ? EMPTY_ERROR_ARRAY : Object.freeze(collected);\n }\n\n private _accumulateErrors(dependency: ComputedAtomImpl<unknown>, collected: Error[]): void {\n const error = dependency._error;\n if (error !== null && !collected.includes(error)) {\n collected.push(error);\n }\n\n const dependencies = dependency._deps;\n if (!dependencies.hasComputeds) return;\n\n const size = dependencies.size;\n for (let i = 0; i < size; i++) {\n const link = dependencies.getAt(i);\n const node = link?.node;\n if (node !== undefined && (node.flags & IS_COMPUTED) !== 0) {\n this._accumulateErrors(node as unknown as ComputedAtomImpl<unknown>, collected);\n }\n }\n }\n\n get lastError(): Error | null {\n const context = trackingContext.current;\n if (context !== null) context.addDependency(this);\n return this._error;\n }\n\n get isPending(): boolean {\n const context = trackingContext.current;\n if (context !== null) context.addDependency(this);\n return (this.flags & PENDING) !== 0;\n }\n\n get isResolved(): boolean {\n const context = trackingContext.current;\n if (context !== null) context.addDependency(this);\n return (this.flags & RESOLVED) !== 0;\n }\n\n invalidate(): void {\n this.flags |= FORCE_COMPUTE;\n this._markDirty();\n }\n\n dispose(): void {\n const flags = this.flags;\n if ((flags & DISPOSED) !== 0) return;\n\n this._deps.disposeAll();\n\n if (this._slots !== null) {\n this._slots.clear();\n }\n this.flags = DISPOSED | DIRTY | IDLE;\n\n this._error = null;\n this._value = undefined as T;\n this._hotIndex = -1;\n }\n\n addDependency(dependency: Dependency): void {\n const trackEpoch = this._trackEpoch;\n if (dependency._lastSeenEpoch === trackEpoch) return;\n dependency._lastSeenEpoch = trackEpoch;\n\n const trackIndex = this._trackCount++;\n const dependencies = this._deps;\n\n // Unrolled hot-path check for existing dependencies\n let existing: DependencyLink | null = null;\n if (trackIndex < 4) {\n if (trackIndex === 0) existing = dependencies._s0;\n else if (trackIndex === 1) existing = dependencies._s1;\n else if (trackIndex === 2) existing = dependencies._s2;\n else existing = dependencies._s3;\n } else {\n const overflow = dependencies._overflow;\n if (overflow !== null) existing = overflow[trackIndex - 4] ?? null;\n }\n\n if (existing !== null && existing.node === dependency) {\n existing.version = dependency.version;\n } else if (dependencies.claimExisting(dependency, trackIndex)) {\n // Version and relocation handled inside claimExisting\n } else {\n const link = new DependencyLink(dependency, dependency.version, dependency.subscribe(this));\n dependencies.insertNew(trackIndex, link);\n }\n\n if ((dependency.flags & IS_COMPUTED) !== 0) {\n dependencies.hasComputeds = true;\n }\n }\n\n private _recompute(): void {\n if ((this.flags & RECOMPUTING) !== 0) return;\n this.flags = (this.flags | RECOMPUTING) & ~FORCE_COMPUTE;\n\n this._trackEpoch = nextEpoch();\n this._trackCount = 0;\n this._deps.prepareTracking();\n this._hotIndex = -1;\n\n let committed = false;\n try {\n const result = trackingContext.run(this, this._computation);\n this._deps.truncateFrom(this._trackCount);\n committed = true;\n\n if (isPromise(result)) {\n this._handleAsyncComputation(result);\n } else {\n this._finalizeResolution(result);\n }\n } catch (e) {\n if (!committed) {\n try {\n this._deps.truncateFrom(this._trackCount);\n } catch (commitError) {\n if (IS_DEV) {\n console.warn('[atom-effect] _commitDeps failed during error recovery:', commitError);\n }\n }\n }\n this._handleError(e as Error, ERROR_MESSAGES.COMPUTED_COMPUTATION_FAILED, true);\n } finally {\n this._trackEpoch = EPOCH_CONSTANTS.UNINITIALIZED;\n this._trackCount = 0;\n this.flags &= ~RECOMPUTING;\n }\n }\n\n private _handleAsyncComputation(promise: Promise<T>): void {\n this.flags = (this.flags | PENDING) & ~(IDLE | DIRTY | RESOLVED | REJECTED);\n this._notifySubscribers(undefined, undefined);\n\n this._promiseId = (this._promiseId + 1) % COMPUTED_CONFIG.MAX_PROMISE_ID;\n const promiseId = this._promiseId;\n\n promise.then(\n (result) => {\n if (promiseId !== this._promiseId) return;\n if (this._isDirty()) return this._markDirty();\n\n this._finalizeResolution(result);\n this._notifySubscribers(result, undefined);\n },\n (error) =>\n promiseId === this._promiseId &&\n this._handleError(error, ERROR_MESSAGES.COMPUTED_ASYNC_COMPUTATION_FAILED)\n );\n }\n\n private _handleError(error: unknown, message: string, shouldThrow = false): void {\n const wrappedError = wrapError(error, ComputedError, message);\n\n if (!this.isRejected || this._error !== wrappedError) {\n this.version = nextVersion(this.version);\n }\n\n this._error = wrappedError;\n this.flags = (this.flags & ~(IDLE | DIRTY | PENDING | RESOLVED)) | REJECTED | HAS_ERROR;\n\n if (this._onError) {\n try {\n this._onError(wrappedError);\n } catch (e) {\n console.error(ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER, e);\n }\n }\n\n this._notifySubscribers(undefined, undefined);\n if (shouldThrow) throw wrappedError;\n }\n\n private _finalizeResolution(value: T): void {\n const flags = this.flags;\n if ((flags & RESOLVED) === 0 || !this._equal(this._value, value)) {\n this.version = nextVersion(this.version);\n }\n\n this._value = value;\n this._error = null;\n this.flags = (flags | RESOLVED) & ~(IDLE | DIRTY | PENDING | REJECTED | HAS_ERROR);\n }\n\n execute(): void {\n this._markDirty();\n }\n\n /** @internal */\n _markDirty(): void {\n const flags = this.flags;\n if ((flags & (RECOMPUTING | DIRTY)) !== 0) return;\n this.flags = flags | DIRTY;\n debug.trackUpdate(this.id, debug.getDebugName(this));\n this._notifySubscribers(undefined, undefined);\n }\n\n /**\n * Deep dirty check for computations.\n * Optimized with hot-index caching and unrolled scanning.\n */\n protected override _deepDirtyCheck(): boolean {\n const dependencies = this._deps;\n const size = dependencies.size;\n const hotIndex = this._hotIndex;\n\n return untracked(() => {\n // 1. Try last known dirty dependency first\n if (hotIndex !== -1 && hotIndex < size) {\n const link = dependencies.getAt(hotIndex);\n if (link !== null && this._checkLinkDirty(link)) return true;\n }\n\n // 2. Scan from beginning, skipping hot entry\n for (let i = 0; i < size; i++) {\n if (i === hotIndex) continue;\n const link = dependencies.getAt(i);\n if (link !== null && this._checkLinkDirty(link)) {\n this._hotIndex = i;\n return true;\n }\n }\n\n this._hotIndex = -1;\n return false;\n });\n }\n\n private _checkLinkDirty(link: DependencyLink): boolean {\n const dependency = link.node;\n if ((dependency.flags & IS_COMPUTED) !== 0) {\n try {\n void (dependency as { value: unknown }).value;\n } catch {\n if (IS_DEV) console.warn(`[atom-effect] Dependency #${dependency.id} threw during check`);\n }\n }\n return dependency.version !== link.version;\n }\n}\n\n/**\n * Creates a computed value.\n * @param computation - Computation function\n * @param options - Options object\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);\n}\n","import {\n DEBUG_CONFIG,\n EFFECT_STATE_FLAGS,\n EPOCH_CONSTANTS,\n IS_DEV,\n SCHEDULER_CONFIG,\n} from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { EffectError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport { BRAND, BrandFlags } from '@/symbols';\nimport type { Dependency, EffectFunction, EffectObject, EffectOptions } from '@/types';\nimport { debug } from '@/utils/debug';\nimport { isPromise } from '@/utils/type-guards';\nimport { DepSlotBuffer } from './buffers';\nimport {\n currentFlushEpoch,\n flushExecutionCount,\n incrementFlushExecutionCount,\n nextEpoch,\n scheduler,\n} from './scheduler';\nimport { DependencyLink, type DependencyTracker, trackingContext } from './tracking';\n\n/**\n * Effect implementation.\n */\nclass EffectImpl extends ReactiveNode<void> implements EffectObject, DependencyTracker {\n /** @internal */\n readonly [BRAND] = BrandFlags.Effect;\n\n // Bookkeeping fields grouped at top for V8 layout optimization\n private _currentEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _lastFlushEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _executionsInEpoch = 0;\n private _executionCount = 0;\n private _windowStart = 0;\n private _windowCount = 0;\n private _execId = 0;\n private _trackCount = 0;\n\n private _cleanup: (() => void) | null = null;\n /** Initialized in constructor to maintain God Class object shape */\n _deps = new DepSlotBuffer();\n\n /** Pre-allocated notify callback shared by all subscriptions */\n private readonly _notifyCallback: () => void;\n\n private readonly _onError: ((error: unknown) => void) | null;\n\n private readonly _fn: EffectFunction;\n private readonly _sync: boolean;\n private readonly _maxExecutions: number;\n private readonly _maxExecutionsPerFlush: number;\n\n constructor(fn: EffectFunction, options: EffectOptions = {}) {\n super();\n this._fn = fn;\n this._onError = options.onError ?? null;\n this._sync = options.sync ?? false;\n this._maxExecutions =\n options.maxExecutionsPerSecond ?? SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_SECOND;\n this._maxExecutionsPerFlush =\n options.maxExecutionsPerFlush ?? SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_EFFECT;\n\n // Pre-allocate callbacks once — eliminates per-dependency closure allocation\n if (this._sync) {\n this._notifyCallback = () => this.execute();\n } else {\n this._notifyCallback = () => scheduler.schedule(this);\n }\n\n debug.attachDebugInfo(this, 'effect', this.id, options.name);\n }\n\n public run(): void {\n if (this.isDisposed) {\n throw new EffectError(ERROR_MESSAGES.EFFECT_DISPOSED);\n }\n this.execute(true);\n }\n\n public dispose(): void {\n if (this.isDisposed) return;\n this.flags |= EFFECT_STATE_FLAGS.DISPOSED;\n\n this._execCleanup();\n this._deps?.disposeAll();\n }\n\n public addDependency(dep: Dependency): void {\n if ((this.flags & EFFECT_STATE_FLAGS.EXECUTING) === 0) return;\n\n if (dep._lastSeenEpoch === this._currentEpoch) return;\n dep._lastSeenEpoch = this._currentEpoch;\n\n const trackIndex = this._trackCount++;\n const deps = this._deps;\n const version = dep.version;\n\n // [Optimization] Fast-path lookup bypassing SlotBuffer.getAt() or switch statements\n let existing: DependencyLink | null = null;\n if (trackIndex < 4) {\n if (trackIndex === 0) existing = deps._s0;\n else if (trackIndex === 1) existing = deps._s1;\n else if (trackIndex === 2) existing = deps._s2;\n else existing = deps._s3;\n } else {\n const ov = deps._overflow;\n if (ov !== null) existing = ov[trackIndex - 4] ?? null;\n }\n\n if (existing !== null && existing.node === dep) {\n existing.version = version;\n } else if (!deps.claimExisting(dep, trackIndex)) {\n this._insertNewDependency(dep, trackIndex, version);\n }\n\n if (dep.isComputed && !deps.hasComputeds) {\n deps.hasComputeds = true;\n }\n }\n\n private _insertNewDependency(dep: Dependency, trackIndex: number, version: number): void {\n let link: DependencyLink;\n try {\n const unsubscribe = dep.subscribe(this._notifyCallback);\n link = new DependencyLink(dep, version, unsubscribe);\n } catch (error) {\n const wrapped = wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_EXECUTION_FAILED);\n console.error(wrapped);\n if (this._onError) {\n try {\n this._onError(wrapped);\n } catch {}\n }\n link = new DependencyLink(dep, version, undefined);\n }\n\n this._deps.insertNew(trackIndex, link);\n }\n\n /**\n * Executes effect with tracking.\n */\n public execute(force = false): void {\n const flags = this.flags;\n // Guard: Combined bitwise check for efficiency\n if ((flags & (EFFECT_STATE_FLAGS.DISPOSED | EFFECT_STATE_FLAGS.EXECUTING)) !== 0) return;\n\n // Skip if not dirty or forced\n const deps = this._deps;\n if (!force && deps.physicalSize > 0 && !this._isDirty()) return;\n\n this._checkInfiniteLoops();\n debug.trackUpdate(this.id, debug.getDebugName(this));\n\n this.flags = flags | EFFECT_STATE_FLAGS.EXECUTING;\n this._execCleanup();\n\n this._currentEpoch = nextEpoch();\n this._trackCount = 0;\n deps.prepareTracking();\n this._hotIndex = -1;\n\n let committed = false;\n try {\n const result = trackingContext.run(this, this._fn);\n\n // Clean up any remaining trailing dependencies\n deps.truncateFrom(this._trackCount);\n committed = true;\n\n // Handle result\n if (typeof result === 'function') {\n this._cleanup = result as () => void;\n } else if (isPromise(result)) {\n this._handleAsyncResult(result);\n } else {\n this._cleanup = null;\n }\n } catch (error) {\n // Commit on error gracefully to maintain state for recovery\n if (!committed) {\n try {\n deps.truncateFrom(this._trackCount);\n } catch (commitErr) {\n if (IS_DEV) {\n console.warn('[atom-effect] _commitDeps failed during error recovery:', commitErr);\n }\n }\n }\n this._handleExecutionError(error);\n this._cleanup = null;\n } finally {\n this.flags &= ~EFFECT_STATE_FLAGS.EXECUTING;\n }\n }\n\n private _handleAsyncResult(promise: Promise<unknown>): void {\n const execId = ++this._execId;\n promise.then(\n (cleanup) => {\n if (execId !== this._execId || (this.flags & EFFECT_STATE_FLAGS.DISPOSED) !== 0) {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (e) {\n this._handleExecutionError(e, ERROR_MESSAGES.EFFECT_CLEANUP_FAILED);\n }\n }\n return;\n }\n if (typeof cleanup === 'function') this._cleanup = cleanup as () => void;\n },\n (err) => execId === this._execId && this._handleExecutionError(err)\n );\n }\n\n protected override _isDirty(): boolean {\n const deps = this._deps;\n const size = deps.size;\n if (size === 0) return false;\n\n // Fast path: Check hot index first without switching context\n const hotIndex = this._hotIndex;\n if (hotIndex !== -1 && hotIndex < size) {\n const link = deps.getAt(hotIndex);\n if (link !== null) {\n const dep = link.node;\n // Correctness: Only non-computed deps can skip context switch/deep check\n if (!dep.isComputed && dep.version !== link.version) return true;\n }\n }\n\n return this._deepDirtyCheck();\n }\n\n protected override _deepDirtyCheck(): boolean {\n const deps = this._deps;\n const size = deps.size;\n const hotIdx = this._hotIndex;\n\n const prevContext = trackingContext.current;\n trackingContext.current = null;\n\n try {\n // Priority 1: Check others with hotIdx skip\n for (let i = 0; i < size; i++) {\n if (i === hotIdx) continue;\n const link = deps.getAt(i);\n if (link === null) continue;\n\n const dep = link.node;\n if (dep.isComputed) {\n try {\n void (dep as { value: unknown }).value;\n } catch {\n if (IS_DEV) {\n console.warn(`[atom-effect] Dependency #${dep.id} error in check`);\n }\n }\n }\n\n if (dep.version !== link.version) {\n this._hotIndex = i;\n return true;\n }\n }\n this._hotIndex = -1;\n return false;\n } finally {\n trackingContext.current = prevContext;\n }\n }\n\n private _execCleanup(): void {\n const cleanup = this._cleanup;\n if (cleanup == null) return;\n this._cleanup = null;\n try {\n cleanup();\n } catch (error) {\n this._handleExecutionError(error, ERROR_MESSAGES.EFFECT_CLEANUP_FAILED);\n }\n }\n\n private _checkInfiniteLoops(): void {\n const epoch = currentFlushEpoch();\n if (this._lastFlushEpoch !== epoch) {\n this._lastFlushEpoch = epoch;\n this._executionsInEpoch = 0;\n }\n\n const executions = ++this._executionsInEpoch;\n if (executions > this._maxExecutionsPerFlush) this._throwInfiniteLoopError('per-effect');\n\n const globalExecutions = incrementFlushExecutionCount();\n if (globalExecutions > SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH) {\n this._throwInfiniteLoopError('global');\n }\n\n this._executionCount++;\n\n if (IS_DEV) this._checkFrequencyLimit();\n }\n\n private _checkFrequencyLimit(): void {\n if (!Number.isFinite(this._maxExecutions)) return;\n\n const now = Date.now();\n if (now - this._windowStart >= DEBUG_CONFIG.EFFECT_FREQUENCY_WINDOW) {\n this._windowStart = now;\n this._windowCount = 1;\n return;\n }\n\n if (++this._windowCount > this._maxExecutions) {\n const err = new EffectError(ERROR_MESSAGES.EFFECT_FREQUENCY_LIMIT_EXCEEDED);\n this.dispose();\n this._handleExecutionError(err);\n throw err;\n }\n }\n\n get executionCount(): number {\n return this._executionCount;\n }\n get isExecuting(): boolean {\n return (this.flags & EFFECT_STATE_FLAGS.EXECUTING) !== 0;\n }\n\n private _throwInfiniteLoopError(type: 'per-effect' | 'global'): never {\n const error = new EffectError(\n `Infinite loop detected (${type}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${flushExecutionCount}`\n );\n this.dispose();\n console.error(error);\n throw error;\n }\n\n private _handleExecutionError(\n error: unknown,\n message: string = ERROR_MESSAGES.EFFECT_EXECUTION_FAILED\n ): void {\n const errorObj = wrapError(error, EffectError, message);\n console.error(errorObj);\n if (this._onError) {\n try {\n this._onError(errorObj);\n } catch (e) {\n console.error(wrapError(e, EffectError, ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER));\n }\n }\n }\n}\n\n/**\n * Creates and starts an effect.\n *\n * @param fn - Effect function.\n * @param options - Configuration options.\n * @returns Effect instance.\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 effectInstance.execute();\n\n return effectInstance;\n}\n","import { BRAND, BrandFlags } from '@/symbols';\nimport type { Paths, PathValue, WritableAtom } from '../types';\n\n/**\n * Internal recursive helper for creating deep immutable copies with structural sharing.\n * Optimized for performance: avoids Regex overhead and minimizes object allocations.\n */\nexport function setDeepValue(obj: unknown, keys: string[], index: number, value: unknown): unknown {\n if (index === keys.length) return value;\n\n const key = keys[index]!;\n // Fast string-based safety check instead of Regex\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') return obj;\n\n const isObj = obj != null && typeof obj === 'object';\n const curr = (isObj ? obj : {}) as Record<string, unknown>;\n const oldVal = curr[key];\n const newVal = setDeepValue(oldVal, keys, index + 1, value);\n\n // Return original if value is unchanged (structural sharing)\n if (Object.is(oldVal, newVal)) return obj;\n\n if (Array.isArray(curr)) {\n const copy = curr.slice();\n const idx = +key;\n // Check for valid array index (positive integer, non-empty)\n if (key.trim() !== '' && idx >= 0 && idx % 1 === 0) {\n copy[idx] = newVal;\n } else {\n (copy as unknown as Record<string, unknown>)[key] = newVal;\n }\n return copy;\n }\n\n const res = { ...curr };\n res[key] = newVal;\n return res;\n}\n\n/**\n * Helper to retrieve a nested value from an object/array at a given path.\n */\nexport function getPathValue(source: unknown, parts: string[]): unknown {\n let res = source;\n const len = parts.length;\n for (let i = 0; i < len; i++) {\n if (res == null) return undefined;\n const key = parts[i]!;\n // Performance: Fast string comparison avoids Regex overhead in hot paths\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') return undefined;\n res = (res as Record<string, unknown>)[key];\n }\n return res;\n}\n\n/**\n * Creates a two-way \"lens\" for a specific property path on an object-based atom.\n *\n * @example\n * const store = atom({ user: { name: 'Alice' } });\n * const nameLens = atomLens(store, 'user.name');\n * console.log(nameLens.value); // 'Alice'\n * nameLens.value = 'Bob'; // Updates store.user.name immutably\n */\nexport function atomLens<T extends object, P extends Paths<T>>(\n atom: WritableAtom<T>,\n path: P\n): WritableAtom<PathValue<T, P>> {\n const parts = path.includes('.') ? path.split('.') : [path];\n const unsubs = new Set<() => void>();\n const dispose = () => {\n unsubs.forEach((u) => u());\n unsubs.clear();\n };\n\n return {\n get value() {\n return getPathValue(atom.value, parts) as PathValue<T, P>;\n },\n set value(newVal: PathValue<T, P>) {\n const cur = atom.peek(),\n next = setDeepValue(cur, parts, 0, newVal);\n if (next !== cur) atom.value = next as T;\n },\n peek: () => getPathValue(atom.peek(), parts) as PathValue<T, P>,\n subscribe(listener: (nv: PathValue<T, P>, ov: PathValue<T, P>) => void) {\n // Local tracking of prevValue cuts getPathValue calls by 50% during root updates\n let prevValue = getPathValue(atom.peek(), parts) as PathValue<T, P>;\n\n const unsub = atom.subscribe((np) => {\n const nv = getPathValue(np, parts) as PathValue<T, P>;\n if (!Object.is(nv, prevValue)) {\n const ov = prevValue;\n prevValue = nv;\n listener(nv, ov);\n }\n });\n unsubs.add(unsub);\n return () => {\n unsub();\n unsubs.delete(unsub);\n };\n },\n subscriberCount: () => unsubs.size,\n dispose,\n [BRAND]: BrandFlags.Atom | BrandFlags.Writable,\n } as unknown as WritableAtom<PathValue<T, P>>;\n}\n\n/**\n * Composes an existing lens with a sub-path to create a deeper lens.\n */\nexport const composeLens = <T extends object, P extends Paths<T>>(lens: WritableAtom<T>, path: P) =>\n atomLens(lens, path);\n\n/**\n * Creates a lens factory bound to a specific atom.\n */\nexport const lensFor =\n <T extends object>(atom: WritableAtom<T>) =>\n <P extends Paths<T>>(path: P) =>\n atomLens(atom, path);\n"],"mappings":"mEAWA,IAAM,EAAQ,CAEZ,SAAU,EACV,YAAa,EAGb,MAAO,IACP,YAAa,IACb,UAAW,KACX,cAAe,KAGf,KAAM,MACN,QAAS,GAAK,GACd,SAAU,GAAK,GACf,SAAU,GAAK,GAGf,UAAW,GAAK,GAChB,4BAA6B,GAAK,GAGlC,iBAAkB,GAAK,IAMZ,GAAc,OAAO,OAAO,CAEvC,YAAa,EAAM,KAAO,EAAM,QAAU,EAAM,SAAW,EAAM,SAEjE,oBAAqB,EAAM,MAAQ,EAAM,YAAc,EAAM,cAC9D,EAKY,EAAa,OAAO,OAAO,CACtC,KAAM,OACN,QAAS,UACT,SAAU,WACV,SAAU,WACX,EAKY,EAAqB,OAAO,OAAO,CAC9C,SAAU,EAAM,SAChB,UAAW,EAAM,iBAClB,EAKY,EAAuB,O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