@bquery/bquery 1.0.2 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +61 -7
  2. package/dist/component/index.d.ts +8 -0
  3. package/dist/component/index.d.ts.map +1 -1
  4. package/dist/component.es.mjs +80 -53
  5. package/dist/component.es.mjs.map +1 -1
  6. package/dist/core/collection.d.ts +46 -0
  7. package/dist/core/collection.d.ts.map +1 -1
  8. package/dist/core/element.d.ts +124 -22
  9. package/dist/core/element.d.ts.map +1 -1
  10. package/dist/core/utils.d.ts +13 -0
  11. package/dist/core/utils.d.ts.map +1 -1
  12. package/dist/core.es.mjs +298 -55
  13. package/dist/core.es.mjs.map +1 -1
  14. package/dist/full.d.ts +2 -2
  15. package/dist/full.d.ts.map +1 -1
  16. package/dist/full.es.mjs +38 -33
  17. package/dist/full.iife.js +1 -1
  18. package/dist/full.iife.js.map +1 -1
  19. package/dist/full.umd.js +1 -1
  20. package/dist/full.umd.js.map +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.es.mjs +38 -33
  23. package/dist/reactive/index.d.ts +2 -2
  24. package/dist/reactive/index.d.ts.map +1 -1
  25. package/dist/reactive/signal.d.ts +107 -0
  26. package/dist/reactive/signal.d.ts.map +1 -1
  27. package/dist/reactive.es.mjs +92 -55
  28. package/dist/reactive.es.mjs.map +1 -1
  29. package/dist/security/sanitize.d.ts.map +1 -1
  30. package/dist/security.es.mjs +136 -66
  31. package/dist/security.es.mjs.map +1 -1
  32. package/package.json +16 -16
  33. package/src/component/index.ts +414 -360
  34. package/src/core/collection.ts +454 -339
  35. package/src/core/element.ts +740 -493
  36. package/src/core/utils.ts +444 -425
  37. package/src/full.ts +106 -101
  38. package/src/index.ts +27 -27
  39. package/src/reactive/index.ts +22 -9
  40. package/src/reactive/signal.ts +506 -347
  41. package/src/security/sanitize.ts +553 -446
