@effuse/store 1.0.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.
@@ -0,0 +1,31 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2025 Chris M. Perez
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+ export {
25
+ connectDevTools,
26
+ hasDevTools,
27
+ devToolsMiddleware,
28
+ createDevToolsMiddleware,
29
+ disconnectDevTools,
30
+ disconnectAllDevTools,
31
+ } from './connector.js';
package/src/errors.ts ADDED
@@ -0,0 +1,81 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2025 Chris M. Perez
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { Data } from 'effect';
26
+
27
+ export class StoreNotFoundError extends Data.TaggedError('StoreNotFoundError')<{
28
+ readonly name: string;
29
+ }> {
30
+ get message(): string {
31
+ return `Store "${this.name}" not found`;
32
+ }
33
+ }
34
+
35
+ export class StoreAlreadyExistsError extends Data.TaggedError(
36
+ 'StoreAlreadyExistsError'
37
+ )<{
38
+ readonly name: string;
39
+ }> {
40
+ get message(): string {
41
+ return `Store "${this.name}" already exists`;
42
+ }
43
+ }
44
+
45
+ export class ActionNotFoundError extends Data.TaggedError(
46
+ 'ActionNotFoundError'
47
+ )<{
48
+ readonly actionName: string;
49
+ }> {}
50
+
51
+ export class TimeoutError extends Data.TaggedError('TimeoutError')<{
52
+ readonly ms: number;
53
+ }> {
54
+ get message(): string {
55
+ return `Operation timed out after ${String(this.ms)}ms`;
56
+ }
57
+ }
58
+
59
+ export class CancellationError extends Data.TaggedError('CancellationError')<{
60
+ readonly message: string;
61
+ }> {}
62
+
63
+ export class ValidationError extends Data.TaggedError('ValidationError')<{
64
+ readonly errors: string[];
65
+ }> {
66
+ get message(): string {
67
+ return `Validation failed: ${this.errors.join(', ')}`;
68
+ }
69
+ }
70
+
71
+ export class RaceEmptyError extends Data.TaggedError('RaceEmptyError')<object> {
72
+ get message(): string {
73
+ return 'raceAll requires at least one effect';
74
+ }
75
+ }
76
+
77
+ export class HydrationError extends Data.TaggedError('HydrationError')<object> {
78
+ get message(): string {
79
+ return 'Failed to hydrate stores';
80
+ }
81
+ }
package/src/index.ts ADDED
@@ -0,0 +1,157 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2025 Chris M. Perez
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ export {
26
+ createStore,
27
+ createAtomicState,
28
+ type Store,
29
+ type StoreState,
30
+ type StoreContext,
31
+ type StoreDefinition,
32
+ type StoreOptions,
33
+ type InferStoreState,
34
+ type ActionContext,
35
+ type Middleware,
36
+ type CreateStoreOptions,
37
+ type AtomicState,
38
+ } from './core/index.js';
39
+
40
+ export {
41
+ getStoreConfig,
42
+ resetStoreConfigCache,
43
+ StoreConstants,
44
+ STORAGE_PREFIX,
45
+ ROOT_SCOPE_ID,
46
+ SCOPE_PREFIX,
47
+ DEFAULT_TIMEOUT_MS,
48
+ DEFAULT_RETRY_INITIAL_DELAY_MS,
49
+ DEFAULT_RETRY_MAX_DELAY_MS,
50
+ DEFAULT_RETRY_BACKOFF_FACTOR,
51
+ type StoreConfigValues,
52
+ } from './config/index.js';
53
+
54
+ export {
55
+ createScope,
56
+ disposeScope,
57
+ enterScope,
58
+ exitScope,
59
+ getCurrentScope,
60
+ getRootScope,
61
+ registerScopedStore,
62
+ getScopedStore,
63
+ hasScopedStore,
64
+ runInScope,
65
+ withScope,
66
+ type ScopeNode,
67
+ type ScopeId,
68
+ } from './context/index.js';
69
+
70
+ export {
71
+ createAsyncAction,
72
+ createCancellableAction,
73
+ dispatch,
74
+ dispatchSync,
75
+ withTimeout,
76
+ withRetry,
77
+ withAbortSignal,
78
+ takeLatest,
79
+ takeFirst,
80
+ debounceAction,
81
+ throttleAction,
82
+ createCancellationToken,
83
+ createCancellationScope,
84
+ type ActionResult,
85
+ type AsyncAction,
86
+ type CancellableAction,
87
+ type RetryConfig,
88
+ type CancellationToken,
89
+ type CancellationScope,
90
+ } from './actions/index.js';
91
+
92
+ export {
93
+ validateState,
94
+ validateStateAsync,
95
+ createValidatedSetter,
96
+ createFieldValidator,
97
+ createSafeFieldSetter,
98
+ type StateSchema,
99
+ type ValidationResult,
100
+ } from './validation/index.js';
101
+
102
+ export {
103
+ composeStores,
104
+ defineSlice,
105
+ mergeStores,
106
+ type ComposedStore,
107
+ type StoreSlice,
108
+ } from './composition/index.js';
109
+
110
+ export {
111
+ deriveFrom,
112
+ deriveFromAsync,
113
+ serializeStores,
114
+ hydrateStoresSync,
115
+ createStoreStream,
116
+ streamAll,
117
+ createSelector,
118
+ createSelectorAsync,
119
+ pick,
120
+ combineSelectors,
121
+ shallowEqual,
122
+ type StoreStream,
123
+ type Selector,
124
+ type AsyncSelector,
125
+ type EqualityFn,
126
+ } from './reactivity/index.js';
127
+
128
+ export {
129
+ createMiddlewareManager,
130
+ type MiddlewareManager,
131
+ } from './middleware/index.js';
132
+
133
+ export {
134
+ connectDevTools,
135
+ hasDevTools,
136
+ devToolsMiddleware,
137
+ createDevToolsMiddleware,
138
+ disconnectDevTools,
139
+ disconnectAllDevTools,
140
+ } from './devtools/index.js';
141
+
142
+ export {
143
+ getStore,
144
+ hasStore,
145
+ removeStore,
146
+ clearStores,
147
+ getStoreNames,
148
+ } from './registry/index.js';
149
+
150
+ export {
151
+ StoreNotFoundError,
152
+ StoreAlreadyExistsError,
153
+ ActionNotFoundError,
154
+ TimeoutError,
155
+ CancellationError,
156
+ ValidationError,
157
+ } from './errors.js';
@@ -0,0 +1,25 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2025 Chris M. Perez
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ export { createMiddlewareManager, type MiddlewareManager } from './manager.js';
@@ -0,0 +1,61 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2025 Chris M. Perez
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { Array as Arr } from 'effect';
26
+ import type { Middleware } from '../core/types.js';
27
+
28
+ // Middleware pipeline manager
29
+ export interface MiddlewareManager<T extends Record<string, unknown>> {
30
+ add: (middleware: Middleware<T>) => () => void;
31
+ remove: (middleware: Middleware<T>) => void;
32
+ execute: (state: T, action: string, args: unknown[]) => T;
33
+ getAll: () => readonly Middleware<T>[];
34
+ }
35
+
36
+ // Initialize middleware manager
37
+ export const createMiddlewareManager = <
38
+ T extends Record<string, unknown>,
39
+ >(): MiddlewareManager<T> => {
40
+ const middlewares: Middleware<T>[] = [];
41
+
42
+ return {
43
+ add: (middleware: Middleware<T>) => {
44
+ middlewares.push(middleware);
45
+ return () => {
46
+ const idx = middlewares.indexOf(middleware);
47
+ if (idx > -1) middlewares.splice(idx, 1);
48
+ };
49
+ },
50
+
51
+ remove: (middleware: Middleware<T>) => {
52
+ const idx = middlewares.indexOf(middleware);
53
+ if (idx > -1) middlewares.splice(idx, 1);
54
+ },
55
+
56
+ execute: (state: T, action: string, args: unknown[]): T =>
57
+ Arr.reduce(middlewares, state, (acc, mw) => mw(acc, action, args) ?? acc),
58
+
59
+ getAll: () => [...middlewares],
60
+ };
61
+ };
@@ -0,0 +1,96 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2025 Chris M. Perez
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { Effect, Option } from 'effect';
26
+
27
+ // Storage engine interface
28
+ export interface StorageAdapter {
29
+ getItem: (key: string) => Effect.Effect<Option.Option<string>>;
30
+ setItem: (key: string, value: string) => Effect.Effect<void>;
31
+ removeItem: (key: string) => Effect.Effect<void>;
32
+ }
33
+
34
+ // Browser local storage adapter
35
+ export const localStorageAdapter: StorageAdapter = {
36
+ getItem: (key) =>
37
+ Effect.try({
38
+ try: () => Option.fromNullable(localStorage.getItem(key)),
39
+ catch: () => Option.none<string>(),
40
+ }).pipe(Effect.catchAll(() => Effect.succeed(Option.none<string>()))),
41
+ setItem: (key, value) =>
42
+ Effect.try(() => {
43
+ localStorage.setItem(key, value);
44
+ }).pipe(Effect.catchAll(() => Effect.void)),
45
+ removeItem: (key) =>
46
+ Effect.try(() => {
47
+ localStorage.removeItem(key);
48
+ }).pipe(Effect.catchAll(() => Effect.void)),
49
+ };
50
+
51
+ // Browser session storage adapter
52
+ export const sessionStorageAdapter: StorageAdapter = {
53
+ getItem: (key) =>
54
+ Effect.try({
55
+ try: () => Option.fromNullable(sessionStorage.getItem(key)),
56
+ catch: () => Option.none<string>(),
57
+ }).pipe(Effect.catchAll(() => Effect.succeed(Option.none<string>()))),
58
+ setItem: (key, value) =>
59
+ Effect.try(() => {
60
+ sessionStorage.setItem(key, value);
61
+ }).pipe(Effect.catchAll(() => Effect.void)),
62
+ removeItem: (key) =>
63
+ Effect.try(() => {
64
+ sessionStorage.removeItem(key);
65
+ }).pipe(Effect.catchAll(() => Effect.void)),
66
+ };
67
+
68
+ // Build in memory storage adapter
69
+ export const createMemoryAdapter = (): StorageAdapter => {
70
+ const storage = new Map<string, string>();
71
+ return {
72
+ getItem: (key) => Effect.succeed(Option.fromNullable(storage.get(key))),
73
+ setItem: (key, value) =>
74
+ Effect.sync(() => {
75
+ storage.set(key, value);
76
+ }),
77
+ removeItem: (key) =>
78
+ Effect.sync(() => {
79
+ storage.delete(key);
80
+ }),
81
+ };
82
+ };
83
+
84
+ // Synchronous storage adapter bridge
85
+ export const runAdapter = {
86
+ getItem: (adapter: StorageAdapter, key: string): string | null =>
87
+ Effect.runSync(
88
+ adapter.getItem(key).pipe(Effect.map((opt) => Option.getOrNull(opt)))
89
+ ),
90
+ setItem: (adapter: StorageAdapter, key: string, value: string): void => {
91
+ Effect.runSync(adapter.setItem(key, value));
92
+ },
93
+ removeItem: (adapter: StorageAdapter, key: string): void => {
94
+ Effect.runSync(adapter.removeItem(key));
95
+ },
96
+ };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2025 Chris M. Perez
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ export {
26
+ type StorageAdapter,
27
+ localStorageAdapter,
28
+ sessionStorageAdapter,
29
+ createMemoryAdapter,
30
+ runAdapter,
31
+ } from './adapters.js';
@@ -0,0 +1,170 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2025 Chris M. Perez
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { Effect, Option } from 'effect';
26
+ import { signal, type Signal } from '@effuse/core';
27
+ import type { Store } from '../core/types.js';
28
+ import { getStoreNames, getStore } from '../registry/index.js';
29
+ import {
30
+ createCancellationToken,
31
+ type CancellationToken,
32
+ } from '../actions/cancellation.js';
33
+ import { HydrationError } from '../errors.js';
34
+
35
+ // Build derived reactive signal
36
+ export const deriveFrom = <S extends Store<unknown>[], R>(
37
+ stores: [...S],
38
+ selector: (
39
+ ...snapshots: { [K in keyof S]: ReturnType<S[K]['getSnapshot']> }
40
+ ) => R
41
+ ): Signal<R> & { cleanup: () => void } => {
42
+ const getSnapshots = () =>
43
+ stores.map((s) => s.getSnapshot()) as {
44
+ [K in keyof S]: ReturnType<S[K]['getSnapshot']>;
45
+ };
46
+
47
+ const initialValue = selector(...getSnapshots());
48
+ const derivedSignal = signal<R>(initialValue);
49
+
50
+ const update = () => {
51
+ const newValue = selector(...getSnapshots());
52
+ if (derivedSignal.value !== newValue) {
53
+ derivedSignal.value = newValue;
54
+ }
55
+ };
56
+
57
+ const unsubscribers = stores.map((store) => store.subscribe(update));
58
+
59
+ const signalWithCleanup = derivedSignal as Signal<R> & {
60
+ cleanup: () => void;
61
+ };
62
+ signalWithCleanup.cleanup = () => {
63
+ for (const unsub of unsubscribers) {
64
+ unsub();
65
+ }
66
+ };
67
+
68
+ return signalWithCleanup;
69
+ };
70
+
71
+ // Build asynchronous derived signal
72
+ export const deriveFromAsync = <S extends Store<unknown>[], R>(
73
+ stores: [...S],
74
+ asyncSelector: (
75
+ snapshots: { [K in keyof S]: ReturnType<S[K]['getSnapshot']> },
76
+ token: CancellationToken
77
+ ) => Promise<R>,
78
+ initialValue: R
79
+ ): Signal<R> & { cleanup: () => void; pending: Signal<boolean> } => {
80
+ const getSnapshots = () =>
81
+ stores.map((s) => s.getSnapshot()) as {
82
+ [K in keyof S]: ReturnType<S[K]['getSnapshot']>;
83
+ };
84
+
85
+ const derivedSignal = signal<R>(initialValue);
86
+ const pendingSignal = signal<boolean>(false);
87
+ let currentToken = createCancellationToken();
88
+
89
+ const update = () => {
90
+ currentToken.cancel();
91
+ currentToken = createCancellationToken();
92
+ const myToken = currentToken;
93
+ pendingSignal.value = true;
94
+
95
+ asyncSelector(getSnapshots(), myToken)
96
+ .then((newValue) => {
97
+ if (!myToken.isCancelled && derivedSignal.value !== newValue) {
98
+ derivedSignal.value = newValue;
99
+ }
100
+ })
101
+ .catch(() => {})
102
+ .finally(() => {
103
+ if (!myToken.isCancelled) {
104
+ pendingSignal.value = false;
105
+ }
106
+ });
107
+ };
108
+
109
+ const unsubscribers = stores.map((store) => store.subscribe(update));
110
+ update();
111
+
112
+ const signalWithCleanup = derivedSignal as Signal<R> & {
113
+ cleanup: () => void;
114
+ pending: Signal<boolean>;
115
+ };
116
+ signalWithCleanup.cleanup = () => {
117
+ currentToken.cancel();
118
+ for (const unsub of unsubscribers) {
119
+ unsub();
120
+ }
121
+ };
122
+ signalWithCleanup.pending = pendingSignal;
123
+
124
+ return signalWithCleanup;
125
+ };
126
+
127
+ // Serialize registered stores
128
+ export const serializeStores = (): string => {
129
+ const storeNames = getStoreNames();
130
+ const allSnapshots: Record<string, unknown> = {};
131
+ for (const name of storeNames) {
132
+ const store = getStore(name);
133
+ allSnapshots[name] = store.getSnapshot();
134
+ }
135
+ return JSON.stringify(allSnapshots);
136
+ };
137
+
138
+ // Hydrate stores with Effect
139
+ export const hydrateStores = (serialized: string): Effect.Effect<void> =>
140
+ Effect.try({
141
+ try: () => {
142
+ const allSnapshots = JSON.parse(serialized) as Record<
143
+ string,
144
+ Record<string, unknown>
145
+ >;
146
+ for (const [name, snapshot] of Object.entries(allSnapshots)) {
147
+ Effect.runSync(
148
+ Effect.try(() => {
149
+ const store = getStore<Record<string, unknown>>(name);
150
+ store.update((draft: Record<string, unknown>) => {
151
+ Object.assign(draft, snapshot);
152
+ });
153
+ }).pipe(Effect.catchAll(() => Effect.void))
154
+ );
155
+ }
156
+ },
157
+ catch: () => new HydrationError({}),
158
+ }).pipe(Effect.catchAll(() => Effect.void));
159
+
160
+ // Hydrate stores synchronously
161
+ export const hydrateStoresSync = (serialized: string): void => {
162
+ Effect.runSync(
163
+ hydrateStores(serialized).pipe(
164
+ Effect.match({
165
+ onSuccess: () => Option.some(undefined),
166
+ onFailure: () => Option.none(),
167
+ })
168
+ )
169
+ );
170
+ };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2025 Chris M. Perez
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ export {
26
+ deriveFrom,
27
+ deriveFromAsync,
28
+ serializeStores,
29
+ hydrateStores,
30
+ hydrateStoresSync,
31
+ } from './derived.js';
32
+ export { createStoreStream, streamAll, type StoreStream } from './streams.js';
33
+ export {
34
+ createSelector,
35
+ createSelectorAsync,
36
+ pick,
37
+ combineSelectors,
38
+ shallowEqual,
39
+ type Selector,
40
+ type AsyncSelector,
41
+ type EqualityFn,
42
+ } from './selectors.js';