@zeix/cause-effect 0.14.1 → 0.15.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.
Files changed (45) hide show
  1. package/README.md +256 -27
  2. package/biome.json +35 -0
  3. package/index.d.ts +32 -7
  4. package/index.dev.js +629 -0
  5. package/index.js +1 -1
  6. package/index.ts +41 -21
  7. package/package.json +6 -7
  8. package/src/computed.ts +30 -21
  9. package/src/diff.ts +136 -0
  10. package/src/effect.ts +59 -49
  11. package/src/match.ts +57 -0
  12. package/src/resolve.ts +58 -0
  13. package/src/scheduler.ts +3 -3
  14. package/src/signal.ts +48 -15
  15. package/src/state.ts +4 -3
  16. package/src/store.ts +325 -0
  17. package/src/util.ts +57 -5
  18. package/test/batch.test.ts +29 -25
  19. package/test/benchmark.test.ts +81 -45
  20. package/test/computed.test.ts +43 -39
  21. package/test/diff.test.ts +638 -0
  22. package/test/effect.test.ts +657 -49
  23. package/test/match.test.ts +378 -0
  24. package/test/resolve.test.ts +156 -0
  25. package/test/state.test.ts +33 -33
  26. package/test/store.test.ts +719 -0
  27. package/test/util/framework-types.ts +2 -2
  28. package/test/util/perf-tests.ts +2 -2
  29. package/test/util/reactive-framework.ts +1 -1
  30. package/tsconfig.json +9 -10
  31. package/types/index.d.ts +15 -0
  32. package/{src → types/src}/computed.d.ts +2 -2
  33. package/types/src/diff.d.ts +27 -0
  34. package/types/src/effect.d.ts +16 -0
  35. package/types/src/match.d.ts +21 -0
  36. package/types/src/resolve.d.ts +29 -0
  37. package/{src → types/src}/scheduler.d.ts +2 -2
  38. package/types/src/signal.d.ts +40 -0
  39. package/{src → types/src}/state.d.ts +1 -1
  40. package/types/src/store.d.ts +57 -0
  41. package/types/src/util.d.ts +15 -0
  42. package/types/test-new-effect.d.ts +1 -0
  43. package/src/effect.d.ts +0 -17
  44. package/src/signal.d.ts +0 -26
  45. package/src/util.d.ts +0 -7
@@ -1,5 +1,5 @@
1
- import { TestResult } from './perf-tests'
2
- import { ReactiveFramework } from './reactive-framework'
1
+ import type { TestResult } from './perf-tests'
2
+ import type { ReactiveFramework } from './reactive-framework'
3
3
 
