@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,467 @@
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, pipe, Predicate } from 'effect';
26
+ import { signal, type Signal } from '@effuse/core';
27
+ import type {
28
+ Store,
29
+ StoreState,
30
+ StoreDefinition,
31
+ StoreOptions,
32
+ Middleware,
33
+ } from './types.js';
34
+ import { createAtomicState } from './state.js';
35
+ import { getStoreConfig } from '../config/index.js';
36
+ import { createMiddlewareManager } from '../middleware/index.js';
37
+ import { registerStore } from '../registry/index.js';
38
+ import {
39
+ type StorageAdapter,
40
+ runAdapter,
41
+ localStorageAdapter,
42
+ } from '../persistence/index.js';
43
+ import {
44
+ createCancellationScope,
45
+ createCancellationToken,
46
+ type CancellationScope,
47
+ type CancellationToken,
48
+ } from '../actions/cancellation.js';
49
+
50
+ interface StoreInternals {
51
+ signalMap: Map<string, Signal<unknown>>;
52
+ initialState: Record<string, unknown>;
53
+ actions: Record<string, (...args: unknown[]) => unknown>;
54
+ subscribers: Set<() => void>;
55
+ keySubscribers: Map<string, Set<(value: unknown) => void>>;
56
+ computedSelectors: Map<
57
+ (s: Record<string, unknown>) => unknown,
58
+ Signal<unknown>
59
+ >;
60
+ isBatching: boolean;
61
+ cancellationScope: CancellationScope;
62
+ pendingActions: Map<string, CancellationToken>;
63
+ }
64
+
65
+ const getSnapshot = (
66
+ signalMap: Map<string, Signal<unknown>>
67
+ ): Record<string, unknown> => {
68
+ const snapshot: Record<string, unknown> = {};
69
+ for (const [key, sig] of signalMap) {
70
+ snapshot[key] = sig.value;
71
+ }
72
+ return snapshot;
73
+ };
74
+
75
+ // Store configuration options
76
+ export interface CreateStoreOptions extends StoreOptions {
77
+ storage?: StorageAdapter;
78
+ }
79
+
80
+ // Initialize reactive store
81
+ export const createStore = <T extends object>(
82
+ name: string,
83
+ definition: StoreDefinition<T>,
84
+ options?: CreateStoreOptions
85
+ ): Store<T> & StoreState<T> => {
86
+ const config = getStoreConfig();
87
+ const shouldPersist = pipe(
88
+ Option.fromNullable(options),
89
+ Option.flatMap((o) => Option.fromNullable(o.persist)),
90
+ Option.getOrElse(() => config.persistByDefault)
91
+ );
92
+ const storageKey = pipe(
93
+ Option.fromNullable(options),
94
+ Option.flatMap((o) => Option.fromNullable(o.storageKey)),
95
+ Option.getOrElse(() => `${config.storagePrefix}${name}`)
96
+ );
97
+ const enableDevtools = pipe(
98
+ Option.fromNullable(options),
99
+ Option.flatMap((o) => Option.fromNullable(o.devtools)),
100
+ Option.getOrElse(() => config.debug)
101
+ );
102
+ const adapter = pipe(
103
+ Option.fromNullable(options),
104
+ Option.flatMap((o) => Option.fromNullable(o.storage)),
105
+ Option.getOrElse(() => localStorageAdapter)
106
+ );
107
+
108
+ if (config.debug) {
109
+ console.log(`[store] Creating: ${name}`);
110
+ }
111
+
112
+ const internals: StoreInternals = {
113
+ signalMap: new Map(),
114
+ initialState: {},
115
+ actions: {},
116
+ subscribers: new Set(),
117
+ keySubscribers: new Map(),
118
+ computedSelectors: new Map(),
119
+ isBatching: false,
120
+ cancellationScope: createCancellationScope(),
121
+ pendingActions: new Map(),
122
+ };
123
+
124
+ const middlewareManager = createMiddlewareManager<Record<string, unknown>>();
125
+
126
+ for (const [key, value] of Object.entries(definition)) {
127
+ if (typeof value === 'function') {
128
+ internals.actions[key] = value as (...args: unknown[]) => unknown;
129
+ } else {
130
+ internals.initialState[key] = value;
131
+ internals.signalMap.set(key, signal(value));
132
+ }
133
+ }
134
+
135
+ const atomicState = createAtomicState({ ...internals.initialState });
136
+
137
+ if (shouldPersist) {
138
+ pipe(
139
+ runAdapter.getItem(adapter, storageKey),
140
+ Option.fromNullable,
141
+ Option.flatMap((saved) =>
142
+ Effect.runSync(
143
+ Effect.try(() => JSON.parse(saved) as Record<string, unknown>).pipe(
144
+ Effect.map(Option.some),
145
+ Effect.catchAll(() =>
146
+ Effect.succeed(Option.none<Record<string, unknown>>())
147
+ )
148
+ )
149
+ )
150
+ ),
151
+ Option.map((parsed) => {
152
+ for (const [key, value] of Object.entries(parsed)) {
153
+ const sig = internals.signalMap.get(key);
154
+ if (sig) sig.value = value;
155
+ }
156
+ atomicState.set({ ...atomicState.get(), ...parsed });
157
+ })
158
+ );
159
+ }
160
+
161
+ const notifySubscribers = (): void => {
162
+ if (internals.isBatching) return;
163
+ for (const callback of internals.subscribers) callback();
164
+ };
165
+
166
+ const notifyKeySubscribers = (key: string, value: unknown): void => {
167
+ if (internals.isBatching) return;
168
+ const subs = internals.keySubscribers.get(key);
169
+ if (subs) for (const cb of subs) cb(value);
170
+ };
171
+
172
+ const persistState = (): void => {
173
+ if (!shouldPersist) return;
174
+ const snapshot = getSnapshot(internals.signalMap);
175
+ runAdapter.setItem(adapter, storageKey, JSON.stringify(snapshot));
176
+ };
177
+
178
+ const updateComputed = (): void => {
179
+ const snapshot = getSnapshot(internals.signalMap);
180
+ for (const [selector, sig] of internals.computedSelectors) {
181
+ const newValue = selector(snapshot);
182
+ if (sig.value !== newValue) sig.value = newValue;
183
+ }
184
+ };
185
+
186
+ const stateProxy = new Proxy({} as Record<string, unknown>, {
187
+ get(_, prop: string) {
188
+ const sig = internals.signalMap.get(prop);
189
+ if (sig) return sig;
190
+ const action = internals.actions[prop];
191
+ if (action) return action.bind(stateProxy);
192
+ return undefined;
193
+ },
194
+ set(_, prop: string, value: unknown) {
195
+ if (!internals.signalMap.has(prop)) return false;
196
+
197
+ const sig = internals.signalMap.get(prop);
198
+ if (!sig) return false;
199
+ const newState = middlewareManager.execute(
200
+ { ...atomicState.get(), [prop]: value },
201
+ `set:${prop}`,
202
+ [value]
203
+ );
204
+
205
+ sig.value = newState[prop];
206
+ atomicState.update((s) => ({ ...s, [prop]: newState[prop] }));
207
+
208
+ if (enableDevtools) {
209
+ const time = new Date().toLocaleTimeString();
210
+ console.groupCollapsed(
211
+ `%caction %c${name}/set:${prop} %c@ ${time}`,
212
+ 'color: gray; font-weight: lighter;',
213
+ 'color: inherit; font-weight: bold;',
214
+ 'color: gray; font-weight: lighter;'
215
+ );
216
+ console.log(
217
+ '%cprev state',
218
+ 'color: #9E9E9E; font-weight: bold;',
219
+ atomicState.get()
220
+ );
221
+ console.log('%caction', 'color: #03A9F4; font-weight: bold;', {
222
+ type: `set:${prop}`,
223
+ payload: value,
224
+ });
225
+ console.log('%cnext state', 'color: #4CAF50; font-weight: bold;', {
226
+ ...atomicState.get(),
227
+ [prop]: newState[prop],
228
+ });
229
+ console.groupEnd();
230
+ }
231
+
232
+ notifySubscribers();
233
+ notifyKeySubscribers(prop, newState[prop]);
234
+ persistState();
235
+ updateComputed();
236
+ return true;
237
+ },
238
+ });
239
+
240
+ const boundActions: Record<string, (...args: unknown[]) => unknown> = {};
241
+ for (const [key, action] of Object.entries(internals.actions)) {
242
+ boundActions[key] = (...args: unknown[]) => {
243
+ const prevState = enableDevtools
244
+ ? getSnapshot(internals.signalMap)
245
+ : undefined;
246
+
247
+ const existingToken = internals.pendingActions.get(key);
248
+ if (existingToken) {
249
+ existingToken.cancel();
250
+ }
251
+
252
+ const result = action.apply(stateProxy, args);
253
+
254
+ if (result instanceof Promise) {
255
+ const token = createCancellationToken();
256
+ internals.pendingActions.set(key, token);
257
+
258
+ return result
259
+ .then((value: unknown) => {
260
+ if (!token.isCancelled) {
261
+ internals.pendingActions.delete(key);
262
+ const currentState = getSnapshot(internals.signalMap);
263
+ middlewareManager.execute(currentState, key, args);
264
+
265
+ if (enableDevtools) {
266
+ const time = new Date().toLocaleTimeString();
267
+ console.groupCollapsed(
268
+ `%caction %c${name}/${key} (async) %c@ ${time}`,
269
+ 'color: gray; font-weight: lighter;',
270
+ 'color: inherit; font-weight: bold;',
271
+ 'color: gray; font-weight: lighter;'
272
+ );
273
+ console.log(
274
+ '%cprev state',
275
+ 'color: #9E9E9E; font-weight: bold;',
276
+ prevState
277
+ );
278
+ console.log('%caction', 'color: #03A9F4; font-weight: bold;', {
279
+ type: `${name}/${key}`,
280
+ payload: args,
281
+ });
282
+ console.log(
283
+ '%cnext state',
284
+ 'color: #4CAF50; font-weight: bold;',
285
+ currentState
286
+ );
287
+ console.groupEnd();
288
+ }
289
+
290
+ notifySubscribers();
291
+ }
292
+ return value;
293
+ })
294
+ .catch((error: unknown) => {
295
+ internals.pendingActions.delete(key);
296
+ throw error;
297
+ });
298
+ }
299
+
300
+ const currentState = getSnapshot(internals.signalMap);
301
+ middlewareManager.execute(currentState, key, args);
302
+
303
+ if (enableDevtools) {
304
+ const time = new Date().toLocaleTimeString();
305
+ console.groupCollapsed(
306
+ `%caction %c${name}/${key} %c@ ${time}`,
307
+ 'color: gray; font-weight: lighter;',
308
+ 'color: inherit; font-weight: bold;',
309
+ 'color: gray; font-weight: lighter;'
310
+ );
311
+ console.log(
312
+ '%cprev state',
313
+ 'color: #9E9E9E; font-weight: bold;',
314
+ prevState
315
+ );
316
+ console.log('%caction', 'color: #03A9F4; font-weight: bold;', {
317
+ type: `${name}/${key}`,
318
+ payload: args,
319
+ });
320
+ console.log(
321
+ '%cnext state',
322
+ 'color: #4CAF50; font-weight: bold;',
323
+ currentState
324
+ );
325
+ console.groupEnd();
326
+ }
327
+
328
+ notifySubscribers();
329
+
330
+ return result;
331
+ };
332
+ }
333
+
334
+ const storeState: Record<string, unknown> = {};
335
+ for (const [key, sig] of internals.signalMap) storeState[key] = sig;
336
+ for (const [key, action] of Object.entries(boundActions))
337
+ storeState[key] = action;
338
+
339
+ const store: Store<T> = {
340
+ name,
341
+ state: storeState as StoreState<T>,
342
+
343
+ subscribe: (callback) => {
344
+ internals.subscribers.add(callback);
345
+ return () => {
346
+ internals.subscribers.delete(callback);
347
+ };
348
+ },
349
+
350
+ subscribeToKey: (key, callback) => {
351
+ const keyStr = String(key);
352
+ let subs = internals.keySubscribers.get(keyStr);
353
+ if (!subs) {
354
+ subs = new Set();
355
+ internals.keySubscribers.set(keyStr, subs);
356
+ }
357
+ const typedCallback = callback as (value: unknown) => void;
358
+ subs.add(typedCallback);
359
+ return () => {
360
+ const subsSet = internals.keySubscribers.get(keyStr);
361
+ if (Predicate.isNotNullable(subsSet)) {
362
+ subsSet.delete(typedCallback);
363
+ }
364
+ };
365
+ },
366
+
367
+ getSnapshot: () =>
368
+ getSnapshot(internals.signalMap) as ReturnType<Store<T>['getSnapshot']>,
369
+
370
+ computed: <R>(
371
+ selector: (snapshot: Record<string, unknown>) => R
372
+ ): Signal<R> => {
373
+ const selectorKey = selector as (s: Record<string, unknown>) => unknown;
374
+ const existing = internals.computedSelectors.get(selectorKey);
375
+ if (existing) return existing as Signal<R>;
376
+
377
+ const initial = selector(getSnapshot(internals.signalMap));
378
+ const sig = signal<R>(initial);
379
+ internals.computedSelectors.set(selectorKey, sig as Signal<unknown>);
380
+ return sig;
381
+ },
382
+
383
+ batch: (updates) => {
384
+ internals.isBatching = true;
385
+ updates();
386
+ internals.isBatching = false;
387
+ notifySubscribers();
388
+ persistState();
389
+ updateComputed();
390
+ },
391
+
392
+ reset: () => {
393
+ for (const [key, value] of Object.entries(internals.initialState)) {
394
+ const sig = internals.signalMap.get(key);
395
+ if (sig) sig.value = value;
396
+ }
397
+ atomicState.set({ ...internals.initialState });
398
+ notifySubscribers();
399
+ persistState();
400
+ updateComputed();
401
+ },
402
+
403
+ use: (middleware: Middleware<Record<string, unknown>>) =>
404
+ middlewareManager.add(middleware),
405
+
406
+ toJSON: () =>
407
+ getSnapshot(internals.signalMap) as ReturnType<Store<T>['getSnapshot']>,
408
+
409
+ update: (updater) => {
410
+ const draft = { ...getSnapshot(internals.signalMap) } as {
411
+ [K in keyof T]: T[K] extends (...args: unknown[]) => unknown
412
+ ? never
413
+ : T[K];
414
+ };
415
+
416
+ updater(draft);
417
+
418
+ internals.isBatching = true;
419
+ for (const [key, val] of Object.entries(draft)) {
420
+ const sig = internals.signalMap.get(key);
421
+ if (sig && sig.value !== val) {
422
+ sig.value = val;
423
+ atomicState.update((s) => ({ ...s, [key]: val }));
424
+ }
425
+ }
426
+ internals.isBatching = false;
427
+
428
+ notifySubscribers();
429
+ persistState();
430
+ updateComputed();
431
+ },
432
+
433
+ select: <R>(
434
+ selector: (snapshot: Record<string, unknown>) => R
435
+ ): Signal<R> => {
436
+ const selectorKey = selector as (s: Record<string, unknown>) => unknown;
437
+ const existing = internals.computedSelectors.get(selectorKey);
438
+ if (existing) return existing as Signal<R>;
439
+
440
+ const initial = selector(getSnapshot(internals.signalMap));
441
+ const sig = signal<R>(initial);
442
+ internals.computedSelectors.set(selectorKey, sig as Signal<unknown>);
443
+
444
+ internals.subscribers.add(() => {
445
+ const newValue = selector(getSnapshot(internals.signalMap));
446
+ if (sig.value !== newValue) sig.value = newValue;
447
+ });
448
+
449
+ return sig;
450
+ },
451
+ };
452
+
453
+ const storeProxy = new Proxy(store as unknown as Record<string, unknown>, {
454
+ get(target, prop: string | symbol): unknown {
455
+ const propStr = String(prop);
456
+ if (propStr === 'toJSON') return () => getSnapshot(internals.signalMap);
457
+ if (propStr in target) return target[propStr];
458
+ const sig = internals.signalMap.get(propStr);
459
+ if (sig) return sig;
460
+ if (propStr in boundActions) return boundActions[propStr];
461
+ return undefined;
462
+ },
463
+ }) as Store<T> & StoreState<T>;
464
+
465
+ registerStore(name, storeProxy);
466
+ return storeProxy;
467
+ };
@@ -0,0 +1,107 @@
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 { Schema } from 'effect';
26
+ import type { Signal } from '@effuse/core';
27
+
28
+ export const StoreOptionsSchema = Schema.Struct({
29
+ persist: Schema.optional(Schema.Boolean),
30
+ storageKey: Schema.optional(Schema.String),
31
+ devtools: Schema.optional(Schema.Boolean),
32
+ });
33
+
34
+ // Store configuration schema
35
+ export type StoreOptions = Schema.Schema.Type<typeof StoreOptionsSchema>;
36
+
37
+ // Reactive store state
38
+ export type StoreState<T> = {
39
+ [K in keyof T]: T[K] extends (...args: infer A) => infer R
40
+ ? (...args: A) => R
41
+ : Signal<T[K]>;
42
+ };
43
+
44
+ // Internal store context
45
+ export type StoreContext<T> = {
46
+ [K in keyof T]: T[K] extends (...args: unknown[]) => unknown
47
+ ? T[K]
48
+ : Signal<T[K]>;
49
+ };
50
+
51
+ // Store definition structure
52
+ export type StoreDefinition<T> = {
53
+ [K in keyof T]: T[K] extends (...args: infer A) => infer R
54
+ ? (this: StoreContext<T>, ...args: A) => R
55
+ : T[K];
56
+ };
57
+
58
+ // Action execution context
59
+ export type ActionContext<T> = StoreContext<T>;
60
+
61
+ // Global state middleware
62
+ export type Middleware<T> = (
63
+ state: T,
64
+ action: string,
65
+ args: unknown[]
66
+ ) => T | undefined;
67
+
68
+ // Reactive store instance
69
+ export interface Store<T> {
70
+ readonly name: string;
71
+ readonly state: StoreState<T>;
72
+ subscribe: (callback: () => void) => () => void;
73
+ subscribeToKey: <K extends keyof T>(
74
+ key: K,
75
+ callback: (value: T[K]) => void
76
+ ) => () => void;
77
+ getSnapshot: () => {
78
+ [K in keyof T]: T[K] extends (...args: unknown[]) => unknown ? never : T[K];
79
+ };
80
+ computed: <R>(
81
+ selector: (snapshot: Record<string, unknown>) => R
82
+ ) => Signal<R>;
83
+ batch: (updates: () => void) => void;
84
+ reset: () => void;
85
+ use: (middleware: Middleware<Record<string, unknown>>) => () => void;
86
+ toJSON: () => {
87
+ [K in keyof T]: T[K] extends (...args: unknown[]) => unknown ? never : T[K];
88
+ };
89
+ update: (
90
+ updater: (draft: {
91
+ [K in keyof T]: T[K] extends (...args: unknown[]) => unknown
92
+ ? never
93
+ : T[K];
94
+ }) => void
95
+ ) => void;
96
+ select: <R>(selector: (snapshot: Record<string, unknown>) => R) => Signal<R>;
97
+ }
98
+
99
+ // Extract state type from store
100
+ export type InferStoreState<S> =
101
+ S extends Store<infer T>
102
+ ? {
103
+ [K in keyof T]: T[K] extends (...args: unknown[]) => unknown
104
+ ? never
105
+ : T[K];
106
+ }
107
+ : never;
@@ -0,0 +1,115 @@
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 { Option, pipe } from 'effect';
26
+ import type { Store } from '../core/types.js';
27
+
28
+ interface DevToolsExtension {
29
+ connect: (options?: { name?: string }) => DevToolsConnection;
30
+ }
31
+
32
+ interface DevToolsConnection {
33
+ init: (state: unknown) => void;
34
+ send: (action: { type: string; payload?: unknown }, state: unknown) => void;
35
+ subscribe: (listener: (message: { type: string }) => void) => () => void;
36
+ }
37
+
38
+ // Detect Redux DevTools extension
39
+ export const hasDevTools = (): boolean => {
40
+ if (typeof globalThis === 'undefined') return false;
41
+ const w = globalThis as unknown as {
42
+ __REDUX_DEVTOOLS_EXTENSION__?: DevToolsExtension;
43
+ };
44
+ return w.__REDUX_DEVTOOLS_EXTENSION__ !== undefined;
45
+ };
46
+
47
+ const connections = new Map<string, DevToolsConnection>();
48
+
49
+ // Connect store to DevTools
50
+ export const connectDevTools = <T>(
51
+ store: Store<T>,
52
+ options?: { name?: string }
53
+ ): (() => void) => {
54
+ if (!hasDevTools()) {
55
+ return () => {};
56
+ }
57
+
58
+ const w = globalThis as unknown as {
59
+ __REDUX_DEVTOOLS_EXTENSION__?: DevToolsExtension;
60
+ };
61
+ const extension = w.__REDUX_DEVTOOLS_EXTENSION__;
62
+ if (!extension) return () => {};
63
+
64
+ const storeName = pipe(
65
+ Option.fromNullable(options),
66
+ Option.flatMap((o) => Option.fromNullable(o.name)),
67
+ Option.getOrElse(() => store.name)
68
+ );
69
+
70
+ if (connections.has(storeName)) {
71
+ return () => {};
72
+ }
73
+
74
+ const devTools = extension.connect({ name: `Effuse: ${storeName}` });
75
+ connections.set(storeName, devTools);
76
+
77
+ devTools.init(store.getSnapshot());
78
+
79
+ const unsubscribe = store.subscribe(() => {
80
+ devTools.send({ type: `${storeName}/update` }, store.getSnapshot());
81
+ });
82
+
83
+ return () => {
84
+ unsubscribe();
85
+ connections.delete(storeName);
86
+ };
87
+ };
88
+
89
+ // DevTools reporting middleware
90
+ export const devToolsMiddleware = <T>(storeName: string) => {
91
+ return (state: T, action: string, args: unknown[]): T | undefined => {
92
+ const connection = connections.get(storeName);
93
+ if (connection) {
94
+ connection.send(
95
+ { type: action, payload: args.length === 1 ? args[0] : args },
96
+ state
97
+ );
98
+ }
99
+ return undefined;
100
+ };
101
+ };
102
+
103
+ // Build DevTools middleware
104
+ export const createDevToolsMiddleware = <T>(storeName: string) =>
105
+ devToolsMiddleware<T>(storeName);
106
+
107
+ // Disconnect store from DevTools
108
+ export const disconnectDevTools = (storeName: string): void => {
109
+ connections.delete(storeName);
110
+ };
111
+
112
+ // Disconnect all DevTools connections
113
+ export const disconnectAllDevTools = (): void => {
114
+ connections.clear();
115
+ };