@slimlib/store 2.0.1 → 2.0.3

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/src/core.ts DELETED
@@ -1,434 +0,0 @@
1
- /**
2
- * Core reactive system implementation using push/pull algorithm:
3
- *
4
- * PUSH PHASE: When a source value changes (signal/state write):
5
- * - Increment globalVersion
6
- * - Eagerly propagate CHECK flags to all dependents
7
- * - Schedule effects for execution
8
- *
9
- * PULL PHASE: When a computed/effect is read:
10
- * - Check if recomputation is needed (via flags and source versions)
11
- * - Lazily recompute by pulling values from sources
12
- * - Update cached value and version
13
- */
14
-
15
- import { computedRead } from './computed';
16
- import { Flag } from './flags';
17
- import { scheduler } from './globals';
18
- import { unwrap } from './symbols';
19
- import type { ReactiveNode, SourceEntry } from './internal-types';
20
-
21
- /**
22
- * No-op getter used as default for DepsSet.$_getter to ensure all DepsSet
23
- * instances have the same field representation (function, never undefined).
24
- * This avoids V8 field representation deopts when some DepsSets have a getter
25
- * and others don't.
26
- */
27
- /* v8 ignore next -- @preserve */
28
- export const noopGetter = (): unknown => undefined;
29
-
30
- /**
31
- * DepsSet extends Set with $_version and $_getter properties for dependency
32
- * tracking. Using a class ensures all instances share the same V8 hidden class,
33
- * avoiding hidden class transitions and field constness changes.
34
- *
35
- * IMPORTANT: $_getter always defaults to a no-op function (never undefined)
36
- * so that all DepsSet instances share the same V8 field representation.
37
- * This prevents "dependent field representation changed" deopts.
38
- */
39
- export class DepsSet<T> extends Set<T> {
40
- $_version = 0;
41
- $_getter: () => unknown;
42
- constructor(getter: () => unknown) {
43
- super();
44
- this.$_getter = getter;
45
- }
46
- }
47
-
48
- /**
49
- * Factory for creating source entries (unified allocation site).
50
- *
51
- * Both state and computed source entries MUST be created through this single
52
- * factory to ensure they share the same V8 hidden class. Using separate
53
- * object literals in different functions creates different allocation sites,
54
- * causing V8 to assign different hidden classes and making all property
55
- * accesses on source entries polymorphic.
56
- *
57
- * @param dependents - The DepsSet tracking dependents of this source
58
- * @param node - The source ReactiveNode (undefined for state/signal sources)
59
- * @param version - Initial version number
60
- * @param getter - Value getter (undefined for computed sources)
61
- * @param storedValue - Cached value (undefined for computed sources)
62
- */
63
- export const createSourceEntry = (
64
- dependents: DepsSet<ReactiveNode>,
65
- node: ReactiveNode | undefined,
66
- version: number,
67
- getter: undefined | (() => unknown),
68
- storedValue: unknown
69
- ): SourceEntry => ({
70
- $_dependents: dependents,
71
- $_node: node,
72
- $_version: version,
73
- $_getter: getter,
74
- $_storedValue: storedValue,
75
- });
76
-
77
- let flushScheduled = false;
78
-
79
- /**
80
- * Global version counter - increments on every signal/state write
81
- * Used for fast-path: if globalVersion hasn't changed since last read, skip all checks
82
- */
83
- export let globalVersion = 1;
84
-
85
- export const batched: ReactiveNode[] = [];
86
-
87
- let lastAddedId = 0;
88
-
89
- let needsSort = false;
90
-
91
- // Computation tracking state
92
- export let currentComputing: ReactiveNode | undefined;
93
- export let tracked = true;
94
-
95
- /**
96
- * Set the tracked state for dependency tracking (internal use only)
97
- */
98
- export const setTracked = (value: boolean) => {
99
- tracked = value;
100
- };
101
-
102
- /**
103
- * Add an effect to the batched set
104
- * PUSH PHASE: Part of effect scheduling during dirty propagation
105
- * Caller must check Flag.NEEDS_WORK before calling to avoid duplicates
106
- */
107
- export const batchedAdd = (node: ReactiveNode): void => {
108
- const nodeId = node.$_stamp;
109
- // Track if we're adding out of order
110
- if (nodeId < lastAddedId) {
111
- needsSort = true;
112
- }
113
- lastAddedId = nodeId;
114
- batched.push(node);
115
- };
116
-
117
- /**
118
- * Add a newly created effect to the batched set
119
- * Used during effect creation - new effects always have the highest ID
120
- * so we unconditionally update lastAddedId without checking order
121
- */
122
- export const batchedAddNew = (node: ReactiveNode, effectId: number): void => {
123
- lastAddedId = effectId;
124
- batched.push(node);
125
- };
126
-
127
- /**
128
- * Unwraps a proxied value to get the underlying object
129
- * (Utility - not specific to push/pull phases)
130
- */
131
- export const unwrapValue = <T>(value: T): T =>
132
- (value !== null &&
133
- (typeof value === 'object' || typeof value === 'function') &&
134
- ((value as unknown as Record<symbol, unknown>)[unwrap] as T)) ||
135
- value;
136
-
137
- /**
138
- * Make a computed live - register it with all its sources
139
- * Called when a live consumer starts reading this computed
140
- * PUSH PHASE: Enables push notifications to flow through this node
141
- */
142
- export const makeLive = (node: ReactiveNode): void => {
143
- node.$_flags |= Flag.LIVE;
144
- const nodeSources = node.$_sources;
145
- for (let i = 0, len = nodeSources.length; i < len; ++i) {
146
- const { $_dependents, $_node: sourceNode } = nodeSources[i] as SourceEntry;
147
- $_dependents.add(node);
148
- if (sourceNode !== undefined && (sourceNode.$_flags & (Flag.EFFECT | Flag.LIVE)) === 0) {
149
- makeLive(sourceNode);
150
- }
151
- }
152
- };
153
-
154
- /**
155
- * Make a computed non-live - unregister it from all its sources
156
- * Called when all live consumers stop depending on this computed
157
- * PUSH PHASE: Disables push notifications through this node
158
- */
159
- export const makeNonLive = (node: ReactiveNode): void => {
160
- node.$_flags &= ~Flag.LIVE;
161
- const nodeSources = node.$_sources;
162
- for (let i = 0, len = nodeSources.length; i < len; ++i) {
163
- const { $_dependents, $_node: sourceNode } = nodeSources[i] as SourceEntry;
164
- $_dependents.delete(node);
165
- // Check: has Flag.LIVE but not Flag.EFFECT (effects never become non-live)
166
- if (
167
- sourceNode !== undefined &&
168
- (sourceNode.$_flags & (Flag.EFFECT | Flag.LIVE)) === Flag.LIVE &&
169
- (sourceNode.$_deps as Set<ReactiveNode>).size === 0
170
- ) {
171
- makeNonLive(sourceNode);
172
- }
173
- }
174
- };
175
-
176
- /**
177
- * Clear sources for a node starting from a specific index
178
- * PULL PHASE: Cleanup during dependency tracking when sources change
179
- */
180
- export const clearSources = (node: ReactiveNode, fromIndex = 0): void => {
181
- const isLive = (node.$_flags & (Flag.EFFECT | Flag.LIVE)) !== 0;
182
- const nodeSources = node.$_sources;
183
-
184
- for (let i = fromIndex, len = nodeSources.length; i < len; ++i) {
185
- const { $_dependents, $_node: sourceNode } = nodeSources[i] as SourceEntry;
186
-
187
- // Check if this deps is retained (exists in kept portion) - avoid removing shared deps
188
- let retained = false;
189
- for (let j = 0; j < fromIndex && !retained; ++j) {
190
- retained = (nodeSources[j] as SourceEntry).$_dependents === $_dependents;
191
- }
192
-
193
- if (!retained) {
194
- // Always remove from deps to prevent stale notifications
195
- $_dependents.delete(node);
196
- // If source is a computed and we're live, check if it became non-live
197
- if (
198
- isLive &&
199
- sourceNode !== undefined &&
200
- (sourceNode.$_flags & (Flag.EFFECT | Flag.LIVE)) === Flag.LIVE &&
201
- (sourceNode.$_deps as Set<ReactiveNode>).size === 0
202
- ) {
203
- makeNonLive(sourceNode);
204
- }
205
- }
206
- }
207
- nodeSources.length = fromIndex;
208
- };
209
-
210
- /**
211
- * Execute all pending effects immediately
212
- * This function can be called to manually trigger all scheduled effects
213
- * before the next microtask
214
- * PULL PHASE: Executes batched effects, each effect pulls its dependencies
215
- */
216
- export const flushEffects = (): void => {
217
- flushScheduled = false;
218
- // Collect nodes, only sort if effects were added out of order
219
- // Use a copy of the array for execution to allow re-scheduling
220
- const nodes = batched.slice();
221
- batched.length = 0;
222
-
223
- if (needsSort) {
224
- nodes.sort((a, b) => a.$_stamp - b.$_stamp);
225
- }
226
-
227
- lastAddedId = 0;
228
- needsSort = false;
229
-
230
- // Call $_fn on each node instead of calling nodes directly as functions
231
- // This enables effect nodes to be plain objects (same hidden class as computed)
232
- for (let i = 0, len = nodes.length; i < len; ++i) {
233
- const node = nodes[i] as ReactiveNode;
234
- try {
235
- node.$_fn?.();
236
- } catch (e) {
237
- console.error(e);
238
- }
239
- }
240
- };
241
-
242
- /**
243
- * Schedule flush via scheduler (default: microtask)
244
- * PUSH PHASE: Schedules the transition from push to pull phase
245
- */
246
- export const scheduleFlush = (): void => {
247
- if (!flushScheduled) {
248
- flushScheduled = true;
249
- scheduler(flushEffects);
250
- }
251
- };
252
-
253
- /**
254
- * Track a state/signal dependency between currentComputing and a deps Set
255
- * Uses liveness tracking - only live consumers register with sources
256
- * PULL PHASE: Records dependencies during computation for future invalidation
257
- */
258
- export const trackStateDependency = <T>(deps: DepsSet<ReactiveNode>, valueGetter: () => T, cachedValue: T): void => {
259
- // Callers guarantee tracked && currentComputing are true
260
-
261
- const sourcesArray = (currentComputing as ReactiveNode).$_sources;
262
- const skipIndex = (currentComputing as ReactiveNode).$_skipped;
263
- const existing = sourcesArray[skipIndex];
264
- const noSource = existing === undefined;
265
-
266
- if (noSource || existing.$_dependents !== deps) {
267
- // Different dependency - clear old ones from this point and rebuild
268
- if (!noSource) {
269
- clearSources(currentComputing as ReactiveNode, skipIndex);
270
- }
271
-
272
- // Track deps version, value getter, and last seen value for polling
273
- // Uses shared createSourceEntry factory for V8 hidden class monomorphism
274
- sourcesArray.push(
275
- createSourceEntry(deps, undefined, (deps as DepsSet<ReactiveNode>).$_version as number, valueGetter, cachedValue)
276
- );
277
-
278
- // Mark that this node has state/signal sources (for polling optimization)
279
- (currentComputing as ReactiveNode).$_flags |= Flag.HAS_STATE_SOURCE;
280
-
281
- // Only register with source if we're live
282
- if (((currentComputing as ReactiveNode).$_flags & (Flag.EFFECT | Flag.LIVE)) !== 0) {
283
- deps.add(currentComputing as ReactiveNode);
284
- }
285
- } else {
286
- // Same state source - update depsVersion, getter, and storedValue for accurate polling
287
- const entry = sourcesArray[skipIndex] as SourceEntry;
288
- entry.$_version = (deps as DepsSet<ReactiveNode>).$_version as number;
289
- entry.$_getter = valueGetter;
290
- entry.$_storedValue = cachedValue;
291
- // Re-set Flag.HAS_STATE_SOURCE (may have been cleared by runWithTracking)
292
- (currentComputing as ReactiveNode).$_flags |= Flag.HAS_STATE_SOURCE;
293
- }
294
- ++(currentComputing as ReactiveNode).$_skipped;
295
- };
296
-
297
- /**
298
- * Mark a node as needing check (eager propagation with equality cutoff)
299
- * PUSH PHASE: Eagerly propagates CHECK flag up the dependency graph
300
- */
301
- export const markNeedsCheck = (node: ReactiveNode): void => {
302
- const flags = node.$_flags;
303
- // Fast path: skip if already computing, dirty, or marked CHECK
304
- // (COMPUTING | DIRTY | CHECK) (bits 0, 1, 2)
305
- if ((flags & (Flag.COMPUTING | Flag.DIRTY | Flag.CHECK)) !== 0) {
306
- // Exception: computing effect that's not dirty yet needs to be marked dirty
307
- // Uses combined mask: (flags & 13) === 12 means COMPUTING + EFFECT set, DIRTY not set
308
- if ((flags & (Flag.COMPUTING | Flag.EFFECT | Flag.DIRTY)) === (Flag.COMPUTING | Flag.EFFECT)) {
309
- node.$_flags = flags | Flag.DIRTY;
310
- batchedAdd(node);
311
- scheduleFlush();
312
- }
313
- return;
314
- }
315
- // Not skipped: set CHECK and propagate to dependents
316
- node.$_flags = flags | Flag.CHECK;
317
- if ((flags & Flag.EFFECT) !== 0) {
318
- batchedAdd(node);
319
- scheduleFlush();
320
- }
321
- for (const dep of node.$_deps) {
322
- markNeedsCheck(dep);
323
- }
324
- };
325
-
326
- /**
327
- * Mark all dependents in a Set as needing check
328
- * PUSH PHASE: Entry point for push propagation when a source value changes
329
- */
330
- export const markDependents = (deps: DepsSet<ReactiveNode>): void => {
331
- ++globalVersion;
332
- // Increment deps version for non-live computed polling
333
- ++deps.$_version;
334
- for (const dep of deps) {
335
- markNeedsCheck(dep);
336
- }
337
- };
338
-
339
- /**
340
- * Run a getter function with dependency tracking
341
- * Handles cycle detection, context setup, and source cleanup
342
- * PULL PHASE: Core of pull - executes computation while tracking dependencies
343
- */
344
- export const runWithTracking = <T>(node: ReactiveNode, getter: () => T): T => {
345
- // Clear (DIRTY | CHECK) and source flags (will be recalculated during tracking)
346
- // Note: Even when called from checkComputedSources (which sets tracked=false), this works
347
- // because runWithTracking sets tracked=true, so trackDependency will re-set the flag
348
- node.$_flags = (node.$_flags & ~(Flag.DIRTY | Flag.CHECK | Flag.HAS_STATE_SOURCE | Flag.HAS_COMPUTED_SOURCE)) | Flag.COMPUTING;
349
- node.$_skipped = 0;
350
-
351
- const prev = currentComputing;
352
- const prevTracked = tracked;
353
- currentComputing = node;
354
- tracked = true;
355
-
356
- try {
357
- return getter();
358
- } finally {
359
- currentComputing = prev;
360
- tracked = prevTracked;
361
- // biome-ignore lint/suspicious/noAssignInExpressions: optimization
362
- const flags = (node.$_flags &= ~Flag.COMPUTING);
363
- const nodeSources = node.$_sources;
364
- const skipped = node.$_skipped;
365
- const nodeSourcesLength = nodeSources.length;
366
- // Only update versions if there are computed sources (state sources update inline)
367
- if ((flags & Flag.HAS_COMPUTED_SOURCE) !== 0) {
368
- const updateLen = Math.min(skipped, nodeSourcesLength);
369
- for (let i = 0; i < updateLen; ++i) {
370
- const entry = nodeSources[i] as SourceEntry;
371
- const entryNode = entry.$_node;
372
- if (entryNode !== undefined) {
373
- entry.$_version = entryNode.$_version;
374
- }
375
- }
376
- }
377
- // Clean up any excess sources that weren't reused
378
- if (nodeSourcesLength > skipped) {
379
- clearSources(node, skipped);
380
- }
381
- }
382
- };
383
-
384
- /**
385
- * Execute a callback without tracking any reactive dependencies
386
- * Useful when reading signals/state without creating a dependency relationship
387
- * PULL PHASE: Temporarily disables dependency tracking during pull
388
- */
389
- export const untracked = <T>(callback: () => T): T => {
390
- const prevTracked = tracked;
391
- tracked = false;
392
- try {
393
- return callback();
394
- } finally {
395
- tracked = prevTracked;
396
- }
397
- };
398
-
399
- /**
400
- * Check if any computed sources have changed or errored.
401
- * Used by CHECK path optimization in computed and effect.
402
- * PULL PHASE: Verifies if sources actually changed before recomputing (equality cutoff)
403
- *
404
- * Note: Callers must check HAS_STATE_SOURCE flag before calling this function.
405
- * This function assumes all sources are computed (have $_node).
406
- *
407
- * @param sourcesArray - The sources to check (must all be computed sources)
408
- * @returns true if sources changed, false if unchanged
409
- */
410
- export const checkComputedSources = (sourcesArray: SourceEntry[]): boolean => {
411
- const prevTracked = tracked;
412
- tracked = false;
413
- const len = sourcesArray.length;
414
- for (let i = 0; i < len; ++i) {
415
- const sourceEntry = sourcesArray[i] as SourceEntry;
416
- const sourceNode = sourceEntry.$_node as ReactiveNode;
417
- // Access source to trigger its recomputation if needed
418
- try {
419
- computedRead(sourceNode);
420
- } catch {
421
- // Error counts as changed - caller will recompute and may handle differently
422
- tracked = prevTracked;
423
- return true;
424
- }
425
- // Check if source version changed (meaning its value changed)
426
- // Early exit - runWithTracking will update all versions during recomputation
427
- if (sourceEntry.$_version !== sourceNode.$_version) {
428
- tracked = prevTracked;
429
- return true;
430
- }
431
- }
432
- tracked = prevTracked;
433
- return false;
434
- };
package/src/debug.ts DELETED
@@ -1,115 +0,0 @@
1
- import { DEV } from 'esm-env';
2
-
3
- import { currentComputing } from './core';
4
- import { Flag } from './flags';
5
- import type { Scope } from './types';
6
-
7
- /**
8
- * Debug configuration flag: Warn when writing to signals/state inside a computed
9
- */
10
- export const WARN_ON_WRITE_IN_COMPUTED = 1 << 0;
11
-
12
- /**
13
- * Debug configuration flag: Suppress warning when effects are disposed by GC instead of explicitly
14
- */
15
- export const SUPPRESS_EFFECT_GC_WARNING = 1 << 1;
16
-
17
- /**
18
- * Debug configuration flag: Warn when effects are created without an active scope
19
- * This is an allowed pattern, but teams may choose to enforce scope usage for better effect lifecycle management
20
- */
21
- export const WARN_ON_UNTRACKED_EFFECT = 1 << 2;
22
-
23
- /**
24
- * Current debug configuration bitfield
25
- */
26
- let debugConfigFlags = 0;
27
-
28
- /**
29
- * Configure debug behavior using a bitfield of flags
30
- */
31
- export const debugConfig = (flags: number): void => {
32
- debugConfigFlags = flags | 0;
33
- };
34
-
35
- /**
36
- * Safely call each function in an iterable, logging any errors to console
37
- */
38
- export const safeForEach = (fns: Array<() => void>): void => {
39
- for (let i = 0, len = fns.length; i < len; ++i) {
40
- const fn = fns[i] as () => void;
41
- try {
42
- fn?.();
43
- } catch (e) {
44
- console.error(e);
45
- }
46
- }
47
- };
48
-
49
- /**
50
- * Warn if writing inside a computed (not an effect)
51
- * Only runs in DEV mode and when configured
52
- */
53
- export const warnIfWriteInComputed = (context: string): void => {
54
- if (DEV && (debugConfigFlags & WARN_ON_WRITE_IN_COMPUTED) !== 0 && currentComputing && (currentComputing.$_flags & Flag.EFFECT) === 0) {
55
- console.warn(
56
- `[@slimlib/store] Writing to ${context} inside a computed is not recommended. The computed will not automatically re-run when this value changes, which may lead to stale values.`
57
- );
58
- }
59
- };
60
-
61
- /**
62
- * FinalizationRegistry for detecting effects that are GC'd without being properly disposed.
63
- * Only created in DEV mode.
64
- */
65
- const effectRegistry: FinalizationRegistry<string> | null = DEV
66
- ? new FinalizationRegistry((stackTrace: string) => {
67
- if ((debugConfigFlags & SUPPRESS_EFFECT_GC_WARNING) === 0) {
68
- console.warn(
69
- `[@slimlib/store] Effect was garbage collected without being disposed. This may indicate a memory leak. Effects should be disposed by calling the returned dispose function or by using a scope that is properly disposed.\n\nEffect was created at:\n${stackTrace}`
70
- );
71
- }
72
- })
73
- : null;
74
-
75
- /**
76
- * Register an effect for GC tracking.
77
- * Returns a token that must be passed to unregisterEffect when the effect is properly disposed.
78
- * Only active in DEV mode; returns undefined in production.
79
- */
80
- export const registerEffect: () => object | undefined = DEV
81
- ? () => {
82
- const token = {};
83
- // Capture stack trace at effect creation for better debugging
84
- // Remove the first few lines (Error + registerEffect call) to get to the actual effect() call
85
- const relevantStack = String(new Error().stack).split('\n').slice(3).join('\n');
86
- (effectRegistry as FinalizationRegistry<string>).register(token, relevantStack, token);
87
- return token;
88
- }
89
- : () => undefined;
90
-
91
- /**
92
- * Unregister an effect from GC tracking (called when effect is properly disposed).
93
- * Only active in DEV mode.
94
- */
95
- export const unregisterEffect: (token: object | undefined) => void = DEV
96
- ? (token: object | undefined) => {
97
- effectRegistry?.unregister(token as WeakKey);
98
- }
99
- : () => {};
100
-
101
- /**
102
- * Warn if an effect is created without an active scope.
103
- * Only runs in DEV mode and when WARN_ON_UNTRACKED_EFFECT is enabled.
104
- */
105
- export const warnIfNoActiveScope: (activeScope: Scope | undefined) => void = DEV
106
- ? (activeScope: Scope | undefined) => {
107
- if ((debugConfigFlags & WARN_ON_UNTRACKED_EFFECT) !== 0 && !activeScope) {
108
- console.warn(
109
- `[@slimlib/store] Effect created without an active scope. Consider using scope() or setActiveScope() to track effects for proper lifecycle management.`
110
- );
111
- }
112
- }
113
- : () => {};
114
-
115
- export const cycleMessage = 'Detected cycle in computations.';
package/src/effect.ts DELETED
@@ -1,125 +0,0 @@
1
- import { batchedAddNew, checkComputedSources, clearSources, DepsSet, noopGetter, runWithTracking, scheduleFlush } from './core';
2
- import { cycleMessage, registerEffect, unregisterEffect, warnIfNoActiveScope } from './debug';
3
- import { Flag } from './flags';
4
- import { activeScope } from './globals';
5
- import { trackSymbol } from './symbols';
6
- import type { ReactiveNode } from './internal-types';
7
- import type { EffectCleanup } from './types';
8
-
9
- /**
10
- * Effect creation counter - increments on every effect creation
11
- * Used to maintain effect execution order by creation time
12
- */
13
- let effectCreationCounter = 0;
14
-
15
- /**
16
- * Creates a reactive effect that runs when dependencies change
17
- */
18
- // biome-ignore lint/suspicious/noConfusingVoidType: void is semantically correct here - callback may return nothing or a cleanup function
19
- export const effect = (callback: () => void | EffectCleanup): (() => void) => {
20
- let disposed = false;
21
-
22
- // Register effect for GC tracking (only in DEV mode)
23
- const gcToken = registerEffect();
24
-
25
- // Warn if effect is created without an active scope (only in DEV mode when enabled)
26
- warnIfNoActiveScope(activeScope);
27
-
28
- // Declare node first so the runner closure can capture it.
29
- // The variable will be assigned before the runner is ever called.
30
- let node: ReactiveNode;
31
-
32
- // Define the runner function BEFORE creating the node so that $_fn
33
- // is a function from the start (Fix #1: avoids hidden class transition
34
- // from undefined → function on the $_fn field).
35
- const runner = () => {
36
- // Skip if effect was disposed (may still be in batched queue from before disposal)
37
- if (disposed) {
38
- return;
39
- }
40
-
41
- // Cycle detection: if this node is already being computed, we have a cycle
42
- const flags = node.$_flags;
43
- if ((flags & Flag.COMPUTING) !== 0) {
44
- throw new Error(cycleMessage);
45
- }
46
-
47
- // ----------------------------------------------------------------
48
- // PULL PHASE: Verify if sources actually changed before running
49
- // ----------------------------------------------------------------
50
- // Bail-out optimization: if only CHECK flag is set (not DIRTY),
51
- // verify that computed sources actually changed before running
52
- if ((flags & (Flag.DIRTY | Flag.CHECK | Flag.HAS_STATE_SOURCE)) === Flag.CHECK) {
53
- // PULL: Read computed sources to check if they changed
54
- // If false, sources didn't change - clear CHECK flag and skip
55
- // If true, sources changed or errored - proceed to run
56
- if (!checkComputedSources(node.$_sources)) {
57
- node.$_flags = flags & ~Flag.CHECK;
58
- return;
59
- }
60
- }
61
-
62
- // ----------------------------------------------------------------
63
- // PULL PHASE: Execute effect and track dependencies
64
- // ----------------------------------------------------------------
65
- runWithTracking(node, () => {
66
- // Run previous cleanup if it exists (stored in $_value)
67
- if (typeof node.$_value === 'function') {
68
- (node.$_value as EffectCleanup)();
69
- }
70
- // Run the callback and store new cleanup in $_value
71
- // (callback will PULL values from signals/state/computed)
72
- node.$_value = callback();
73
- });
74
- };
75
-
76
- // Create effect node as a plain object with IDENTICAL initial field types
77
- // as computed nodes to ensure V8 hidden class monomorphism (Fix #2):
78
- // $_deps: new DepsSet() (Set object, same as computed — never used for effects)
79
- // $_fn: runner (function, same as computed's getter)
80
- // $_equals: Object.is (function, same as computed's equality comparator)
81
- //
82
- // $_value: stores cleanup function returned by the effect callback
83
- // $_stamp: creation order counter for effect scheduling
84
- node = {
85
- $_sources: [],
86
- $_deps: new DepsSet<ReactiveNode>(noopGetter),
87
- $_flags: Flag.DIRTY | Flag.EFFECT,
88
- $_skipped: 0,
89
- $_version: 0,
90
- $_value: undefined as unknown,
91
- $_stamp: ++effectCreationCounter,
92
- $_fn: runner,
93
- $_equals: Object.is,
94
- } as unknown as ReactiveNode;
95
-
96
- const effectId = node.$_stamp;
97
-
98
- const dispose = (): void => {
99
- // Mark as disposed to prevent running if still in batched queue
100
- disposed = true;
101
- // Unregister from GC tracking (only in DEV mode)
102
- unregisterEffect(gcToken);
103
- // Run cleanup if it exists (stored in $_value)
104
- if (typeof node.$_value === 'function') {
105
- (node.$_value as EffectCleanup)();
106
- }
107
- clearSources(node);
108
- };
109
-
110
- // Track to appropriate scope
111
- if (activeScope) {
112
- (activeScope[trackSymbol] as (dispose: () => void) => void)(dispose);
113
- }
114
-
115
- // ----------------------------------------------------------------
116
- // Initial scheduling (triggers first PULL when flush runs)
117
- // ----------------------------------------------------------------
118
- // Trigger first run via batched queue
119
- // node is already dirty
120
- // and effect is for sure with the latest id so we directly adding without the sort
121
- batchedAddNew(node, effectId);
122
- scheduleFlush();
123
-
124
- return dispose;
125
- };