4
4
  /** Parameters for a running a performance benchmark test
5
5
  *
@@ -1,4 +1,4 @@
1
- import { FrameworkInfo, TestConfig } from './framework-types'
1
+ import type { FrameworkInfo, TestConfig } from './framework-types'
2
2
 
3
3
  export interface TestResult {
4
4
  sum: number
@@ -25,7 +25,7 @@ export function verifyBenchResult(
25
25
 
26
26
  if (expected.sum) {
27
27
  console.assert(
28
- result.sum == expected.sum,
28
+ result.sum === expected.sum,
29
29
  `sum ${framework.name} ${config.name} result:${result.sum} expected:${expected.sum}`,
30
30
  )
31
31
  }
@@ -6,7 +6,7 @@ export interface ReactiveFramework {
6
6
  name: string
7
7
  signal<T>(initialValue: T): Signal<T>
8
8
  computed<T>(fn: () => T): Computed<T>
9
- effect(fn: () => void): void
9
+ effect(fn: () => undefined): void
10
10
  withBatch<T>(fn: () => T): void
11
11
  withBuild<T>(fn: () => T): T
12
12
  }
package/tsconfig.json CHANGED
@@ -7,28 +7,27 @@
7
7
  "moduleDetection": "force",
8
8
  "jsx": "react-jsx",
9
9
  "allowJs": true,
10
-
10
+
11
11
  // Bundler mode
12
12
  "moduleResolution": "bundler",
13
13
  "allowImportingTsExtensions": true,
14
14
  "verbatimModuleSyntax": true,
15
-
15
+
16
16
  // Best practices
17
17
  "strict": true,
18
18
  "skipLibCheck": true,
19
19
  "noFallthroughCasesInSwitch": true,
20
-
20
+
21
21
  // Some stricter flags (disabled by default)
22
22
  "noUnusedLocals": false,
23
23
  "noUnusedParameters": false,
24
24
  "noPropertyAccessFromIndexSignature": false,
25
-
25
+
26
26
  // Declarations
27
27
  "declaration": true,
28
- "declarationDir": "./",
29
- "emitDeclarationOnly": true,
28
+ "declarationDir": "./types",
29
+ "emitDeclarationOnly": true
30
30
  },
31
- "include": ["./*.ts", "./lib/*.ts"],
32
- "exclude": ["node_modules", "test"],
33
- }
34
-
31
+ "include": ["./*.ts", "./src/*.ts"],
32
+ "exclude": ["node_modules", "test", "types"]
33
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @name Cause & Effect
3
+ * @version 0.15.0
4
+ * @author Esther Brunner
5
+ */
6
+ export { type Computed, type ComputedCallback, computed, isComputed, isComputedCallback, TYPE_COMPUTED, } from './src/computed';
7
+ export { type DiffResult, diff, isEqual, type UnknownRecord } from './src/diff';
8
+ export { type EffectCallback, effect, type MaybeCleanup } from './src/effect';
9
+ export { type MatchHandlers, match } from './src/match';
10
+ export { type ResolveResult, resolve } from './src/resolve';
11
+ export { batch, type Cleanup, enqueue, flush, notify, observe, subscribe, type Updater, type Watcher, watch, } from './src/scheduler';
12
+ export { isSignal, type MaybeSignal, type Signal, type SignalValues, toSignal, UNSET, } from './src/signal';
13
+ export { isState, type State, state, TYPE_STATE } from './src/state';
14
+ export { isStore, type Store, type StoreAddEvent, type StoreChangeEvent, type StoreEventMap, type StoreRemoveEvent, store, TYPE_STORE, } from './src/store';
15
+ export { CircularDependencyError, isAbortError, isAsyncFunction, isFunction, toError, } from './src/util';
@@ -3,7 +3,7 @@ type Computed<T extends {}> = {
3
3
  get(): T;
4
4
  };
5
5
  type ComputedCallback<T extends {} & {
6
- then?: void;
6
+ then?: undefined;
7
7
  }> = ((abort: AbortSignal) => Promise<T>) | (() => T);
8
8
  declare const TYPE_COMPUTED = "Computed";
9
9
  /**
@@ -30,4 +30,4 @@ declare const isComputed: <T extends {}>(value: unknown) => value is Computed<T>
30
30
  * @returns {boolean} - true if value is a callback or callbacks object, false otherwise
31
31
  */
32
32
  declare const isComputedCallback: <T extends {}>(value: unknown) => value is ComputedCallback<T>;
