lume-js 2.2.0 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -15
- package/dist/addons.min.mjs +1 -1
- package/dist/addons.mjs +12 -3
- package/dist/addons.mjs.map +1 -1
- package/dist/handlers.min.mjs +1 -1
- package/dist/handlers.mjs +12 -2
- package/dist/handlers.mjs.map +1 -1
- package/dist/index.min.mjs +1 -1
- package/dist/index.mjs +2 -2
- 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-Dcokqj5a.mjs → shared-x2HJmEyO.mjs} +12 -1
- package/dist/shared-x2HJmEyO.mjs.map +1 -0
- package/package.json +1 -1
- package/src/addons/computed.js +5 -0
- package/src/addons/hydrateState.js +32 -4
- package/src/addons/withPlugins.js +7 -1
- package/src/core/bindDom.js +5 -0
- package/src/core/state.js +20 -1
- package/src/handlers/stringAttr.js +14 -2
- package/dist/shared-Dcokqj5a.mjs.map +0 -1
|
@@ -2,8 +2,16 @@
|
|
|
2
2
|
* Reads initial state from a `<script type="application/json">` element
|
|
3
3
|
* embedded in the server-rendered HTML. Useful for SSR / hydration patterns.
|
|
4
4
|
*
|
|
5
|
+
* @security Hydration trusts the DOM. An attacker who can inject HTML before
|
|
6
|
+
* the legitimate script (DOM clobbering) can control the parsed data. The
|
|
7
|
+
* element must be a real `<script type="application/json">` tag; non-script
|
|
8
|
+
* elements are rejected. Use the optional `validate` parameter to enforce a
|
|
9
|
+
* schema (e.g., whitelist allowed keys) before passing to `state()`.
|
|
10
|
+
*
|
|
5
11
|
* @param {string} [selector='#__LUME_DATA__'] - CSS selector for the script element
|
|
6
|
-
* @
|
|
12
|
+
* @param {function} [validate] - Optional validator: (data) => boolean. If it
|
|
13
|
+
* returns false, hydrateState returns {} instead of the parsed data.
|
|
14
|
+
* @returns {object} Parsed JSON object, or empty object if not found / invalid / rejected
|
|
7
15
|
*
|
|
8
16
|
* @example
|
|
9
17
|
* ```html
|
|
@@ -16,15 +24,35 @@
|
|
|
16
24
|
* import { state } from 'lume-js';
|
|
17
25
|
* import { hydrateState } from 'lume-js/addons';
|
|
18
26
|
*
|
|
19
|
-
*
|
|
27
|
+
* // With optional schema validation
|
|
28
|
+
* const data = hydrateState('#__LUME_DATA__', d =>
|
|
29
|
+
* typeof d.title === 'string' && typeof d.count === 'number'
|
|
30
|
+
* );
|
|
31
|
+
* const store = state(data);
|
|
20
32
|
* ```
|
|
21
33
|
*/
|
|
22
|
-
export function hydrateState(selector = '#__LUME_DATA__') {
|
|
34
|
+
export function hydrateState(selector = '#__LUME_DATA__', validate) {
|
|
23
35
|
const el = typeof document !== 'undefined' ? document.querySelector(selector) : null;
|
|
24
36
|
if (!el) return {};
|
|
37
|
+
|
|
38
|
+
// Reject non-script elements or scripts without the correct type.
|
|
39
|
+
// This mitigates DOM clobbering where an attacker injects a matching
|
|
40
|
+
// element with a different tag name (e.g., a div or a script with
|
|
41
|
+
// a different type that would still match querySelector by id).
|
|
42
|
+
if (el.tagName !== 'SCRIPT' || el.type !== 'application/json') {
|
|
43
|
+
return {};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let data;
|
|
25
47
|
try {
|
|
26
|
-
|
|
48
|
+
data = JSON.parse(el.textContent);
|
|
27
49
|
} catch {
|
|
28
50
|
return {};
|
|
29
51
|
}
|
|
52
|
+
|
|
53
|
+
if (typeof validate === 'function' && !validate(data)) {
|
|
54
|
+
return {};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return data;
|
|
30
58
|
}
|
|
@@ -24,6 +24,10 @@
|
|
|
24
24
|
* onNotify(key, value) — called before subscribers are notified
|
|
25
25
|
* onSubscribe(key) — called when $subscribe is invoked
|
|
26
26
|
*
|
|
27
|
+
* @security Plugins run with full application privilege. A plugin can read
|
|
28
|
+
* all state, alter any write, or suppress mutations. Only pass trusted objects.
|
|
29
|
+
* Plugin objects are frozen after registration to prevent post-init mutation.
|
|
30
|
+
*
|
|
27
31
|
* @param {object} store - A reactive proxy from state()
|
|
28
32
|
* @param {Array<object>} plugins - Array of plugin objects
|
|
29
33
|
* @returns {Proxy} A new proxy wrapping the store with plugin behavior
|
|
@@ -33,13 +37,15 @@ import { logError } from '../utils/log.js';
|
|
|
33
37
|
export function withPlugins(store, plugins = []) {
|
|
34
38
|
if (!plugins.length) return store;
|
|
35
39
|
|
|
36
|
-
// Call onInit hooks once at wrap time
|
|
40
|
+
// Call onInit hooks once at wrap time, then freeze each plugin to prevent
|
|
41
|
+
// post-registration mutation of its hooks (defense-in-depth).
|
|
37
42
|
for (const p of plugins) {
|
|
38
43
|
try {
|
|
39
44
|
p.onInit?.();
|
|
40
45
|
} catch (e) {
|
|
41
46
|
logError(`[Lume.js] Plugin "${p.name}" error in onInit:`, e);
|
|
42
47
|
}
|
|
48
|
+
Object.freeze(p);
|
|
43
49
|
}
|
|
44
50
|
|
|
45
51
|
// Track pending notifications for onNotify hooks.
|
package/src/core/bindDom.js
CHANGED
|
@@ -24,6 +24,11 @@
|
|
|
24
24
|
* Usage:
|
|
25
25
|
* import { bindDom } from "lume-js";
|
|
26
26
|
* const cleanup = bindDom(document.body, store);
|
|
27
|
+
*
|
|
28
|
+
* @security `data-bind` attribute values are resolved once at bind time and
|
|
29
|
+
* trusted as state path expressions. If an attacker can inject `data-bind`
|
|
30
|
+
* attributes into the DOM, they can subscribe to any reachable reactive state.
|
|
31
|
+
* Ensure your HTML is trusted or sanitize it before calling bindDom().
|
|
27
32
|
*/
|
|
28
33
|
|
|
29
34
|
import { logWarn } from '../utils/log.js';
|
package/src/core/state.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* unsub(); // cleanup
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
|
-
import { logError } from '../utils/log.js';
|
|
25
|
+
import { logError, logWarn } from '../utils/log.js';
|
|
26
26
|
|
|
27
27
|
// Per-state batching – each state object maintains its own microtask flush.
|
|
28
28
|
// This keeps effects simple and aligned with Lume's minimal philosophy.
|
|
@@ -55,6 +55,12 @@ const readers = new Set();
|
|
|
55
55
|
*
|
|
56
56
|
* Internal API — used by effect.js for auto-tracking. May be stabilized
|
|
57
57
|
* for third-party addons in a future release.
|
|
58
|
+
*
|
|
59
|
+
* @security The observer sees reads from ALL state instances within the same
|
|
60
|
+
* module instance, including nested scopes. Only pass trusted observer functions.
|
|
61
|
+
* A future scoped variant (e.g., scopedReadObserver(store, fn)) may limit
|
|
62
|
+
* observation to a single state instance.
|
|
63
|
+
*
|
|
58
64
|
* @param {function} onRead - Called on each property access inside fn
|
|
59
65
|
* @param {function} fn - The function to run under observation
|
|
60
66
|
*/
|
|
@@ -191,6 +197,8 @@ export function state(obj) {
|
|
|
191
197
|
};
|
|
192
198
|
};
|
|
193
199
|
|
|
200
|
+
const BLOCKED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
201
|
+
|
|
194
202
|
const proxy = new Proxy(obj, {
|
|
195
203
|
get(target, key) {
|
|
196
204
|
// Skip effect tracking for internal meta methods (e.g. $subscribe)
|
|
@@ -211,6 +219,11 @@ export function state(obj) {
|
|
|
211
219
|
},
|
|
212
220
|
|
|
213
221
|
set(target, key, value) {
|
|
222
|
+
if (typeof key === 'string' && BLOCKED_KEYS.has(key)) {
|
|
223
|
+
logWarn(`[Lume.js state] Blocked write to reserved key "${key}"`);
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
|
|
214
227
|
const oldValue = target[key];
|
|
215
228
|
|
|
216
229
|
// Skip update if value unchanged - Object.is() handles NaN and -0 correctly
|
|
@@ -256,12 +269,18 @@ export function state(obj) {
|
|
|
256
269
|
};
|
|
257
270
|
};
|
|
258
271
|
|
|
272
|
+
const MAX_SUBSCRIBERS = 1000;
|
|
273
|
+
|
|
259
274
|
obj.$subscribe = (key, fn) => {
|
|
260
275
|
if (typeof fn !== 'function') {
|
|
261
276
|
throw new Error('Subscriber must be a function');
|
|
262
277
|
}
|
|
263
278
|
|
|
264
279
|
if (!listeners[key]) listeners[key] = [];
|
|
280
|
+
if (listeners[key].length >= MAX_SUBSCRIBERS) {
|
|
281
|
+
logWarn(`[Lume.js state] Subscriber limit (${MAX_SUBSCRIBERS}) reached for key "${key}". New subscriber ignored.`);
|
|
282
|
+
return () => {};
|
|
283
|
+
}
|
|
265
284
|
listeners[key].push(fn);
|
|
266
285
|
|
|
267
286
|
// Call immediately with current value (NOT batched)
|
|
@@ -5,12 +5,24 @@
|
|
|
5
5
|
* @param {string} name - HTML attribute name (e.g., 'href', 'src', 'title')
|
|
6
6
|
* @returns {{ attr: string, apply: function }}
|
|
7
7
|
*/
|
|
8
|
+
|
|
9
|
+
const DANGEROUS_SCHEME = /^(javascript|vbscript|data\s*:\s*text\/html)/i;
|
|
10
|
+
const URI_ATTRS = new Set(['href', 'src', 'action', 'srcset', 'poster', 'formaction']);
|
|
11
|
+
|
|
8
12
|
export function stringAttr(name) {
|
|
9
13
|
return {
|
|
10
14
|
attr: `data-${name}`,
|
|
11
15
|
apply(el, val) {
|
|
12
|
-
if (val == null)
|
|
13
|
-
|
|
16
|
+
if (val == null) {
|
|
17
|
+
el.removeAttribute(name);
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
const strVal = String(val);
|
|
21
|
+
if (URI_ATTRS.has(name) && DANGEROUS_SCHEME.test(strVal)) {
|
|
22
|
+
el.removeAttribute(name);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
el.setAttribute(name, strVal);
|
|
14
26
|
}
|
|
15
27
|
};
|
|
16
28
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"shared-Dcokqj5a.mjs","sources":["../src/utils/log.js","../src/core/state.js","../src/core/effect.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","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}"],"names":["effect"],"mappings":"AASO,SAAS,QAAQ,QAAQ,MAAM;AACpC,MAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,SAAS,YAAY;AACxE,YAAQ,KAAK,KAAK,GAAG,IAAI;AAAA,EAC3B;AACF;AAEO,SAAS,SAAS,QAAQ,MAAM;AACrC,MAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,UAAU,YAAY;AACzE,YAAQ,MAAM,KAAK,GAAG,IAAI;AAAA,EAC5B;AACF;AC6BA,MAAM,UAAU,oBAAI,IAAG;AAYhB,SAAS,iBAAiB,QAAQ,IAAI;AAC3C,UAAQ,IAAI,MAAM;AAClB,MAAI;AACF,WAAO,GAAE;AAAA,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