@@ -1,347 +1,506 @@
1
- /**
2
- * Reactive primitives inspired by fine-grained reactivity.
3
- *
4
- * This module provides a minimal but powerful reactive system:
5
- * - Signal: A reactive value that notifies subscribers when changed
6
- * - Computed: A derived value that automatically updates when dependencies change
7
- * - Effect: A side effect that re-runs when its dependencies change
8
- * - Batch: Group multiple updates to prevent intermediate re-renders
9
- *
10
- * @module bquery/reactive
11
- *
12
- * @example
13
- * ```ts
14
- * const count = signal(0);
15
- * const doubled = computed(() => count.value * 2);
16
- *
17
- * effect(() => {
18
- * console.log(`Count: ${count.value}, Doubled: ${doubled.value}`);
19
- * });
20
- *
21
- * batch(() => {
22
- * count.value = 1;
23
- * count.value = 2;
24
- * });
25
- * // Logs: "Count: 2, Doubled: 4" (only once due to batching)
26
- * ```
27
- */
28
-
29
- /**
30
- * Observer function type used internally for tracking reactivity.
31
- */
32
- export type Observer = () => void;
33
-
34
- /**
35
- * Cleanup function returned by effects for disposal.
36
- */
37
- export type CleanupFn = () => void;
38
-
39
- // Internal state for tracking the current observer context
40
- let observerStack: Observer[] = [];
41
- let batchDepth = 0;
42
- const pendingObservers = new Set<Observer>();
43
-
44
- /**
45
- * Tracks dependencies during a function execution.
46
- * @internal
47
- */
48
- const track = <T>(observer: Observer, fn: () => T): T => {
49
- observerStack = [...observerStack, observer];
50
- try {
51
- return fn();
52
- } finally {
53
- observerStack = observerStack.slice(0, -1);
54
- }
55
- };
56
-
57
- /**
58
- * Schedules an observer to run, respecting batch mode.
59
- * @internal
60
- */
61
- const scheduleObserver = (observer: Observer) => {
62
- if (batchDepth > 0) {
63
- pendingObservers.add(observer);
64
- return;
65
- }
66
- observer();
67
- };
68
-
69
- /**
70
- * Flushes all pending observers after a batch completes.
71
- * @internal
72
- */
73
- const flushObservers = () => {
74
- for (const observer of Array.from(pendingObservers)) {
75
- pendingObservers.delete(observer);
76
- observer();
77
- }
78
- };
79
-
80
- /**
81
- * A reactive value container that notifies subscribers on change.
82
- *
83
- * Signals are the foundational primitive of the reactive system.
84
- * Reading a signal's value inside an effect or computed automatically
85
- * establishes a reactive dependency.
86
- *
87
- * @template T - The type of the stored value
88
- *
89
- * @example
90
- * ```ts
91
- * const name = signal('World');
92
- * console.log(name.value); // 'World'
93
- *
94
- * name.value = 'bQuery';
95
- * console.log(name.value); // 'bQuery'
96
- * ```
97
- */
98
- export class Signal<T> {
99
- private subscribers = new Set<Observer>();
100
-
101
- /**
102
- * Creates a new signal with an initial value.
103
- * @param _value - The initial value
104
- */
105
- constructor(private _value: T) {}
106
-
107
- /**
108
- * Gets the current value and tracks the read if inside an observer.
109
- */
110
- get value(): T {
111
- const current = observerStack[observerStack.length - 1];
112
- if (current) {
113
- this.subscribers.add(current);
114
- }
115
- return this._value;
116
- }
117
-
118
- /**
119
- * Sets a new value and notifies all subscribers if the value changed.
120
- * Uses Object.is for equality comparison.
121
- */
122
- set value(next: T) {
123
- if (Object.is(this._value, next)) return;
124
- this._value = next;
125
- for (const subscriber of this.subscribers) {
126
- scheduleObserver(subscriber);
127
- }
128
- }
129
-
130
- /**
131
- * Reads the current value without tracking.
132
- * Useful when you need the value but don't want to create a dependency.
133
- *
134
- * @returns The current value
135
- */
136
- peek(): T {
137
- return this._value;
138
- }
139
-
140
- /**
141
- * Updates the value using a function.
142
- * Useful for updates based on the current value.
143
- *
144
- * @param updater - Function that receives current value and returns new value
145
- */
146
- update(updater: (current: T) => T): void {
147
- this.value = updater(this._value);
148
- }
149
- }
150
-
151
- /**
152
- * A computed value that derives from other reactive sources.
153
- *
154
- * Computed values are lazily evaluated and cached. They only
155
- * recompute when their dependencies change.
156
- *
157
- * @template T - The type of the computed value
158
- *
159
- * @example
160
- * ```ts
161
- * const price = signal(100);
162
- * const quantity = signal(2);
163
- * const total = computed(() => price.value * quantity.value);
164
- *
165
- * console.log(total.value); // 200
166
- * price.value = 150;
167
- * console.log(total.value); // 300
168
- * ```
169
- */
170
- export class Computed<T> {
171
- private cachedValue!: T;
172
- private dirty = true;
173
- private subscribers = new Set<Observer>();
174
- private readonly markDirty = () => {
175
- this.dirty = true;
176
- for (const subscriber of this.subscribers) {
177
- scheduleObserver(subscriber);
178
- }
179
- };
180
-
181
- /**
182
- * Creates a new computed value.
183
- * @param compute - Function that computes the value
184
- */
185
- constructor(private readonly compute: () => T) {}
186
-
187
- /**
188
- * Gets the computed value, recomputing if dependencies changed.
189
- */
190
- get value(): T {
191
- const current = observerStack[observerStack.length - 1];
192
- if (current) {
193
- this.subscribers.add(current);
194
- }
195
- if (this.dirty) {
196
- this.dirty = false;
197
- this.cachedValue = track(this.markDirty, this.compute);
198
- }
199
- return this.cachedValue;
200
- }
201
- }
202
-
203
- /**
204
- * Creates a new reactive signal.
205
- *
206
- * @template T - The type of the signal value
207
- * @param value - The initial value
208
- * @returns A new Signal instance
209
- *
210
- * @example
211
- * ```ts
212
- * const count = signal(0);
213
- * count.value++; // Triggers subscribers
214
- * ```
215
- */
216
- export const signal = <T>(value: T): Signal<T> => new Signal(value);
217
-
218
- /**
219
- * Creates a new computed value.
220
- *
221
- * @template T - The type of the computed value
222
- * @param fn - Function that computes the value from reactive sources
223
- * @returns A new Computed instance
224
- *
225
- * @example
226
- * ```ts
227
- * const doubled = computed(() => count.value * 2);
228
- * ```
229
- */
230
- export const computed = <T>(fn: () => T): Computed<T> => new Computed(fn);
231
-
232
- /**
233
- * Creates a side effect that automatically re-runs when dependencies change.
234
- *
235
- * The effect runs immediately upon creation and then re-runs whenever
236
- * any signal or computed value read inside it changes.
237
- *
238
- * @param fn - The effect function to run
239
- * @returns A cleanup function to stop the effect
240
- *
241
- * @example
242
- * ```ts
243
- * const count = signal(0);
244
- *
245
- * const cleanup = effect(() => {
246
- * document.title = `Count: ${count.value}`;
247
- * });
248
- *
249
- * // Later, to stop the effect:
250
- * cleanup();
251
- * ```
252
- */
253
- export const effect = (fn: () => void | CleanupFn): CleanupFn => {
254
- let cleanupFn: CleanupFn | void;
255
- let isDisposed = false;
256
-
257
- const observer: Observer = () => {
258
- if (isDisposed) return;
259
-
260
- // Run previous cleanup if exists
261
- if (cleanupFn) {
262
- cleanupFn();
263
- }
264
-
265
- // Run effect and capture cleanup
266
- cleanupFn = track(observer, fn);
267
- };
268
-
269
- observer();
270
-
271
- return () => {
272
- isDisposed = true;
273
- if (cleanupFn) {
274
- cleanupFn();
275
- }
276
- };
277
- };
278
-
279
- /**
280
- * Batches multiple signal updates into a single notification cycle.
281
- *
282
- * Updates made inside the batch function are deferred until the batch
283
- * completes, preventing intermediate re-renders and improving performance.
284
- *
285
- * @param fn - Function containing multiple signal updates
286
- *
287
- * @example
288
- * ```ts
289
- * batch(() => {
290
- * firstName.value = 'John';
291
- * lastName.value = 'Doe';
292
- * age.value = 30;
293
- * });
294
- * // Effects only run once with all three updates
295
- * ```
296
- */
297
- export const batch = (fn: () => void): void => {
298
- batchDepth += 1;
299
- try {
300
- fn();
301
- } finally {
302
- batchDepth -= 1;
303
- if (batchDepth === 0) {
304
- flushObservers();
305
- }
306
- }
307
- };
308
-
309
- /**
310
- * Creates a signal that persists to localStorage.
311
- *
312
- * @template T - The type of the signal value
313
- * @param key - The localStorage key
314
- * @param initialValue - The initial value if not found in storage
315
- * @returns A Signal that syncs with localStorage
316
- *
317
- * @example
318
- * ```ts
319
- * const theme = persistedSignal('theme', 'light');
320
- * theme.value = 'dark'; // Automatically saved to localStorage
321
- * ```
322
- */
323
- export const persistedSignal = <T>(key: string, initialValue: T): Signal<T> => {
324
- let stored: T = initialValue;
325
-
326
- try {
327
- const raw = localStorage.getItem(key);
328
- if (raw !== null) {
329
- stored = JSON.parse(raw) as T;
330
- }
331
- } catch {
332
- // Use initial value on parse error
333
- }
334
-
335
- const sig = signal(stored);
336
-
337
- // Create an effect to persist changes
338
- effect(() => {
339
- try {
340
- localStorage.setItem(key, JSON.stringify(sig.value));
341
- } catch {
342
- // Ignore storage errors
343
- }
344
- });
345
-
346
- return sig;
347
- };
1
+ /**
2
+ * Reactive primitives inspired by fine-grained reactivity.
3
+ *
4
+ * This module provides a minimal but powerful reactive system:
5
+ * - Signal: A reactive value that notifies subscribers when changed
6
+ * - Computed: A derived value that automatically updates when dependencies change
7
+ * - Effect: A side effect that re-runs when its dependencies change
8
+ * - Batch: Group multiple updates to prevent intermediate re-renders
9
+ *
10
+ * @module bquery/reactive
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * const count = signal(0);
15
+ * const doubled = computed(() => count.value * 2);
16
+ *
17
+ * effect(() => {
18
+ * console.log(`Count: ${count.value}, Doubled: ${doubled.value}`);
19
+ * });
20
+ *
21
+ * batch(() => {
22
+ * count.value = 1;
23
+ * count.value = 2;
24
+ * });
25
+ * // Logs: "Count: 2, Doubled: 4" (only once due to batching)
26
+ * ```
27
+ */
28
+
29
+ /**
30
+ * Observer function type used internally for tracking reactivity.
31
+ */
32
+ export type Observer = () => void;
33
+
34
+ /**
35
+ * Cleanup function returned by effects for disposal.
36
+ */
37
+ export type CleanupFn = () => void;
38
+
39
+ // Internal state for tracking the current observer context
40
+ const observerStack: Observer[] = [];
41
+ let batchDepth = 0;
42
+ const pendingObservers = new Set<Observer>();
43
+
44
+ // Flag to disable tracking temporarily (for untrack)
45
+ let trackingEnabled = true;
46
+
47
+ /**
48
+ * Tracks dependencies during a function execution.
49
+ * Uses direct push/pop for O(1) operations instead of array copying.
50
+ * @internal
51
+ */
52
+ const track = <T>(observer: Observer, fn: () => T): T => {
53
+ observerStack.push(observer);
54
+ try {
55
+ return fn();
56
+ } finally {
57
+ observerStack.pop();
58
+ }
59
+ };
60
+
61
+ /**
62
+ * Schedules an observer to run, respecting batch mode.
63
+ * @internal
64
+ */
65
+ const scheduleObserver = (observer: Observer) => {
66
+ if (batchDepth > 0) {
67
+ pendingObservers.add(observer);
68
+ return;
69
+ }
70
+ observer();
71
+ };
72
+
73
+ /**
74
+ * Flushes all pending observers after a batch completes.
75
+ * @internal
76
+ */
77
+ const flushObservers = () => {
78
+ for (const observer of Array.from(pendingObservers)) {
79
+ pendingObservers.delete(observer);
80
+ observer();
81
+ }
82
+ };
83
+
84
+ /**
85
+ * A reactive value container that notifies subscribers on change.
86
+ *
87
+ * Signals are the foundational primitive of the reactive system.
88
+ * Reading a signal's value inside an effect or computed automatically
89
+ * establishes a reactive dependency.
90
+ *
91
+ * @template T - The type of the stored value
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * const name = signal('World');
96
+ * console.log(name.value); // 'World'
97
+ *
98
+ * name.value = 'bQuery';
99
+ * console.log(name.value); // 'bQuery'
100
+ * ```
101
+ */
102
+ export class Signal<T> {
103
+ private subscribers = new Set<Observer>();
104
+
105
+ /**
106
+ * Creates a new signal with an initial value.
107
+ * @param _value - The initial value
108
+ */
109
+ constructor(private _value: T) {}
110
+
111
+ /**
112
+ * Gets the current value and tracks the read if inside an observer.
113
+ * Respects the global tracking state (disabled during untrack calls).
114
+ */
115
+ get value(): T {
116
+ if (trackingEnabled) {
117
+ const current = observerStack[observerStack.length - 1];
118
+ if (current) {
119
+ this.subscribers.add(current);
120
+ }
121
+ }
122
+ return this._value;
123
+ }
124
+
125
+ /**
126
+ * Sets a new value and notifies all subscribers if the value changed.
127
+ * Uses Object.is for equality comparison.
128
+ */
129
+ set value(next: T) {
130
+ if (Object.is(this._value, next)) return;
131
+ this._value = next;
132
+ for (const subscriber of this.subscribers) {
133
+ scheduleObserver(subscriber);
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Reads the current value without tracking.
139
+ * Useful when you need the value but don't want to create a dependency.
140
+ *
141
+ * @returns The current value
142
+ */
143
+ peek(): T {
144
+ return this._value;
145
+ }
146
+
147
+ /**
148
+ * Updates the value using a function.
149
+ * Useful for updates based on the current value.
150
+ *
151
+ * @param updater - Function that receives current value and returns new value
152
+ */
153
+ update(updater: (current: T) => T): void {
154
+ this.value = updater(this._value);
155
+ }
156
+ }
157
+
158
+ /**
159
+ * A computed value that derives from other reactive sources.
160
+ *
161
+ * Computed values are lazily evaluated and cached. They only
162
+ * recompute when their dependencies change.
163
+ *
164
+ * @template T - The type of the computed value
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * const price = signal(100);
169
+ * const quantity = signal(2);
170
+ * const total = computed(() => price.value * quantity.value);
171
+ *
172
+ * console.log(total.value); // 200
173
+ * price.value = 150;
174
+ * console.log(total.value); // 300
175
+ * ```
176
+ */
177
+ export class Computed<T> {
178
+ private cachedValue!: T;
179
+ private dirty = true;
180
+ private subscribers = new Set<Observer>();
181
+ private readonly markDirty = () => {
182
+ this.dirty = true;
183
+ for (const subscriber of this.subscribers) {
184
+ scheduleObserver(subscriber);
185
+ }
186
+ };
187
+
188
+ /**
189
+ * Creates a new computed value.
190
+ * @param compute - Function that computes the value
191
+ */
192
+ constructor(private readonly compute: () => T) {}
193
+
194
+ /**
195
+ * Gets the computed value, recomputing if dependencies changed.
196
+ */
197
+ get value(): T {
198
+ const current = observerStack[observerStack.length - 1];
199
+ if (current) {
200
+ this.subscribers.add(current);
201
+ }
202
+ if (this.dirty) {
203
+ this.dirty = false;
204
+ this.cachedValue = track(this.markDirty, this.compute);
205
+ }
206
+ return this.cachedValue;
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Creates a new reactive signal.
212
+ *
213
+ * @template T - The type of the signal value
214
+ * @param value - The initial value
215
+ * @returns A new Signal instance
216
+ *
217
+ * @example
218
+ * ```ts
219
+ * const count = signal(0);
220
+ * count.value++; // Triggers subscribers
221
+ * ```
222
+ */
223
+ export const signal = <T>(value: T): Signal<T> => new Signal(value);
224
+
225
+ /**
226
+ * Creates a new computed value.
227
+ *
228
+ * @template T - The type of the computed value
229
+ * @param fn - Function that computes the value from reactive sources
230
+ * @returns A new Computed instance
231
+ *
232
+ * @example
233
+ * ```ts
234
+ * const doubled = computed(() => count.value * 2);
235
+ * ```
236
+ */
237
+ export const computed = <T>(fn: () => T): Computed<T> => new Computed(fn);
238
+
239
+ /**
240
+ * Creates a side effect that automatically re-runs when dependencies change.
241
+ *
242
+ * The effect runs immediately upon creation and then re-runs whenever
243
+ * any signal or computed value read inside it changes.
244
+ *
245
+ * @param fn - The effect function to run
246
+ * @returns A cleanup function to stop the effect
247
+ *
248
+ * @example
249
+ * ```ts
250
+ * const count = signal(0);
251
+ *
252
+ * const cleanup = effect(() => {
253
+ * document.title = `Count: ${count.value}`;
254
+ * });
255
+ *
256
+ * // Later, to stop the effect:
257
+ * cleanup();
258
+ * ```
259
+ */
260
+ export const effect = (fn: () => void | CleanupFn): CleanupFn => {
261
+ let cleanupFn: CleanupFn | void;
262
+ let isDisposed = false;
263
+
264
+ const observer: Observer = () => {
265
+ if (isDisposed) return;
266
+
267
+ // Run previous cleanup if exists
268
+ if (cleanupFn) {
269
+ cleanupFn();
270
+ }
271
+
272
+ // Run effect and capture cleanup
273
+ cleanupFn = track(observer, fn);
274
+ };
275
+
276
+ observer();
277
+
278
+ return () => {
279
+ isDisposed = true;
280
+ if (cleanupFn) {
281
+ cleanupFn();
282
+ }
283
+ };
284
+ };
285
+
286
+ /**
287
+ * Batches multiple signal updates into a single notification cycle.
288
+ *
289
+ * Updates made inside the batch function are deferred until the batch
290
+ * completes, preventing intermediate re-renders and improving performance.
291
+ *
292
+ * @param fn - Function containing multiple signal updates
293
+ *
294
+ * @example
295
+ * ```ts
296
+ * batch(() => {
297
+ * firstName.value = 'John';
298
+ * lastName.value = 'Doe';
299
+ * age.value = 30;
300
+ * });
301
+ * // Effects only run once with all three updates
302
+ * ```
303
+ */
304
+ export const batch = (fn: () => void): void => {
305
+ batchDepth += 1;
306
+ try {
307
+ fn();
308
+ } finally {
309
+ batchDepth -= 1;
310
+ if (batchDepth === 0) {
311
+ flushObservers();
312
+ }
313
+ }
314
+ };
315
+
316
+ /**
317
+ * Creates a signal that persists to localStorage.
318
+ *
319
+ * @template T - The type of the signal value
320
+ * @param key - The localStorage key
321
+ * @param initialValue - The initial value if not found in storage
322
+ * @returns A Signal that syncs with localStorage
323
+ *
324
+ * @example
325
+ * ```ts
326
+ * const theme = persistedSignal('theme', 'light');
327
+ * theme.value = 'dark'; // Automatically saved to localStorage
328
+ * ```
329
+ */
330
+ export const persistedSignal = <T>(key: string, initialValue: T): Signal<T> => {
331
+ let stored: T = initialValue;
332
+
333
+ try {
334
+ const raw = localStorage.getItem(key);
335
+ if (raw !== null) {
336
+ stored = JSON.parse(raw) as T;
337
+ }
338
+ } catch {
339
+ // Use initial value on parse error
340
+ }
341
+
342
+ const sig = signal(stored);
343
+
344
+ // Create an effect to persist changes
345
+ effect(() => {
346
+ try {
347
+ localStorage.setItem(key, JSON.stringify(sig.value));
348
+ } catch {
349
+ // Ignore storage errors
350
+ }
351
+ });
352
+
353
+ return sig;
354
+ };
355
+
356
+ // ============================================================================
357
+ // Extended Reactive Utilities
358
+ // ============================================================================
359
+
360
+ /**
361
+ * A readonly wrapper around a signal that prevents writes.
362
+ * Provides read-only access to a signal's value while maintaining reactivity.
363
+ *
364
+ * @template T - The type of the wrapped value
365
+ */
366
+ export interface ReadonlySignal<T> {
367
+ /** Gets the current value with dependency tracking. */
368
+ readonly value: T;
369
+ /** Gets the current value without dependency tracking. */
370
+ peek(): T;
371
+ }
372
+
373
+ /**
374
+ * Creates a read-only view of a signal.
375
+ * Useful for exposing reactive state without allowing modifications.
376
+ *
377
+ * @template T - The type of the signal value
378
+ * @param sig - The signal to wrap
379
+ * @returns A readonly signal wrapper
380
+ *
381
+ * @example
382
+ * ```ts
383
+ * const _count = signal(0);
384
+ * const count = readonly(_count); // Expose read-only version
385
+ *
386
+ * console.log(count.value); // 0
387
+ * count.value = 1; // TypeScript error: Cannot assign to 'value'
388
+ * ```
389
+ */
390
+ export const readonly = <T>(sig: Signal<T>): ReadonlySignal<T> => ({
391
+ get value(): T {
392
+ return sig.value;
393
+ },
394
+ peek(): T {
395
+ return sig.peek();
396
+ },
397
+ });
398
+
399
+ /**
400
+ * Watches a signal or computed value and calls a callback with old and new values.
401
+ * Unlike effect, watch provides access to the previous value.
402
+ *
403
+ * @template T - The type of the watched value
404
+ * @param source - The signal or computed to watch
405
+ * @param callback - Function called with (newValue, oldValue) on changes
406
+ * @param options - Watch options
407
+ * @returns A cleanup function to stop watching
408
+ *
409
+ * @example
410
+ * ```ts
411
+ * const count = signal(0);
412
+ *
413
+ * const cleanup = watch(count, (newVal, oldVal) => {
414
+ * console.log(`Changed from ${oldVal} to ${newVal}`);
415
+ * });
416
+ *
417
+ * count.value = 5; // Logs: "Changed from 0 to 5"
418
+ * cleanup();
419
+ * ```
420
+ */
421
+ export const watch = <T>(
422
+ source: Signal<T> | Computed<T>,
423
+ callback: (newValue: T, oldValue: T | undefined) => void,
424
+ options: { immediate?: boolean } = {}
425
+ ): CleanupFn => {
426
+ let oldValue: T | undefined;
427
+ let isFirst = true;
428
+
429
+ return effect(() => {
430
+ const newValue = source.value;
431
+
432
+ if (isFirst) {
433
+ isFirst = false;
434
+ oldValue = newValue;
435
+ if (options.immediate) {
436
+ callback(newValue, undefined);
437
+ }
438
+ return;
439
+ }
440
+
441
+ callback(newValue, oldValue);
442
+ oldValue = newValue;
443
+ });
444
+ };
445
+
446
+ /**
447
+ * Executes a function without tracking any signal dependencies.
448
+ * Useful when reading a signal value without creating a reactive dependency.
449
+ *
450
+ * @template T - The return type of the function
451
+ * @param fn - The function to execute without tracking
452
+ * @returns The result of the function
453
+ *
454
+ * @example
455
+ * ```ts
456
+ * const count = signal(0);
457
+ *
458
+ * effect(() => {
459
+ * // This creates a dependency
460
+ * console.log('Tracked:', count.value);
461
+ *
462
+ * // This does NOT create a dependency
463
+ * const untracked = untrack(() => otherSignal.value);
464
+ * });
465
+ * ```
466
+ */
467
+ export const untrack = <T>(fn: () => T): T => {
468
+ const prevTracking = trackingEnabled;
469
+ trackingEnabled = false;
470
+ try {
471
+ return fn();
472
+ } finally {
473
+ trackingEnabled = prevTracking;
474
+ }
475
+ };
476
+
477
+ /**
478
+ * Type guard to check if a value is a Signal instance.
479
+ *
480
+ * @param value - The value to check
481
+ * @returns True if the value is a Signal
482
+ *
483
+ * @example
484
+ * ```ts
485
+ * const count = signal(0);
486
+ * const num = 42;
487
+ *
488
+ * isSignal(count); // true
489
+ * isSignal(num); // false
490
+ * ```
491
+ */
492
+ export const isSignal = (value: unknown): value is Signal<unknown> => value instanceof Signal;
493
+
494
+ /**
495
+ * Type guard to check if a value is a Computed instance.
496
+ *
497
+ * @param value - The value to check
498
+ * @returns True if the value is a Computed
499
+ *
500
+ * @example
501
+ * ```ts
502
+ * const doubled = computed(() => count.value * 2);
503
+ * isComputed(doubled); // true
504
+ * ```
505
+ */
506
+ export const isComputed = (value: unknown): value is Computed<unknown> => value instanceof Computed;