33
- export { type Computed, type ComputedCallback, TYPE_COMPUTED, computed, isComputed, isComputedCallback, };
33
+ export { TYPE_COMPUTED, computed, isComputed, isComputedCallback, type Computed, type ComputedCallback, };
@@ -0,0 +1,27 @@
1
+ type UnknownRecord = Record<string, unknown & {}>;
2
+ type DiffResult<T extends UnknownRecord = UnknownRecord> = {
3
+ changed: boolean;
4
+ add: Partial<T>;
5
+ change: Partial<T>;
6
+ remove: Partial<T>;
7
+ };
8
+ /**
9
+ * Checks if two values are equal with cycle detection
10
+ *
11
+ * @since 0.15.0
12
+ * @param {T} a - First value to compare
13
+ * @param {T} b - Second value to compare
14
+ * @param {WeakSet<object>} visited - Set to track visited objects for cycle detection
15
+ * @returns {boolean} Whether the two values are equal
16
+ */
17
+ declare const isEqual: <T>(a: T, b: T, visited?: WeakSet<object>) => boolean;
18
+ /**
19
+ * Compares two records and returns a result object containing the differences.
20
+ *
21
+ * @since 0.15.0
22
+ * @param {T} oldObj - The old record to compare
23
+ * @param {T} newObj - The new record to compare
24
+ * @returns {DiffResult<T>} The result of the comparison
25
+ */
26
+ declare const diff: <T extends UnknownRecord>(oldObj: T, newObj: T) => DiffResult<T>;
27
+ export { type DiffResult, diff, isEqual, type UnknownRecord };
@@ -0,0 +1,16 @@
1
+ import { type Cleanup } from './scheduler';
2
+ type MaybeCleanup = Cleanup | undefined | void;
3
+ type EffectCallback = (() => MaybeCleanup) | ((abort: AbortSignal) => Promise<MaybeCleanup>);
4
+ /**
5
+ * Define what happens when a reactive state changes
6
+ *
7
+ * The callback can be synchronous or asynchronous. Async callbacks receive
8
+ * an AbortSignal parameter, which is automatically aborted when the effect
9
+ * re-runs or is cleaned up, preventing stale async operations.
10
+ *
11
+ * @since 0.1.0
12
+ * @param {EffectCallback} callback - Synchronous or asynchronous effect callback
13
+ * @returns {Cleanup} - Cleanup function for the effect
14
+ */
15
+ declare const effect: (callback: EffectCallback) => Cleanup;
16
+ export { type MaybeCleanup, type EffectCallback, effect };
@@ -0,0 +1,21 @@
1
+ import type { ResolveResult } from './resolve';
2
+ import type { Signal, SignalValues } from './signal';
3
+ type MatchHandlers<S extends Record<string, Signal<unknown & {}>>> = {
4
+ ok?: (values: SignalValues<S>) => void;
5
+ err?: (errors: readonly Error[]) => void;
6
+ nil?: () => void;
7
+ };
8
+ /**
9
+ * Match on resolve result and call appropriate handler for side effects
10
+ *
11
+ * This is a utility function for those who prefer the handler pattern.
12
+ * All handlers are for side effects only and return void. If you need
13
+ * cleanup logic, use a hoisted let variable in your effect.
14
+ *
15
+ * @since 0.15.0
16
+ * @param {ResolveResult<S>} result - Result from resolve()
17
+ * @param {MatchHandlers<S>} handlers - Handlers for different states (side effects only)
18
+ * @returns {void} - Always returns void
19
+ */
20
+ declare function match<S extends Record<string, Signal<unknown & {}>>>(result: ResolveResult<S>, handlers: MatchHandlers<S>): void;
21
+ export { match, type MatchHandlers };
@@ -0,0 +1,29 @@
1
+ import { type Signal, type SignalValues } from './signal';
2
+ type ResolveResult<S extends Record<string, Signal<unknown & {}>>> = {
3
+ ok: true;
4
+ values: SignalValues<S>;
5
+ errors?: never;
6
+ pending?: never;
7
+ } | {
8
+ ok: false;
9
+ errors: readonly Error[];
10
+ values?: never;
11
+ pending?: never;
12
+ } | {
13
+ ok: false;
14
+ pending: true;
15
+ values?: never;
16
+ errors?: never;
17
+ };
18
+ /**
19
+ * Resolve signal values with perfect type inference
20
+ *
21
+ * Always returns a discriminated union result, regardless of whether
22
+ * handlers are provided or not. This ensures a predictable API.
23
+ *
24
+ * @since 0.15.0
25
+ * @param {S} signals - Signals to resolve
26
+ * @returns {ResolveResult<S>} - Discriminated union result
27
+ */
28
+ declare function resolve<S extends Record<string, Signal<unknown & {}>>>(signals: S): ResolveResult<S>;
29
+ export { resolve, type ResolveResult };
@@ -4,7 +4,7 @@ type Watcher = {
4
4
  off(cleanup: Cleanup): void;
5
5
  cleanup(): void;
6
6
  };
