lume-js 2.2.0 → 2.3.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/README.md +90 -19
- package/dist/addons.min.mjs +1 -1
- package/dist/addons.mjs +160 -6
- package/dist/addons.mjs.map +1 -1
- package/dist/handlers.min.mjs +1 -1
- package/dist/handlers.mjs +38 -2
- package/dist/handlers.mjs.map +1 -1
- package/dist/index.min.mjs +1 -1
- package/dist/index.mjs +4 -141
- package/dist/index.mjs.map +1 -1
- package/dist/lume.global.js +1 -1
- package/dist/lume.global.js.map +1 -1
- package/dist/shared-Bk_gndPJ.mjs +232 -0
- package/dist/shared-Bk_gndPJ.mjs.map +1 -0
- package/dist/shared-DNe4ez8V.mjs +249 -0
- package/dist/shared-DNe4ez8V.mjs.map +1 -0
- package/dist/shared-DmpHYKx7.mjs +15 -0
- package/dist/shared-DmpHYKx7.mjs.map +1 -0
- package/dist/state.min.mjs +1 -0
- package/dist/state.mjs +7 -0
- package/dist/state.mjs.map +1 -0
- package/package.json +5 -1
- package/src/addons/computed.js +5 -0
- package/src/addons/hydrateState.js +32 -4
- package/src/addons/index.d.ts +70 -2
- package/src/addons/index.js +13 -2
- package/src/addons/persist.js +152 -0
- package/src/addons/repeat.js +120 -5
- package/src/addons/withPlugins.js +7 -1
- package/src/core/batch.js +139 -0
- package/src/core/bindDom.js +12 -3
- package/src/core/effect.js +34 -5
- package/src/core/state.js +124 -68
- package/src/handlers/index.d.ts +24 -0
- package/src/handlers/index.js +1 -0
- package/src/handlers/on.js +60 -0
- package/src/handlers/stringAttr.js +14 -2
- package/src/index.d.ts +40 -0
- package/src/index.js +3 -1
- package/src/state.d.ts +17 -0
- package/src/state.js +25 -0
- package/dist/shared-Dcokqj5a.mjs +0 -249
- package/dist/shared-Dcokqj5a.mjs.map +0 -1
package/dist/lume.global.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lume.global.js","sources":["../src/utils/log.js","../src/core/state.js","../src/core/bindDom.js","../src/core/effect.js","../src/addons/repeat.js","../src/addons/debug.js","../src/handlers/show.js","../src/handlers/className.js","../src/handlers/boolAttr.js","../src/handlers/ariaAttr.js","../src/handlers/stringAttr.js","../src/handlers/htmlAttrs.js","../src/handlers/presets.js","../src/handlers/classToggle.js","../src/addons/computed.js","../src/addons/cleanupGroup.js","../src/addons/hydrateState.js","../src/addons/index.js","../src/addons/watch.js","../src/addons/withPlugins.js"],"sourcesContent":["/**\n * Environment-safe logging utilities for constrained runtimes\n * (e.g. service workers, embedded engines, SSR environments).\n *\n * All core and addon files should import these instead of\n * calling console.* directly to avoid ReferenceError when\n * console is not defined.\n */\n\nexport function logWarn(msg, ...rest) {\n if (typeof console !== 'undefined' && typeof console.warn === 'function') {\n console.warn(msg, ...rest);\n }\n}\n\nexport function logError(msg, ...rest) {\n if (typeof console !== 'undefined' && typeof console.error === 'function') {\n console.error(msg, ...rest);\n }\n}\n","/**\n * Lume-JS Reactive State Core\n *\n * Provides minimal reactive state with standard JavaScript.\n * Features automatic microtask batching for performance.\n * Read tracking is opt-in via withReadObserver — state.js has zero permanent\n * dependency on effect.js or any other module.\n *\n * Features:\n * - Lightweight and Go-style\n * - Explicit nested states\n * - $subscribe for listening to key changes\n * - Cleanup with unsubscribe\n * - Per-state microtask batching for writes\n * - Scope-based read tracking via withReadObserver (multi-observer safe)\n *\n * Usage:\n * import { state } from \"lume-js\";\n *\n * const store = state({ count: 0 });\n * const unsub = store.$subscribe(\"count\", val => console.log(val));\n * unsub(); // cleanup\n */\n\nimport { logError } from '../utils/log.js';\n\n// Per-state batching – each state object maintains its own microtask flush.\n// This keeps effects simple and aligned with Lume's minimal philosophy.\n\n/**\n * Creates a reactive state object.\n *\n * @param {Object} obj - Initial state object (must be plain object)\n * @returns {Proxy} Reactive proxy with $subscribe method\n *\n * @example\n * const store = state({ count: 0 });\n */\n\n// Active read observers — only populated during withReadObserver scopes.\n// This keeps state.js pure: tracking only happens when someone explicitly\n// asks to observe reads within a synchronous function call.\n//\n// Note: This Set is module-level, so all reactive state instances and effects\n// within the SAME module instance share it. This is standard behavior for\n// auto-tracking reactive libraries (Vue, MobX, Solid, etc.). Multiple copies\n// of the lume-js module (e.g. from different bundled chunks) each get their\n// own independent Set via ES module / CommonJS isolation.\nconst readers = new Set();\n\n/**\n * Run a function with a read observer active.\n * The observer receives (proxy, key, registerEffect) for every property read.\n * Multiple observers can be active simultaneously (nested effects, devtools, etc.)\n *\n * Internal API — used by effect.js for auto-tracking. May be stabilized\n * for third-party addons in a future release.\n * @param {function} onRead - Called on each property access inside fn\n * @param {function} fn - The function to run under observation\n */\nexport function withReadObserver(onRead, fn) {\n readers.add(onRead);\n try {\n return fn();\n } finally {\n readers.delete(onRead);\n }\n}\n\nexport function state(obj) {\n // Validate input\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {\n throw new Error('state() requires a plain object');\n }\n if (Object.isFrozen(obj) || Object.isSealed(obj)) {\n throw new Error('state() requires a mutable plain object');\n }\n\n // Object.create(null) - no prototype chain lookups\n const listeners = Object.create(null);\n const pendingNotifications = new Map(); // Per-state pending changes\n const pendingEffects = new Set(); // Dedupe effects per state\n const beforeFlushHooks = [];\n let flushScheduled = false;\n\n /**\n * Schedule a single microtask flush for this state object.\n *\n * Flush order per state:\n * 1) Notify subscribers for changed keys (key → subscribers)\n * 2) Run each queued effect exactly once (Set-based dedupe)\n * 3) Repeat up to 100 iterations to handle cascading updates,\n * then log an error to prevent infinite loops.\n *\n * Notes:\n * - Batching is per state; effects that depend on multiple states\n * may run once per state that changed (by design).\n */\n function scheduleFlush() {\n if (flushScheduled) return;\n\n flushScheduled = true;\n // eslint-disable-next-line sonarjs/cognitive-complexity -- single-pass flush loop: hooks → subscribers → effects → cycle detection; must stay atomic\n queueMicrotask(() => {\n let iterations = 0;\n const MAX_ITERATIONS = 100;\n\n try {\n while ((pendingNotifications.size > 0 || pendingEffects.size > 0) && iterations < MAX_ITERATIONS) {\n iterations++;\n\n // Run registered before-flush hooks (e.g. plugin onNotify)\n for (let i = 0; i < beforeFlushHooks.length; i++) {\n try {\n beforeFlushHooks[i]();\n } catch (err) {\n logError('[Lume.js state] Error in beforeFlush hook:', err);\n }\n }\n\n // Notify all subscribers of changed keys\n for (const [key, value] of pendingNotifications) {\n if (listeners[key]) {\n const subs = listeners[key];\n let i = 0;\n while (i < subs.length) {\n const fn = subs[i];\n try {\n fn(value);\n } catch (err) {\n logError(`[Lume.js state] Error notifying subscriber for key \"${String(key)}\":`, err);\n }\n // Only advance if fn wasn't removed (something shifted into its place)\n if (subs[i] === fn) i++;\n }\n }\n }\n\n pendingNotifications.clear();\n\n // Run each effect exactly once (Set deduplicates)\n const effects = new Array(pendingEffects.size);\n let idx = 0;\n for (const effect of pendingEffects) {\n effects[idx++] = effect;\n }\n pendingEffects.clear();\n for (let i = 0; i < effects.length; i++) {\n try {\n effects[i]();\n } catch (err) {\n logError('[Lume.js state] Error in effect:', err);\n }\n }\n }\n } finally {\n flushScheduled = false;\n }\n\n if (iterations >= MAX_ITERATIONS) {\n logError(\n '[Lume.js state] Maximum flush iterations reached (100). ' +\n 'This usually indicates an infinite loop caused by an effect or computed mutating state it depends on.'\n );\n }\n });\n }\n\n // Brand symbol for type-level reactive identification\n const REACTIVE_BRAND = Symbol('lume.reactive');\n obj[REACTIVE_BRAND] = true;\n\n // Defined once per state instance — not per property read — to avoid per-read closure allocation.\n const registerEffect = (key, executeFn) => {\n if (!listeners[key]) listeners[key] = [];\n\n const callback = () => {\n pendingEffects.add(executeFn);\n };\n\n listeners[key].push(callback);\n\n return () => {\n if (listeners[key]) {\n const idx = listeners[key].indexOf(callback);\n if (idx !== -1) {\n listeners[key].splice(idx, 1);\n if (listeners[key].length === 0) delete listeners[key];\n }\n }\n };\n };\n\n const proxy = new Proxy(obj, {\n get(target, key) {\n // Skip effect tracking for internal meta methods (e.g. $subscribe)\n if (typeof key === 'string' && key.startsWith('$')) {\n return target[key];\n }\n\n const value = target[key];\n\n // Notify active read observers (effects, devtools, etc.)\n if (readers.size > 0) {\n for (const reader of readers) {\n reader(proxy, key, registerEffect);\n }\n }\n\n return value;\n },\n\n set(target, key, value) {\n const oldValue = target[key];\n\n // Skip update if value unchanged - Object.is() handles NaN and -0 correctly\n if (Object.is(oldValue, value)) return true;\n\n target[key] = value;\n\n // Batch notifications at the state level (per-state, not global)\n pendingNotifications.set(key, value);\n scheduleFlush();\n\n return true;\n }\n });\n\n /**\n * Subscribe to changes for a specific key.\n * Calls the callback immediately with the current value.\n * Returns an unsubscribe function for cleanup.\n *\n * @param {string} key - Property key to watch\n * @param {function} fn - Callback function\n * @returns {function} Unsubscribe function\n */\n // Set on obj (not proxy) to avoid triggering the set trap.\n // The get trap already returns target[key] directly for $-prefixed keys.\n /**\n * Register a callback to run before each flush.\n * Returns an unsubscribe function.\n */\n obj.$beforeFlush = (fn) => {\n if (typeof fn !== 'function') {\n throw new Error('$beforeFlush requires a function');\n }\n if (beforeFlushHooks.indexOf(fn) === -1) {\n beforeFlushHooks.push(fn);\n }\n return () => {\n const idx = beforeFlushHooks.indexOf(fn);\n if (idx !== -1) {\n beforeFlushHooks.splice(idx, 1);\n }\n };\n };\n\n obj.$subscribe = (key, fn) => {\n if (typeof fn !== 'function') {\n throw new Error('Subscriber must be a function');\n }\n\n if (!listeners[key]) listeners[key] = [];\n listeners[key].push(fn);\n\n // Call immediately with current value (NOT batched)\n fn(proxy[key]);\n\n // Return unsubscribe function\n return () => {\n if (listeners[key]) {\n const idx = listeners[key].indexOf(fn);\n if (idx !== -1) {\n listeners[key].splice(idx, 1);\n if (listeners[key].length === 0) delete listeners[key];\n }\n }\n };\n };\n\n return proxy;\n}\n","// src/core/bindDom.js\n/**\n * Lume-JS DOM Binding\n *\n * Binds reactive state to DOM elements using data-* attributes.\n *\n * Built-in attributes (always available):\n * data-bind=\"key\" → Two-way binding for inputs, textContent for others\n * data-hidden=\"key\" → Toggles hidden (truthy = hidden)\n * data-disabled=\"key\" → Toggles disabled (truthy = disabled)\n * data-checked=\"key\" → Toggles checked (for checkboxes/radios)\n * data-required=\"key\" → Toggles required (truthy = required)\n * data-aria-expanded=\"key\" → Sets aria-expanded to \"true\"/\"false\"\n * data-aria-hidden=\"key\" → Sets aria-hidden to \"true\"/\"false\"\n *\n * Extensible via handlers option:\n * import { show, classToggle } from 'lume-js/handlers';\n * bindDom(root, store, { handlers: [show, classToggle('active')] });\n *\n * Custom handlers:\n * const tooltip = { attr: 'data-tooltip', apply(el, val) { el.title = val ?? ''; } };\n * bindDom(root, store, { handlers: [tooltip] });\n *\n * Usage:\n * import { bindDom } from \"lume-js\";\n * const cleanup = bindDom(document.body, store);\n */\n\nimport { logWarn } from '../utils/log.js';\n\n// --- Default Handlers (always active, backwards compatible) ---\n\nconst boolHandler = (name) => ({\n attr: `data-${name}`,\n apply(el, val) { el[name] = Boolean(val); }\n});\n\nconst ariaHandler = (name) => ({\n attr: `data-${name}`,\n apply(el, val) { el.setAttribute(name, val ? 'true' : 'false'); }\n});\n\nconst DEFAULT_HANDLERS = [\n boolHandler('hidden'),\n boolHandler('disabled'),\n boolHandler('checked'),\n boolHandler('required'),\n ariaHandler('aria-expanded'),\n ariaHandler('aria-hidden'),\n];\n\n/**\n * Merge default and user handlers.\n * User handlers override defaults with same attr (Map deduplicates).\n * User handler arrays are flattened one level (supports classToggle()).\n */\nfunction mergeHandlers(defaults, userHandlers) {\n if (!userHandlers.length) return defaults;\n const merged = new Map();\n for (const h of defaults) merged.set(h.attr, h);\n for (const h of userHandlers.flat()) merged.set(h.attr, h);\n return [...merged.values()];\n}\n\n/**\n * DOM binding for reactive state\n */\nexport function bindDom(root, store, options = {}) {\n if (!(root instanceof HTMLElement)) {\n throw new Error('bindDom() requires a valid HTMLElement as root');\n }\n if (!store || typeof store !== 'object') {\n throw new Error('bindDom() requires a reactive state object');\n }\n\n const { immediate = false, handlers: userHandlers = [] } = options;\n const handlers = mergeHandlers(DEFAULT_HANDLERS, userHandlers);\n\n const performBinding = () => {\n const cleanups = [];\n const bindingMap = new WeakMap();\n\n // Build compiled selector: data-bind (always) + all handler attrs\n const selector = ['[data-bind]', ...handlers.map(h => `[${h.attr}]`)].join(',');\n const elements = root.querySelectorAll(selector);\n\n for (const el of elements) {\n // data-bind (two-way) — always in core, special handling\n if (el.hasAttribute('data-bind')) {\n const c = handleDataBind(el, store, el.getAttribute('data-bind'), bindingMap);\n if (c) cleanups.push(c);\n }\n\n // All registered handlers (default + user)\n for (const handler of handlers) {\n if (el.hasAttribute(handler.attr)) {\n const c = applyHandler(el, store, el.getAttribute(handler.attr), handler);\n if (c) cleanups.push(c);\n }\n }\n }\n\n // Event delegation for two-way bindings\n const inputHandler = e => {\n const binding = bindingMap.get(e.target);\n if (binding) binding.target[binding.key] = getInputValue(e.target);\n };\n root.addEventListener(\"input\", inputHandler);\n cleanups.push(() => root.removeEventListener(\"input\", inputHandler));\n\n return () => cleanups.forEach(c => c());\n };\n\n // Auto-wait for DOM if needed\n if (!immediate && document.readyState === 'loading') {\n let cleanup = null;\n const onReady = () => { cleanup = performBinding(); };\n document.addEventListener('DOMContentLoaded', onReady, { once: true });\n return () => cleanup ? cleanup() : document.removeEventListener('DOMContentLoaded', onReady);\n }\n\n return performBinding();\n}\n\n/**\n * Apply a handler to an element via subscription.\n * Resolves the state path and subscribes to changes.\n */\nfunction applyHandler(el, store, path, handler) {\n const result = resolveProp(store, path);\n if (!result) return null;\n const { target, key } = result;\n return target.$subscribe(key, val => handler.apply(el, val));\n}\n\n/**\n * Handle data-bind (two-way for inputs, textContent for others)\n */\nfunction handleDataBind(el, store, path, bindingMap) {\n const result = resolveProp(store, path);\n if (!result) return null;\n\n const { target, key } = result;\n const unsub = target.$subscribe(key, val => updateElement(el, val));\n\n if (isFormInput(el)) {\n bindingMap.set(el, { target, key });\n }\n\n return unsub;\n}\n\n/**\n * Resolve a nested path in an object.\n * Example: resolvePath(obj, ['user', 'address']) returns obj.user.address\n */\nfunction resolvePath(obj, pathArr) {\n if (!pathArr || pathArr.length === 0) {\n return obj;\n }\n let current = obj;\n for (let i = 0; i < pathArr.length; i++) {\n const key = pathArr[i];\n if (current === null || current === undefined) {\n return null;\n }\n if (!(key in current)) {\n return null;\n }\n current = current[key];\n }\n return current;\n}\n\n/**\n * Resolve path to target and key.\n *\n * ⚠️ Path bindings are resolved once at bind time. If an intermediate\n * object in the path is null/undefined at bindDom call time, the binding\n * is permanently dead and will not self-heal when the path later becomes valid.\n */\nfunction resolveProp(store, path) {\n if (!path) return null;\n\n const pathArr = path.split(\".\");\n const key = pathArr.pop();\n const target = resolvePath(store, pathArr);\n\n if (target === null || target === undefined) {\n logWarn(`[Lume.js] Invalid path \"${path}\"`);\n return null;\n }\n\n if (!target?.$subscribe) {\n logWarn(`[Lume.js] Target for \"${path}\" is not reactive`);\n return null;\n }\n\n return { target, key };\n}\n\n/**\n * Update element with value (for data-bind)\n */\nfunction updateElement(el, val) {\n if (el.tagName === \"INPUT\") {\n if (el.type === \"checkbox\") el.checked = Boolean(val);\n else if (el.type === \"radio\") el.checked = el.value === String(val);\n else el.value = val ?? '';\n } else if (el.tagName === \"TEXTAREA\" || el.tagName === \"SELECT\") {\n el.value = val ?? '';\n } else {\n el.textContent = val ?? '';\n }\n}\n\n/**\n * Get value from input\n */\nfunction getInputValue(el) {\n if (el.type === \"checkbox\") return el.checked;\n if (el.type === \"number\" || el.type === \"range\") return el.valueAsNumber;\n return el.value;\n}\n\n/**\n * Check if element is form input\n */\nfunction isFormInput(el) {\n return el.tagName === \"INPUT\" || el.tagName === \"TEXTAREA\" || el.tagName === \"SELECT\";\n}","import { withReadObserver } from './state.js';\nimport { logError } from '../utils/log.js';\n\n/**\n * Lume-JS Effect\n *\n * Reactive effects with two modes:\n * 1. Auto-tracking (default): Tracks dependencies automatically via withReadObserver\n * 2. Explicit deps: You specify exactly what triggers re-runs\n *\n * Auto-tracking uses scope-based read observation — state.js has zero permanent\n * dependency on this module. Read tracking is only active during the synchronous\n * execution of an effect's body.\n *\n * Usage:\n * import { effect } from \"lume-js\";\n *\n * // Auto-tracking mode (existing behavior)\n * effect(() => {\n * console.log('Count is:', store.count);\n * // Automatically re-runs when store.count changes\n * });\n *\n * // Explicit deps mode (new - no magic)\n * effect(() => {\n * console.log('Count is:', store.count);\n * }, [[store, 'count']]); // Only re-runs when store.count changes\n *\n * Features:\n * - Automatic dependency collection via withReadObserver scope (default)\n * - Explicit dependencies for side-effects\n * - Returns cleanup function\n * - Compatible with per-state batching\n */\n\n// Module-scoped effect context (prevents third-party spoofing via globalThis)\nlet currentEffect = null;\n\n// withReadObserver is used below to scope read tracking to synchronous effect execution.\n\n/**\n * Creates an effect that runs reactively\n *\n * @param {function} fn - Function to run reactively\n * @param {Array<[object, string]>} [deps] - Optional explicit dependencies as [store, key] tuples\n * @returns {function} Cleanup function to stop the effect\n *\n * @example\n * // Auto-tracking (default)\n * const store = state({ count: 0 });\n * effect(() => {\n * document.title = `Count: ${store.count}`;\n * });\n * \n * @example\n * // Explicit deps (no magic)\n * effect(() => {\n * analytics.log(store.count); // Won't track store.count automatically\n * }, [[store, 'count']]); // Explicit: only re-run on store.count\n */\n// eslint-disable-next-line sonarjs/cognitive-complexity -- handles both auto-tracking and explicit-deps modes with cleanup; splitting would require exporting internal state\nexport function effect(fn, deps) {\n if (typeof fn !== 'function') {\n throw new Error('effect() requires a function');\n }\n\n const cleanups = [];\n let isRunning = false;\n\n /**\n * Execute the effect function\n */\n const execute = () => {\n /* v8 ignore next -- re-entry guard: unreachable because $subscribe fires via microtask after isRunning resets in finally */\n if (isRunning) return;\n isRunning = true;\n\n try {\n fn();\n } catch (error) {\n logError('[Lume.js effect] Error in effect:', error);\n throw error;\n } finally {\n isRunning = false;\n }\n };\n\n // EXPLICIT DEPS MODE: deps array provided\n if (Array.isArray(deps)) {\n // Subscribe to each [store, key1, key2, ...] tuple explicitly\n for (const dep of deps) {\n if (Array.isArray(dep) && dep.length >= 2) {\n const [store, ...keys] = dep;\n if (store && typeof store.$subscribe === 'function') {\n // Subscribe to each key in this tuple\n for (const key of keys) {\n // $subscribe calls immediately, then on changes\n // We want: call execute immediately once, then on changes\n let isFirst = true;\n const unsub = store.$subscribe(key, () => {\n if (isFirst) {\n isFirst = false;\n return; // Skip first call, we'll run execute() below\n }\n execute();\n });\n cleanups.push(unsub);\n }\n }\n }\n }\n // Run immediately\n execute();\n }\n // AUTO-TRACKING MODE: no deps (existing behavior)\n else {\n const executeWithTracking = () => {\n /* v8 ignore next -- defensive guard: synchronous re-entry is unreachable through the public API */\n if (isRunning) return;\n\n // Save previous subscriptions instead of cleaning immediately.\n // If fn() doesn't read any state (early return / error), we restore\n // them so the effect stays reactive.\n const oldCleanups = cleanups.splice(0);\n\n // Create effect context for tracking\n const myContext = {\n fn,\n cleanups,\n execute: executeWithTracking,\n tracking: {}\n };\n\n // Set as current effect (for state.js to detect)\n // Save previous context to support nested effects/computed\n const previousEffect = currentEffect;\n currentEffect = myContext;\n isRunning = true;\n\n try {\n const onRead = (proxy, key, registerEffect) => {\n // Only the currently active effect (not a nested one) creates subscriptions\n if (currentEffect !== myContext) return;\n if (myContext.tracking[key]) return;\n myContext.tracking[key] = true;\n myContext.cleanups.push(registerEffect(key, myContext.execute));\n };\n withReadObserver(onRead, fn);\n } catch (error) {\n // On error, restore old subscriptions so the effect stays reactive\n cleanups.length = 0;\n cleanups.push(...oldCleanups);\n logError('[Lume.js effect] Error in effect:', error);\n throw error;\n } finally {\n // Restore previous context (not undefined) to support nesting\n currentEffect = previousEffect;\n isRunning = false;\n }\n\n // If fn() created new subscriptions, clean old ones.\n // If it didn't (e.g., early return), keep old subscriptions intact.\n if (cleanups.length > 0) {\n for (const cleanup of oldCleanups) cleanup();\n } else {\n cleanups.push(...oldCleanups);\n }\n };\n\n // Run immediately to collect initial dependencies\n executeWithTracking();\n }\n\n // Return cleanup function\n return () => {\n // while/pop is faster than forEach\n while (cleanups.length) cleanups.pop()();\n };\n}","/**\n * Lume-JS List Rendering (Addon)\n *\n * Renders lists with automatic subscription and element reuse by key.\n * \n * Core guarantees:\n * Element reuse by key (same DOM nodes, not recreated)\n * Minimal DOM operations (only updates what changed)\n * Memory efficiency (cleanup on remove)\n * \n * Default behavior (can be disabled/customized):\n * ✅ Focus preservation (maintains activeElement and selection)\n * ✅ Scroll preservation (intelligent positioning for add/remove/reorder)\n * \n * Philosophy: No artificial limitations\n * - All preservation logic is overridable via options\n * - Set to null/false to disable, or provide custom functions\n * - Export utilities so you can wrap/extend them\n *\n * ⚠️ IMPORTANT: Arrays must be updated immutably!\n * store.items.push(x) // ❌ Won't trigger update\n * store.items = [...items] // ✅ Triggers update\n * \n * ═══════════════════════════════════════════════════════════════════════\n * PATTERN 1: Simple (render only) - for simple cases or backward compat\n * ═══════════════════════════════════════════════════════════════════════\n * \n * repeat('#list', store, 'todos', {\n * key: todo => todo.id,\n * render: (todo, el) => {\n * el.textContent = todo.name; // Called on every update\n * }\n * });\n *\n * ═══════════════════════════════════════════════════════════════════════\n * PATTERN 2: Clean separation (create + update) - recommended\n * ═══════════════════════════════════════════════════════════════════════\n *\n * repeat('#list', store, 'todos', {\n * key: todo => todo.id,\n * create: (todo, el) => {\n * // Called ONCE when element is created - build DOM structure\n * const nameSpan = document.createElement('span');\n * nameSpan.className = 'name';\n * el.appendChild(nameSpan);\n * const btn = document.createElement('button');\n * btn.textContent = 'Delete';\n * btn.onclick = () => deleteTodo(todo.id);\n * el.appendChild(btn);\n *\n * // Return a cleanup function — called automatically when element is removed\n * return () => {\n * // Unsubscribe from external listeners, remove timers, etc.\n * };\n * },\n * update: (todo, el, index, { isFirstRender }) => {\n * // Called on every update - bind data\n * // isFirstRender = true on initial render, false on subsequent\n * // Skipped if same object reference (optimization)\n * el.querySelector('.name').textContent = todo.name;\n * }\n * });\n *\n * ═══════════════════════════════════════════════════════════════════════\n * ADVANCED: Custom preservation strategies\n * ═══════════════════════════════════════════════════════════════════════\n * \n * import { defaultFocusPreservation, defaultScrollPreservation } from \"lume-js/addons\";\n * \n * repeat('#list', store, 'items', {\n * key: item => item.id,\n * create: (item, el) => { ... },\n * update: (item, el) => { ... },\n * preserveFocus: null, // disable focus preservation\n * preserveScroll: (container, context) => {\n * const restore = defaultScrollPreservation(container, context);\n * return () => { restore(); console.log('Scroll restored!'); };\n * }\n * });\n */\nimport { logWarn, logError } from '../utils/log.js';\n\n/**\n * Default focus preservation strategy\n * Saves activeElement and selection state before DOM updates\n * \n * @param {HTMLElement} container - The list container\n * @returns {Function|null} Restore function, or null if nothing to restore\n */\nexport function defaultFocusPreservation(container) {\n const activeEl = document.activeElement;\n const shouldRestore = container.contains(activeEl);\n\n if (!shouldRestore) return null;\n\n let selectionStart = null;\n let selectionEnd = null;\n\n if (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA') {\n selectionStart = activeEl.selectionStart;\n selectionEnd = activeEl.selectionEnd;\n }\n\n return () => {\n if (document.body.contains(activeEl)) {\n activeEl.focus();\n if (selectionStart !== null && selectionEnd !== null) {\n activeEl.setSelectionRange(selectionStart, selectionEnd);\n }\n }\n };\n}\n\n/**\n * Default scroll preservation strategy\n * Uses anchor-based preservation for add/remove, pixel position for reorder\n * \n * @param {HTMLElement} container - The list container\n * @param {Object} context - Additional context\n * @param {boolean} context.isReorder - Whether this is a reorder operation\n * @returns {Function} Restore function\n */\nexport function defaultScrollPreservation(container, context = {}) {\n const { isReorder = false } = context;\n const scrollTop = container.scrollTop;\n\n // Early return if no scroll\n if (scrollTop === 0) {\n return () => { container.scrollTop = 0; };\n }\n\n let anchorElement = null;\n let anchorOffset = 0;\n\n // Only use anchor-based preservation for add/remove, not reorder\n if (!isReorder) {\n const containerRect = container.getBoundingClientRect();\n // Avoid Array.from - iterate children directly\n for (let child = container.firstElementChild; child; child = child.nextElementSibling) {\n const rect = child.getBoundingClientRect();\n\n if (rect.bottom > containerRect.top) {\n anchorElement = child;\n anchorOffset = rect.top - containerRect.top;\n break;\n }\n }\n }\n\n return () => {\n if (anchorElement && document.body.contains(anchorElement)) {\n const newRect = anchorElement.getBoundingClientRect();\n const containerRect = container.getBoundingClientRect();\n const currentOffset = newRect.top - containerRect.top;\n const scrollAdjustment = currentOffset - anchorOffset;\n\n container.scrollTop = container.scrollTop + scrollAdjustment;\n } else {\n container.scrollTop = scrollTop;\n }\n };\n}\n\n/**\n * Efficiently render a list with element reuse\n * \n * @param {string|HTMLElement} container - Container element or selector\n * @param {Object} store - Reactive state object\n * @param {string} arrayKey - Key in store containing the array\n * @param {Object} options - Configuration\n * @param {Function} options.key - Function to extract unique key: (item) => key\n * @param {Function} [options.render] - Function to render item (called for all items): (item, element, index) => void\n * @param {Function} [options.create] - Function for new elements only: (item, element, index) => void | Function. If a function is returned, it is registered as the element's cleanup and called automatically when the element is removed (by list update or full cleanup).\n * @param {Function} [options.update] - Function for data binding: (item, element, index, { isFirstRender }) => void. Skipped if same item reference AND same index.\n * @param {Function} [options.remove] - Additional cleanup when element is removed: (item, element) => void. Called after any cleanup function returned by create(). Optional — prefer returning a cleanup from create() for automatic lifecycle management.\n * @param {string|Function} [options.element='div'] - Element tag name or factory function\n * @param {Function|null} [options.preserveFocus=defaultFocusPreservation] - Focus preservation strategy (null to disable)\n * @param {Function|null} [options.preserveScroll=defaultScrollPreservation] - Scroll preservation strategy (null to disable)\n * @returns {Function} Cleanup function\n */\n\nexport function repeat(container, store, arrayKey, options) {\n const {\n key,\n render,\n create,\n update,\n remove,\n element = 'div',\n preserveFocus = defaultFocusPreservation,\n preserveScroll = defaultScrollPreservation\n } = options;\n\n // Resolve container\n const containerEl =\n typeof container === 'string'\n ? document.querySelector(container)\n : container;\n\n if (!containerEl) {\n logWarn(`[Lume.js] repeat(): container \"${container}\" not found`);\n return () => { };\n }\n\n if (typeof key !== 'function') {\n throw new Error('[Lume.js] repeat(): options.key must be a function');\n }\n\n if (typeof render !== 'function' && typeof create !== 'function') {\n throw new Error('[Lume.js] repeat(): options.render or options.create must be a function');\n }\n\n // key -> HTMLElement\n const elementsByKey = new Map();\n // key -> previous item (for reference comparison)\n const prevItemsByKey = new Map();\n // key -> previous index (for reorder detection)\n const prevIndexByKey = new Map();\n // key -> cleanup function returned by create()\n const cleanupByKey = new Map();\n const seenKeys = new Set();\n\n function createElement() {\n return typeof element === 'function'\n ? element()\n : document.createElement(element);\n }\n\n function reconcileDOM(container, nextEls) {\n let ptr = container.firstChild;\n\n for (let i = 0; i < nextEls.length; i++) {\n const desired = nextEls[i];\n\n if (ptr === desired) {\n ptr = ptr.nextSibling;\n continue;\n }\n\n container.insertBefore(desired, ptr);\n }\n\n // Remove leftover children not in nextEls\n while (ptr) {\n const next = ptr.nextSibling;\n container.removeChild(ptr);\n ptr = next;\n }\n }\n\n function applyPreservation(container, fn, isReorder) {\n const shouldPreserve = document.body.contains(container);\n const restoreFocus = shouldPreserve && preserveFocus ? preserveFocus(container) : null;\n const restoreScroll = shouldPreserve && preserveScroll ? preserveScroll(container, { isReorder }) : null;\n\n fn();\n\n if (restoreFocus) restoreFocus();\n if (restoreScroll) restoreScroll();\n }\n\n // eslint-disable-next-line sonarjs/cognitive-complexity -- keyed DOM reconciliation: create/reuse/remove nodes, key dedup, scroll/focus preservation\n function updateList() {\n const items = store[arrayKey];\n\n if (!Array.isArray(items)) {\n logWarn(`[Lume.js] repeat(): store.${arrayKey} is not an array`);\n return;\n }\n\n // Only compute isReorder if scroll preservation needs it.\n // Uses elementsByKey (previous state) and items directly — no Set allocations.\n let isReorder = false;\n if (preserveScroll && elementsByKey.size === items.length) {\n isReorder = true;\n for (let i = 0; i < items.length; i++) {\n if (!elementsByKey.has(key(items[i]))) { isReorder = false; break; }\n }\n }\n\n seenKeys.clear();\n const nextEls = [];\n\n // Build ordered list of DOM nodes (created or reused)\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n const k = key(item);\n\n if (seenKeys.has(k)) {\n logWarn(`[Lume.js] repeat(): duplicate key \"${k}\"`);\n continue;\n }\n seenKeys.add(k);\n\n let el = elementsByKey.get(k);\n const isFirstRender = !el;\n\n if (isFirstRender) {\n el = createElement();\n elementsByKey.set(k, el);\n }\n\n try {\n // Call create for new elements (DOM structure)\n if (isFirstRender && create) {\n const cleanup = create(item, el, i);\n if (typeof cleanup === 'function') {\n cleanupByKey.set(k, cleanup);\n }\n }\n\n // Call update for data binding (new and existing elements)\n // Skip if same item reference AND same index (optimization)\n const prevItem = prevItemsByKey.get(k);\n const prevIndex = prevIndexByKey.get(k);\n if (update) {\n if (prevItem !== item || prevIndex !== i) {\n update(item, el, i, { isFirstRender });\n }\n } else if (render) {\n // Backward compatibility: render handles both create and update\n render(item, el, i);\n }\n\n // Store reference and index for next comparison\n prevItemsByKey.set(k, item);\n prevIndexByKey.set(k, i);\n\n } catch (err) {\n logError(`[Lume.js] repeat(): error rendering key \"${k}\":`, err);\n }\n\n nextEls.push(el);\n }\n\n // eslint-disable-next-line sonarjs/cognitive-complexity -- DOM cleanup pass: remove stale nodes, call per-item cleanup callbacks, update maps\n applyPreservation(containerEl, () => {\n reconcileDOM(containerEl, nextEls);\n\n // Clean maps: remove keys not in seenKeys (new state)\n if (elementsByKey.size !== seenKeys.size) {\n for (const k of elementsByKey.keys()) {\n if (!seenKeys.has(k)) {\n const el = elementsByKey.get(k);\n const prevItem = prevItemsByKey.get(k);\n // Call create-returned cleanup first, then remove callback\n const cleanup = cleanupByKey.get(k);\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n logError(`[Lume.js] repeat(): cleanup error for key \"${k}\":`, err);\n }\n }\n if (typeof remove === 'function' && el) {\n remove(prevItem, el);\n }\n elementsByKey.delete(k);\n prevItemsByKey.delete(k);\n prevIndexByKey.delete(k);\n cleanupByKey.delete(k);\n }\n }\n }\n }, isReorder);\n }\n\n // Subscription — $subscribe calls updateList immediately (initial render),\n // so no separate updateList() call is needed for reactive stores.\n let unsubscribe;\n if (typeof store.$subscribe === 'function') {\n unsubscribe = store.$subscribe(arrayKey, updateList);\n } else if (typeof store.subscribe === 'function') {\n // Generic subscribe (e.g. computed) — subscribe first, then initial render\n const subResult = store.subscribe(() => updateList());\n updateList();\n // Normalize both function-style and object-style (RxJS Subscription) returns\n unsubscribe = typeof subResult === 'function'\n ? subResult\n : () => { subResult?.unsubscribe?.(); };\n } else {\n // Non-reactive store — render once and return cleanup\n updateList();\n logWarn('[Lume.js] repeat(): store is not reactive (no $subscribe or subscribe method)');\n return () => {\n for (const [k, el] of elementsByKey) {\n const prevItem = prevItemsByKey.get(k);\n const cleanup = cleanupByKey.get(k);\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n logError(`[Lume.js] repeat(): cleanup error for key \"${k}\":`, err);\n }\n }\n if (typeof remove === 'function') {\n remove(prevItem, el);\n }\n }\n containerEl.replaceChildren();\n elementsByKey.clear();\n prevItemsByKey.clear();\n prevIndexByKey.clear();\n cleanupByKey.clear();\n seenKeys.clear();\n };\n }\n\n return () => {\n if (typeof unsubscribe === 'function') {\n unsubscribe();\n }\n // Invoke cleanup and remove callback for all remaining elements before clearing\n for (const [k, el] of elementsByKey) {\n const prevItem = prevItemsByKey.get(k);\n const cleanup = cleanupByKey.get(k);\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n logError(`[Lume.js] repeat(): cleanup error for key \"${k}\":`, err);\n }\n }\n if (typeof remove === 'function') {\n remove(prevItem, el);\n }\n }\n // Clear DOM elements (replaceChildren is faster than loop)\n containerEl.replaceChildren();\n elementsByKey.clear();\n prevItemsByKey.clear();\n prevIndexByKey.clear();\n cleanupByKey.clear();\n seenKeys.clear();\n };\n}\n","/**\n * Lume-JS Debug Addon\n * \n * Developer-friendly logging and inspection of reactive state operations.\n * Critical for adoption - hard to debug = hard to adopt.\n * \n * Usage:\n * import { state } from \"lume-js\";\n * import { withPlugins, createDebugPlugin, debug } from \"lume-js/addons\";\n * \n * const store = withPlugins(state({ count: 0 }), [createDebugPlugin({ label: 'myStore' })]);\n * \n * debug.enable(); // Enable logging\n * debug.filter('count'); // Only log 'count' key\n * debug.stats(); // Show statistics\n * \n * @module addons/debug\n */\n\n// Global debug state\nlet globalEnabled = true;\nlet globalFilter = null; // string, RegExp, or null\nconst stats = new Map(); // label -> { gets: Map, sets: Map, notifies: Map }\n\n/**\n * Check if a key matches the current filter\n * @param {string} key\n * @returns {boolean}\n */\nfunction matchesFilter(key) {\n if (globalFilter === null) return true;\n if (typeof globalFilter === 'string') {\n return key.includes(globalFilter);\n }\n if (globalFilter instanceof RegExp) {\n return globalFilter.test(key);\n }\n return true;\n}\n\n/**\n * Get or create stats entry for a label\n * @param {string} label\n * @returns {object}\n */\nfunction getStats(label) {\n if (!stats.has(label)) {\n stats.set(label, {\n gets: new Map(),\n sets: new Map(),\n notifies: new Map()\n });\n }\n return stats.get(label);\n}\n\n/**\n * Increment a stat counter\n * @param {string} label\n * @param {'gets'|'sets'|'notifies'} type\n * @param {string} key\n */\nfunction incrementStat(label, type, key) {\n const s = getStats(label);\n const map = s[type];\n map.set(key, (map.get(key) || 0) + 1);\n}\n\nconst MAX_LOG_LEN = 100;\nconst TRUNCATED_LEN = MAX_LOG_LEN - 3;\n\n/**\n * Format value for logging (truncate long values)\n * @param {any} value\n * @returns {string}\n */\nfunction formatValue(value) {\n try {\n const json = JSON.stringify(value);\n if (json.length > MAX_LOG_LEN) {\n return json.slice(0, TRUNCATED_LEN) + '...';\n }\n return json;\n } catch {\n return String(value);\n }\n}\n\n/**\n * Create a debug plugin instance for a reactive state store.\n * \n * @param {object} [options] - Configuration options\n * @param {string} [options.label='store'] - Label for log messages\n * @param {boolean} [options.logGet=false] - Log property reads (can be noisy)\n * @param {boolean} [options.logSet=true] - Log property writes\n * @param {boolean} [options.logNotify=true] - Log subscriber notifications\n * @param {boolean} [options.trace=false] - Show stack trace for SET operations\n * @returns {object} Plugin object for state()\n * \n * @example\n * const store = withPlugins(state({ count: 0 }), [createDebugPlugin({ label: 'counter' })]);\n * \n * @example\n * // With stack traces for debugging where state changes originate\n * const store = withPlugins(state({ count: 0 }), [createDebugPlugin({ label: 'counter', trace: true })]);\n */\nexport function createDebugPlugin(options = {}) {\n const label = options.label ?? 'store';\n\n // IMPORTANT: Do NOT destructure options here!\n // Options may contain getters for dynamic runtime toggling (e.g., from UI).\n // Destructuring would copy values once at creation time, breaking reactivity.\n // Use getOpt() helper to read options dynamically in each hook.\n const getOpt = (name, defaultVal) => {\n const val = options[name];\n return val !== undefined ? val : defaultVal;\n };\n\n return {\n name: `debug:${label}`,\n\n onInit: () => {\n if (globalEnabled) {\n console.log(`%c[${label}]%c initialized`, 'color: #888; font-weight: bold', 'color: inherit');\n }\n },\n\n onGet: (key, value) => {\n // Skip internal properties\n if (typeof key === 'string' && key.startsWith('$')) {\n return value;\n }\n\n incrementStat(label, 'gets', key);\n\n if (globalEnabled && getOpt('logGet', false) && matchesFilter(key)) {\n console.log(\n `%c[${label}]%c GET %c${key}%c = ${formatValue(value)}`,\n 'color: #888; font-weight: bold',\n 'color: #4CAF50',\n 'color: #2196F3; font-weight: bold',\n 'color: inherit'\n );\n }\n\n return value;\n },\n\n onSet: (key, newValue, oldValue) => {\n // Skip internal properties\n if (typeof key === 'string' && key.startsWith('$')) {\n return newValue;\n }\n\n incrementStat(label, 'sets', key);\n\n if (globalEnabled && getOpt('logSet', true) && matchesFilter(key)) {\n console.log(\n `%c[${label}]%c SET %c${key}%c: ${formatValue(oldValue)} → ${formatValue(newValue)}`,\n 'color: #888; font-weight: bold',\n 'color: #FF9800',\n 'color: #2196F3; font-weight: bold',\n 'color: inherit'\n );\n\n // Show stack trace if enabled (helps find where state changes originate)\n if (getOpt('trace', false)) {\n console.trace(`%c[${label}] Stack trace for ${key}`, 'color: #888');\n }\n }\n\n return newValue;\n },\n\n onSubscribe: (key) => {\n if (globalEnabled && matchesFilter(key)) {\n console.log(\n `%c[${label}]%c SUBSCRIBE %c${key}`,\n 'color: #888; font-weight: bold',\n 'color: #9C27B0',\n 'color: #2196F3; font-weight: bold'\n );\n }\n },\n\n onNotify: (key, value) => {\n // Skip internal properties\n if (typeof key === 'string' && key.startsWith('$')) {\n return;\n }\n\n incrementStat(label, 'notifies', key);\n\n if (globalEnabled && getOpt('logNotify', true) && matchesFilter(key)) {\n console.log(\n `%c[${label}]%c NOTIFY %c${key}%c = ${formatValue(value)}`,\n 'color: #888; font-weight: bold',\n 'color: #E91E63',\n 'color: #2196F3; font-weight: bold',\n 'color: inherit'\n );\n }\n }\n };\n}\n\n/**\n * Global debug controls\n */\nexport const debug = {\n /**\n * Enable debug logging globally\n */\n enable() {\n globalEnabled = true;\n console.log('%c[lume-debug]%c Logging enabled', 'color: #888; font-weight: bold', 'color: #4CAF50');\n },\n\n /**\n * Disable debug logging globally\n */\n disable() {\n globalEnabled = false;\n console.log('%c[lume-debug]%c Logging disabled', 'color: #888; font-weight: bold', 'color: #F44336');\n },\n\n /**\n * Check if debug logging is currently enabled\n * @returns {boolean}\n */\n isEnabled() {\n return globalEnabled;\n },\n\n /**\n * Filter logs by key pattern\n * @param {string|RegExp|null} pattern - Pattern to match, or null to clear filter\n */\n filter(pattern) {\n globalFilter = pattern;\n if (pattern === null) {\n console.log('%c[lume-debug]%c Filter cleared', 'color: #888; font-weight: bold', 'color: inherit');\n } else {\n console.log(`%c[lume-debug]%c Filter set: ${pattern}`, 'color: #888; font-weight: bold', 'color: inherit');\n }\n },\n\n /**\n * Get current filter pattern\n * @returns {string|RegExp|null}\n */\n getFilter() {\n return globalFilter;\n },\n\n /**\n * Get statistics data (silent - no console output)\n * Use logStats() if you want to see stats in console.\n * @returns {object} Stats object for programmatic access\n */\n stats() {\n const result = {};\n\n for (const [label, data] of stats) {\n result[label] = {\n gets: Object.fromEntries(data.gets),\n sets: Object.fromEntries(data.sets),\n notifies: Object.fromEntries(data.notifies)\n };\n }\n\n return result;\n },\n\n /**\n * Log statistics summary to console (with formatting)\n * @returns {object} Stats object for programmatic access\n */\n logStats() {\n const result = this.stats();\n\n if (Object.keys(result).length === 0) {\n console.log('%c[lume-debug]%c No stats collected yet', 'color: #888; font-weight: bold', 'color: inherit');\n return result;\n }\n\n console.group('%c[lume-debug] Statistics', 'color: #888; font-weight: bold');\n\n for (const [label, data] of Object.entries(result)) {\n console.group(`%c${label}`, 'color: #2196F3; font-weight: bold');\n\n // Use console.table for better formatted output\n const tableData = [];\n const allKeys = new Set([\n ...Object.keys(data.gets),\n ...Object.keys(data.sets),\n ...Object.keys(data.notifies)\n ]);\n\n for (const key of allKeys) {\n tableData.push({\n key,\n gets: data.gets[key] || 0,\n sets: data.sets[key] || 0,\n notifies: data.notifies[key] || 0\n });\n }\n\n if (tableData.length > 0) {\n console.table(tableData);\n }\n\n console.groupEnd();\n }\n\n console.groupEnd();\n\n return result;\n },\n\n /**\n * Reset all collected statistics\n */\n resetStats() {\n stats.clear();\n console.log('%c[lume-debug]%c Stats reset', 'color: #888; font-weight: bold', 'color: inherit');\n }\n};\n","/** data-show=\"key\" → el.hidden = !Boolean(val) */\nexport const show = {\n attr: 'data-show',\n apply(el, val) { el.hidden = !Boolean(val); }\n};\n","/** data-classname=\"key\" → el.className = val || '' */\nexport const className = {\n attr: 'data-classname',\n apply(el, val) { el.className = val || ''; }\n};\n","/**\n * Create a handler for any HTML boolean attribute.\n * Uses toggleAttribute() — works correctly with any attribute name\n * (readonly, contenteditable, etc.) without worrying about camelCase property names.\n *\n * @param {string} name - Attribute name (e.g., 'readonly', 'open', 'contenteditable')\n * @returns {{ attr: string, apply: function }}\n */\nexport function boolAttr(name) {\n return {\n attr: `data-${name}`,\n apply(el, val) { el.toggleAttribute(name, Boolean(val)); }\n };\n}\n","/**\n * Create a handler for an ARIA attribute.\n * Coerces value to \"true\"/\"false\" string — use stringAttr(\"aria-X\") for token/string ARIA attrs.\n *\n * @param {string} name - ARIA name, with or without \"aria-\" prefix\n * @returns {{ attr: string, apply: function }}\n */\nexport function ariaAttr(name) {\n const fullName = name.startsWith('aria-') ? name : `aria-${name}`;\n return {\n attr: `data-${fullName}`,\n apply(el, val) { el.setAttribute(fullName, val ? 'true' : 'false'); }\n };\n}\n","/**\n * Create a handler for any string attribute (href, src, title, alt, action, etc.)\n * Sets the attribute value as a string. Removes the attribute when value is null/undefined.\n *\n * @param {string} name - HTML attribute name (e.g., 'href', 'src', 'title')\n * @returns {{ attr: string, apply: function }}\n */\nexport function stringAttr(name) {\n return {\n attr: `data-${name}`,\n apply(el, val) {\n if (val == null) el.removeAttribute(name);\n else el.setAttribute(name, String(val));\n }\n };\n}\n","import { show } from './show.js';\nimport { boolAttr } from './boolAttr.js';\nimport { ariaAttr } from './ariaAttr.js';\nimport { stringAttr } from './stringAttr.js';\n\n/** @see https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes#boolean_attributes */\nconst BOOL_ATTRS = [\n 'readonly', 'open', 'novalidate', 'formnovalidate', 'multiple',\n 'autofocus', 'autoplay', 'controls', 'loop', 'muted', 'defer',\n 'async', 'reversed', 'selected', 'inert', 'allowfullscreen',\n];\n\n/** @see https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes */\nconst STRING_ATTRS = [\n 'href', 'src', 'alt', 'title', 'placeholder', 'action', 'method',\n 'target', 'rel', 'type', 'name', 'role', 'lang', 'tabindex',\n 'pattern', 'min', 'max', 'step', 'minlength', 'maxlength',\n 'width', 'height', 'for', 'form', 'accept', 'autocomplete',\n 'loading', 'decoding', 'inputmode', 'enterkeyhint', 'draggable',\n 'contenteditable', 'spellcheck', 'translate', 'dir', 'id',\n 'poster', 'preload', 'download', 'media', 'sizes', 'srcset',\n 'colspan', 'rowspan', 'scope', 'headers', 'wrap', 'sandbox',\n];\n\n/** ARIA boolean state attributes — coerced to \"true\"/\"false\" string. */\nconst ARIA_BOOL_ATTRS = [\n 'pressed', 'selected', 'disabled', 'checked', 'invalid', 'required',\n 'busy', 'modal', 'multiselectable', 'multiline', 'readonly', 'atomic',\n];\n\n/** ARIA string/token/numeric attributes — value passed through as-is. */\nconst ARIA_STRING_ATTRS = [\n 'current', 'live', 'relevant', 'haspopup',\n 'sort', 'autocomplete', 'orientation',\n 'label', 'describedby', 'labelledby', 'controls', 'owns',\n 'activedescendant', 'errormessage', 'details', 'flowto',\n 'valuenow', 'valuemin', 'valuemax', 'valuetext',\n 'colcount', 'colindex', 'colspan', 'rowcount', 'rowindex', 'rowspan',\n 'level', 'setsize', 'posinset', 'placeholder', 'roledescription',\n 'keyshortcuts', 'braillelabel', 'brailleroledescription',\n];\n\n/**\n * One-import preset that enables all standard HTML attributes as reactive handlers.\n * Returns a flat array — pass directly to handlers option.\n *\n * @returns {Array<{ attr: string, apply: function }>}\n */\nexport function htmlAttrs() {\n return [\n show,\n ...BOOL_ATTRS.map(name => boolAttr(name)),\n ...STRING_ATTRS.map(name => stringAttr(name)),\n ...ARIA_BOOL_ATTRS.map(name => ariaAttr(name)),\n ...ARIA_STRING_ATTRS.map(name => stringAttr(`aria-${name}`)),\n ];\n}\n","import { boolAttr } from './boolAttr.js';\nimport { ariaAttr } from './ariaAttr.js';\n\n/** Form-related handlers (beyond built-in disabled/checked/required) */\nexport const formHandlers = [\n boolAttr('readonly'),\n];\n\n/** Additional ARIA handlers (beyond built-in aria-expanded/aria-hidden) */\nexport const a11yHandlers = [\n ariaAttr('pressed'),\n ariaAttr('selected'),\n ariaAttr('disabled'),\n];\n","/**\n * Create handlers for CSS class toggling.\n * Each name creates a handler: data-class-{name}=\"key\" → el.classList.toggle(name, Boolean(val))\n * Returns an array — pass directly to handlers (auto-flattened by bindDom).\n *\n * @param {...string} names - CSS class names to create handlers for\n * @returns {Array<{ attr: string, apply: function }>}\n */\nexport function classToggle(...names) {\n return names.map(name => ({\n attr: `data-class-${name}`,\n apply(el, val) { el.classList.toggle(name, Boolean(val)); }\n }));\n}\n","/**\n * Lume-JS Computed Addon\n * \n * Creates computed values that automatically update when dependencies change.\n * Uses core effect() for automatic dependency tracking.\n * \n * Usage:\n * import { computed } from \"lume-js/addons/computed\";\n * \n * const doubled = computed(() => store.count * 2);\n * console.log(doubled.value); // Auto-updates when store.count changes\n * \n * Features:\n * - Automatic dependency tracking (no manual recompute)\n * - Cached values (only recomputes when dependencies change)\n * - Subscribe to changes\n * - Cleanup with dispose()\n * \n * @module addons/computed\n */\n\nimport { effect } from '../core/effect.js';\nimport { logError } from '../utils/log.js';\n\n/**\n * Creates a computed value with automatic dependency tracking\n * \n * The computation function runs immediately and tracks which state\n * properties are accessed. When any dependency changes, the value\n * is automatically recomputed.\n *\n * ⚠️ Circular self-mutations are automatically suppressed. If a computed\n * mutates a state property it depends on, the flush triggered by that\n * mutation is skipped to prevent an infinite microtask loop.\n *\n * @param {function} fn - Function that computes the value\n * @returns {object} Object with .value property and methods\n * \n * @example\n * const store = state({ count: 5 });\n * \n * const doubled = computed(() => store.count * 2);\n * console.log(doubled.value); // 10\n * \n * store.count = 10;\n * // After microtask:\n * console.log(doubled.value); // 20 (auto-updated)\n * \n * @example\n * // Subscribe to changes\n * const unsub = doubled.subscribe(value => {\n * console.log('Doubled changed to:', value);\n * });\n * \n * @example\n * // Cleanup\n * doubled.dispose();\n */\nexport function computed(fn) {\n if (typeof fn !== 'function') {\n throw new Error('computed() requires a function');\n }\n\n let cachedValue;\n let isInitialized = false;\n let isInComputation = false;\n let disposed = false;\n const subscribers = [];\n\n // Use effect to automatically track dependencies\n const cleanupEffect = effect(() => {\n // Skip re-entry from a flush triggered by our own synchronous mutation.\n // The mutation inside fn() queues a microtask flush; we stay flagged\n // until a subsequent microtask clears it, so that flush is dropped.\n if (isInComputation || disposed) return;\n\n isInComputation = true;\n\n try {\n const newValue = fn();\n\n // Check if value actually changed - Object.is() handles NaN and -0\n if (!isInitialized || !Object.is(newValue, cachedValue)) {\n cachedValue = newValue;\n isInitialized = true;\n\n // Notify all subscribers\n subscribers.forEach(callback => callback(cachedValue));\n }\n } catch (error) {\n logError('[Lume.js computed] Error in computation:', error);\n // Set to undefined on error, mark as initialized\n if (!isInitialized || cachedValue !== undefined) {\n cachedValue = undefined;\n isInitialized = true;\n\n // Notify subscribers of error state\n subscribers.forEach(callback => callback(cachedValue));\n }\n } finally {\n // Defer clearing the flag so any flush microtask queued by fn()\n // sees it still set and skips re-entry.\n queueMicrotask(() => {\n if (!disposed) {\n isInComputation = false;\n }\n });\n }\n });\n\n return {\n /**\n * Get the current computed value\n */\n get value() {\n if (!isInitialized) {\n throw new Error('Computed value accessed before initialization');\n }\n return cachedValue;\n },\n\n /**\n * Subscribe to changes in computed value\n * \n * @param {function} callback - Called when value changes\n * @returns {function} Unsubscribe function\n */\n subscribe(callback) {\n if (typeof callback !== 'function') {\n throw new Error('subscribe() requires a function');\n }\n\n subscribers.push(callback);\n\n // Call immediately with current value\n if (isInitialized) {\n callback(cachedValue);\n }\n\n // Return unsubscribe function\n return () => {\n const index = subscribers.indexOf(callback);\n if (index > -1) {\n subscribers.splice(index, 1);\n }\n };\n },\n\n /**\n * Clean up computed value and stop tracking\n */\n dispose() {\n disposed = true;\n cleanupEffect();\n subscribers.length = 0;\n isInitialized = false;\n isInComputation = false;\n }\n };\n}","/**\n * Creates a cleanup group that can collect and dispose multiple\n * cleanup/unsubscribe functions at once.\n *\n * @returns {CleanupGroup}\n *\n * @example\n * ```js\n * import { createCleanupGroup } from 'lume-js/addons';\n *\n * const group = createCleanupGroup();\n * group.add(bindDom(root, store));\n * group.add(effect(() => { ... }));\n * group.add(store.$subscribe('key', fn));\n *\n * // Dispose everything at once\n * group.dispose();\n * ```\n */\nexport function createCleanupGroup() {\n const cleanups = [];\n\n return {\n /**\n * Add a cleanup function to the group.\n * @param {Function} fn - Cleanup/unsubscribe function\n */\n add(fn) {\n if (typeof fn === 'function') {\n cleanups.push(fn);\n }\n },\n\n /**\n * Run all collected cleanup functions and clear the group.\n */\n dispose() {\n while (cleanups.length) {\n const fn = cleanups.pop();\n try { fn(); } catch (e) { /* ignore cleanup errors */ }\n }\n },\n };\n}\n","/**\n * Reads initial state from a `<script type=\"application/json\">` element\n * embedded in the server-rendered HTML. Useful for SSR / hydration patterns.\n *\n * @param {string} [selector='#__LUME_DATA__'] - CSS selector for the script element\n * @returns {object} Parsed JSON object, or empty object if not found / invalid\n *\n * @example\n * ```html\n * <script id=\"__LUME_DATA__\" type=\"application/json\">\n * {\"title\": \"Welcome\", \"count\": 42}\n * </script>\n * ```\n *\n * ```js\n * import { state } from 'lume-js';\n * import { hydrateState } from 'lume-js/addons';\n *\n * const store = state(hydrateState());\n * ```\n */\nexport function hydrateState(selector = '#__LUME_DATA__') {\n const el = typeof document !== 'undefined' ? document.querySelector(selector) : null;\n if (!el) return {};\n try {\n return JSON.parse(el.textContent);\n } catch {\n return {};\n }\n}\n","export { computed } from \"./computed.js\";\nexport { watch } from \"./watch.js\";\nexport { repeat, defaultFocusPreservation, defaultScrollPreservation } from \"./repeat.js\";\nexport { createDebugPlugin, debug } from \"./debug.js\";\nexport { withPlugins } from \"./withPlugins.js\";\nexport { createCleanupGroup } from \"./cleanupGroup.js\";\nexport { hydrateState } from \"./hydrateState.js\";\n\n/**\n * Returns true if the value is a Lume reactive proxy created by state().\n * Uses duck-typing: checks for the presence of $subscribe.\n * @param {any} obj\n * @returns {boolean}\n */\nexport function isReactive(obj) {\n return !!(obj && typeof obj === 'object' && typeof obj.$subscribe === 'function');\n}\n","/**\n * watch - observes changes to a state key and triggers callback\n * @param {Object} store - reactive store created with state()\n * @param {string} key - key in store to watch\n * @param {Function} callback - called with new value\n * @param {Object} [options]\n * @param {boolean} [options.immediate=true] - call callback immediately with current value\n * @returns {Function} unsubscribe function\n */\nexport function watch(store, key, callback, { immediate = true } = {}) {\n if (!store.$subscribe) {\n throw new Error(\"store must be created with state()\");\n }\n if (!immediate) {\n let skipped = false;\n return store.$subscribe(key, (val) => {\n if (!skipped) { skipped = true; return; }\n callback(val);\n });\n }\n return store.$subscribe(key, callback);\n}","/**\n * Lume-JS withPlugins Addon\n *\n * Wraps a reactive state proxy with a plugin layer that intercepts\n * get/set/notify/subscribe operations via plugin hooks.\n *\n * Only stores that opt into debugging or custom behaviors need this.\n * Core state() is not aware of plugins.\n *\n * Usage:\n * import { state } from \"lume-js\";\n * import { withPlugins, createDebugPlugin } from \"lume-js/addons\";\n *\n * const store = withPlugins(state({ count: 0 }), [createDebugPlugin({ label: 'counter' })]);\n */\n\n/**\n * Wrap a reactive state proxy with plugin hooks.\n *\n * Plugin hooks (all optional):\n * onInit() — called once at wrap time\n * onGet(key, value) → value|void — intercept/transform reads\n * onSet(key, newVal, oldVal) → val|void — intercept/transform writes\n * onNotify(key, value) — called before subscribers are notified\n * onSubscribe(key) — called when $subscribe is invoked\n *\n * @param {object} store - A reactive proxy from state()\n * @param {Array<object>} plugins - Array of plugin objects\n * @returns {Proxy} A new proxy wrapping the store with plugin behavior\n */\nimport { logError } from '../utils/log.js';\n\nexport function withPlugins(store, plugins = []) {\n if (!plugins.length) return store;\n\n // Call onInit hooks once at wrap time\n for (const p of plugins) {\n try {\n p.onInit?.();\n } catch (e) {\n logError(`[Lume.js] Plugin \"${p.name}\" error in onInit:`, e);\n }\n }\n\n // Track pending notifications for onNotify hooks.\n // Instead of a separate microtask, we hook into the underlying state's\n // flush via $beforeFlush so onNotify and subscribers share one microtask.\n const pendingNotifications = new Map();\n\n function runNotifyHooks() {\n for (const [key, value] of pendingNotifications) {\n for (const p of plugins) {\n try {\n p.onNotify?.(key, value);\n } catch (e) {\n logError(`[Lume.js] Plugin \"${p.name}\" error in onNotify:`, e);\n }\n }\n }\n pendingNotifications.clear();\n }\n\n // Register once on the underlying state; capture unsubscribe for cleanup.\n let flushUnsub;\n if (typeof store.$beforeFlush === 'function') {\n flushUnsub = store.$beforeFlush(runNotifyHooks);\n }\n\n return new Proxy(store, {\n get(target, key) {\n // $dispose — remove the beforeFlush hook and clear pending state\n if (key === '$dispose') {\n return () => {\n if (flushUnsub) flushUnsub();\n pendingNotifications.clear();\n };\n }\n\n // Pass $-prefixed meta methods through without interception\n if (typeof key === 'string' && key.startsWith('$')) {\n const method = target[key];\n if (key === '$subscribe' && typeof method === 'function') {\n // Wrap $subscribe to call onSubscribe hooks\n return (subKey, fn) => {\n for (const p of plugins) {\n try {\n p.onSubscribe?.(subKey);\n } catch (e) {\n logError(`[Lume.js] Plugin \"${p.name}\" error in onSubscribe:`, e);\n }\n }\n return method(subKey, fn);\n };\n }\n return method;\n }\n\n let value = target[key];\n\n // onGet chain\n for (const p of plugins) {\n try {\n const r = p.onGet?.(key, value);\n if (r !== undefined) value = r;\n } catch (e) {\n logError(`[Lume.js] Plugin \"${p.name}\" error in onGet:`, e);\n }\n }\n\n return value;\n },\n\n set(target, key, value) {\n const oldValue = target[key];\n let newValue = value;\n\n // onSet chain\n for (const p of plugins) {\n try {\n const r = p.onSet?.(key, newValue, oldValue);\n if (r !== undefined) newValue = r;\n } catch (e) {\n logError(`[Lume.js] Plugin \"${p.name}\" error in onSet:`, e);\n }\n }\n\n // Only queue onNotify if the value actually changed after plugin chain\n if (!Object.is(newValue, oldValue)) {\n pendingNotifications.set(key, newValue);\n }\n\n target[key] = newValue;\n return true;\n }\n });\n}\n"],"names":["logWarn","msg","rest","console","warn","logError","error","readers","Set","withReadObserver","onRead","fn","add","delete","boolHandler","name","attr","apply","el","val","ariaHandler","setAttribute","DEFAULT_HANDLERS","applyHandler","store","path","handler","result","resolveProp","target","key","$subscribe","handleDataBind","bindingMap","unsub","tagName","type","checked","value","String","textContent","updateElement","isFormInput","set","pathArr","split","pop","obj","length","current","i","resolvePath","currentEffect","effect","deps","Error","cleanups","isRunning","execute","Array","isArray","dep","keys","isFirst","push","executeWithTracking","oldCleanups","splice","myContext","tracking","previousEffect","proxy","registerEffect","cleanup","defaultFocusPreservation","container","activeEl","document","activeElement","contains","selectionStart","selectionEnd","body","focus","setSelectionRange","defaultScrollPreservation","context","isReorder","scrollTop","anchorElement","anchorOffset","containerRect","getBoundingClientRect","child","firstElementChild","nextElementSibling","rect","bottom","top","newRect","scrollAdjustment","globalEnabled","globalFilter","stats","Map","matchesFilter","includes","RegExp","test","incrementStat","label","s","has","gets","sets","notifies","get","getStats","map","formatValue","json","JSON","stringify","slice","MAX_LOG_LEN","debug","enable","log","disable","isEnabled","filter","pattern","getFilter","data","Object","fromEntries","logStats","this","group","entries","tableData","allKeys","table","groupEnd","resetStats","clear","show","hidden","className","boolAttr","toggleAttribute","ariaAttr","fullName","startsWith","stringAttr","removeAttribute","BOOL_ATTRS","STRING_ATTRS","ARIA_BOOL_ATTRS","ARIA_STRING_ATTRS","formHandlers","a11yHandlers","root","options","HTMLElement","immediate","handlers","userHandlers","defaults","merged","h","flat","values","mergeHandlers","performBinding","WeakMap","selector","join","elements","querySelectorAll","hasAttribute","c","getAttribute","inputHandler","e","binding","valueAsNumber","addEventListener","removeEventListener","forEach","readyState","onReady","once","names","classList","toggle","cachedValue","isInitialized","isInComputation","disposed","subscribers","cleanupEffect","newValue","is","callback","queueMicrotask","subscribe","index","indexOf","dispose","getOpt","defaultVal","onInit","onGet","onSet","oldValue","trace","onSubscribe","onNotify","querySelector","parse","arrayKey","render","create","update","remove","element","preserveFocus","preserveScroll","containerEl","elementsByKey","prevItemsByKey","prevIndexByKey","cleanupByKey","seenKeys","createElement","updateList","items","size","nextEls","item","k","isFirstRender","prevItem","prevIndex","err","shouldPreserve","restoreFocus","restoreScroll","ptr","firstChild","desired","insertBefore","nextSibling","next","removeChild","reconcileDOM","applyPreservation","unsubscribe","replaceChildren","subResult","isFrozen","isSealed","listeners","pendingNotifications","pendingEffects","beforeFlushHooks","flushScheduled","Symbol","executeFn","idx","Proxy","reader","iterations","subs","effects","$beforeFlush","skipped","plugins","p","flushUnsub","method","subKey","r"],"mappings":"kCASO,SAASA,EAAQC,KAAQC,QACP,IAAZC,SAAmD,mBAAjBA,QAAQC,MACnDD,QAAQC,KAAKH,KAAQC,EAEzB,CAEO,SAASG,EAASJ,KAAQC,QACR,IAAZC,SAAoD,mBAAlBA,QAAQG,OACnDH,QAAQG,MAAML,KAAQC,EAE1B,CC6BA,MAAMK,MAAcC,IAYb,SAASC,EAAiBC,EAAQC,GACvCJ,EAAQK,IAAIF,GACZ,IACE,OAAOC,GACT,CAAA,QACEJ,EAAQM,OAAOH,EACjB,CACF,CCnCA,MAAMI,EAAeC,IAAA,CACnBC,KA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,EAAQ/Q,KACd,IAAA,MAAW4Q,KAAKD,EACd,IACEC,EAAE9D,cAAciE,EAClB,OAASlG,GACPnL,EAAS,qBAAqBkR,EAAExQ,8BAA+ByK,EACjE,CAEF,OAAOiG,EAAOC,EAAQ/Q,IAGnB8Q,CACT,CAEA,IAAInP,EAAQT,EAAOC,GAGnB,IAAA,MAAWyP,KAAKD,EACd,IACE,MAAMK,EAAIJ,EAAElE,QAAQvL,EAAKQ,QACf,IAANqP,IAAiBrP,EAAQqP,EAC/B,OAASnG,GACPnL,EAAS,qBAAqBkR,EAAExQ,wBAAyByK,EAC3D,CAGF,OAAOlJ,CACT,EAEA,GAAAK,CAAId,EAAQC,EAAKQ,GACf,MAAMiL,EAAW1L,EAAOC,GACxB,IAAI4K,EAAWpK,EAGf,IAAA,MAAWiP,KAAKD,EACd,IACE,MAAMK,EAAIJ,EAAEjE,QAAQxL,EAAK4K,EAAUa,QACzB,IAANoE,IAAiBjF,EAAWiF,EAClC,OAASnG,GACPnL,EAAS,qBAAqBkR,EAAExQ,wBAAyByK,EAC3D,CASF,OALKlD,OAAOqE,GAAGD,EAAUa,IACvBiD,EAAqB7N,IAAIb,EAAK4K,GAGhC7K,EAAOC,GAAO4K,GACP,CACT,GAEJ"}
|
|
1
|
+
{"version":3,"file":"lume.global.js","sources":["../src/utils/log.js","../src/core/batch.js","../src/core/state.js","../src/core/bindDom.js","../src/core/effect.js","../src/addons/repeat.js","../src/addons/debug.js","../src/addons/persist.js","../src/handlers/show.js","../src/handlers/className.js","../src/handlers/boolAttr.js","../src/handlers/ariaAttr.js","../src/handlers/stringAttr.js","../src/handlers/on.js","../src/handlers/htmlAttrs.js","../src/handlers/presets.js","../src/handlers/classToggle.js","../src/addons/computed.js","../src/addons/cleanupGroup.js","../src/addons/hydrateState.js","../src/addons/index.js","../src/addons/watch.js","../src/addons/withPlugins.js"],"sourcesContent":["/**\n * Environment-safe logging utilities for constrained runtimes\n * (e.g. service workers, embedded engines, SSR environments).\n *\n * All core and addon files should import these instead of\n * calling console.* directly to avoid ReferenceError when\n * console is not defined.\n */\n\nexport function logWarn(msg, ...rest) {\n if (typeof console !== 'undefined' && typeof console.warn === 'function') {\n console.warn(msg, ...rest);\n }\n}\n\nexport function logError(msg, ...rest) {\n if (typeof console !== 'undefined' && typeof console.error === 'function') {\n console.error(msg, ...rest);\n }\n}\n","/**\n * Lume-JS Cross-Store Batching\n *\n * While batchDepth > 0, states skip their microtask flush and enqueue a\n * small flush handle here instead (via enqueueIfBatching, called from\n * state.js's scheduler); batch() drains the set synchronously when the\n * outermost batch ends. Effects collected from all enqueued states run\n * from one Set per wave, so an effect depending on several mutated stores\n * runs exactly once per batch instead of once per store.\n *\n * This module never imports state.js — state.js imports from here — so\n * there is no cycle, no global scheduler object, and no import side effect.\n */\n\nimport { logError, logWarn } from '../utils/log.js';\n\n// Cap for cascading flush waves (effects mutating state that re-triggers\n// effects). Shared with the per-state microtask flush in state.js.\nexport const MAX_FLUSH_ITERATIONS = 100;\n\nlet batchDepth = 0;\nconst batchedStates = new Set();\n\n/**\n * Called by state.js when a write is scheduled. Returns true if a batch is\n * active and the state's flush handle was captured (the caller must then\n * skip its own microtask scheduling).\n *\n * Internal API between core modules — not exported from the package root.\n *\n * @param {{runBeforeFlushHooks: function, notifySubscribers: function, takeEffects: function}} handle\n * @returns {boolean}\n */\nexport function enqueueIfBatching(handle) {\n if (batchDepth === 0) return false;\n batchedStates.add(handle);\n return true;\n}\n\nfunction flushBatchedStates() {\n let iterations = 0;\n while (batchedStates.size > 0 && iterations < MAX_FLUSH_ITERATIONS) {\n iterations++;\n const wave = Array.from(batchedStates);\n batchedStates.clear();\n\n // Notify each state's subscribers, collecting effects into one\n // deduplicated set (the same effect queued by N stores runs once).\n const effects = new Set();\n for (const s of wave) {\n s.runBeforeFlushHooks();\n s.notifySubscribers();\n for (const fx of s.takeEffects()) effects.add(fx);\n }\n\n // Effects run after all subscribers of the wave. Writes they make\n // re-enter batchedStates (depth is still held) → next iteration.\n for (const fx of effects) {\n try { fx(); }\n catch (err) { logError('[Lume.js state] Error in effect:', err); }\n }\n }\n if (iterations >= MAX_FLUSH_ITERATIONS) {\n // Drop the runaway wave so a future, unrelated batch doesn't inherit\n // it. Nothing is lost permanently: the states keep their queued work\n // and flush it on their next write via the normal microtask path.\n batchedStates.clear();\n logError(\n '[Lume.js state] Maximum batch flush iterations reached (100). ' +\n 'This usually indicates an infinite loop caused by an effect or computed mutating state it depends on.'\n );\n }\n}\n\n/**\n * Group multiple state writes and flush them together, synchronously,\n * when the outermost batch() returns.\n *\n * Guarantees:\n * - Subscribers see only the final value of each key (intermediate writes\n * within the batch are coalesced, as with microtask batching).\n * - An effect that depends on several stores mutated in the batch runs\n * exactly ONCE — unlike microtask batching, which is per-state and runs\n * such effects once per store.\n * - Nested batch() calls are absorbed: everything flushes when the\n * outermost batch ends.\n * - If fn throws, writes made before the throw still flush, then the\n * error propagates. State scheduling is left clean either way.\n *\n * `fn` must be synchronous — writes after an `await` happen outside the\n * batch and fall back to normal per-state microtask flushing (a console\n * warning is logged if fn returns a Promise).\n *\n * @param {function} fn - Function performing state writes\n * @returns {*} The return value of fn\n *\n * @example\n * import { state, effect, batch } from 'lume-js';\n *\n * const a = state({ value: 1 });\n * const b = state({ value: 2 });\n * effect(() => render(a.value + b.value));\n *\n * batch(() => {\n * a.value = 10;\n * b.value = 20;\n * }); // render() ran exactly once, seeing 30\n */\nexport function batch(fn) {\n if (typeof fn !== 'function') {\n throw new Error('batch() requires a function');\n }\n\n // Nested batch: let the outermost batch flush everything\n if (batchDepth > 0) return fn();\n\n batchDepth++;\n let result;\n try {\n result = fn();\n if (result && typeof result.then === 'function') {\n logWarn(\n '[Lume.js batch] batch() received an async function. Only writes before the first await are batched; ' +\n 'later writes flush via normal microtasks.'\n );\n }\n return result;\n } finally {\n // Flush while depth is still held so cascading writes from\n // subscribers/effects keep collecting into batchedStates (deduped),\n // then release. Runs on success AND when fn throws (writes made\n // before the throw are committed, then the error propagates).\n try {\n flushBatchedStates();\n } finally {\n batchDepth--;\n }\n }\n}\n","/**\n * Lume-JS Reactive State Core\n *\n * Provides minimal reactive state with standard JavaScript.\n * Features automatic microtask batching for performance.\n * Read tracking is opt-in via withReadObserver — state.js has zero permanent\n * dependency on effect.js or any other module.\n *\n * Features:\n * - Lightweight and Go-style\n * - Explicit nested states\n * - $subscribe for listening to key changes\n * - Cleanup with unsubscribe\n * - Per-state microtask batching for writes\n * - batch() for grouping writes across states with cross-store effect dedupe\n * - Scope-based read tracking via withReadObserver (multi-observer safe)\n *\n * Usage:\n * import { state } from \"lume-js\";\n *\n * const store = state({ count: 0 });\n * const unsub = store.$subscribe(\"count\", val => console.log(val));\n * unsub(); // cleanup\n */\n\nimport { logError, logWarn } from '../utils/log.js';\nimport { enqueueIfBatching, MAX_FLUSH_ITERATIONS } from './batch.js';\n\n// Per-state batching – each state object maintains its own microtask flush.\n// This keeps effects simple and aligned with Lume's minimal philosophy.\n\n/**\n * Creates a reactive state object.\n *\n * @param {Object} obj - Initial state object (must be plain object)\n * @returns {Proxy} Reactive proxy with $subscribe method\n *\n * @example\n * const store = state({ count: 0 });\n */\n\n// Active read observers — only populated during withReadObserver scopes.\n// This keeps state.js pure: tracking only happens when someone explicitly\n// asks to observe reads within a synchronous function call.\n//\n// Note: This Set is module-level, so all reactive state instances and effects\n// within the SAME module instance share it. This is standard behavior for\n// auto-tracking reactive libraries (Vue, MobX, Solid, etc.). Multiple copies\n// of the lume-js module (e.g. from different bundled chunks) each get their\n// own independent Set via ES module / CommonJS isolation.\nconst readers = new Set();\n\n/**\n * Brand symbol stamped on every object passed to state().\n *\n * Uses the global symbol registry (Symbol.for) so independent copies of\n * lume-js on the same page (e.g. a CDN build next to a bundled chunk)\n * agree on the same brand. This is a type tag for reliable detection\n * (see isReactive in addons), not a security boundary — any code can\n * stamp it.\n *\n * Internal API — exported for addons; not re-exported from the package root.\n */\nexport const REACTIVE_BRAND = Symbol.for('lume.reactive');\n\n// batch() lives in ./batch.js (which never imports this module — no cycle).\n// state.js participates through enqueueIfBatching in scheduleFlush below.\n\n/**\n * Run a function with a read observer active.\n * The observer receives (proxy, key, registerEffect) for every property read.\n * Multiple observers can be active simultaneously (nested effects, devtools, etc.)\n *\n * Internal API — used by effect.js for auto-tracking. May be stabilized\n * for third-party addons in a future release.\n *\n * @security The observer sees reads from ALL state instances within the same\n * module instance, including nested scopes. Only pass trusted observer functions.\n * A future scoped variant (e.g., scopedReadObserver(store, fn)) may limit\n * observation to a single state instance.\n *\n * @param {function} onRead - Called on each property access inside fn\n * @param {function} fn - The function to run under observation\n */\nexport function withReadObserver(onRead, fn) {\n readers.add(onRead);\n try {\n return fn();\n } finally {\n readers.delete(onRead);\n }\n}\n\nexport function state(obj) {\n // Validate input\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {\n throw new Error('state() requires a plain object');\n }\n if (Object.isFrozen(obj) || Object.isSealed(obj)) {\n throw new Error('state() requires a mutable plain object');\n }\n\n // Object.create(null) - no prototype chain lookups\n const listeners = Object.create(null);\n const pendingNotifications = new Map(); // Per-state pending changes\n const pendingEffects = new Set(); // Dedupe effects per state\n const beforeFlushHooks = [];\n let flushScheduled = false;\n\n // ── Flush steps ──────────────────────────────────────────────────────\n // Named pieces shared by the per-state microtask flush and batch().\n\n function runBeforeFlushHooks() {\n for (let i = 0; i < beforeFlushHooks.length; i++) {\n try {\n beforeFlushHooks[i]();\n } catch (err) {\n logError('[Lume.js state] Error in beforeFlush hook:', err);\n }\n }\n }\n\n function notifySubscribers() {\n for (const [key, value] of pendingNotifications) {\n if (listeners[key]) {\n const subs = listeners[key];\n let i = 0;\n while (i < subs.length) {\n const fn = subs[i];\n try {\n fn(value);\n } catch (err) {\n logError(`[Lume.js state] Error notifying subscriber for key \"${String(key)}\":`, err);\n }\n // Only advance if fn wasn't removed (something shifted into its place)\n if (subs[i] === fn) i++;\n }\n }\n }\n pendingNotifications.clear();\n }\n\n /** Drain queued effects (Set deduplicates) into an array. */\n function takeEffects() {\n const effects = Array.from(pendingEffects);\n pendingEffects.clear();\n return effects;\n }\n\n // Handle this state gives batch() — flush steps only, no live queues.\n const batchHandle = { runBeforeFlushHooks, notifySubscribers, takeEffects };\n\n /**\n * Schedule a single microtask flush for this state object.\n *\n * Flush order per state:\n * 1) Notify subscribers for changed keys (key → subscribers)\n * 2) Run each queued effect exactly once (Set-based dedupe)\n * 3) Repeat up to 100 iterations to handle cascading updates,\n * then log an error to prevent infinite loops.\n *\n * Notes:\n * - Batching is per state; effects that depend on multiple states\n * may run once per state that changed (by design). Use batch() to\n * group writes across states and run such effects once.\n * - Inside batch(), the microtask is skipped: the state enqueues\n * itself for the synchronous flush at the end of the batch.\n */\n function scheduleFlush() {\n // Inside batch(): the batch captures this state's flush handle and\n // flushes synchronously at the end — skip the microtask.\n if (enqueueIfBatching(batchHandle)) return;\n\n if (flushScheduled) return;\n\n flushScheduled = true;\n queueMicrotask(() => {\n let iterations = 0;\n\n try {\n while ((pendingNotifications.size > 0 || pendingEffects.size > 0) && iterations < MAX_FLUSH_ITERATIONS) {\n iterations++;\n runBeforeFlushHooks();\n notifySubscribers();\n const effects = takeEffects();\n for (let i = 0; i < effects.length; i++) {\n try {\n effects[i]();\n } catch (err) {\n logError('[Lume.js state] Error in effect:', err);\n }\n }\n }\n } finally {\n flushScheduled = false;\n }\n\n if (iterations >= MAX_FLUSH_ITERATIONS) {\n logError(\n '[Lume.js state] Maximum flush iterations reached (100). ' +\n 'This usually indicates an infinite loop caused by an effect or computed mutating state it depends on.'\n );\n }\n });\n }\n\n // Stamp the shared brand (non-enumerable: spreads/Object.assign copies\n // of a store do not inherit the brand and won't masquerade as reactive).\n Object.defineProperty(obj, REACTIVE_BRAND, { value: true });\n\n const MAX_SUBSCRIBERS = 1000;\n const noopUnsubscribe = () => {};\n\n /**\n * Shared listener registration with a per-key cap (subscriber DoS\n * protection). Applied identically to $subscribe callbacks and effect\n * subscriptions so both paths degrade the same way: a loud console\n * error and a no-op unsubscribe.\n */\n function addListener(key, fn, kind) {\n if (!listeners[key]) listeners[key] = [];\n if (listeners[key].length >= MAX_SUBSCRIBERS) {\n logError(\n `[Lume.js state] Subscriber limit (${MAX_SUBSCRIBERS}) reached for key \"${String(key)}\". ` +\n `${kind} ignored — it will NOT receive updates. ` +\n 'This usually means subscriptions are created in a loop without cleanup.'\n );\n return noopUnsubscribe;\n }\n listeners[key].push(fn);\n return () => {\n if (listeners[key]) {\n const idx = listeners[key].indexOf(fn);\n if (idx !== -1) {\n listeners[key].splice(idx, 1);\n if (listeners[key].length === 0) delete listeners[key];\n }\n }\n };\n }\n\n // Defined once per state instance — not per property read — to avoid per-read closure allocation.\n const registerEffect = (key, executeFn) => {\n const callback = () => {\n pendingEffects.add(executeFn);\n };\n return addListener(key, callback, 'Effect subscription');\n };\n\n const BLOCKED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\n const proxy = new Proxy(obj, {\n get(target, key) {\n // Skip effect tracking for internal meta methods (e.g. $subscribe)\n if (typeof key === 'string' && key.startsWith('$')) {\n return target[key];\n }\n\n const value = target[key];\n\n // Notify active read observers (effects, devtools, etc.)\n if (readers.size > 0) {\n for (const reader of readers) {\n reader(proxy, key, registerEffect);\n }\n }\n\n return value;\n },\n\n set(target, key, value) {\n if (typeof key === 'string' && BLOCKED_KEYS.has(key)) {\n logWarn(`[Lume.js state] Blocked write to reserved key \"${key}\"`);\n return true;\n }\n\n const oldValue = target[key];\n\n // Skip update if value unchanged - Object.is() handles NaN and -0 correctly\n if (Object.is(oldValue, value)) return true;\n\n target[key] = value;\n\n // Batch notifications at the state level (per-state, not global)\n pendingNotifications.set(key, value);\n scheduleFlush();\n\n return true;\n }\n });\n\n /**\n * Subscribe to changes for a specific key.\n * Calls the callback immediately with the current value.\n * Returns an unsubscribe function for cleanup.\n *\n * @param {string} key - Property key to watch\n * @param {function} fn - Callback function\n * @returns {function} Unsubscribe function\n */\n // Set on obj (not proxy) to avoid triggering the set trap.\n // The get trap already returns target[key] directly for $-prefixed keys.\n /**\n * Register a callback to run before each flush.\n * Returns an unsubscribe function.\n */\n obj.$beforeFlush = (fn) => {\n if (typeof fn !== 'function') {\n throw new Error('$beforeFlush requires a function');\n }\n if (beforeFlushHooks.indexOf(fn) === -1) {\n beforeFlushHooks.push(fn);\n }\n return () => {\n const idx = beforeFlushHooks.indexOf(fn);\n if (idx !== -1) {\n beforeFlushHooks.splice(idx, 1);\n }\n };\n };\n\n obj.$subscribe = (key, fn) => {\n if (typeof fn !== 'function') {\n throw new Error('Subscriber must be a function');\n }\n\n const unsubscribe = addListener(key, fn, 'New subscriber');\n\n // Over the cap: listener was not added, skip the immediate call too\n if (unsubscribe === noopUnsubscribe) return unsubscribe;\n\n // Call immediately with current value (NOT batched)\n fn(proxy[key]);\n\n return unsubscribe;\n };\n\n return proxy;\n}\n","// src/core/bindDom.js\n/**\n * Lume-JS DOM Binding\n *\n * Binds reactive state to DOM elements using data-* attributes.\n *\n * Built-in attributes (always available):\n * data-bind=\"key\" → Two-way binding for inputs, textContent for others\n * data-hidden=\"key\" → Toggles hidden (truthy = hidden)\n * data-disabled=\"key\" → Toggles disabled (truthy = disabled)\n * data-checked=\"key\" → Toggles checked (for checkboxes/radios)\n * data-required=\"key\" → Toggles required (truthy = required)\n * data-aria-expanded=\"key\" → Sets aria-expanded to \"true\"/\"false\"\n * data-aria-hidden=\"key\" → Sets aria-hidden to \"true\"/\"false\"\n *\n * Extensible via handlers option:\n * import { show, classToggle } from 'lume-js/handlers';\n * bindDom(root, store, { handlers: [show, classToggle('active')] });\n *\n * Custom handlers:\n * const tooltip = { attr: 'data-tooltip', apply(el, val) { el.title = val ?? ''; } };\n * bindDom(root, store, { handlers: [tooltip] });\n *\n * Usage:\n * import { bindDom } from \"lume-js\";\n * const cleanup = bindDom(document.body, store);\n *\n * @security `data-bind` attribute values are resolved once at bind time and\n * trusted as state path expressions. If an attacker can inject `data-bind`\n * attributes into the DOM, they can subscribe to any reachable reactive state.\n * Ensure your HTML is trusted or sanitize it before calling bindDom().\n */\n\nimport { logWarn } from '../utils/log.js';\n\n// --- Default Handlers (always active, backwards compatible) ---\n\nconst boolHandler = (name) => ({\n attr: `data-${name}`,\n apply(el, val) { el[name] = Boolean(val); }\n});\n\nconst ariaHandler = (name) => ({\n attr: `data-${name}`,\n apply(el, val) { el.setAttribute(name, val ? 'true' : 'false'); }\n});\n\nconst DEFAULT_HANDLERS = [\n boolHandler('hidden'),\n boolHandler('disabled'),\n boolHandler('checked'),\n boolHandler('required'),\n ariaHandler('aria-expanded'),\n ariaHandler('aria-hidden'),\n];\n\n/**\n * Merge default and user handlers.\n * User handlers override defaults with same attr (Map deduplicates).\n * User handler arrays are flattened one level (supports classToggle()).\n */\nfunction mergeHandlers(defaults, userHandlers) {\n if (!userHandlers.length) return defaults;\n const merged = new Map();\n for (const h of defaults) merged.set(h.attr, h);\n for (const h of userHandlers.flat()) merged.set(h.attr, h);\n return [...merged.values()];\n}\n\n/**\n * DOM binding for reactive state\n */\nexport function bindDom(root, store, options = {}) {\n if (!(root instanceof HTMLElement)) {\n throw new Error('bindDom() requires a valid HTMLElement as root');\n }\n if (!store || typeof store !== 'object') {\n throw new Error('bindDom() requires a reactive state object');\n }\n\n const { immediate = false, handlers: userHandlers = [] } = options;\n const handlers = mergeHandlers(DEFAULT_HANDLERS, userHandlers);\n\n const performBinding = () => {\n const cleanups = [];\n const bindingMap = new WeakMap();\n\n // Build compiled selector: data-bind (always) + all handler attrs\n const selector = ['[data-bind]', ...handlers.map(h => `[${h.attr}]`)].join(',');\n const elements = root.querySelectorAll(selector);\n\n for (const el of elements) {\n // data-bind (two-way) — always in core, special handling\n if (el.hasAttribute('data-bind')) {\n const c = handleDataBind(el, store, el.getAttribute('data-bind'), bindingMap);\n if (c) cleanups.push(c);\n }\n\n // All registered handlers (default + user)\n for (const handler of handlers) {\n if (el.hasAttribute(handler.attr)) {\n const c = applyHandler(el, store, el.getAttribute(handler.attr), handler);\n if (c) cleanups.push(c);\n }\n }\n }\n\n // Event delegation for two-way bindings\n const inputHandler = e => {\n const binding = bindingMap.get(e.target);\n if (binding) binding.target[binding.key] = getInputValue(e.target);\n };\n root.addEventListener(\"input\", inputHandler);\n cleanups.push(() => root.removeEventListener(\"input\", inputHandler));\n\n return () => cleanups.forEach(c => c());\n };\n\n // Auto-wait for DOM if needed\n if (!immediate && document.readyState === 'loading') {\n let cleanup = null;\n const onReady = () => { cleanup = performBinding(); };\n document.addEventListener('DOMContentLoaded', onReady, { once: true });\n return () => cleanup ? cleanup() : document.removeEventListener('DOMContentLoaded', onReady);\n }\n\n return performBinding();\n}\n\n/**\n * Apply a handler to an element via subscription.\n * Resolves the state path and subscribes to changes.\n */\nfunction applyHandler(el, store, path, handler) {\n const result = resolveProp(store, path);\n if (!result) return null;\n const { target, key } = result;\n return target.$subscribe(key, val => handler.apply(el, val));\n}\n\n/**\n * Handle data-bind (two-way for inputs, textContent for others)\n */\nfunction handleDataBind(el, store, path, bindingMap) {\n const result = resolveProp(store, path);\n if (!result) return null;\n\n const { target, key } = result;\n const unsub = target.$subscribe(key, val => applyBindValue(el, val));\n\n if (isFormInput(el)) {\n bindingMap.set(el, { target, key });\n }\n\n return unsub;\n}\n\n/**\n * Resolve a nested path in an object.\n * Example: resolvePath(obj, ['user', 'address']) returns obj.user.address\n */\nfunction resolvePath(obj, pathArr) {\n if (!pathArr || pathArr.length === 0) {\n return obj;\n }\n let current = obj;\n for (let i = 0; i < pathArr.length; i++) {\n const key = pathArr[i];\n if (current === null || current === undefined) {\n return null;\n }\n if (!(key in current)) {\n return null;\n }\n current = current[key];\n }\n return current;\n}\n\n/**\n * Resolve path to target and key.\n *\n * ⚠️ Path bindings are resolved once at bind time. If an intermediate\n * object in the path is null/undefined at bindDom call time, the binding\n * is permanently dead and will not self-heal when the path later becomes valid.\n */\nfunction resolveProp(store, path) {\n if (!path) return null;\n\n const pathArr = path.split(\".\");\n const key = pathArr.pop();\n const target = resolvePath(store, pathArr);\n\n if (target === null || target === undefined) {\n logWarn(`[Lume.js] Invalid path \"${path}\"`);\n return null;\n }\n\n if (!target?.$subscribe) {\n logWarn(`[Lume.js] Target for \"${path}\" is not reactive`);\n return null;\n }\n\n return { target, key };\n}\n\n/**\n * Update element with value (for data-bind).\n *\n * Exported for internal reuse (e.g. the repeat addon's template bindings)\n * so addon and core data-bind semantics never drift. Not part of the\n * public package API.\n */\nexport function applyBindValue(el, val) {\n if (el.tagName === \"INPUT\") {\n if (el.type === \"checkbox\") el.checked = Boolean(val);\n else if (el.type === \"radio\") el.checked = el.value === String(val);\n else el.value = val ?? '';\n } else if (el.tagName === \"TEXTAREA\" || el.tagName === \"SELECT\") {\n el.value = val ?? '';\n } else {\n el.textContent = val ?? '';\n }\n}\n\n/**\n * Get value from input\n */\nfunction getInputValue(el) {\n if (el.type === \"checkbox\") return el.checked;\n if (el.type === \"number\" || el.type === \"range\") return el.valueAsNumber;\n return el.value;\n}\n\n/**\n * Check if element is form input\n */\nfunction isFormInput(el) {\n return el.tagName === \"INPUT\" || el.tagName === \"TEXTAREA\" || el.tagName === \"SELECT\";\n}","import { withReadObserver } from './state.js';\nimport { logError } from '../utils/log.js';\n\n/**\n * Lume-JS Effect\n *\n * Reactive effects with two modes:\n * 1. Auto-tracking (default): Tracks dependencies automatically via withReadObserver\n * 2. Explicit deps: You specify exactly what triggers re-runs\n *\n * Auto-tracking uses scope-based read observation — state.js has zero permanent\n * dependency on this module. Read tracking is only active during the synchronous\n * execution of an effect's body.\n *\n * Usage:\n * import { effect } from \"lume-js\";\n *\n * // Auto-tracking mode (existing behavior)\n * effect(() => {\n * console.log('Count is:', store.count);\n * // Automatically re-runs when store.count changes\n * });\n *\n * // Explicit deps mode (new - no magic)\n * effect(() => {\n * console.log('Count is:', store.count);\n * }, [[store, 'count']]); // Only re-runs when store.count changes\n *\n * Features:\n * - Automatic dependency collection via withReadObserver scope (default)\n * - Explicit dependencies for side-effects\n * - Explicit-deps notifications are coalesced: one run per microtask,\n * no matter how many tracked keys (or stores) changed in the same tick\n * - Returns cleanup function\n * - Compatible with per-state batching\n */\n\n// Module-scoped effect context (prevents third-party spoofing via globalThis)\nlet currentEffect = null;\n\n// withReadObserver is used below to scope read tracking to synchronous effect execution.\n\n/**\n * Creates an effect that runs reactively\n *\n * @param {function} fn - Function to run reactively\n * @param {Array<[object, string]>} [deps] - Optional explicit dependencies as [store, key] tuples\n * @returns {function} Cleanup function to stop the effect\n *\n * @example\n * // Auto-tracking (default)\n * const store = state({ count: 0 });\n * effect(() => {\n * document.title = `Count: ${store.count}`;\n * });\n * \n * @example\n * // Explicit deps (no magic)\n * effect(() => {\n * analytics.log(store.count); // Won't track store.count automatically\n * }, [[store, 'count']]); // Explicit: only re-run on store.count\n */\n// eslint-disable-next-line sonarjs/cognitive-complexity -- handles both auto-tracking and explicit-deps modes with cleanup; splitting would require exporting internal state\nexport function effect(fn, deps) {\n if (typeof fn !== 'function') {\n throw new Error('effect() requires a function');\n }\n\n const cleanups = [];\n let isRunning = false;\n\n /**\n * Execute the effect function\n */\n const execute = () => {\n /* v8 ignore next -- re-entry guard: unreachable because $subscribe fires via microtask after isRunning resets in finally */\n if (isRunning) return;\n isRunning = true;\n\n try {\n fn();\n } catch (error) {\n logError('[Lume.js effect] Error in effect:', error);\n throw error;\n } finally {\n isRunning = false;\n }\n };\n\n // EXPLICIT DEPS MODE: deps array provided\n if (Array.isArray(deps)) {\n // Coalesce notifications: when several tracked keys change in the same\n // flush (or several stores flush in the same tick), run the effect once\n // per microtask instead of once per changed key. This matches the\n // dedupe guarantee auto-tracking mode gets from the per-state effect queue.\n let scheduled = false;\n let disposed = false;\n cleanups.push(() => { disposed = true; });\n\n const scheduleExecute = () => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n if (disposed) return;\n // execute() logs and re-throws; swallow here so a throwing effect\n // doesn't become an uncaught error inside the microtask (same\n // containment the state flush loop provides for subscribers).\n try { execute(); } catch { /* already logged by execute() */ }\n });\n };\n\n // Subscribe to each [store, key1, key2, ...] tuple explicitly\n for (const dep of deps) {\n if (Array.isArray(dep) && dep.length >= 2) {\n const [store, ...keys] = dep;\n if (store && typeof store.$subscribe === 'function') {\n // Subscribe to each key in this tuple\n for (const key of keys) {\n // $subscribe calls immediately, then on changes\n // We want: call execute immediately once, then on changes\n let isFirst = true;\n const unsub = store.$subscribe(key, () => {\n if (isFirst) {\n isFirst = false;\n return; // Skip first call, we'll run execute() below\n }\n scheduleExecute();\n });\n cleanups.push(unsub);\n }\n }\n }\n }\n // Run immediately\n execute();\n }\n // AUTO-TRACKING MODE: no deps (existing behavior)\n else {\n const executeWithTracking = () => {\n /* v8 ignore next -- defensive guard: synchronous re-entry is unreachable through the public API */\n if (isRunning) return;\n\n // Save previous subscriptions instead of cleaning immediately.\n // If fn() doesn't read any state (early return / error), we restore\n // them so the effect stays reactive.\n const oldCleanups = cleanups.splice(0);\n\n // Tracking is keyed per store proxy (WeakMap<proxy, Set<key>>) so the\n // same key name on two different stores creates two subscriptions.\n const myContext = {\n fn,\n cleanups,\n execute: executeWithTracking,\n tracking: new WeakMap()\n };\n\n // Set as current effect (for state.js to detect)\n // Save previous context to support nested effects/computed\n const previousEffect = currentEffect;\n currentEffect = myContext;\n isRunning = true;\n\n try {\n const onRead = (proxy, key, registerEffect) => {\n // Only the currently active effect (not a nested one) creates subscriptions\n if (currentEffect !== myContext) return;\n let keys = myContext.tracking.get(proxy);\n if (!keys) {\n keys = new Set();\n myContext.tracking.set(proxy, keys);\n }\n if (keys.has(key)) return;\n keys.add(key);\n myContext.cleanups.push(registerEffect(key, myContext.execute));\n };\n withReadObserver(onRead, fn);\n } catch (error) {\n // On error, restore old subscriptions so the effect stays reactive\n cleanups.length = 0;\n cleanups.push(...oldCleanups);\n logError('[Lume.js effect] Error in effect:', error);\n throw error;\n } finally {\n // Restore previous context (not undefined) to support nesting\n currentEffect = previousEffect;\n isRunning = false;\n }\n\n // If fn() created new subscriptions, clean old ones.\n // If it didn't (e.g., early return), keep old subscriptions intact.\n if (cleanups.length > 0) {\n for (const cleanup of oldCleanups) cleanup();\n } else {\n cleanups.push(...oldCleanups);\n }\n };\n\n // Run immediately to collect initial dependencies\n executeWithTracking();\n }\n\n // Return cleanup function\n return () => {\n // while/pop is faster than forEach\n while (cleanups.length) cleanups.pop()();\n };\n}","/**\n * Lume-JS List Rendering (Addon)\n *\n * Renders lists with automatic subscription and element reuse by key.\n * \n * Core guarantees:\n * Element reuse by key (same DOM nodes, not recreated)\n * Minimal DOM operations (only updates what changed)\n * Memory efficiency (cleanup on remove)\n * \n * Default behavior (can be disabled/customized):\n * ✅ Focus preservation (maintains activeElement and selection)\n * ✅ Scroll preservation (intelligent positioning for add/remove/reorder)\n * \n * Philosophy: No artificial limitations\n * - All preservation logic is overridable via options\n * - Set to null/false to disable, or provide custom functions\n * - Export utilities so you can wrap/extend them\n *\n * ⚠️ IMPORTANT: Arrays must be updated immutably!\n * store.items.push(x) // ❌ Won't trigger update\n * store.items = [...items] // ✅ Triggers update\n * \n * ═══════════════════════════════════════════════════════════════════════\n * PATTERN 0: Template-based (recommended) — declarative, zero DOM code\n * ═══════════════════════════════════════════════════════════════════════\n *\n * HTML — a standard <template> element, valid HTML, no custom syntax:\n *\n * <ul id=\"list\">\n * <template>\n * <li>\n * <strong data-bind=\"name\"></strong>\n * <span data-bind=\"role\"></span>\n * <em data-bind=\"$index\"></em>\n * </li>\n * </template>\n * </ul>\n *\n * JS:\n *\n * repeat('#list', store, 'people', {\n * key: p => p.id,\n * template: true // use the <template> inside the container\n * });\n *\n * data-bind paths resolve against EACH ITEM: \"name\" → item.name,\n * \"user.city\" → item.user.city, \"$item\" → the item itself (primitive\n * arrays), \"$index\" → current index. Inputs get .value/.checked, other\n * elements get textContent — identical semantics to bindDom's data-bind.\n * These are one-way snapshot bindings re-applied per list update (items\n * are plain objects, not stores). Combine with create/update for event\n * listeners or extra binding. template also accepts a CSS selector or an\n * HTMLTemplateElement.\n *\n * ═══════════════════════════════════════════════════════════════════════\n * PATTERN 1: Simple (render only) - for simple cases or backward compat\n * ═══════════════════════════════════════════════════════════════════════\n * \n * repeat('#list', store, 'todos', {\n * key: todo => todo.id,\n * render: (todo, el) => {\n * el.textContent = todo.name; // Called on every update\n * }\n * });\n *\n * ═══════════════════════════════════════════════════════════════════════\n * PATTERN 2: Clean separation (create + update) - recommended\n * ═══════════════════════════════════════════════════════════════════════\n *\n * repeat('#list', store, 'todos', {\n * key: todo => todo.id,\n * create: (todo, el) => {\n * // Called ONCE when element is created - build DOM structure\n * const nameSpan = document.createElement('span');\n * nameSpan.className = 'name';\n * el.appendChild(nameSpan);\n * const btn = document.createElement('button');\n * btn.textContent = 'Delete';\n * btn.onclick = () => deleteTodo(todo.id);\n * el.appendChild(btn);\n *\n * // Return a cleanup function — called automatically when element is removed\n * return () => {\n * // Unsubscribe from external listeners, remove timers, etc.\n * };\n * },\n * update: (todo, el, index, { isFirstRender }) => {\n * // Called on every update - bind data\n * // isFirstRender = true on initial render, false on subsequent\n * // Skipped if same object reference (optimization)\n * el.querySelector('.name').textContent = todo.name;\n * }\n * });\n *\n * ═══════════════════════════════════════════════════════════════════════\n * ADVANCED: Custom preservation strategies\n * ═══════════════════════════════════════════════════════════════════════\n * \n * import { defaultFocusPreservation, defaultScrollPreservation } from \"lume-js/addons\";\n * \n * repeat('#list', store, 'items', {\n * key: item => item.id,\n * create: (item, el) => { ... },\n * update: (item, el) => { ... },\n * preserveFocus: null, // disable focus preservation\n * preserveScroll: (container, context) => {\n * const restore = defaultScrollPreservation(container, context);\n * return () => { restore(); console.log('Scroll restored!'); };\n * }\n * });\n */\nimport { logWarn, logError } from '../utils/log.js';\nimport { applyBindValue } from '../core/bindDom.js';\n\n/**\n * Resolve the template option to its single root element.\n * Accepts true (first <template> inside the container), a CSS selector,\n * or an HTMLTemplateElement directly.\n */\nfunction resolveTemplateRoot(template, containerEl) {\n let templateEl = template;\n if (template === true) {\n templateEl = containerEl.querySelector('template');\n } else if (typeof template === 'string') {\n templateEl = document.querySelector(template);\n }\n if (!templateEl || templateEl.tagName !== 'TEMPLATE') {\n throw new Error('[Lume.js] repeat(): template not found or not a <template> element');\n }\n if (templateEl.content.children.length !== 1) {\n throw new Error('[Lume.js] repeat(): template must contain exactly one root element');\n }\n return templateEl.content.firstElementChild;\n}\n\n/**\n * Collect [data-bind] nodes of a cloned item element into a compiled\n * binding list. Paths are resolved against the ITEM (not the store):\n * data-bind=\"name\" → item.name\n * data-bind=\"user.city\" → item.user.city\n * data-bind=\"$item\" → the item itself (for primitive arrays)\n * data-bind=\"$index\" → the item's current index\n */\nfunction collectItemBindings(el) {\n const bindings = [];\n const add = (node) => {\n const path = node.getAttribute('data-bind');\n bindings.push({ node, path, keys: path === '$item' || path === '$index' ? null : path.split('.') });\n };\n if (el.hasAttribute('data-bind')) add(el);\n for (const node of el.querySelectorAll('[data-bind]')) add(node);\n return bindings;\n}\n\nfunction applyItemBindings(bindings, item, index) {\n for (const b of bindings) {\n let val;\n if (b.path === '$index') {\n val = index;\n } else if (b.path === '$item') {\n val = item;\n } else {\n val = item;\n for (let i = 0; i < b.keys.length && val != null; i++) {\n val = val[b.keys[i]];\n }\n }\n applyBindValue(b.node, val);\n }\n}\n\n/**\n * Default focus preservation strategy\n * Saves activeElement and selection state before DOM updates\n * \n * @param {HTMLElement} container - The list container\n * @returns {Function|null} Restore function, or null if nothing to restore\n */\nexport function defaultFocusPreservation(container) {\n const activeEl = document.activeElement;\n const shouldRestore = container.contains(activeEl);\n\n if (!shouldRestore) return null;\n\n let selectionStart = null;\n let selectionEnd = null;\n\n if (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA') {\n selectionStart = activeEl.selectionStart;\n selectionEnd = activeEl.selectionEnd;\n }\n\n return () => {\n if (document.body.contains(activeEl)) {\n activeEl.focus();\n if (selectionStart !== null && selectionEnd !== null) {\n activeEl.setSelectionRange(selectionStart, selectionEnd);\n }\n }\n };\n}\n\n/**\n * Default scroll preservation strategy\n * Uses anchor-based preservation for add/remove, pixel position for reorder\n * \n * @param {HTMLElement} container - The list container\n * @param {Object} context - Additional context\n * @param {boolean} context.isReorder - Whether this is a reorder operation\n * @returns {Function} Restore function\n */\nexport function defaultScrollPreservation(container, context = {}) {\n const { isReorder = false } = context;\n const scrollTop = container.scrollTop;\n\n // Early return if no scroll\n if (scrollTop === 0) {\n return () => { container.scrollTop = 0; };\n }\n\n let anchorElement = null;\n let anchorOffset = 0;\n\n // Only use anchor-based preservation for add/remove, not reorder\n if (!isReorder) {\n const containerRect = container.getBoundingClientRect();\n // Avoid Array.from - iterate children directly\n for (let child = container.firstElementChild; child; child = child.nextElementSibling) {\n const rect = child.getBoundingClientRect();\n\n if (rect.bottom > containerRect.top) {\n anchorElement = child;\n anchorOffset = rect.top - containerRect.top;\n break;\n }\n }\n }\n\n return () => {\n if (anchorElement && document.body.contains(anchorElement)) {\n const newRect = anchorElement.getBoundingClientRect();\n const containerRect = container.getBoundingClientRect();\n const currentOffset = newRect.top - containerRect.top;\n const scrollAdjustment = currentOffset - anchorOffset;\n\n container.scrollTop = container.scrollTop + scrollAdjustment;\n } else {\n container.scrollTop = scrollTop;\n }\n };\n}\n\n/**\n * Efficiently render a list with element reuse\n * \n * @param {string|HTMLElement} container - Container element or selector\n * @param {Object} store - Reactive state object\n * @param {string} arrayKey - Key in store containing the array\n * @param {Object} options - Configuration\n * @param {Function} options.key - Function to extract unique key: (item) => key\n * @param {Function} [options.render] - Function to render item (called for all items): (item, element, index) => void\n * @param {Function} [options.create] - Function for new elements only: (item, element, index) => void | Function. If a function is returned, it is registered as the element's cleanup and called automatically when the element is removed (by list update or full cleanup).\n * @param {Function} [options.update] - Function for data binding: (item, element, index, { isFirstRender }) => void. Skipped if same item reference AND same index.\n * @param {Function} [options.remove] - Additional cleanup when element is removed: (item, element) => void. Called after any cleanup function returned by create(). Optional — prefer returning a cleanup from create() for automatic lifecycle management.\n * @param {true|string|HTMLTemplateElement} [options.template] - Declarative item structure from a <template> element: true = first <template> inside the container, string = CSS selector, or the element itself. The template must have exactly one root element; it is cloned per item and its [data-bind] paths are bound to the item on every update (\"name\", \"user.city\", \"$item\", \"$index\"). When set, options.element is ignored and options.render is ignored (with a warning); create/update remain available on top.\n * @param {string|Function} [options.element='div'] - Element tag name or factory function (ignored when options.template is set)\n * @param {Function|null} [options.preserveFocus=defaultFocusPreservation] - Focus preservation strategy (null to disable)\n * @param {Function|null} [options.preserveScroll=defaultScrollPreservation] - Scroll preservation strategy (null to disable)\n * @returns {Function} Cleanup function\n */\n\nexport function repeat(container, store, arrayKey, options) {\n const {\n key,\n render,\n create,\n update,\n remove,\n template = null,\n element = 'div',\n preserveFocus = defaultFocusPreservation,\n preserveScroll = defaultScrollPreservation\n } = options;\n\n // Resolve container\n const containerEl =\n typeof container === 'string'\n ? document.querySelector(container)\n : container;\n\n if (!containerEl) {\n logWarn(`[Lume.js] repeat(): container \"${container}\" not found`);\n return () => { };\n }\n\n if (typeof key !== 'function') {\n throw new Error('[Lume.js] repeat(): options.key must be a function');\n }\n\n // Template mode: structure and data binding come from the <template>;\n // render/create/update are all optional on top of it.\n const templateRoot = template ? resolveTemplateRoot(template, containerEl) : null;\n\n if (templateRoot && typeof render === 'function') {\n logWarn('[Lume.js] repeat(): options.render is ignored when options.template is set — use create/update instead');\n }\n\n if (!templateRoot && typeof render !== 'function' && typeof create !== 'function') {\n throw new Error('[Lume.js] repeat(): options.render or options.create must be a function');\n }\n\n // key -> HTMLElement\n const elementsByKey = new Map();\n // key -> previous item (for reference comparison)\n const prevItemsByKey = new Map();\n // key -> previous index (for reorder detection)\n const prevIndexByKey = new Map();\n // key -> cleanup function returned by create()\n const cleanupByKey = new Map();\n // key -> compiled [data-bind] nodes of the clone (template mode only)\n const bindingsByKey = new Map();\n const seenKeys = new Set();\n\n function createElement() {\n if (templateRoot) return templateRoot.cloneNode(true);\n return typeof element === 'function'\n ? element()\n : document.createElement(element);\n }\n\n function reconcileDOM(container, nextEls) {\n let ptr = container.firstChild;\n\n for (let i = 0; i < nextEls.length; i++) {\n const desired = nextEls[i];\n\n if (ptr === desired) {\n ptr = ptr.nextSibling;\n continue;\n }\n\n container.insertBefore(desired, ptr);\n }\n\n // Remove leftover children not in nextEls\n while (ptr) {\n const next = ptr.nextSibling;\n container.removeChild(ptr);\n ptr = next;\n }\n }\n\n function applyPreservation(container, fn, isReorder) {\n const shouldPreserve = document.body.contains(container);\n const restoreFocus = shouldPreserve && preserveFocus ? preserveFocus(container) : null;\n const restoreScroll = shouldPreserve && preserveScroll ? preserveScroll(container, { isReorder }) : null;\n\n fn();\n\n if (restoreFocus) restoreFocus();\n if (restoreScroll) restoreScroll();\n }\n\n // eslint-disable-next-line sonarjs/cognitive-complexity -- keyed DOM reconciliation: create/reuse/remove nodes, key dedup, scroll/focus preservation\n function updateList() {\n const items = store[arrayKey];\n\n if (!Array.isArray(items)) {\n logWarn(`[Lume.js] repeat(): store.${arrayKey} is not an array`);\n return;\n }\n\n // Only compute isReorder if scroll preservation needs it.\n // Uses elementsByKey (previous state) and items directly — no Set allocations.\n let isReorder = false;\n if (preserveScroll && elementsByKey.size === items.length) {\n isReorder = true;\n for (let i = 0; i < items.length; i++) {\n if (!elementsByKey.has(key(items[i]))) { isReorder = false; break; }\n }\n }\n\n seenKeys.clear();\n const nextEls = [];\n\n // Build ordered list of DOM nodes (created or reused)\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n const k = key(item);\n\n if (seenKeys.has(k)) {\n logWarn(`[Lume.js] repeat(): duplicate key \"${k}\"`);\n continue;\n }\n seenKeys.add(k);\n\n let el = elementsByKey.get(k);\n const isFirstRender = !el;\n\n if (isFirstRender) {\n el = createElement();\n elementsByKey.set(k, el);\n if (templateRoot) {\n bindingsByKey.set(k, collectItemBindings(el));\n }\n }\n\n try {\n // Call create for new elements (DOM structure / event listeners)\n if (isFirstRender && create) {\n const cleanup = create(item, el, i);\n if (typeof cleanup === 'function') {\n cleanupByKey.set(k, cleanup);\n }\n }\n\n // Data binding (new and existing elements)\n // Skip if same item reference AND same index (optimization)\n const prevItem = prevItemsByKey.get(k);\n const prevIndex = prevIndexByKey.get(k);\n if (templateRoot) {\n if (prevItem !== item || prevIndex !== i) {\n applyItemBindings(bindingsByKey.get(k), item, i);\n // update is optional extra binding on top of the template\n if (update) update(item, el, i, { isFirstRender });\n }\n } else if (update) {\n if (prevItem !== item || prevIndex !== i) {\n update(item, el, i, { isFirstRender });\n }\n } else if (render) {\n // Backward compatibility: render handles both create and update\n render(item, el, i);\n }\n\n // Store reference and index for next comparison\n prevItemsByKey.set(k, item);\n prevIndexByKey.set(k, i);\n\n } catch (err) {\n logError(`[Lume.js] repeat(): error rendering key \"${k}\":`, err);\n }\n\n nextEls.push(el);\n }\n\n // eslint-disable-next-line sonarjs/cognitive-complexity -- DOM cleanup pass: remove stale nodes, call per-item cleanup callbacks, update maps\n applyPreservation(containerEl, () => {\n reconcileDOM(containerEl, nextEls);\n\n // Clean maps: remove keys not in seenKeys (new state)\n if (elementsByKey.size !== seenKeys.size) {\n for (const k of elementsByKey.keys()) {\n if (!seenKeys.has(k)) {\n const el = elementsByKey.get(k);\n const prevItem = prevItemsByKey.get(k);\n // Call create-returned cleanup first, then remove callback\n const cleanup = cleanupByKey.get(k);\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n logError(`[Lume.js] repeat(): cleanup error for key \"${k}\":`, err);\n }\n }\n if (typeof remove === 'function' && el) {\n remove(prevItem, el);\n }\n elementsByKey.delete(k);\n prevItemsByKey.delete(k);\n prevIndexByKey.delete(k);\n cleanupByKey.delete(k);\n bindingsByKey.delete(k);\n }\n }\n }\n }, isReorder);\n }\n\n // Subscription — $subscribe calls updateList immediately (initial render),\n // so no separate updateList() call is needed for reactive stores.\n let unsubscribe;\n if (typeof store.$subscribe === 'function') {\n unsubscribe = store.$subscribe(arrayKey, updateList);\n } else if (typeof store.subscribe === 'function') {\n // Generic subscribe (e.g. computed) — subscribe first, then initial render\n const subResult = store.subscribe(() => updateList());\n updateList();\n // Normalize both function-style and object-style (RxJS Subscription) returns\n unsubscribe = typeof subResult === 'function'\n ? subResult\n : () => { subResult?.unsubscribe?.(); };\n } else {\n // Non-reactive store — render once and return cleanup\n updateList();\n logWarn('[Lume.js] repeat(): store is not reactive (no $subscribe or subscribe method)');\n return () => {\n for (const [k, el] of elementsByKey) {\n const prevItem = prevItemsByKey.get(k);\n const cleanup = cleanupByKey.get(k);\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n logError(`[Lume.js] repeat(): cleanup error for key \"${k}\":`, err);\n }\n }\n if (typeof remove === 'function') {\n remove(prevItem, el);\n }\n }\n containerEl.replaceChildren();\n elementsByKey.clear();\n prevItemsByKey.clear();\n prevIndexByKey.clear();\n cleanupByKey.clear();\n bindingsByKey.clear();\n seenKeys.clear();\n };\n }\n\n return () => {\n if (typeof unsubscribe === 'function') {\n unsubscribe();\n }\n // Invoke cleanup and remove callback for all remaining elements before clearing\n for (const [k, el] of elementsByKey) {\n const prevItem = prevItemsByKey.get(k);\n const cleanup = cleanupByKey.get(k);\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n logError(`[Lume.js] repeat(): cleanup error for key \"${k}\":`, err);\n }\n }\n if (typeof remove === 'function') {\n remove(prevItem, el);\n }\n }\n // Clear DOM elements (replaceChildren is faster than loop)\n containerEl.replaceChildren();\n elementsByKey.clear();\n prevItemsByKey.clear();\n prevIndexByKey.clear();\n cleanupByKey.clear();\n bindingsByKey.clear();\n seenKeys.clear();\n };\n}\n","/**\n * Lume-JS Debug Addon\n * \n * Developer-friendly logging and inspection of reactive state operations.\n * Critical for adoption - hard to debug = hard to adopt.\n * \n * Usage:\n * import { state } from \"lume-js\";\n * import { withPlugins, createDebugPlugin, debug } from \"lume-js/addons\";\n * \n * const store = withPlugins(state({ count: 0 }), [createDebugPlugin({ label: 'myStore' })]);\n * \n * debug.enable(); // Enable logging\n * debug.filter('count'); // Only log 'count' key\n * debug.stats(); // Show statistics\n * \n * @module addons/debug\n */\n\n// Global debug state\nlet globalEnabled = true;\nlet globalFilter = null; // string, RegExp, or null\nconst stats = new Map(); // label -> { gets: Map, sets: Map, notifies: Map }\n\n/**\n * Check if a key matches the current filter\n * @param {string} key\n * @returns {boolean}\n */\nfunction matchesFilter(key) {\n if (globalFilter === null) return true;\n if (typeof globalFilter === 'string') {\n return key.includes(globalFilter);\n }\n if (globalFilter instanceof RegExp) {\n return globalFilter.test(key);\n }\n return true;\n}\n\n/**\n * Get or create stats entry for a label\n * @param {string} label\n * @returns {object}\n */\nfunction getStats(label) {\n if (!stats.has(label)) {\n stats.set(label, {\n gets: new Map(),\n sets: new Map(),\n notifies: new Map()\n });\n }\n return stats.get(label);\n}\n\n/**\n * Increment a stat counter\n * @param {string} label\n * @param {'gets'|'sets'|'notifies'} type\n * @param {string} key\n */\nfunction incrementStat(label, type, key) {\n const s = getStats(label);\n const map = s[type];\n map.set(key, (map.get(key) || 0) + 1);\n}\n\nconst MAX_LOG_LEN = 100;\nconst TRUNCATED_LEN = MAX_LOG_LEN - 3;\n\n/**\n * Format value for logging (truncate long values)\n * @param {any} value\n * @returns {string}\n */\nfunction formatValue(value) {\n try {\n const json = JSON.stringify(value);\n if (json.length > MAX_LOG_LEN) {\n return json.slice(0, TRUNCATED_LEN) + '...';\n }\n return json;\n } catch {\n return String(value);\n }\n}\n\n/**\n * Create a debug plugin instance for a reactive state store.\n * \n * @param {object} [options] - Configuration options\n * @param {string} [options.label='store'] - Label for log messages\n * @param {boolean} [options.logGet=false] - Log property reads (can be noisy)\n * @param {boolean} [options.logSet=true] - Log property writes\n * @param {boolean} [options.logNotify=true] - Log subscriber notifications\n * @param {boolean} [options.trace=false] - Show stack trace for SET operations\n * @returns {object} Plugin object for state()\n * \n * @example\n * const store = withPlugins(state({ count: 0 }), [createDebugPlugin({ label: 'counter' })]);\n * \n * @example\n * // With stack traces for debugging where state changes originate\n * const store = withPlugins(state({ count: 0 }), [createDebugPlugin({ label: 'counter', trace: true })]);\n */\nexport function createDebugPlugin(options = {}) {\n const label = options.label ?? 'store';\n\n // IMPORTANT: Do NOT destructure options here!\n // Options may contain getters for dynamic runtime toggling (e.g., from UI).\n // Destructuring would copy values once at creation time, breaking reactivity.\n // Use getOpt() helper to read options dynamically in each hook.\n const getOpt = (name, defaultVal) => {\n const val = options[name];\n return val !== undefined ? val : defaultVal;\n };\n\n return {\n name: `debug:${label}`,\n\n onInit: () => {\n if (globalEnabled) {\n console.log(`%c[${label}]%c initialized`, 'color: #888; font-weight: bold', 'color: inherit');\n }\n },\n\n onGet: (key, value) => {\n // Skip internal properties\n if (typeof key === 'string' && key.startsWith('$')) {\n return value;\n }\n\n incrementStat(label, 'gets', key);\n\n if (globalEnabled && getOpt('logGet', false) && matchesFilter(key)) {\n console.log(\n `%c[${label}]%c GET %c${key}%c = ${formatValue(value)}`,\n 'color: #888; font-weight: bold',\n 'color: #4CAF50',\n 'color: #2196F3; font-weight: bold',\n 'color: inherit'\n );\n }\n\n return value;\n },\n\n onSet: (key, newValue, oldValue) => {\n // Skip internal properties\n if (typeof key === 'string' && key.startsWith('$')) {\n return newValue;\n }\n\n incrementStat(label, 'sets', key);\n\n if (globalEnabled && getOpt('logSet', true) && matchesFilter(key)) {\n console.log(\n `%c[${label}]%c SET %c${key}%c: ${formatValue(oldValue)} → ${formatValue(newValue)}`,\n 'color: #888; font-weight: bold',\n 'color: #FF9800',\n 'color: #2196F3; font-weight: bold',\n 'color: inherit'\n );\n\n // Show stack trace if enabled (helps find where state changes originate)\n if (getOpt('trace', false)) {\n console.trace(`%c[${label}] Stack trace for ${key}`, 'color: #888');\n }\n }\n\n return newValue;\n },\n\n onSubscribe: (key) => {\n if (globalEnabled && matchesFilter(key)) {\n console.log(\n `%c[${label}]%c SUBSCRIBE %c${key}`,\n 'color: #888; font-weight: bold',\n 'color: #9C27B0',\n 'color: #2196F3; font-weight: bold'\n );\n }\n },\n\n onNotify: (key, value) => {\n // Skip internal properties\n if (typeof key === 'string' && key.startsWith('$')) {\n return;\n }\n\n incrementStat(label, 'notifies', key);\n\n if (globalEnabled && getOpt('logNotify', true) && matchesFilter(key)) {\n console.log(\n `%c[${label}]%c NOTIFY %c${key}%c = ${formatValue(value)}`,\n 'color: #888; font-weight: bold',\n 'color: #E91E63',\n 'color: #2196F3; font-weight: bold',\n 'color: inherit'\n );\n }\n }\n };\n}\n\n/**\n * Global debug controls\n */\nexport const debug = {\n /**\n * Enable debug logging globally\n */\n enable() {\n globalEnabled = true;\n console.log('%c[lume-debug]%c Logging enabled', 'color: #888; font-weight: bold', 'color: #4CAF50');\n },\n\n /**\n * Disable debug logging globally\n */\n disable() {\n globalEnabled = false;\n console.log('%c[lume-debug]%c Logging disabled', 'color: #888; font-weight: bold', 'color: #F44336');\n },\n\n /**\n * Check if debug logging is currently enabled\n * @returns {boolean}\n */\n isEnabled() {\n return globalEnabled;\n },\n\n /**\n * Filter logs by key pattern\n * @param {string|RegExp|null} pattern - Pattern to match, or null to clear filter\n */\n filter(pattern) {\n globalFilter = pattern;\n if (pattern === null) {\n console.log('%c[lume-debug]%c Filter cleared', 'color: #888; font-weight: bold', 'color: inherit');\n } else {\n console.log(`%c[lume-debug]%c Filter set: ${pattern}`, 'color: #888; font-weight: bold', 'color: inherit');\n }\n },\n\n /**\n * Get current filter pattern\n * @returns {string|RegExp|null}\n */\n getFilter() {\n return globalFilter;\n },\n\n /**\n * Get statistics data (silent - no console output)\n * Use logStats() if you want to see stats in console.\n * @returns {object} Stats object for programmatic access\n */\n stats() {\n const result = {};\n\n for (const [label, data] of stats) {\n result[label] = {\n gets: Object.fromEntries(data.gets),\n sets: Object.fromEntries(data.sets),\n notifies: Object.fromEntries(data.notifies)\n };\n }\n\n return result;\n },\n\n /**\n * Log statistics summary to console (with formatting)\n * @returns {object} Stats object for programmatic access\n */\n logStats() {\n const result = this.stats();\n\n if (Object.keys(result).length === 0) {\n console.log('%c[lume-debug]%c No stats collected yet', 'color: #888; font-weight: bold', 'color: inherit');\n return result;\n }\n\n console.group('%c[lume-debug] Statistics', 'color: #888; font-weight: bold');\n\n for (const [label, data] of Object.entries(result)) {\n console.group(`%c${label}`, 'color: #2196F3; font-weight: bold');\n\n // Use console.table for better formatted output\n const tableData = [];\n const allKeys = new Set([\n ...Object.keys(data.gets),\n ...Object.keys(data.sets),\n ...Object.keys(data.notifies)\n ]);\n\n for (const key of allKeys) {\n tableData.push({\n key,\n gets: data.gets[key] || 0,\n sets: data.sets[key] || 0,\n notifies: data.notifies[key] || 0\n });\n }\n\n if (tableData.length > 0) {\n console.table(tableData);\n }\n\n console.groupEnd();\n }\n\n console.groupEnd();\n\n return result;\n },\n\n /**\n * Reset all collected statistics\n */\n resetStats() {\n stats.clear();\n console.log('%c[lume-debug]%c Stats reset', 'color: #888; font-weight: bold', 'color: inherit');\n }\n};\n","/**\n * Lume-JS Persist Addon\n *\n * Keeps selected store keys in sync with localStorage/sessionStorage (or\n * any Storage-like object): hydrates them on call, then saves on change.\n *\n * Usage:\n * import { state } from \"lume-js\";\n * import { persist } from \"lume-js/addons\";\n *\n * const store = state({ todos: [], filter: 'all', draft: '' });\n *\n * // Hydrate + auto-save todos/filter; draft stays in-memory only\n * const stop = persist(store, 'my-app', { keys: ['todos', 'filter'] });\n *\n * Behavior:\n * - Hydration assigns stored values through the proxy, so subscribers and\n * bindings see them like any other write.\n * - Saves are coalesced to one storage write per microtask, and skipped\n * entirely when the serialized snapshot is unchanged.\n * - Storage failures (quota, unavailable, corrupted JSON, unserializable\n * values) are contained: a console warning, never a throw.\n *\n * @security Storage is same-origin but survives schema changes — hydration\n * only assigns keys you watch (never unknown keys from storage), and the\n * core set trap independently blocks prototype-polluting keys.\n *\n * @module addons/persist\n */\n\nimport { logWarn } from '../utils/log.js';\n\n/**\n * Read and parse the stored JSON blob. Returns a plain object, or null\n * when missing, corrupted, or not an object (warns on read errors).\n */\nfunction readStored(storage, storageKey) {\n try {\n const raw = storage.getItem(storageKey);\n if (!raw) return null;\n const data = JSON.parse(raw);\n return data && typeof data === 'object' && !Array.isArray(data) ? data : null;\n } catch {\n logWarn(`[Lume.js] persist(): could not read \"${storageKey}\" — starting fresh`);\n return null;\n }\n}\n\n/** Serialize the watched subset of the store. May throw (circular refs). */\nfunction serializeKeys(store, watched) {\n const out = {};\n for (const k of watched) out[k] = store[k];\n return JSON.stringify(out);\n}\n\n/**\n * Sync store keys with a Storage object.\n *\n * @param {object} store - Reactive store created with state()\n * @param {string} storageKey - The storage entry name to read/write\n * @param {object} [options]\n * @param {string[]} [options.keys] - Keys to persist. Default: all own\n * non-$ keys of the store at call time.\n * @param {Storage} [options.storage] - Storage object. Default: localStorage.\n * Pass sessionStorage for per-tab persistence.\n * @returns {function} Dispose function — stops watching and saving.\n */\nexport function persist(store, storageKey, options = {}) {\n if (!store || typeof store.$subscribe !== 'function') {\n throw new Error('[Lume.js] persist() requires a reactive store from state()');\n }\n if (typeof storageKey !== 'string' || storageKey.length === 0) {\n throw new Error('[Lume.js] persist() requires a non-empty storage key');\n }\n\n const storage = options.storage !== undefined\n ? options.storage\n : globalThis.localStorage;\n\n if (!storage || typeof storage.getItem !== 'function') {\n logWarn('[Lume.js] persist(): no storage available — persistence disabled');\n return () => {};\n }\n\n const watched = Array.isArray(options.keys) && options.keys.length > 0\n ? options.keys.slice()\n : Object.keys(store).filter(k => !k.startsWith('$'));\n\n // ── Hydrate ────────────────────────────────────────────────────────────\n // Only watched keys are assigned — stale storage can't inject others.\n const stored = readStored(storage, storageKey);\n if (stored) {\n for (const k of watched) {\n if (Object.prototype.hasOwnProperty.call(stored, k)) {\n store[k] = stored[k];\n }\n }\n }\n\n // ── Save on change ─────────────────────────────────────────────────────\n // Remember what storage holds (post-hydration) so unchanged flushes —\n // including the hydration echo itself — skip the write.\n let lastWritten = null;\n try {\n lastWritten = serializeKeys(store, watched);\n } catch {\n // Unserializable initial state: first save attempt will warn.\n }\n\n let scheduled = false;\n let disposed = false;\n\n const flushSave = () => {\n scheduled = false;\n if (disposed) return;\n\n let json;\n try {\n json = serializeKeys(store, watched);\n } catch (err) {\n logWarn('[Lume.js] persist(): state not serializable — skipping save', err);\n return;\n }\n if (json === lastWritten) return;\n\n try {\n storage.setItem(storageKey, json);\n lastWritten = json;\n } catch (err) {\n logWarn('[Lume.js] persist(): could not write — storage full or unavailable?', err);\n }\n };\n\n const save = () => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(flushSave);\n };\n\n const unsubs = watched.map(k => {\n let first = true;\n return store.$subscribe(k, () => {\n if (first) { first = false; return; } // skip $subscribe's immediate call\n save();\n });\n });\n\n return () => {\n disposed = true;\n while (unsubs.length) unsubs.pop()();\n };\n}\n","/** data-show=\"key\" → el.hidden = !Boolean(val) */\nexport const show = {\n attr: 'data-show',\n apply(el, val) { el.hidden = !Boolean(val); }\n};\n","/** data-classname=\"key\" → el.className = val || '' */\nexport const className = {\n attr: 'data-classname',\n apply(el, val) { el.className = val || ''; }\n};\n","/**\n * Create a handler for any HTML boolean attribute.\n * Uses toggleAttribute() — works correctly with any attribute name\n * (readonly, contenteditable, etc.) without worrying about camelCase property names.\n *\n * @param {string} name - Attribute name (e.g., 'readonly', 'open', 'contenteditable')\n * @returns {{ attr: string, apply: function }}\n */\nexport function boolAttr(name) {\n return {\n attr: `data-${name}`,\n apply(el, val) { el.toggleAttribute(name, Boolean(val)); }\n };\n}\n","/**\n * Create a handler for an ARIA attribute.\n * Coerces value to \"true\"/\"false\" string — use stringAttr(\"aria-X\") for token/string ARIA attrs.\n *\n * @param {string} name - ARIA name, with or without \"aria-\" prefix\n * @returns {{ attr: string, apply: function }}\n */\nexport function ariaAttr(name) {\n const fullName = name.startsWith('aria-') ? name : `aria-${name}`;\n return {\n attr: `data-${fullName}`,\n apply(el, val) { el.setAttribute(fullName, val ? 'true' : 'false'); }\n };\n}\n","/**\n * Create a handler for any string attribute (href, src, title, alt, action, etc.)\n * Sets the attribute value as a string. Removes the attribute when value is null/undefined.\n *\n * @param {string} name - HTML attribute name (e.g., 'href', 'src', 'title')\n * @returns {{ attr: string, apply: function }}\n */\n\nconst DANGEROUS_SCHEME = /^(javascript|vbscript|data\\s*:\\s*text\\/html)/i;\nconst URI_ATTRS = new Set(['href', 'src', 'action', 'srcset', 'poster', 'formaction']);\n\nexport function stringAttr(name) {\n return {\n attr: `data-${name}`,\n apply(el, val) {\n if (val == null) {\n el.removeAttribute(name);\n return;\n }\n const strVal = String(val);\n if (URI_ATTRS.has(name) && DANGEROUS_SCHEME.test(strVal)) {\n el.removeAttribute(name);\n return;\n }\n el.setAttribute(name, strVal);\n }\n };\n}\n","/**\n * Create handlers for declarative event wiring.\n * Each type creates a handler: data-on{type}=\"key\" wires the function held\n * at that store key as a DOM event listener.\n *\n * <button data-onclick=\"addTodo\">Add</button>\n *\n * const store = state({\n * addTodo: (event) => { ... } // a plain function in state\n * });\n * bindDom(root, store, { handlers: [on('click')] });\n *\n * Reactive like any binding: assigning a new function to the key re-wires\n * the listener; assigning null/undefined detaches it.\n *\n * Returns an array — pass directly to handlers (auto-flattened by bindDom).\n *\n * @security Same trust model as data-bind: an injected data-on* attribute\n * can only reference functions that already exist in reachable state — no\n * expressions, no eval. Ensure your HTML is trusted or sanitized.\n *\n * Note: bindDom's cleanup stops future re-wiring but does not detach\n * listeners already attached to elements that remain in the DOM. Discard\n * the bound subtree (the normal SPA teardown) to drop them.\n *\n * @param {...string} types - DOM event types ('click', 'input', 'submit', ...)\n * @returns {Array<{ attr: string, apply: function }>}\n */\n\nimport { logWarn } from '../utils/log.js';\n\n// element → Map<eventType, listener> — tracks what we attached so a\n// re-assigned store key swaps the listener instead of stacking a second one.\nconst attached = new WeakMap();\n\nexport function on(...types) {\n return types.map(type => ({\n attr: `data-on${type}`,\n apply(el, val) {\n let byType = attached.get(el);\n const prev = byType ? byType.get(type) : undefined;\n\n if (prev) {\n el.removeEventListener(type, prev);\n byType.delete(type);\n }\n\n if (typeof val === 'function') {\n el.addEventListener(type, val);\n if (!byType) {\n byType = new Map();\n attached.set(el, byType);\n }\n byType.set(type, val);\n } else if (val != null) {\n logWarn(`[Lume.js] on('${type}'): bound value is not a function — listener detached`);\n }\n }\n }));\n}\n","import { show } from './show.js';\nimport { boolAttr } from './boolAttr.js';\nimport { ariaAttr } from './ariaAttr.js';\nimport { stringAttr } from './stringAttr.js';\n\n/** @see https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes#boolean_attributes */\nconst BOOL_ATTRS = [\n 'readonly', 'open', 'novalidate', 'formnovalidate', 'multiple',\n 'autofocus', 'autoplay', 'controls', 'loop', 'muted', 'defer',\n 'async', 'reversed', 'selected', 'inert', 'allowfullscreen',\n];\n\n/** @see https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes */\nconst STRING_ATTRS = [\n 'href', 'src', 'alt', 'title', 'placeholder', 'action', 'method',\n 'target', 'rel', 'type', 'name', 'role', 'lang', 'tabindex',\n 'pattern', 'min', 'max', 'step', 'minlength', 'maxlength',\n 'width', 'height', 'for', 'form', 'accept', 'autocomplete',\n 'loading', 'decoding', 'inputmode', 'enterkeyhint', 'draggable',\n 'contenteditable', 'spellcheck', 'translate', 'dir', 'id',\n 'poster', 'preload', 'download', 'media', 'sizes', 'srcset',\n 'colspan', 'rowspan', 'scope', 'headers', 'wrap', 'sandbox',\n];\n\n/** ARIA boolean state attributes — coerced to \"true\"/\"false\" string. */\nconst ARIA_BOOL_ATTRS = [\n 'pressed', 'selected', 'disabled', 'checked', 'invalid', 'required',\n 'busy', 'modal', 'multiselectable', 'multiline', 'readonly', 'atomic',\n];\n\n/** ARIA string/token/numeric attributes — value passed through as-is. */\nconst ARIA_STRING_ATTRS = [\n 'current', 'live', 'relevant', 'haspopup',\n 'sort', 'autocomplete', 'orientation',\n 'label', 'describedby', 'labelledby', 'controls', 'owns',\n 'activedescendant', 'errormessage', 'details', 'flowto',\n 'valuenow', 'valuemin', 'valuemax', 'valuetext',\n 'colcount', 'colindex', 'colspan', 'rowcount', 'rowindex', 'rowspan',\n 'level', 'setsize', 'posinset', 'placeholder', 'roledescription',\n 'keyshortcuts', 'braillelabel', 'brailleroledescription',\n];\n\n/**\n * One-import preset that enables all standard HTML attributes as reactive handlers.\n * Returns a flat array — pass directly to handlers option.\n *\n * @returns {Array<{ attr: string, apply: function }>}\n */\nexport function htmlAttrs() {\n return [\n show,\n ...BOOL_ATTRS.map(name => boolAttr(name)),\n ...STRING_ATTRS.map(name => stringAttr(name)),\n ...ARIA_BOOL_ATTRS.map(name => ariaAttr(name)),\n ...ARIA_STRING_ATTRS.map(name => stringAttr(`aria-${name}`)),\n ];\n}\n","import { boolAttr } from './boolAttr.js';\nimport { ariaAttr } from './ariaAttr.js';\n\n/** Form-related handlers (beyond built-in disabled/checked/required) */\nexport const formHandlers = [\n boolAttr('readonly'),\n];\n\n/** Additional ARIA handlers (beyond built-in aria-expanded/aria-hidden) */\nexport const a11yHandlers = [\n ariaAttr('pressed'),\n ariaAttr('selected'),\n ariaAttr('disabled'),\n];\n","/**\n * Create handlers for CSS class toggling.\n * Each name creates a handler: data-class-{name}=\"key\" → el.classList.toggle(name, Boolean(val))\n * Returns an array — pass directly to handlers (auto-flattened by bindDom).\n *\n * @param {...string} names - CSS class names to create handlers for\n * @returns {Array<{ attr: string, apply: function }>}\n */\nexport function classToggle(...names) {\n return names.map(name => ({\n attr: `data-class-${name}`,\n apply(el, val) { el.classList.toggle(name, Boolean(val)); }\n }));\n}\n","/**\n * Lume-JS Computed Addon\n * \n * Creates computed values that automatically update when dependencies change.\n * Uses core effect() for automatic dependency tracking.\n * \n * Usage:\n * import { computed } from \"lume-js/addons/computed\";\n * \n * const doubled = computed(() => store.count * 2);\n * console.log(doubled.value); // Auto-updates when store.count changes\n * \n * Features:\n * - Automatic dependency tracking (no manual recompute)\n * - Cached values (only recomputes when dependencies change)\n * - Subscribe to changes\n * - Cleanup with dispose()\n * \n * @module addons/computed\n */\n\nimport { effect } from '../core/effect.js';\nimport { logError } from '../utils/log.js';\n\n/**\n * Creates a computed value with automatic dependency tracking\n * \n * The computation function runs immediately and tracks which state\n * properties are accessed. When any dependency changes, the value\n * is automatically recomputed.\n *\n * ⚠️ Circular self-mutations are automatically suppressed. If a computed\n * mutates a state property it depends on, the flush triggered by that\n * mutation is skipped to prevent an infinite microtask loop.\n *\n * @security After each computation, a re-entry guard stays active until the\n * next microtask. If a dependency changes synchronously during this window,\n * the computed will not recompute until a subsequent microtask. This is\n * intentional — it prevents infinite loops from self-mutating computeds.\n *\n * @param {function} fn - Function that computes the value\n * @returns {object} Object with .value property and methods\n * \n * @example\n * const store = state({ count: 5 });\n * \n * const doubled = computed(() => store.count * 2);\n * console.log(doubled.value); // 10\n * \n * store.count = 10;\n * // After microtask:\n * console.log(doubled.value); // 20 (auto-updated)\n * \n * @example\n * // Subscribe to changes\n * const unsub = doubled.subscribe(value => {\n * console.log('Doubled changed to:', value);\n * });\n * \n * @example\n * // Cleanup\n * doubled.dispose();\n */\nexport function computed(fn) {\n if (typeof fn !== 'function') {\n throw new Error('computed() requires a function');\n }\n\n let cachedValue;\n let isInitialized = false;\n let isInComputation = false;\n let disposed = false;\n const subscribers = [];\n\n // Use effect to automatically track dependencies\n const cleanupEffect = effect(() => {\n // Skip re-entry from a flush triggered by our own synchronous mutation.\n // The mutation inside fn() queues a microtask flush; we stay flagged\n // until a subsequent microtask clears it, so that flush is dropped.\n if (isInComputation || disposed) return;\n\n isInComputation = true;\n\n try {\n const newValue = fn();\n\n // Check if value actually changed - Object.is() handles NaN and -0\n if (!isInitialized || !Object.is(newValue, cachedValue)) {\n cachedValue = newValue;\n isInitialized = true;\n\n // Notify all subscribers\n subscribers.forEach(callback => callback(cachedValue));\n }\n } catch (error) {\n logError('[Lume.js computed] Error in computation:', error);\n // Set to undefined on error, mark as initialized\n if (!isInitialized || cachedValue !== undefined) {\n cachedValue = undefined;\n isInitialized = true;\n\n // Notify subscribers of error state\n subscribers.forEach(callback => callback(cachedValue));\n }\n } finally {\n // Defer clearing the flag so any flush microtask queued by fn()\n // sees it still set and skips re-entry.\n queueMicrotask(() => {\n if (!disposed) {\n isInComputation = false;\n }\n });\n }\n });\n\n return {\n /**\n * Get the current computed value\n */\n get value() {\n if (!isInitialized) {\n throw new Error('Computed value accessed before initialization');\n }\n return cachedValue;\n },\n\n /**\n * Subscribe to changes in computed value\n * \n * @param {function} callback - Called when value changes\n * @returns {function} Unsubscribe function\n */\n subscribe(callback) {\n if (typeof callback !== 'function') {\n throw new Error('subscribe() requires a function');\n }\n\n subscribers.push(callback);\n\n // Call immediately with current value\n if (isInitialized) {\n callback(cachedValue);\n }\n\n // Return unsubscribe function\n return () => {\n const index = subscribers.indexOf(callback);\n if (index > -1) {\n subscribers.splice(index, 1);\n }\n };\n },\n\n /**\n * Clean up computed value and stop tracking\n */\n dispose() {\n disposed = true;\n cleanupEffect();\n subscribers.length = 0;\n isInitialized = false;\n isInComputation = false;\n }\n };\n}","/**\n * Creates a cleanup group that can collect and dispose multiple\n * cleanup/unsubscribe functions at once.\n *\n * @returns {CleanupGroup}\n *\n * @example\n * ```js\n * import { createCleanupGroup } from 'lume-js/addons';\n *\n * const group = createCleanupGroup();\n * group.add(bindDom(root, store));\n * group.add(effect(() => { ... }));\n * group.add(store.$subscribe('key', fn));\n *\n * // Dispose everything at once\n * group.dispose();\n * ```\n */\nexport function createCleanupGroup() {\n const cleanups = [];\n\n return {\n /**\n * Add a cleanup function to the group.\n * @param {Function} fn - Cleanup/unsubscribe function\n */\n add(fn) {\n if (typeof fn === 'function') {\n cleanups.push(fn);\n }\n },\n\n /**\n * Run all collected cleanup functions and clear the group.\n */\n dispose() {\n while (cleanups.length) {\n const fn = cleanups.pop();\n try { fn(); } catch (e) { /* ignore cleanup errors */ }\n }\n },\n };\n}\n","/**\n * Reads initial state from a `<script type=\"application/json\">` element\n * embedded in the server-rendered HTML. Useful for SSR / hydration patterns.\n *\n * @security Hydration trusts the DOM. An attacker who can inject HTML before\n * the legitimate script (DOM clobbering) can control the parsed data. The\n * element must be a real `<script type=\"application/json\">` tag; non-script\n * elements are rejected. Use the optional `validate` parameter to enforce a\n * schema (e.g., whitelist allowed keys) before passing to `state()`.\n *\n * @param {string} [selector='#__LUME_DATA__'] - CSS selector for the script element\n * @param {function} [validate] - Optional validator: (data) => boolean. If it\n * returns false, hydrateState returns {} instead of the parsed data.\n * @returns {object} Parsed JSON object, or empty object if not found / invalid / rejected\n *\n * @example\n * ```html\n * <script id=\"__LUME_DATA__\" type=\"application/json\">\n * {\"title\": \"Welcome\", \"count\": 42}\n * </script>\n * ```\n *\n * ```js\n * import { state } from 'lume-js';\n * import { hydrateState } from 'lume-js/addons';\n *\n * // With optional schema validation\n * const data = hydrateState('#__LUME_DATA__', d =>\n * typeof d.title === 'string' && typeof d.count === 'number'\n * );\n * const store = state(data);\n * ```\n */\nexport function hydrateState(selector = '#__LUME_DATA__', validate) {\n const el = typeof document !== 'undefined' ? document.querySelector(selector) : null;\n if (!el) return {};\n\n // Reject non-script elements or scripts without the correct type.\n // This mitigates DOM clobbering where an attacker injects a matching\n // element with a different tag name (e.g., a div or a script with\n // a different type that would still match querySelector by id).\n if (el.tagName !== 'SCRIPT' || el.type !== 'application/json') {\n return {};\n }\n\n let data;\n try {\n data = JSON.parse(el.textContent);\n } catch {\n return {};\n }\n\n if (typeof validate === 'function' && !validate(data)) {\n return {};\n }\n\n return data;\n}\n","import { REACTIVE_BRAND } from \"../core/state.js\";\n\nexport { computed } from \"./computed.js\";\nexport { watch } from \"./watch.js\";\nexport { repeat, defaultFocusPreservation, defaultScrollPreservation } from \"./repeat.js\";\nexport { createDebugPlugin, debug } from \"./debug.js\";\nexport { withPlugins } from \"./withPlugins.js\";\nexport { createCleanupGroup } from \"./cleanupGroup.js\";\nexport { hydrateState } from \"./hydrateState.js\";\nexport { persist } from \"./persist.js\";\n\n/**\n * Returns true if the value is a Lume reactive proxy created by state().\n *\n * Checks the shared reactive brand first (a registry symbol stamped by\n * state(), reliable across module copies), then falls back to duck-typing\n * ($subscribe) for proxies from older lume-js versions whose brand was not\n * shared. The brand check uses the `in` operator, which does not pass\n * through the proxy `get` trap — calling isReactive inside an effect does\n * not create a spurious dependency.\n *\n * @param {any} obj\n * @returns {boolean}\n */\nexport function isReactive(obj) {\n return !!(obj && typeof obj === 'object' &&\n (REACTIVE_BRAND in obj || typeof obj.$subscribe === 'function'));\n}\n","/**\n * watch - observes changes to a state key and triggers callback\n * @param {Object} store - reactive store created with state()\n * @param {string} key - key in store to watch\n * @param {Function} callback - called with new value\n * @param {Object} [options]\n * @param {boolean} [options.immediate=true] - call callback immediately with current value\n * @returns {Function} unsubscribe function\n */\nexport function watch(store, key, callback, { immediate = true } = {}) {\n if (!store.$subscribe) {\n throw new Error(\"store must be created with state()\");\n }\n if (!immediate) {\n let skipped = false;\n return store.$subscribe(key, (val) => {\n if (!skipped) { skipped = true; return; }\n callback(val);\n });\n }\n return store.$subscribe(key, callback);\n}","/**\n * Lume-JS withPlugins Addon\n *\n * Wraps a reactive state proxy with a plugin layer that intercepts\n * get/set/notify/subscribe operations via plugin hooks.\n *\n * Only stores that opt into debugging or custom behaviors need this.\n * Core state() is not aware of plugins.\n *\n * Usage:\n * import { state } from \"lume-js\";\n * import { withPlugins, createDebugPlugin } from \"lume-js/addons\";\n *\n * const store = withPlugins(state({ count: 0 }), [createDebugPlugin({ label: 'counter' })]);\n */\n\n/**\n * Wrap a reactive state proxy with plugin hooks.\n *\n * Plugin hooks (all optional):\n * onInit() — called once at wrap time\n * onGet(key, value) → value|void — intercept/transform reads\n * onSet(key, newVal, oldVal) → val|void — intercept/transform writes\n * onNotify(key, value) — called before subscribers are notified\n * onSubscribe(key) — called when $subscribe is invoked\n *\n * @security Plugins run with full application privilege. A plugin can read\n * all state, alter any write, or suppress mutations. Only pass trusted objects.\n * Plugin objects are frozen after registration to prevent post-init mutation.\n *\n * @param {object} store - A reactive proxy from state()\n * @param {Array<object>} plugins - Array of plugin objects\n * @returns {Proxy} A new proxy wrapping the store with plugin behavior\n */\nimport { logError } from '../utils/log.js';\n\nexport function withPlugins(store, plugins = []) {\n if (!plugins.length) return store;\n\n // Call onInit hooks once at wrap time, then freeze each plugin to prevent\n // post-registration mutation of its hooks (defense-in-depth).\n for (const p of plugins) {\n try {\n p.onInit?.();\n } catch (e) {\n logError(`[Lume.js] Plugin \"${p.name}\" error in onInit:`, e);\n }\n Object.freeze(p);\n }\n\n // Track pending notifications for onNotify hooks.\n // Instead of a separate microtask, we hook into the underlying state's\n // flush via $beforeFlush so onNotify and subscribers share one microtask.\n const pendingNotifications = new Map();\n\n function runNotifyHooks() {\n for (const [key, value] of pendingNotifications) {\n for (const p of plugins) {\n try {\n p.onNotify?.(key, value);\n } catch (e) {\n logError(`[Lume.js] Plugin \"${p.name}\" error in onNotify:`, e);\n }\n }\n }\n pendingNotifications.clear();\n }\n\n // Register once on the underlying state; capture unsubscribe for cleanup.\n let flushUnsub;\n if (typeof store.$beforeFlush === 'function') {\n flushUnsub = store.$beforeFlush(runNotifyHooks);\n }\n\n return new Proxy(store, {\n get(target, key) {\n // $dispose — remove the beforeFlush hook and clear pending state\n if (key === '$dispose') {\n return () => {\n if (flushUnsub) flushUnsub();\n pendingNotifications.clear();\n };\n }\n\n // Pass $-prefixed meta methods through without interception\n if (typeof key === 'string' && key.startsWith('$')) {\n const method = target[key];\n if (key === '$subscribe' && typeof method === 'function') {\n // Wrap $subscribe to call onSubscribe hooks\n return (subKey, fn) => {\n for (const p of plugins) {\n try {\n p.onSubscribe?.(subKey);\n } catch (e) {\n logError(`[Lume.js] Plugin \"${p.name}\" error in onSubscribe:`, e);\n }\n }\n return method(subKey, fn);\n };\n }\n return method;\n }\n\n let value = target[key];\n\n // onGet chain\n for (const p of plugins) {\n try {\n const r = p.onGet?.(key, value);\n if (r !== undefined) value = r;\n } catch (e) {\n logError(`[Lume.js] Plugin \"${p.name}\" error in onGet:`, e);\n }\n }\n\n return value;\n },\n\n set(target, key, value) {\n const oldValue = target[key];\n let newValue = value;\n\n // onSet chain\n for (const p of plugins) {\n try {\n const r = p.onSet?.(key, newValue, oldValue);\n if (r !== undefined) newValue = r;\n } catch (e) {\n logError(`[Lume.js] Plugin \"${p.name}\" error in onSet:`, e);\n }\n }\n\n // Only queue onNotify if the value actually changed after plugin chain\n if (!Object.is(newValue, oldValue)) {\n pendingNotifications.set(key, newValue);\n }\n\n target[key] = newValue;\n return true;\n }\n });\n}\n"],"names":["logWarn","msg","rest","console","warn","logError","error","MAX_FLUSH_ITERATIONS","batchDepth","batchedStates","Set","readers","REACTIVE_BRAND","Symbol","for","withReadObserver","onRead","fn","add","delete","boolHandler","name","attr","apply","el","val","ariaHandler","setAttribute","DEFAULT_HANDLERS","applyHandler","store","path","handler","result","resolveProp","target","key","$subscribe","handleDataBind","bindingMap","unsub","applyBindValue","tagName","isFormInput","set","pathArr","split","pop","obj","length","current","i","resolvePath","type","checked","value","String","textContent","currentEffect","effect","deps","Error","cleanups","isRunning","execute","Array","isArray","scheduled","disposed","push","scheduleExecute","queueMicrotask","dep","keys","isFirst","executeWithTracking","oldCleanups","splice","myContext","tracking","WeakMap","previousEffect","proxy","registerEffect","get","has","cleanup","collectItemBindings","bindings","node","getAttribute","hasAttribute","querySelectorAll","applyItemBindings","item","index","b","defaultFocusPreservation","container","activeEl","document","activeElement","contains","selectionStart","selectionEnd","body","focus","setSelectionRange","defaultScrollPreservation","context","isReorder","scrollTop","anchorElement","anchorOffset","containerRect","getBoundingClientRect","child","firstElementChild","nextElementSibling","rect","bottom","top","newRect","scrollAdjustment","globalEnabled","globalFilter","stats","Map","matchesFilter","includes","RegExp","test","incrementStat","label","s","gets","sets","notifies","getStats","map","formatValue","json","JSON","stringify","slice","MAX_LOG_LEN","debug","enable","log","disable","isEnabled","filter","pattern","getFilter","data","Object","fromEntries","logStats","this","group","entries","tableData","allKeys","table","groupEnd","resetStats","clear","serializeKeys","watched","out","k","show","hidden","className","boolAttr","toggleAttribute","ariaAttr","fullName","startsWith","DANGEROUS_SCHEME","URI_ATTRS","stringAttr","removeAttribute","strVal","attached","BOOL_ATTRS","STRING_ATTRS","ARIA_BOOL_ATTRS","ARIA_STRING_ATTRS","formHandlers","a11yHandlers","then","iterations","size","wave","from","effects","runBeforeFlushHooks","notifySubscribers","fx","takeEffects","err","flushBatchedStates","root","options","HTMLElement","immediate","handlers","userHandlers","defaults","merged","h","flat","values","mergeHandlers","performBinding","selector","join","elements","c","inputHandler","e","binding","valueAsNumber","addEventListener","removeEventListener","forEach","readyState","onReady","once","names","classList","toggle","cachedValue","isInitialized","isInComputation","subscribers","cleanupEffect","newValue","is","callback","subscribe","indexOf","dispose","getOpt","defaultVal","onInit","onGet","onSet","oldValue","trace","onSubscribe","onNotify","validate","querySelector","parse","types","byType","prev","storageKey","storage","globalThis","localStorage","getItem","stored","raw","readStored","prototype","hasOwnProperty","call","lastWritten","flushSave","setItem","unsubs","first","arrayKey","render","create","update","remove","template","element","preserveFocus","preserveScroll","containerEl","templateRoot","templateEl","content","children","resolveTemplateRoot","elementsByKey","prevItemsByKey","prevIndexByKey","cleanupByKey","bindingsByKey","seenKeys","createElement","cloneNode","updateList","items","nextEls","isFirstRender","prevItem","prevIndex","shouldPreserve","restoreFocus","restoreScroll","ptr","firstChild","desired","insertBefore","nextSibling","next","removeChild","reconcileDOM","applyPreservation","unsubscribe","replaceChildren","subResult","isFrozen","isSealed","listeners","pendingNotifications","pendingEffects","beforeFlushHooks","flushScheduled","subs","batchHandle","defineProperty","noopUnsubscribe","addListener","kind","idx","executeFn","BLOCKED_KEYS","Proxy","reader","handle","$beforeFlush","skipped","plugins","p","freeze","flushUnsub","method","subKey","r"],"mappings":"kCASO,SAASA,EAAQC,KAAQC,QACP,IAAZC,SAAmD,mBAAjBA,QAAQC,MACnDD,QAAQC,KAAKH,KAAQC,EAEzB,CAEO,SAASG,EAASJ,KAAQC,QACR,IAAZC,SAAoD,mBAAlBA,QAAQG,OACnDH,QAAQG,MAAML,KAAQC,EAE1B,CCDO,MAAMK,EAAuB,IAEpC,IAAIC,EAAa,EACjB,MAAMC,MAAoBC,IC6BpBC,MAAcD,IAaPE,EAAiBC,OAAOC,IAAI,iBAqBlC,SAASC,EAAiBC,EAA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