7
- type Updater = <T>() => T | boolean | void;
7
+ type Updater = <T>() => T | boolean | undefined;
8
8
  /**
9
9
  * Create a watcher that can be used to observe changes to a signal
10
10
  *
@@ -51,5 +51,5 @@ declare const observe: (run: () => void, watcher?: Watcher) => void;
51
51
  * @param {Updater} fn - function to be executed on the next animation frame; can return updated value <T>, success <boolean> or void
52
52
  * @param {symbol} dedupe - Symbol for deduplication; if not provided, a unique Symbol is created ensuring the update is always executed
53
53
  */
54
- declare const enqueue: <T>(fn: Updater, dedupe?: symbol) => Promise<boolean | void | T>;
54
+ declare const enqueue: <T>(fn: Updater, dedupe?: symbol) => Promise<boolean | T | undefined>;
55
55
  export { type Cleanup, type Watcher, type Updater, subscribe, notify, flush, batch, watch, observe, enqueue, };
@@ -0,0 +1,40 @@
1
+ import { type Computed, type ComputedCallback } from './computed';
2
+ import { type State } from './state';
3
+ import { type Store } from './store';
4
+ type Signal<T extends {}> = {
5
+ get(): T;
6
+ };
7
+ type MaybeSignal<T extends {}> = T | Signal<T> | ComputedCallback<T>;
8
+ type SignalValues<S extends Record<string, Signal<unknown & {}>>> = {
9
+ [K in keyof S]: S[K] extends Signal<infer T> ? T : never;
10
+ };
11
+ declare const UNSET: any;
12
+ /**
13
+ * Check whether a value is a Signal or not
14
+ *
15
+ * @since 0.9.0
16
+ * @param {unknown} value - value to check
17
+ * @returns {boolean} - true if value is a Signal, false otherwise
18
+ */
19
+ declare const isSignal: <T extends {}>(value: unknown) => value is Signal<T>;
20
+ /**
21
+ * Convert a value to a Signal if it's not already a Signal
22
+ *
23
+ * @since 0.9.6
24
+ */
25
+ declare function toSignal<T extends Array<unknown & {}>>(value: T[]): Store<Record<string, T>>;
26
+ declare function toSignal<T extends Record<keyof T, T[keyof T]>>(value: T): Store<T>;
27
+ declare function toSignal<T extends {}>(value: ComputedCallback<T>): Computed<T>;
28
+ declare function toSignal<T extends {}>(value: Signal<T>): Signal<T>;
29
+ declare function toSignal<T extends {}>(value: T): State<T>;
30
+ /**
31
+ * Convert a value to a mutable Signal if it's not already a Signal
32
+ *
33
+ * @since 0.9.6
34
+ */
35
+ declare function toMutableSignal<T extends Array<unknown & {}>>(value: T[]): Store<Record<string, T>>;
36
+ declare function toMutableSignal<T extends Record<keyof T, T[keyof T]>>(value: T): Store<T>;
37
+ declare function toMutableSignal<T extends State<T>>(value: State<T>): State<T>;
38
+ declare function toMutableSignal<T extends Store<T>>(value: Store<T>): Store<T>;
39
+ declare function toMutableSignal<T extends {}>(value: T): State<T>;
40
+ export { type Signal, type MaybeSignal, type SignalValues, UNSET, isSignal, toSignal, toMutableSignal, };
@@ -21,4 +21,4 @@ declare const state: <T extends {}>(initialValue: T) => State<T>;
21
21
  * @returns {boolean} - true if the value is a State instance, false otherwise
22
22
  */
23
23
  declare const isState: <T extends {}>(value: unknown) => value is State<T>;
24
- export { type State, TYPE_STATE, state, isState };
24
+ export { TYPE_STATE, isState, state, type State };
@@ -0,0 +1,57 @@
1
+ import { type UnknownRecord } from './diff';
2
+ import { type Signal } from './signal';
3
+ import { type State } from './state';
4
+ declare const TYPE_STORE = "Store";
5
+ interface StoreAddEvent<T extends UnknownRecord> extends CustomEvent {
6
+ type: 'store-add';
7
+ detail: Partial<T>;
8
+ }
9
+ interface StoreChangeEvent<T extends UnknownRecord> extends CustomEvent {
10
+ type: 'store-change';
11
+ detail: Partial<T>;
12
+ }
13
+ interface StoreRemoveEvent<T extends UnknownRecord> extends CustomEvent {
14
+ type: 'store-remove';
15
+ detail: Partial<T>;
16
+ }
17
+ type StoreEventMap<T extends UnknownRecord> = {
18
+ 'store-add': StoreAddEvent<T>;
19
+ 'store-change': StoreChangeEvent<T>;
20
+ 'store-remove': StoreRemoveEvent<T>;
21
+ };
22
+ interface StoreEventTarget<T extends UnknownRecord> extends EventTarget {
23
+ addEventListener<K extends keyof StoreEventMap<T>>(type: K, listener: (event: StoreEventMap<T>[K]) => void, options?: boolean | AddEventListenerOptions): void;
24
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
25
+ removeEventListener<K extends keyof StoreEventMap<T>>(type: K, listener: (event: StoreEventMap<T>[K]) => void, options?: boolean | EventListenerOptions): void;
26
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
27
+ dispatchEvent(event: Event): boolean;
28
+ }
29
+ type Store<T extends UnknownRecord = UnknownRecord> = {
30
+ [K in keyof T & string]: T[K] extends UnknownRecord ? Store<T[K]> : State<T[K]>;
31
+ } & StoreEventTarget<T> & {
32
+ [Symbol.toStringTag]: 'Store';
33
+ [Symbol.iterator](): IterableIterator<[string, Signal<T[keyof T]>]>;
34
+ add<K extends keyof T & string>(key: K, value: T[K]): void;
35
+ get(): T;
36
+ remove<K extends keyof T & string>(key: K): void;
37
+ set(value: T): void;
38
+ update(updater: (value: T) => T): void;
39
+ size: State<number>;
40
+ };
41
+ /**
42
+ * Create a new store with deeply nested reactive properties
43
+ *
44
+ * @since 0.15.0
45
+ * @param {T} initialValue - initial object value of the store
46
+ * @returns {Store<T>} - new store with reactive properties
47
+ */
48
+ declare const store: <T extends UnknownRecord>(initialValue: T) => Store<T>;
49
+ /**
50
+ * Check if the provided value is a Store instance
51
+ *
52
+ * @since 0.15.0
53
+ * @param {unknown} value - value to check
54
+ * @returns {boolean} - true if the value is a Store instance, false otherwise
55
+ */
56
+ declare const isStore: <T extends UnknownRecord>(value: unknown) => value is Store<T>;
57
+ export { TYPE_STORE, isStore, store, type Store, type StoreAddEvent, type StoreChangeEvent, type StoreRemoveEvent, type StoreEventMap, };
@@ -0,0 +1,15 @@
1
+ declare const isNumber: (value: unknown) => value is number;
2
+ declare const isString: (value: unknown) => value is string;
3
+ declare const isFunction: <T>(fn: unknown) => fn is (...args: unknown[]) => T;
4
+ declare const isAsyncFunction: <T>(fn: unknown) => fn is (...args: unknown[]) => Promise<T>;
5
+ declare const isObjectOfType: <T>(value: unknown, type: string) => value is T;
6
+ declare const isRecord: <T extends Record<string, unknown>>(value: unknown) => value is T;
7
+ declare const isPrimitive: (value: unknown) => boolean;
8
+ declare const arrayToRecord: <T extends unknown & {}>(array: T[]) => Record<string, T>;
9
+ declare const hasMethod: <T extends object & Record<string, (...args: unknown[]) => unknown>>(obj: T, methodName: string) => obj is T & Record<string, (...args: unknown[]) => unknown>;
10
+ declare const isAbortError: (error: unknown) => boolean;
11
+ declare const toError: (reason: unknown) => Error;
12
+ declare class CircularDependencyError extends Error {
13
+ constructor(where: string);
14
+ }
15
+ export { isNumber, isString, isFunction, isAsyncFunction, isObjectOfType, isRecord, isPrimitive, arrayToRecord, hasMethod, isAbortError, toError, CircularDependencyError, };
@@ -0,0 +1 @@
1
+ export {};
package/src/effect.d.ts DELETED
@@ -1,17 +0,0 @@
1
- import { type Signal, type SignalValues } from './signal';
2
- import { type Cleanup } from './scheduler';
3
- type EffectMatcher<S extends Signal<{}>[]> = {
4
- signals: S;
5
- ok: (...values: SignalValues<S>) => void | Cleanup;
6
- err?: (...errors: Error[]) => void | Cleanup;
7
- nil?: () => void | Cleanup;
8
- };
9
- /**
10
- * Define what happens when a reactive state changes
11
- *
12
- * @since 0.1.0
13
- * @param {EffectMatcher<S> | (() => void | Cleanup)} matcher - effect matcher or callback
14
- * @returns {Cleanup} - cleanup function for the effect
15
- */
16
- declare function effect<S extends Signal<{}>[]>(matcher: EffectMatcher<S> | (() => void | Cleanup)): Cleanup;
17
- export { type EffectMatcher, effect };
package/src/signal.d.ts DELETED
@@ -1,26 +0,0 @@
1
- import { type ComputedCallback, isComputedCallback } from './computed';
2
- type Signal<T extends {}> = {
3
- get(): T;
4
- };
5
- type MaybeSignal<T extends {}> = T | Signal<T> | ComputedCallback<T>;
6
- type SignalValues<S extends Signal<{}>[]> = {
7
- [K in keyof S]: S[K] extends Signal<infer T> ? T : never;
8
- };
9
- declare const UNSET: any;
10
- /**
11
- * Check whether a value is a Signal or not
12
- *
13
- * @since 0.9.0
14
- * @param {unknown} value - value to check
15
- * @returns {boolean} - true if value is a Signal, false otherwise
16
- */
17
- declare const isSignal: <T extends {}>(value: unknown) => value is Signal<T>;
18
- /**
19
- * Convert a value to a Signal if it's not already a Signal
20
- *
21
- * @since 0.9.6
22
- * @param {MaybeSignal<T>} value - value to convert to a Signal
23
- * @returns {Signal<T>} - converted Signal
24
- */
25
- declare const toSignal: <T extends {}>(value: MaybeSignal<T>) => Signal<T>;
26
- export { type Signal, type MaybeSignal, type SignalValues, UNSET, isSignal, isComputedCallback, toSignal, };
package/src/util.d.ts DELETED
@@ -1,7 +0,0 @@
1
- declare const isFunction: <T>(value: unknown) => value is (...args: unknown[]) => T;
2
- declare const isObjectOfType: <T>(value: unknown, type: string) => value is T;
3
- declare const toError: (reason: unknown) => Error;
4
- declare class CircularDependencyError extends Error {
5
- constructor(where: string);
6
- }
7
- export { isFunction, isObjectOfType, toError, CircularDependencyError };