@oxog/state 1.2.0 → 1.3.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.
package/dist/index.d.ts CHANGED
@@ -1,375 +1,5 @@
1
- /**
2
- * Deep partial type for nested optional properties.
3
- *
4
- * @typeParam T - The type to make partially deep
5
- *
6
- * @example
7
- * ```typescript
8
- * type User = {
9
- * name: string;
10
- * profile: { age: number; city: string; };
11
- * };
12
- *
13
- * const partial: DeepPartial<User> = {
14
- * name: 'John',
15
- * profile: { age: 30 } // city is optional
16
- * };
17
- * ```
18
- */
19
- type DeepPartial<T> = T extends object ? {
20
- [P in keyof T]?: DeepPartial<T[P]>;
21
- } : T;
22
- /**
23
- * Action function that receives state and optional arguments, returning a partial state update.
24
- *
25
- * @typeParam TState - The store state type
26
- * @typeParam TArgs - The action argument types tuple
27
- *
28
- * @example
29
- * ```typescript
30
- * type CounterAction = Action<{ count: number }, [number: number]>;
31
- *
32
- * const incrementBy: CounterAction = (state, amount) => ({
33
- * count: state.count + amount
34
- * });
35
- * ```
36
- */
37
- type Action<TState, TArgs extends unknown[] = []> = (state: TState, ...args: TArgs) => Partial<TState> | Promise<Partial<TState>>;
38
- /**
39
- * Collection of actions indexed by name.
40
- *
41
- * @typeParam TState - The store state type
42
- *
43
- * @example
44
- * ```typescript
45
- * const actions: Actions<{ count: number }> = {
46
- * increment: (state) => ({ count: state.count + 1 }),
47
- * decrement: (state) => ({ count: state.count - 1 })
48
- * };
49
- * ```
50
- */
51
- type Actions<TState> = Record<string, Action<TState>>;
52
- /**
53
- * Selector function to extract a slice of state.
54
- *
55
- * @typeParam TState - The store state type
56
- * @typeParam TSelected - The selected value type
57
- *
58
- * @example
59
- * ```typescript
60
- * const selectCount: Selector<{ count: number; name: string }, number> =
61
- * (state) => state.count;
62
- * ```
63
- */
64
- type Selector<TState, TSelected> = (state: TState) => TSelected;
65
- /**
66
- * Equality function for comparing two values.
67
- *
68
- * @typeParam T - The type to compare
69
- *
70
- * @example
71
- * ```typescript
72
- * const shallowEquality: EqualityFn<{ a: number }> = (a, b) =>
73
- * a.a === b.a;
74
- * ```
75
- */
76
- type EqualityFn<T> = (a: T, b: T) => boolean;
77
- /**
78
- * Listener function called when state changes.
79
- *
80
- * @typeParam TState - The store state type
81
- *
82
- * @example
83
- * ```typescript
84
- * const listener: Listener<{ count: number }> = (state, prevState) => {
85
- * console.log(`Count changed from ${prevState.count} to ${state.count}`);
86
- * };
87
- * ```
88
- */
89
- type Listener<TState> = (state: TState, prevState: TState) => void;
90
- /**
91
- * Storage interface for persisting state.
92
- *
93
- * @example
94
- * ```typescript
95
- * const sessionStorage: StorageLike = {
96
- * getItem: (key) => sessionStorage.getItem(key),
97
- * setItem: (key, value) => sessionStorage.setItem(key, value),
98
- * removeItem: (key) => sessionStorage.removeItem(key)
99
- * };
100
- * ```
101
- */
102
- interface StorageLike$1 {
103
- /** Get an item from storage */
104
- getItem(key: string): string | null;
105
- /** Set an item in storage */
106
- setItem(key: string, value: string): void;
107
- /** Remove an item from storage */
108
- removeItem(key: string): void;
109
- }
110
- /**
111
- * Store configuration options.
112
- *
113
- * @typeParam TState - The store state type
114
- *
115
- * @example
116
- * ```typescript
117
- * const options: StoreOptions<{ count: number }> = {
118
- * name: 'Counter',
119
- * devtools: true
120
- * };
121
- * ```
122
- */
123
- interface StoreOptions<TState> {
124
- /** Initial state */
125
- initialState: TState;
126
- /** Store name for debugging */
127
- name?: string;
128
- /** Enable/disable devtools (default: true in development) */
129
- devtools?: boolean;
130
- }
131
- /**
132
- * Plugin interface for extending store functionality.
133
- *
134
- * @typeParam TState - The store state type
135
- *
136
- * @example
137
- * ```typescript
138
- * const loggerPlugin: Plugin<{ count: number }> = {
139
- * name: 'logger',
140
- * version: '1.0.0',
141
- * install(store) {
142
- * store.subscribe((state) => console.log('State:', state));
143
- * }
144
- * };
145
- * ```
146
- */
147
- interface Plugin<TState = unknown> {
148
- /** Unique plugin identifier (kebab-case) */
149
- name: string;
150
- /** Semantic version (e.g., "1.0.0") */
151
- version: string;
152
- /** Other plugins this plugin depends on */
153
- dependencies?: string[];
154
- /**
155
- * Called when plugin is registered.
156
- *
157
- * @param store - The store instance
158
- * @param options - Plugin-specific options
159
- */
160
- install: (store: Store<TState>, options?: unknown) => void;
161
- /**
162
- * Called after all plugins are installed.
163
- *
164
- * @param store - The store instance
165
- */
166
- onInit?: (store: Store<TState>) => void | Promise<void>;
167
- /**
168
- * Called when plugin is unregistered.
169
- */
170
- onDestroy?: () => void | Promise<void>;
171
- /**
172
- * Called on state change.
173
- *
174
- * @param state - New state
175
- * @param prevState - Previous state
176
- */
177
- onStateChange?: (state: TState, prevState: TState) => void;
178
- /**
179
- * Called on error in store.
180
- *
181
- * @param error - The error that occurred
182
- */
183
- onError?: (error: Error) => void;
184
- }
185
- /**
186
- * Store instance with state management methods.
187
- *
188
- * @typeParam TState - The store state type
189
- *
190
- * @example
191
- * ```typescript
192
- * const store: Store<{ count: number }> = createStore({ count: 0 });
193
- * const state = store.getState(); // { count: 0 }
194
- * store.setState({ count: 1 });
195
- * ```
196
- */
197
- interface Store<TState> {
198
- /** Get current state snapshot */
199
- getState(): TState;
200
- /**
201
- * Update state with partial object or function.
202
- *
203
- * @param partial - Partial state or updater function
204
- *
205
- * @example
206
- * ```typescript
207
- * store.setState({ count: 10 });
208
- * store.setState((state) => ({ count: state.count + 1 }));
209
- * ```
210
- */
211
- setState(partial: Partial<TState> | ((state: TState) => Partial<TState>)): void;
212
- /**
213
- * Deep merge state.
214
- *
215
- * @param partial - Partial state to merge
216
- *
217
- * @example
218
- * ```typescript
219
- * store.merge({ user: { name: 'John' } });
220
- * ```
221
- */
222
- merge(partial: DeepPartial<TState>): void;
223
- /** Reset to initial state */
224
- reset(): void;
225
- /**
226
- * Subscribe to state changes.
227
- *
228
- * @param listener - Function called on state changes
229
- * @returns Unsubscribe function
230
- *
231
- * @example
232
- * ```typescript
233
- * const unsubscribe = store.subscribe((state) => console.log(state));
234
- * unsubscribe();
235
- * ```
236
- */
237
- subscribe(listener: Listener<TState>): () => void;
238
- /**
239
- * Subscribe to state changes with selector.
240
- *
241
- * @param selector - Function to extract state slice
242
- * @param listener - Function called when selected value changes
243
- * @param equalityFn - Optional custom equality function
244
- * @returns Unsubscribe function
245
- *
246
- * @example
247
- * ```typescript
248
- * const unsubscribe = store.subscribe(
249
- * (state) => state.count,
250
- * (count) => console.log('Count:', count)
251
- * );
252
- * ```
253
- */
254
- subscribe<TSelected>(selector: Selector<TState, TSelected>, listener: Listener<TSelected>, equalityFn?: EqualityFn<TSelected>): () => void;
255
- /**
256
- * Register a plugin.
257
- *
258
- * @param plugin - The plugin to register
259
- * @param options - Plugin-specific options
260
- * @returns The store instance for chaining
261
- *
262
- * @example
263
- * ```typescript
264
- * store.use(persist({ key: 'app' }));
265
- * ```
266
- */
267
- use<TPlugin extends Plugin<TState>>(plugin: TPlugin, options?: unknown): this;
268
- /** Destroy store and cleanup all resources */
269
- destroy(): void;
270
- }
271
- /**
272
- * Store builder interface for fluent API.
273
- *
274
- * @typeParam TState - The store state type
275
- *
276
- * @example
277
- * ```typescript
278
- * createStore({ count: 0 })
279
- * .action('increment', (s) => ({ count: s.count + 1 }))
280
- * .action('decrement', (s) => ({ count: s.count - 1 }));
281
- * ```
282
- */
283
- interface StoreBuilder<TState> extends Store<TState> {
284
- /**
285
- * Add an action to the store.
286
- *
287
- * @param name - Action name
288
- * @param fn - Action function
289
- * @returns The builder for chaining
290
- */
291
- action<K extends string>(name: K, fn: Action<TState & Record<K, Action<TState>>>): this;
292
- }
293
- /**
294
- * Error codes for store errors.
295
- */
296
- declare enum StoreErrorCode {
297
- /** Store was destroyed and cannot be used */
298
- STORE_DESTROYED = "STORE_DESTROYED",
299
- /** Plugin with same name already registered */
300
- PLUGIN_EXISTS = "PLUGIN_EXISTS",
301
- /** Required plugin dependency not found */
302
- PLUGIN_DEPENDENCY_MISSING = "PLUGIN_DEPENDENCY_MISSING",
303
- /** Invalid state update argument */
304
- INVALID_STATE_UPDATE = "INVALID_STATE_UPDATE",
305
- /** Action threw an error */
306
- ACTION_ERROR = "ACTION_ERROR"
307
- }
308
- /**
309
- * Store error class.
310
- */
311
- declare class StoreError extends Error {
312
- code: StoreErrorCode;
313
- constructor(code: StoreErrorCode, message: string);
314
- }
315
-
316
- /**
317
- * Create a new reactive store.
318
- *
319
- * Supports three action definition styles:
320
- * - **Inline**: Actions defined within state object (functions starting with $)
321
- * - **Separate**: Actions passed as second argument
322
- * - **Fluent**: Actions added via `.action()` method
323
- *
324
- * @typeParam TState - The type of the store state
325
- * @param initialState - Initial state object, may include inline actions
326
- * @param actions - Optional separate actions object
327
- * @returns A new Store instance
328
- *
329
- * @example
330
- * ```typescript
331
- * // Style A: Inline actions (prefix with $)
332
- * const store = createStore({
333
- * count: 0,
334
- * $increment: (state) => ({ count: state.count + 1 }),
335
- * });
336
- *
337
- * // Style B: Separate actions
338
- * const store = createStore(
339
- * { count: 0 },
340
- * { increment: (state) => ({ count: state.count + 1 }) }
341
- * );
342
- *
343
- * // Style C: Fluent builder
344
- * const store = createStore({ count: 0 })
345
- * .action('increment', (state) => ({ count: state.count + 1 }));
346
- * ```
347
- */
348
- declare function createStore<TState>(initialState: TState, actions?: Actions<TState>): Store<TState>;
349
- /**
350
- * Batch multiple state updates into a single notification.
351
- *
352
- * @param fn - Function containing state updates
353
- * @returns The return value of fn
354
- *
355
- * @example
356
- * ```typescript
357
- * import { batch } from '@oxog/state';
358
- *
359
- * // Without batch - 3 re-renders
360
- * store.setState({ a: 1 });
361
- * store.setState({ b: 2 });
362
- * store.setState({ c: 3 });
363
- *
364
- * // With batch - 1 re-render
365
- * batch(() => {
366
- * store.setState({ a: 1 });
367
- * store.setState({ b: 2 });
368
- * store.setState({ c: 3 });
369
- * });
370
- * ```
371
- */
372
- declare function batch<T>(fn: () => T): T;
1
+ import { Store, Selector, EqualityFn } from './vanilla.js';
2
+ export { Action, Actions, BoundAction, BoundActions, Computed, ComputedOptions, CreatedStore, DeepPartial, DevtoolsOptions, EffectCleanup, EffectDefinition, EffectFn, EffectUtils, EffectsOptions, EqualityCheck, ExtractStateType, FederatedState, Federation, FederationListener, FederationOptions, GetSlice, HistoryOptions, HistoryStore, InlineActions, Listener, LogLevel, LoggerOptions, MiddlewareFn, MiddlewareGetState, MiddlewareSetState, MiddlewareStoreApi, MiddlewareSubscribe, MockStorage, MockedAction, PersistOptions, Plugin, SelectorFn, SelectorOptions, SetSlice, SliceCreator, SliceDefinition, StateAssertion, StateChange, StateCreatorFn, StateWithActions, StateWithoutInlineActions, StorageLike, StoreBuilder, StoreError, StoreError as StoreErrorClass, StoreErrorCode, StoreOptions, StoreSpy, StoreState, SubscribeOptions, SyncOptions, TestStore, TestStoreOptions, TransactionFn, ValidateOptions, ValidationAPI, ValidationError, ValidationResult, ValidationTiming, ValidatorFn, assertState, batch, combineComputed, combineEffects, combineSlices, combineValidators, compose, computed, createAsyncValidator, createDebouncedEffect, createEffect, createFederatedComputed, createFederatedSelector, createFederation, createFieldValidator, createLogger, createMockStorage, createNamespacedSlice, createSimpleEffect, createSimpleMiddleware, createSlice, createStorage, createStore, createSubscriber, createTestStore, createValidator, createWithMiddleware, deepClone, deepEqual, deepMerge, delay, devtools, effects, extendStore, flushMicrotasks, hasHistory, history, identity, immer, isFunction, logger, memoizeSelector, middlewareCompat, mockAction, omit, persist, pick, produce, resetSlices, selector, sessionStorage, shallowEqual, snapshot, spyOnStore, stateDiff, subscribeOnce, subscribeToMany, subscribeWithOptions, sync, toMiddlewareApi, triggerSync, validate, waitForFederated } from './vanilla.js';
373
3
 
374
4
  /**
375
5
  * React hook for subscribing to store state changes.
@@ -422,7 +52,9 @@ declare function useStore<TState, TSelected = TState>(store: Store<TState>, sele
422
52
  /**
423
53
  * React hook for creating and using a store.
424
54
  *
425
- * Creates a store on first render and destroys it on unmount.
55
+ * Creates a store on first render and destroys it after the component
56
+ * unmounts. Safe under React StrictMode (the simulated unmount/remount in
57
+ * development does not destroy the store).
426
58
  *
427
59
  * @typeParam TState - The store state type
428
60
  * @param initialState - The initial state
@@ -618,2164 +250,4 @@ declare function useTransientSubscribe<TState, TSelected>(store: Store<TState>,
618
250
  */
619
251
  declare function useSetState<TState>(store: Store<TState>): (partial: Partial<TState> | ((state: TState) => Partial<TState>)) => void;
620
252
 
621
- /**
622
- * Enhanced subscription system with advanced options.
623
- *
624
- * @module subscribe
625
- */
626
-
627
- /**
628
- * Options for enhanced subscriptions.
629
- *
630
- * @typeParam T - The store state type
631
- * @typeParam U - The selected value type
632
- *
633
- * @example
634
- * ```typescript
635
- * const options: SubscribeOptions<State, number> = {
636
- * debounce: 100,
637
- * fireImmediately: true,
638
- * when: (state) => state.isReady
639
- * };
640
- * ```
641
- */
642
- interface SubscribeOptions<T, U = T> {
643
- /** Custom equality function for comparing selected values */
644
- equalityFn?: EqualityFn<U>;
645
- /** Fire callback immediately with current state */
646
- fireImmediately?: boolean;
647
- /** Debounce notifications (ms) */
648
- debounce?: number;
649
- /** Throttle notifications (ms) */
650
- throttle?: number;
651
- /** Only fire when condition is met */
652
- when?: (state: T, prevState: T) => boolean;
653
- }
654
- /**
655
- * Enhanced subscribe function with advanced options.
656
- *
657
- * @param store - The store to subscribe to
658
- * @param selectorOrListener - Selector function or direct listener
659
- * @param listenerOrOptions - Listener function or options (if no selector)
660
- * @param options - Subscription options
661
- * @returns Unsubscribe function
662
- *
663
- * @example
664
- * ```typescript
665
- * // With debounce
666
- * const unsubscribe = subscribeWithOptions(
667
- * store,
668
- * (state) => state.searchQuery,
669
- * (query) => performSearch(query),
670
- * { debounce: 300 }
671
- * );
672
- *
673
- * // With throttle and condition
674
- * const unsubscribe = subscribeWithOptions(
675
- * store,
676
- * (state) => state.scrollPosition,
677
- * (pos) => updateUI(pos),
678
- * { throttle: 16, when: (state) => state.isVisible }
679
- * );
680
- *
681
- * // Fire immediately
682
- * const unsubscribe = subscribeWithOptions(
683
- * store,
684
- * (state) => state.user,
685
- * (user) => console.log('User:', user),
686
- * { fireImmediately: true }
687
- * );
688
- * ```
689
- */
690
- declare function subscribeWithOptions<TState, TSelected>(store: Store<TState>, selector: Selector<TState, TSelected>, listener: Listener<TSelected>, options?: SubscribeOptions<TState, TSelected>): () => void;
691
- /**
692
- * Create a subscription factory with preset options.
693
- *
694
- * @param defaultOptions - Default options for all subscriptions
695
- * @returns A subscribe function with preset options
696
- *
697
- * @example
698
- * ```typescript
699
- * const debouncedSubscribe = createSubscriber({ debounce: 100 });
700
- *
701
- * const unsubscribe = debouncedSubscribe(
702
- * store,
703
- * (state) => state.input,
704
- * (input) => validate(input)
705
- * );
706
- * ```
707
- */
708
- declare function createSubscriber<TState>(defaultOptions?: SubscribeOptions<TState, any>): <TSelected>(store: Store<TState>, selector: Selector<TState, TSelected>, listener: Listener<TSelected>, options?: SubscribeOptions<TState, TSelected>) => () => void;
709
- /**
710
- * Subscribe to multiple selectors with a single listener.
711
- *
712
- * @param store - The store to subscribe to
713
- * @param selectors - Object of named selectors
714
- * @param listener - Listener called when any selector value changes
715
- * @param options - Subscription options
716
- * @returns Unsubscribe function
717
- *
718
- * @example
719
- * ```typescript
720
- * const unsubscribe = subscribeToMany(
721
- * store,
722
- * {
723
- * count: (s) => s.count,
724
- * name: (s) => s.name,
725
- * },
726
- * ({ count, name }) => console.log(`${name}: ${count}`)
727
- * );
728
- * ```
729
- */
730
- declare function subscribeToMany<TState, TSelectors extends Record<string, Selector<TState, any>>>(store: Store<TState>, selectors: TSelectors, listener: (values: {
731
- [K in keyof TSelectors]: ReturnType<TSelectors[K]>;
732
- }) => void, options?: Omit<SubscribeOptions<TState, any>, 'equalityFn'>): () => void;
733
- /**
734
- * Subscribe only once - automatically unsubscribes after first call.
735
- *
736
- * @param store - The store to subscribe to
737
- * @param selector - Selector function
738
- * @param listener - Listener called once when value changes
739
- * @param options - Subscription options
740
- * @returns Unsubscribe function (can be called to cancel before trigger)
741
- *
742
- * @example
743
- * ```typescript
744
- * // Wait for user to be loaded
745
- * subscribeOnce(
746
- * store,
747
- * (state) => state.user,
748
- * (user) => console.log('User loaded:', user),
749
- * { when: (state) => state.user !== null }
750
- * );
751
- * ```
752
- */
753
- declare function subscribeOnce<TState, TSelected>(store: Store<TState>, selector: Selector<TState, TSelected>, listener: Listener<TSelected>, options?: SubscribeOptions<TState, TSelected>): () => void;
754
-
755
- /**
756
- * Computed values (derived state) with memoization.
757
- *
758
- * @module computed
759
- */
760
-
761
- /**
762
- * Options for computed values.
763
- *
764
- * @typeParam T - The store state type
765
- * @typeParam U - The computed value type
766
- */
767
- interface ComputedOptions<T, U> {
768
- /** Custom equality for caching */
769
- equals?: EqualityFn<U>;
770
- /** Lazy evaluation (only compute when accessed) */
771
- lazy?: boolean;
772
- /** Keep last N values in cache for time-travel debugging */
773
- cacheSize?: number;
774
- }
775
- /**
776
- * Computed value interface with getter and utilities.
777
- */
778
- interface Computed<U> {
779
- /** Get the computed value */
780
- (): U;
781
- /** Get value (alias) */
782
- get(): U;
783
- /** Force recomputation */
784
- invalidate(): void;
785
- /** Subscribe to value changes */
786
- subscribe(listener: (value: U, prevValue: U) => void): () => void;
787
- /** Get cache history (if cacheSize > 1) */
788
- getHistory(): U[];
789
- /** Destroy and cleanup */
790
- destroy(): void;
791
- }
792
- /**
793
- * Create a computed (derived) value from store state.
794
- *
795
- * Computed values are memoized and only recompute when dependencies change.
796
- *
797
- * @param store - The store to derive from
798
- * @param selector - Function to compute the derived value
799
- * @param options - Computed options
800
- * @returns A computed value accessor
801
- *
802
- * @example
803
- * ```typescript
804
- * const store = createStore({ items: [], filter: 'all' });
805
- *
806
- * // Simple computed
807
- * const filteredItems = computed(store, (state) => {
808
- * if (state.filter === 'all') return state.items;
809
- * return state.items.filter(item => item.status === state.filter);
810
- * });
811
- *
812
- * console.log(filteredItems()); // Get computed value
813
- *
814
- * // With caching for debugging
815
- * const total = computed(
816
- * store,
817
- * (state) => state.items.reduce((sum, item) => sum + item.price, 0),
818
- * { cacheSize: 10 }
819
- * );
820
- *
821
- * console.log(total.getHistory()); // See past values
822
- * ```
823
- */
824
- declare function computed<TState, TComputed>(store: Store<TState>, selector: Selector<TState, TComputed>, options?: ComputedOptions<TState, TComputed>): Computed<TComputed>;
825
- /**
826
- * Create a computed value that depends on other computed values.
827
- *
828
- * @param computeds - Array of computed values to depend on
829
- * @param combiner - Function to combine the computed values
830
- * @param options - Computed options
831
- * @returns A combined computed value
832
- *
833
- * @example
834
- * ```typescript
835
- * const subtotal = computed(store, (s) => s.items.reduce((sum, i) => sum + i.price, 0));
836
- * const tax = computed(store, (s) => s.taxRate);
837
- *
838
- * const total = combineComputed(
839
- * [subtotal, tax],
840
- * ([subtotalVal, taxVal]) => subtotalVal * (1 + taxVal)
841
- * );
842
- *
843
- * console.log(total()); // Subtotal + tax
844
- * ```
845
- */
846
- declare function combineComputed<TInputs extends Computed<any>[], TOutput>(computeds: [...TInputs], combiner: (values: {
847
- [K in keyof TInputs]: TInputs[K] extends Computed<infer U> ? U : never;
848
- }) => TOutput, options?: Omit<ComputedOptions<any, TOutput>, 'lazy'>): Computed<TOutput>;
849
- /**
850
- * Create a memoized selector for use with store.subscribe.
851
- *
852
- * @param selector - The selector function to memoize
853
- * @param equals - Custom equality function
854
- * @returns A memoized selector
855
- *
856
- * @example
857
- * ```typescript
858
- * const selectExpensiveComputation = memoizeSelector(
859
- * (state: State) => expensiveOperation(state.data)
860
- * );
861
- *
862
- * store.subscribe(selectExpensiveComputation, (result) => {
863
- * console.log('Result:', result);
864
- * });
865
- * ```
866
- */
867
- declare function memoizeSelector<TState, TSelected>(selector: Selector<TState, TSelected>, equals?: EqualityFn<TSelected>): Selector<TState, TSelected>;
868
-
869
- /**
870
- * Slices pattern for modular store composition.
871
- *
872
- * @module slices
873
- */
874
-
875
- /**
876
- * SetSlice function type for updating slice state.
877
- */
878
- type SetSlice<TState> = {
879
- (partial: Partial<TState>): void;
880
- (updater: (state: TState) => Partial<TState>): void;
881
- };
882
- /**
883
- * GetSlice function type for getting current state.
884
- */
885
- type GetSlice<TState> = () => TState;
886
- /**
887
- * Slice creator function signature.
888
- *
889
- * @typeParam TState - The full store state type
890
- * @typeParam TSlice - The slice state type
891
- */
892
- type SliceCreator<TState, TSlice extends Partial<TState>> = (set: SetSlice<TState>, get: GetSlice<TState>, store: Store<TState>) => TSlice;
893
- /**
894
- * Slice definition with state and actions.
895
- */
896
- interface SliceDefinition<TState, TSlice extends Partial<TState>> {
897
- /** Slice name for debugging */
898
- name: string;
899
- /** Slice creator function */
900
- creator: SliceCreator<TState, TSlice>;
901
- }
902
- /**
903
- * Create a slice definition for use with combineSlices.
904
- *
905
- * Slices are modular pieces of state and actions that can be combined
906
- * to create a complete store.
907
- *
908
- * @param name - Slice name for debugging
909
- * @param creator - Slice creator function
910
- * @returns A slice definition
911
- *
912
- * @example
913
- * ```typescript
914
- * // Define a counter slice
915
- * const counterSlice = createSlice('counter', (set, get) => ({
916
- * count: 0,
917
- * increment: () => set((s) => ({ count: s.count + 1 })),
918
- * decrement: () => set((s) => ({ count: s.count - 1 })),
919
- * reset: () => set({ count: 0 }),
920
- * }));
921
- *
922
- * // Define a user slice
923
- * const userSlice = createSlice('user', (set, get) => ({
924
- * user: null as User | null,
925
- * setUser: (user: User) => set({ user }),
926
- * logout: () => set({ user: null }),
927
- * }));
928
- *
929
- * // Combine slices into a store
930
- * const store = combineSlices(counterSlice, userSlice);
931
- *
932
- * // Use the store
933
- * store.increment();
934
- * store.setUser({ name: 'John' });
935
- * ```
936
- */
937
- declare function createSlice<TState, TSlice extends Partial<TState>>(name: string, creator: SliceCreator<TState, TSlice>): SliceDefinition<TState, TSlice>;
938
- /**
939
- * Internal slice creator type for type inference.
940
- */
941
- type InferSlice<T> = T extends SliceDefinition<any, infer S> ? S : never;
942
- /**
943
- * Combined state type from multiple slices.
944
- */
945
- type CombinedState<TSlices extends SliceDefinition<any, any>[]> = {
946
- [K in keyof TSlices]: InferSlice<TSlices[K]>;
947
- }[number] extends infer U ? U extends object ? {
948
- [K in keyof U as U extends Record<K, any> ? K : never]: U[K];
949
- } : never : never;
950
- /**
951
- * Combine multiple slices into a single store.
952
- *
953
- * @param slices - Slice definitions to combine
954
- * @returns A store with combined state and actions
955
- *
956
- * @example
957
- * ```typescript
958
- * const counterSlice = createSlice('counter', (set) => ({
959
- * count: 0,
960
- * increment: () => set((s) => ({ count: s.count + 1 })),
961
- * }));
962
- *
963
- * const userSlice = createSlice('user', (set) => ({
964
- * user: null,
965
- * setUser: (user) => set({ user }),
966
- * }));
967
- *
968
- * const store = combineSlices(counterSlice, userSlice);
969
- *
970
- * // Type-safe access to all slice methods
971
- * store.increment();
972
- * store.setUser({ name: 'John' });
973
- * ```
974
- */
975
- declare function combineSlices<TSlices extends SliceDefinition<any, any>[]>(...slices: TSlices): Store<CombinedState<TSlices>> & CombinedState<TSlices>;
976
- /**
977
- * Create a namespaced slice that prefixes all state keys.
978
- *
979
- * @param namespace - The namespace prefix
980
- * @param creator - Slice creator function
981
- * @returns A namespaced slice definition
982
- *
983
- * @example
984
- * ```typescript
985
- * const settingsSlice = createNamespacedSlice('settings', (set) => ({
986
- * theme: 'dark',
987
- * language: 'en',
988
- * setTheme: (theme) => set({ theme }),
989
- * }));
990
- *
991
- * // State will be: { settings: { theme: 'dark', language: 'en' } }
992
- * // Actions will be: setTheme
993
- * ```
994
- */
995
- declare function createNamespacedSlice<TSlice extends Record<string, any>>(namespace: string, creator: (set: (partial: Partial<TSlice>) => void, get: () => TSlice) => TSlice): SliceDefinition<Record<string, any>, Record<string, any>>;
996
- /**
997
- * Extend an existing store with additional slices.
998
- *
999
- * @param store - The existing store
1000
- * @param slices - Additional slices to add
1001
- * @returns The extended store
1002
- *
1003
- * @example
1004
- * ```typescript
1005
- * const baseStore = createStore({ count: 0 });
1006
- *
1007
- * const extendedStore = extendStore(
1008
- * baseStore,
1009
- * createSlice('user', (set) => ({
1010
- * user: null,
1011
- * setUser: (user) => set({ user }),
1012
- * }))
1013
- * );
1014
- * ```
1015
- */
1016
- declare function extendStore<TState, TSlices extends SliceDefinition<TState & any, any>[]>(store: Store<TState>, ...slices: TSlices): Store<TState & CombinedState<TSlices>> & CombinedState<TSlices>;
1017
- /**
1018
- * Reset specific slices to their initial state.
1019
- *
1020
- * @param store - The store
1021
- * @param sliceNames - Names of slices to reset
1022
- *
1023
- * @example
1024
- * ```typescript
1025
- * // Reset only the user slice
1026
- * resetSlices(store, 'user');
1027
- *
1028
- * // Reset multiple slices
1029
- * resetSlices(store, 'user', 'cart');
1030
- * ```
1031
- */
1032
- declare function resetSlices<TState>(store: Store<TState>, ...sliceNames: string[]): void;
1033
-
1034
- /**
1035
- * Store Federation - Multi-store coordination and communication.
1036
- *
1037
- * Enables coordinated updates across multiple stores with
1038
- * atomic transactions and unified state access.
1039
- *
1040
- * @module federation
1041
- */
1042
-
1043
- /**
1044
- * Extract state type from a Store.
1045
- */
1046
- type StoreState<S> = S extends Store<infer T> ? T : never;
1047
- /**
1048
- * Map of store names to their state types.
1049
- */
1050
- type FederatedState<Stores extends Record<string, Store<any>>> = {
1051
- [K in keyof Stores]: StoreState<Stores[K]>;
1052
- };
1053
- /**
1054
- * Federation listener callback.
1055
- */
1056
- type FederationListener<Stores extends Record<string, Store<any>>> = (state: FederatedState<Stores>, prevState: FederatedState<Stores>, changedStore: keyof Stores) => void;
1057
- /**
1058
- * Federation transaction function.
1059
- */
1060
- type TransactionFn<Stores extends Record<string, Store<any>>> = (stores: Stores) => void | Promise<void>;
1061
- /**
1062
- * Federation options.
1063
- */
1064
- interface FederationOptions {
1065
- /** Name for debugging */
1066
- name?: string;
1067
- /** Enable transaction logging */
1068
- debug?: boolean;
1069
- }
1070
- /**
1071
- * Federation interface for coordinating multiple stores.
1072
- */
1073
- interface Federation<Stores extends Record<string, Store<any>>> {
1074
- /** Access to individual stores */
1075
- readonly stores: Stores;
1076
- /** Get combined state from all stores */
1077
- getState(): FederatedState<Stores>;
1078
- /** Subscribe to any store change */
1079
- subscribe(listener: FederationListener<Stores>): () => void;
1080
- /** Atomic multi-store update (synchronous) */
1081
- transaction(fn: TransactionFn<Stores>): void;
1082
- /** Async transaction with rollback on error */
1083
- transactionAsync(fn: TransactionFn<Stores>): Promise<void>;
1084
- /** Get a specific store */
1085
- getStore<K extends keyof Stores>(name: K): Stores[K];
1086
- /** Destroy federation and unsubscribe from all stores */
1087
- destroy(): void;
1088
- }
1089
- /**
1090
- * Create a federation of multiple stores.
1091
- *
1092
- * @param stores - Object containing named stores
1093
- * @param options - Federation options
1094
- * @returns A federation instance
1095
- *
1096
- * @example
1097
- * ```typescript
1098
- * import { createStore, createFederation } from '@oxog/state';
1099
- *
1100
- * // Create individual stores
1101
- * const userStore = createStore({
1102
- * user: null,
1103
- * setUser: (state, user) => ({ user }),
1104
- * });
1105
- *
1106
- * const cartStore = createStore({
1107
- * items: [],
1108
- * addItem: (state, item) => ({ items: [...state.items, item] }),
1109
- * clear: () => ({ items: [] }),
1110
- * });
1111
- *
1112
- * const settingsStore = createStore({
1113
- * theme: 'light',
1114
- * setTheme: (state, theme) => ({ theme }),
1115
- * });
1116
- *
1117
- * // Create federation
1118
- * const federation = createFederation({
1119
- * user: userStore,
1120
- * cart: cartStore,
1121
- * settings: settingsStore,
1122
- * });
1123
- *
1124
- * // Get combined state
1125
- * const state = federation.getState();
1126
- * // { user: { user: null, ... }, cart: { items: [], ... }, settings: { theme: 'light', ... } }
1127
- *
1128
- * // Subscribe to any store change
1129
- * federation.subscribe((state, prevState, changedStore) => {
1130
- * console.log(`${changedStore} changed:`, state[changedStore]);
1131
- * });
1132
- *
1133
- * // Atomic cross-store transaction
1134
- * federation.transaction(({ user, cart }) => {
1135
- * cart.setState({ items: [] });
1136
- * user.setState({ user: null });
1137
- * });
1138
- * ```
1139
- */
1140
- declare function createFederation<Stores extends Record<string, Store<any>>>(stores: Stores, options?: FederationOptions): Federation<Stores>;
1141
- /**
1142
- * Create a selector that combines state from multiple stores.
1143
- *
1144
- * @param federation - The federation instance
1145
- * @param selector - Selector function
1146
- * @returns A function that returns the selected value
1147
- *
1148
- * @example
1149
- * ```typescript
1150
- * const getCartTotal = createFederatedSelector(
1151
- * federation,
1152
- * (state) => {
1153
- * const items = state.cart.items;
1154
- * const discount = state.user.user?.discount || 0;
1155
- * const total = items.reduce((sum, item) => sum + item.price, 0);
1156
- * return total * (1 - discount);
1157
- * }
1158
- * );
1159
- *
1160
- * const total = getCartTotal();
1161
- * ```
1162
- */
1163
- declare function createFederatedSelector<Stores extends Record<string, Store<any>>, R>(federation: Federation<Stores>, selector: (state: FederatedState<Stores>) => R): () => R;
1164
- /**
1165
- * Create a computed value from federated state.
1166
- *
1167
- * @param federation - The federation instance
1168
- * @param selector - Selector function
1169
- * @param equalityFn - Optional equality function for caching
1170
- * @returns Object with get() and subscribe() methods
1171
- *
1172
- * @example
1173
- * ```typescript
1174
- * const isLoggedIn = createFederatedComputed(
1175
- * federation,
1176
- * (state) => state.user.user !== null
1177
- * );
1178
- *
1179
- * // Get current value
1180
- * if (isLoggedIn.get()) {
1181
- * showDashboard();
1182
- * }
1183
- *
1184
- * // Subscribe to changes
1185
- * isLoggedIn.subscribe((value) => {
1186
- * console.log('Login status:', value);
1187
- * });
1188
- * ```
1189
- */
1190
- declare function createFederatedComputed<Stores extends Record<string, Store<any>>, R>(federation: Federation<Stores>, selector: (state: FederatedState<Stores>) => R, equalityFn?: (a: R, b: R) => boolean): {
1191
- get(): R;
1192
- subscribe(listener: (value: R, prevValue: R) => void): () => void;
1193
- };
1194
- /**
1195
- * Wait for a condition across federated stores.
1196
- *
1197
- * @param federation - The federation instance
1198
- * @param predicate - Condition to wait for
1199
- * @param timeout - Optional timeout in ms
1200
- * @returns Promise that resolves when condition is met
1201
- *
1202
- * @example
1203
- * ```typescript
1204
- * // Wait for user to be logged in and cart to have items
1205
- * await waitForFederated(
1206
- * federation,
1207
- * (state) => state.user.user !== null && state.cart.items.length > 0,
1208
- * 5000 // 5 second timeout
1209
- * );
1210
- *
1211
- * // Now proceed with checkout
1212
- * checkout();
1213
- * ```
1214
- */
1215
- declare function waitForFederated<Stores extends Record<string, Store<any>>>(federation: Federation<Stores>, predicate: (state: FederatedState<Stores>) => boolean, timeout?: number): Promise<FederatedState<Stores>>;
1216
-
1217
- /**
1218
- * Plugin-specific types and interfaces.
1219
- */
1220
-
1221
- /**
1222
- * Persist plugin options.
1223
- */
1224
- interface PersistOptions<TState> {
1225
- /** Storage key */
1226
- key: string;
1227
- /** Storage implementation (defaults to localStorage) */
1228
- storage?: StorageLike;
1229
- /** List of state keys to persist (whitelist) */
1230
- whitelist?: Array<keyof TState>;
1231
- /** List of state keys to exclude (blacklist) */
1232
- blacklist?: Array<keyof TState>;
1233
- /** Custom function to select which parts of state to persist */
1234
- partialize?: (state: TState) => Partial<TState>;
1235
- /** Custom merge strategy for hydration */
1236
- merge?: (persistedState: Partial<TState>, currentState: TState) => TState;
1237
- /** Version for migration support */
1238
- version?: number;
1239
- /** Migration function between versions */
1240
- migrate?: (persistedState: unknown, version: number) => TState;
1241
- /** Custom serialization */
1242
- serialize?: (state: Partial<TState>) => string;
1243
- /** Custom deserialization */
1244
- deserialize?: (str: string) => Partial<TState>;
1245
- /** Encryption function */
1246
- encrypt?: (data: string) => string;
1247
- /** Decryption function */
1248
- decrypt?: (data: string) => string;
1249
- /** Debounce writes to storage (ms) */
1250
- writeDebounce?: number;
1251
- /** Called when hydration starts */
1252
- onRehydrateStorage?: (state: TState | undefined) => void;
1253
- /** Called when hydration completes */
1254
- onHydrationComplete?: (state: TState) => void;
1255
- /** Called on persistence error */
1256
- onPersistError?: (error: Error) => void;
1257
- }
1258
- /**
1259
- * Storage interface for persistence.
1260
- */
1261
- interface StorageLike {
1262
- getItem(key: string): string | null;
1263
- setItem(key: string, value: string): void;
1264
- removeItem(key: string): void;
1265
- }
1266
- /**
1267
- * Devtools plugin options.
1268
- */
1269
- interface DevtoolsOptions {
1270
- /** Store name for DevTools */
1271
- name?: string;
1272
- /** Enable/disable DevTools */
1273
- enabled?: boolean;
1274
- /** Maximum number of states to keep in history */
1275
- maxAge?: number;
1276
- }
1277
- /**
1278
- * History plugin options.
1279
- */
1280
- interface HistoryOptions<TState> {
1281
- /** Maximum number of past states to keep */
1282
- limit?: number;
1283
- /** Keys to track for history (empty array tracks all) */
1284
- keys?: Array<keyof TState>;
1285
- }
1286
- /**
1287
- * Sync plugin options.
1288
- */
1289
- interface SyncOptions {
1290
- /** Channel name for BroadcastChannel */
1291
- channel?: string;
1292
- }
1293
- /**
1294
- * Selector plugin options.
1295
- */
1296
- interface SelectorOptions<TState> {
1297
- /** Map of computed selectors */
1298
- selectors: {
1299
- [K in keyof TState]?: (state: TState) => TState[K];
1300
- };
1301
- }
1302
- /**
1303
- * History-enabled store interface.
1304
- */
1305
- interface HistoryStore<TState> extends Store<TState> {
1306
- undo(): void;
1307
- redo(): void;
1308
- clearHistory(): void;
1309
- canUndo(): boolean;
1310
- canRedo(): boolean;
1311
- }
1312
-
1313
- /**
1314
- * Persist plugin - Save and restore state from storage.
1315
- *
1316
- * Automatically persists state to localStorage, sessionStorage, or any
1317
- * storage implementation. State is restored on store creation.
1318
- *
1319
- * @example
1320
- * ```typescript
1321
- * import { createStore, persist } from '@oxog/state';
1322
- *
1323
- * const store = createStore({ count: 0, user: null })
1324
- * .use(persist({
1325
- * key: 'my-app',
1326
- * storage: localStorage,
1327
- * whitelist: ['count'] // Only persist count
1328
- * }));
1329
- * ```
1330
- */
1331
-
1332
- /**
1333
- * SessionStorage implementation.
1334
- */
1335
- declare const sessionStorage: StorageLike;
1336
- /**
1337
- * Create a persist plugin.
1338
- *
1339
- * @param options - Plugin options
1340
- * @returns A persist plugin
1341
- *
1342
- * @example
1343
- * ```typescript
1344
- * import { persist, sessionStorage } from '@oxog/state';
1345
- *
1346
- * // Using localStorage (default)
1347
- * const store = createStore({ count: 0 })
1348
- * .use(persist({ key: 'counter' }));
1349
- *
1350
- * // Using sessionStorage
1351
- * const store = createStore({ count: 0 })
1352
- * .use(persist({ key: 'counter', storage: sessionStorage }));
1353
- *
1354
- * // With whitelist
1355
- * const store = createStore({ count: 0, temp: '' })
1356
- * .use(persist({ key: 'app', whitelist: ['count'] }));
1357
- *
1358
- * // With encryption
1359
- * const store = createStore({ secret: 'data' })
1360
- * .use(persist({
1361
- * key: 'secure',
1362
- * encrypt: (data) => btoa(data),
1363
- * decrypt: (data) => atob(data),
1364
- * }));
1365
- *
1366
- * // With debounce and migration
1367
- * const store = createStore({ count: 0 })
1368
- * .use(persist({
1369
- * key: 'app',
1370
- * writeDebounce: 1000,
1371
- * version: 2,
1372
- * migrate: (state, version) => {
1373
- * if (version < 2) return { ...state, newField: 'default' };
1374
- * return state;
1375
- * },
1376
- * }));
1377
- * ```
1378
- */
1379
- declare function persist<TState>(options: PersistOptions<TState>): Plugin<TState>;
1380
- /**
1381
- * Create a custom storage from a storage object.
1382
- *
1383
- * @param storage - Any object with getItem, setItem, removeItem
1384
- * @returns A StorageLike interface
1385
- *
1386
- * @example
1387
- * ```typescript
1388
- * import { createStorage } from '@oxog/state';
1389
- *
1390
- * const AsyncStorage = createStorage({
1391
- * getItem: async (key) => await AsyncStorage.getItem(key),
1392
- * setItem: async (key, value) => await AsyncStorage.setItem(key, value),
1393
- * removeItem: async (key) => await AsyncStorage.removeItem(key),
1394
- * });
1395
- * ```
1396
- */
1397
- declare function createStorage(storage: StorageLike): StorageLike;
1398
-
1399
- /**
1400
- * Devtools plugin - Redux DevTools integration.
1401
- *
1402
- * Connects to Redux DevTools extension for debugging state changes.
1403
- *
1404
- * @example
1405
- * ```typescript
1406
- * import { createStore, devtools } from '@oxog/state';
1407
- *
1408
- * const store = createStore({ count: 0 })
1409
- * .use(devtools({ name: 'Counter' }));
1410
- * ```
1411
- */
1412
-
1413
- /**
1414
- * Create a DevTools plugin.
1415
- *
1416
- * @param options - Plugin options
1417
- * @returns A DevTools plugin
1418
- *
1419
- * @example
1420
- * ```typescript
1421
- * import { devtools } from '@oxog/state';
1422
- *
1423
- * // Basic usage
1424
- * const store = createStore({ count: 0 })
1425
- * .use(devtools({ name: 'My Store' }));
1426
- *
1427
- * // Disabled in production
1428
- * const store = createStore({ count: 0 })
1429
- * .use(devtools({
1430
- * name: 'My Store',
1431
- * enabled: process.env.NODE_ENV === 'development'
1432
- * }));
1433
- * ```
1434
- */
1435
- declare function devtools<TState>(options?: DevtoolsOptions): Plugin<TState>;
1436
-
1437
- /**
1438
- * History plugin - Undo/redo functionality.
1439
- *
1440
- * Tracks state changes and provides undo/redo methods.
1441
- *
1442
- * @example
1443
- * ```typescript
1444
- * import { createStore, history } from '@oxog/state';
1445
- *
1446
- * const store = createStore({ count: 0 })
1447
- * .use(history({ limit: 100 }));
1448
- *
1449
- * // Now store has undo() and redo() methods
1450
- * store.setState({ count: 1 });
1451
- * store.setState({ count: 2 });
1452
- * store.undo(); // { count: 1 }
1453
- * store.redo(); // { count: 2 }
1454
- * ```
1455
- */
1456
-
1457
- /**
1458
- * Create a history plugin.
1459
- *
1460
- * @param options - Plugin options
1461
- * @returns A history plugin
1462
- *
1463
- * @example
1464
- * ```typescript
1465
- * import { history } from '@oxog/state';
1466
- *
1467
- * // Default options
1468
- * const store = createStore({ count: 0 })
1469
- * .use(history());
1470
- *
1471
- * // Custom limit
1472
- * const store = createStore({ count: 0 })
1473
- * .use(history({ limit: 50 }));
1474
- *
1475
- * // Track specific keys only
1476
- * const store = createStore({ count: 0, temp: '' })
1477
- * .use(history({ keys: ['count'] }));
1478
- * ```
1479
- */
1480
- declare function history<TState>(options?: HistoryOptions<TState>): Plugin<TState>;
1481
- /**
1482
- * Check if a store has history capabilities.
1483
- *
1484
- * @param store - The store to check
1485
- * @returns true if store supports undo/redo
1486
- *
1487
- * @example
1488
- * ```typescript
1489
- * import { hasHistory } from '@oxog/state';
1490
- *
1491
- * if (hasHistory(store)) {
1492
- * store.undo();
1493
- * store.redo();
1494
- * }
1495
- * ```
1496
- */
1497
- declare function hasHistory<TState>(store: Store<TState>): store is HistoryStore<TState>;
1498
-
1499
- /**
1500
- * Sync plugin - Cross-tab state synchronization.
1501
- *
1502
- * Synchronizes state across browser tabs using BroadcastChannel API.
1503
- *
1504
- * @example
1505
- * ```typescript
1506
- * import { createStore, sync } from '@oxog/state';
1507
- *
1508
- * const store = createStore({ count: 0 })
1509
- * .use(sync({ channel: 'my-app-state' }));
1510
- *
1511
- * // State changes will sync across all tabs
1512
- * ```
1513
- */
1514
-
1515
- /**
1516
- * Create a sync plugin.
1517
- *
1518
- * @param options - Plugin options
1519
- * @returns A sync plugin
1520
- *
1521
- * @example
1522
- * ```typescript
1523
- * import { sync } from '@oxog/state';
1524
- *
1525
- * // Default channel name
1526
- * const store = createStore({ count: 0 })
1527
- * .use(sync());
1528
- *
1529
- * // Custom channel name
1530
- * const store = createStore({ count: 0 })
1531
- * .use(sync({ channel: 'my-app' }));
1532
- * ```
1533
- */
1534
- declare function sync<TState>(options?: SyncOptions): Plugin<TState>;
1535
- /**
1536
- * Manually trigger a sync broadcast.
1537
- *
1538
- * @param store - The store to sync
1539
- * @param channel - The channel to broadcast on
1540
- *
1541
- * @example
1542
- * ```typescript
1543
- * import { createStore, sync, triggerSync } from '@oxog/state';
1544
- *
1545
- * const store = createStore({ count: 0 })
1546
- * .use(sync({ channel: 'my-app' }));
1547
- *
1548
- * // Manually trigger sync
1549
- * triggerSync(store, 'my-app');
1550
- * ```
1551
- */
1552
- declare function triggerSync<TState>(store: Store<TState>, channel?: string): void;
1553
-
1554
- /**
1555
- * Immer plugin - Immutable updates with mutable syntax.
1556
- *
1557
- * Uses Proxy to enable writing immutable state updates with mutable syntax.
1558
- *
1559
- * @example
1560
- * ```typescript
1561
- * import { createStore, immer } from '@oxog/state';
1562
- *
1563
- * const store = createStore({
1564
- * users: [{ name: 'John', age: 30 }]
1565
- * }).use(immer());
1566
- *
1567
- * // Now you can write mutable-style updates
1568
- * store.setState((draft) => {
1569
- * draft.users[0].age = 31; // Mutate draft directly
1570
- * });
1571
- * ```
1572
- */
1573
-
1574
- /**
1575
- * Produce a new state by applying mutations to a draft.
1576
- *
1577
- * @param base - The base state
1578
- * @param recipe - The mutation function
1579
- * @returns The new state
1580
- *
1581
- * @example
1582
- * ```typescript
1583
- * import { produce } from '@oxog/state';
1584
- *
1585
- * const state = { users: [{ name: 'John', age: 30 }] };
1586
- * const newState = produce(state, (draft) => {
1587
- * draft.users[0].age = 31;
1588
- * });
1589
- * ```
1590
- */
1591
- declare function produce<T>(base: T, recipe: (draft: T) => void): T;
1592
- /**
1593
- * Create an immer plugin.
1594
- *
1595
- * @returns An immer plugin
1596
- *
1597
- * @example
1598
- * ```typescript
1599
- * import { createStore, immer } from '@oxog/state';
1600
- *
1601
- * const store = createStore({
1602
- * items: [{ id: 1, name: 'Item 1' }]
1603
- * }).use(immer());
1604
- *
1605
- * // Now setState can accept a mutable recipe function
1606
- * store.setState((draft) => {
1607
- * draft.items[0].name = 'Updated Item';
1608
- * draft.items.push({ id: 2, name: 'Item 2' });
1609
- * });
1610
- * ```
1611
- */
1612
- declare function immer<TState>(): Plugin<TState>;
1613
-
1614
- /**
1615
- * Selector plugin - Computed/derived values.
1616
- *
1617
- * Define computed values that automatically update when dependencies change.
1618
- *
1619
- * @example
1620
- * ```typescript
1621
- * import { createStore, selector } from '@oxog/state';
1622
- *
1623
- * const store = createStore({
1624
- * items: [],
1625
- * filter: 'all',
1626
- * })
1627
- * .use(selector({
1628
- * // Computed: filtered items
1629
- * filteredItems: (state) => {
1630
- * if (state.filter === 'all') return state.items;
1631
- * return state.items.filter((item: any) => item.status === state.filter);
1632
- * },
1633
- * // Computed: item count
1634
- * itemCount: (state) => state.items.length,
1635
- * }));
1636
- *
1637
- * // Access computed values
1638
- * const state = store.getState();
1639
- * console.log(state.filteredItems); // Computed value
1640
- * ```
1641
- */
1642
-
1643
- /**
1644
- * Create a selector plugin for computed values.
1645
- *
1646
- * @param options - Plugin options with selectors
1647
- * @returns A selector plugin
1648
- *
1649
- * @example
1650
- * ```typescript
1651
- * import { selector } from '@oxog/state';
1652
- *
1653
- * const store = createStore({
1654
- * items: [{ price: 10 }, { price: 20 }],
1655
- * taxRate: 0.1,
1656
- * })
1657
- * .use(selector({
1658
- * // Computed total
1659
- * total: (state) =>
1660
- * state.items.reduce((sum: number, item: any) => sum + item.price, 0),
1661
- *
1662
- * // Computed total with tax
1663
- * totalWithTax: (state) => {
1664
- * const total = state.items.reduce((sum: number, item: any) => sum + item.price, 0);
1665
- * return total * (1 + state.taxRate);
1666
- * },
1667
- * }));
1668
- * ```
1669
- */
1670
- declare function selector<TState>(options: SelectorOptions<TState>): Plugin<TState>;
1671
-
1672
- /**
1673
- * Logger plugin for console logging state changes.
1674
- *
1675
- * @module plugins/logger
1676
- */
1677
-
1678
- /**
1679
- * Log level for filtering messages.
1680
- */
1681
- type LogLevel = 'debug' | 'info' | 'warn' | 'error';
1682
- /**
1683
- * Logger options.
1684
- */
1685
- interface LoggerOptions<TState = unknown> {
1686
- /** Log level filter (default: 'debug') */
1687
- level?: LogLevel;
1688
- /** Custom logger (default: console) */
1689
- logger?: Console;
1690
- /** Use collapsed console groups (default: true) */
1691
- collapsed?: boolean;
1692
- /** Show state diff (default: true) */
1693
- diff?: boolean;
1694
- /** Colorize output (default: true in browsers) */
1695
- colors?: boolean;
1696
- /** Show timestamp (default: true) */
1697
- timestamp?: boolean;
1698
- /** Filter function to skip certain changes */
1699
- filter?: (state: TState, prevState: TState) => boolean;
1700
- /** Transform state before logging */
1701
- stateTransformer?: (state: TState) => unknown;
1702
- /** Custom action name (default: 'STATE_CHANGE') */
1703
- actionName?: string | ((state: TState, prevState: TState) => string);
1704
- /** Name for this logger instance */
1705
- name?: string;
1706
- /** Enabled flag (default: true) */
1707
- enabled?: boolean;
1708
- }
1709
- /**
1710
- * Create a logger plugin.
1711
- *
1712
- * @param options - Logger options
1713
- * @returns A logger plugin
1714
- *
1715
- * @example
1716
- * ```typescript
1717
- * import { createStore, logger } from '@oxog/state';
1718
- *
1719
- * // Basic usage
1720
- * const store = createStore({ count: 0 })
1721
- * .use(logger());
1722
- *
1723
- * // With options
1724
- * const store = createStore({ count: 0 })
1725
- * .use(logger({
1726
- * level: 'info',
1727
- * collapsed: false,
1728
- * diff: true,
1729
- * name: 'CounterStore',
1730
- * }));
1731
- *
1732
- * // Disabled in production
1733
- * const store = createStore({ count: 0 })
1734
- * .use(logger({
1735
- * enabled: process.env.NODE_ENV !== 'production',
1736
- * }));
1737
- * ```
1738
- */
1739
- declare function logger<TState = unknown>(options?: LoggerOptions<TState>): Plugin<TState>;
1740
- /**
1741
- * Create a logger with preset options.
1742
- *
1743
- * @param defaultOptions - Default options
1744
- * @returns A logger factory function
1745
- *
1746
- * @example
1747
- * ```typescript
1748
- * const devLogger = createLogger({
1749
- * enabled: process.env.NODE_ENV === 'development',
1750
- * collapsed: true,
1751
- * });
1752
- *
1753
- * const store = createStore({ count: 0 })
1754
- * .use(devLogger({ name: 'Counter' }));
1755
- * ```
1756
- */
1757
- declare function createLogger<TState = unknown>(defaultOptions?: LoggerOptions<TState>): (options?: LoggerOptions<TState>) => Plugin<TState>;
1758
-
1759
- /**
1760
- * Effects plugin for managing side effects.
1761
- *
1762
- * Provides a declarative way to handle async operations,
1763
- * API calls, and other side effects in response to state changes.
1764
- *
1765
- * @module plugins/effects
1766
- */
1767
-
1768
- /**
1769
- * Effect cleanup function.
1770
- */
1771
- type EffectCleanup = () => void;
1772
- /**
1773
- * Effect function that runs when dependencies change.
1774
- */
1775
- type EffectFn<T> = (value: T, prevValue: T, utils: EffectUtils) => void | EffectCleanup | Promise<void | EffectCleanup>;
1776
- /**
1777
- * Utilities available to effects.
1778
- */
1779
- interface EffectUtils {
1780
- /** Get current store state */
1781
- getState: () => unknown;
1782
- /** Set store state */
1783
- setState: (partial: any) => void;
1784
- /** Check if effect is still active (not cancelled) */
1785
- isActive: () => boolean;
1786
- /** Cancel this effect */
1787
- cancel: () => void;
1788
- /** Run a callback only if effect is active */
1789
- onlyIfActive: <T>(fn: () => T) => T | undefined;
1790
- }
1791
- /**
1792
- * Effect definition for the effects plugin.
1793
- */
1794
- interface EffectDefinition<TState, TSelected = TState> {
1795
- /** Selector to watch */
1796
- selector: Selector<TState, TSelected>;
1797
- /** Effect function */
1798
- effect: EffectFn<TSelected>;
1799
- /** Custom equality function */
1800
- equalityFn?: EqualityFn<TSelected>;
1801
- /** Fire effect immediately with current value */
1802
- fireImmediately?: boolean;
1803
- /** Debounce effect (ms) */
1804
- debounce?: number;
1805
- /** Effect name for debugging */
1806
- name?: string;
1807
- }
1808
- /**
1809
- * Options for the effects plugin.
1810
- */
1811
- interface EffectsOptions<TState> {
1812
- /** Array of effect definitions */
1813
- effects: EffectDefinition<TState, any>[];
1814
- /** Error handler for effect errors */
1815
- onError?: (error: Error, effectName?: string) => void;
1816
- }
1817
- /**
1818
- * Create an effects plugin.
1819
- *
1820
- * @param options - Effects configuration
1821
- * @returns An effects plugin
1822
- *
1823
- * @example
1824
- * ```typescript
1825
- * import { createStore, effects } from '@oxog/state';
1826
- *
1827
- * const store = createStore({
1828
- * userId: null,
1829
- * user: null,
1830
- * loading: false,
1831
- * }).use(effects({
1832
- * effects: [
1833
- * {
1834
- * name: 'fetchUser',
1835
- * selector: (s) => s.userId,
1836
- * effect: async (userId, _prev, { setState, isActive }) => {
1837
- * if (!userId) return;
1838
- *
1839
- * setState({ loading: true });
1840
- * try {
1841
- * const user = await fetchUser(userId);
1842
- * if (isActive()) {
1843
- * setState({ user, loading: false });
1844
- * }
1845
- * } catch (error) {
1846
- * if (isActive()) {
1847
- * setState({ user: null, loading: false });
1848
- * }
1849
- * }
1850
- * },
1851
- * },
1852
- * ],
1853
- * }));
1854
- * ```
1855
- */
1856
- declare function effects<TState>(options: EffectsOptions<TState>): Plugin<TState>;
1857
- /**
1858
- * Create an effect definition helper.
1859
- *
1860
- * @param name - Effect name
1861
- * @param selector - Selector to watch
1862
- * @param effect - Effect function
1863
- * @param options - Additional options
1864
- * @returns Effect definition
1865
- *
1866
- * @example
1867
- * ```typescript
1868
- * const fetchUserEffect = createEffect(
1869
- * 'fetchUser',
1870
- * (s) => s.userId,
1871
- * async (userId, _prev, { setState }) => {
1872
- * const user = await api.getUser(userId);
1873
- * setState({ user });
1874
- * },
1875
- * { fireImmediately: true }
1876
- * );
1877
- *
1878
- * const store = createStore({ userId: null, user: null })
1879
- * .use(effects({ effects: [fetchUserEffect] }));
1880
- * ```
1881
- */
1882
- declare function createEffect<TState, TSelected>(name: string, selector: Selector<TState, TSelected>, effect: EffectFn<TSelected>, options?: Omit<EffectDefinition<TState, TSelected>, 'name' | 'selector' | 'effect'>): EffectDefinition<TState, TSelected>;
1883
- /**
1884
- * Create a simple effect that runs on any state change.
1885
- *
1886
- * @param effect - Effect function
1887
- * @param options - Effect options
1888
- * @returns Effect definition
1889
- *
1890
- * @example
1891
- * ```typescript
1892
- * const logEffect = createSimpleEffect(
1893
- * (state, prevState) => {
1894
- * console.log('State changed:', state);
1895
- * }
1896
- * );
1897
- * ```
1898
- */
1899
- declare function createSimpleEffect<TState>(effect: (state: TState, prevState: TState, utils: EffectUtils) => void | EffectCleanup, options?: Omit<EffectDefinition<TState, TState>, 'selector' | 'effect'>): EffectDefinition<TState, TState>;
1900
- /**
1901
- * Combine multiple effect definitions.
1902
- *
1903
- * @param effectDefs - Effect definitions to combine
1904
- * @returns Combined effects options
1905
- *
1906
- * @example
1907
- * ```typescript
1908
- * const store = createStore({ ... })
1909
- * .use(effects(combineEffects(
1910
- * fetchUserEffect,
1911
- * saveToStorageEffect,
1912
- * analyticsEffect,
1913
- * )));
1914
- * ```
1915
- */
1916
- declare function combineEffects<TState>(...effectDefs: EffectDefinition<TState, any>[]): EffectsOptions<TState>;
1917
- /**
1918
- * Create a debounced effect that only fires after a delay.
1919
- *
1920
- * @param delay - Debounce delay in ms
1921
- * @param selector - Selector to watch
1922
- * @param effect - Effect function
1923
- * @returns Effect definition
1924
- *
1925
- * @example
1926
- * ```typescript
1927
- * const searchEffect = createDebouncedEffect(
1928
- * 300,
1929
- * (s) => s.searchQuery,
1930
- * async (query, _prev, { setState }) => {
1931
- * const results = await api.search(query);
1932
- * setState({ searchResults: results });
1933
- * }
1934
- * );
1935
- * ```
1936
- */
1937
- declare function createDebouncedEffect<TState, TSelected>(delay: number, selector: Selector<TState, TSelected>, effect: EffectFn<TSelected>, options?: Omit<EffectDefinition<TState, TSelected>, 'selector' | 'effect' | 'debounce'>): EffectDefinition<TState, TSelected>;
1938
-
1939
- /**
1940
- * Validation plugin for state schema validation.
1941
- *
1942
- * Provides schema-agnostic validation with support for Zod, Yup,
1943
- * or custom validation functions.
1944
- *
1945
- * @module plugins/validate
1946
- */
1947
-
1948
- /**
1949
- * Validation error type.
1950
- */
1951
- interface ValidationError {
1952
- /** Path to the invalid field */
1953
- path: string[];
1954
- /** Error message */
1955
- message: string;
1956
- /** Validation rule that failed */
1957
- rule?: string;
1958
- /** The invalid value */
1959
- value?: unknown;
1960
- }
1961
- /**
1962
- * Validation result.
1963
- */
1964
- interface ValidationResult {
1965
- /** Whether validation passed */
1966
- valid: boolean;
1967
- /** List of validation errors */
1968
- errors: ValidationError[];
1969
- }
1970
- /**
1971
- * Custom validator function type.
1972
- */
1973
- type ValidatorFn<T> = (state: T) => boolean | ValidationResult | ValidationError[];
1974
- /**
1975
- * Zod-like schema interface.
1976
- */
1977
- interface ZodLikeSchema<T> {
1978
- safeParse(data: unknown): {
1979
- success: boolean;
1980
- error?: {
1981
- issues: Array<{
1982
- path: (string | number)[];
1983
- message: string;
1984
- code?: string;
1985
- }>;
1986
- };
1987
- data?: T;
1988
- };
1989
- }
1990
- /**
1991
- * Yup-like schema interface.
1992
- */
1993
- interface YupLikeSchema<T> {
1994
- validateSync(data: unknown, options?: {
1995
- abortEarly?: boolean;
1996
- }): T;
1997
- validate(data: unknown, options?: {
1998
- abortEarly?: boolean;
1999
- }): Promise<T>;
2000
- }
2001
- /**
2002
- * Schema type - supports Zod, Yup, or custom validators.
2003
- */
2004
- type Schema<T> = ZodLikeSchema<T> | YupLikeSchema<T> | ValidatorFn<T>;
2005
- /**
2006
- * Validation timing options.
2007
- */
2008
- type ValidationTiming = 'change' | 'commit' | 'manual';
2009
- /**
2010
- * Validation plugin options.
2011
- */
2012
- interface ValidateOptions<T> {
2013
- /** Schema to validate against (Zod, Yup, or custom function) */
2014
- schema: Schema<T>;
2015
- /** When to validate: 'change' (every setState), 'commit' (on batch commit), 'manual' (only when validate() called) */
2016
- on?: ValidationTiming;
2017
- /** Callback when validation fails */
2018
- onError?: (errors: ValidationError[]) => void;
2019
- /** Throw error on validation failure */
2020
- throwOnError?: boolean;
2021
- /** Only validate these paths (keys of state) */
2022
- paths?: Array<keyof T>;
2023
- /** Name for debugging */
2024
- name?: string;
2025
- }
2026
- /**
2027
- * Validation API added to store.
2028
- */
2029
- interface ValidationAPI {
2030
- /** Manually trigger validation */
2031
- validate(): ValidationResult;
2032
- /** Check if current state is valid */
2033
- isValid(): boolean;
2034
- /** Get current validation errors */
2035
- getErrors(): ValidationError[];
2036
- /** Clear validation errors */
2037
- clearErrors(): void;
2038
- }
2039
- /**
2040
- * Create a validation plugin.
2041
- *
2042
- * @param options - Validation options
2043
- * @returns A validation plugin
2044
- *
2045
- * @example
2046
- * ```typescript
2047
- * import { createStore, validate } from '@oxog/state';
2048
- * import { z } from 'zod';
2049
- *
2050
- * // With Zod schema
2051
- * const userSchema = z.object({
2052
- * name: z.string().min(1),
2053
- * age: z.number().min(0),
2054
- * email: z.string().email(),
2055
- * });
2056
- *
2057
- * const store = createStore({ name: '', age: 0, email: '' })
2058
- * .use(validate({
2059
- * schema: userSchema,
2060
- * on: 'change',
2061
- * onError: (errors) => console.log('Validation errors:', errors),
2062
- * }));
2063
- *
2064
- * // Manual validation
2065
- * const result = store.validate();
2066
- * if (!result.valid) {
2067
- * console.log(result.errors);
2068
- * }
2069
- *
2070
- * // Check if valid
2071
- * if (store.isValid()) {
2072
- * submitForm();
2073
- * }
2074
- * ```
2075
- *
2076
- * @example
2077
- * ```typescript
2078
- * // With custom validator function
2079
- * const store = createStore({ password: '', confirmPassword: '' })
2080
- * .use(validate({
2081
- * schema: (state) => {
2082
- * const errors = [];
2083
- * if (state.password.length < 8) {
2084
- * errors.push({
2085
- * path: ['password'],
2086
- * message: 'Password must be at least 8 characters',
2087
- * });
2088
- * }
2089
- * if (state.password !== state.confirmPassword) {
2090
- * errors.push({
2091
- * path: ['confirmPassword'],
2092
- * message: 'Passwords must match',
2093
- * });
2094
- * }
2095
- * return errors;
2096
- * },
2097
- * on: 'change',
2098
- * }));
2099
- * ```
2100
- *
2101
- * @example
2102
- * ```typescript
2103
- * // With partial validation
2104
- * const store = createStore({ name: '', age: 0, temp: '' })
2105
- * .use(validate({
2106
- * schema: userSchema,
2107
- * paths: ['name', 'age'], // Only validate these fields
2108
- * }));
2109
- * ```
2110
- */
2111
- declare function validate<TState>(options: ValidateOptions<TState>): Plugin<TState>;
2112
- /**
2113
- * Create a simple boolean validator.
2114
- *
2115
- * @param predicate - Validation predicate function
2116
- * @param message - Error message when validation fails
2117
- * @returns A validator function
2118
- *
2119
- * @example
2120
- * ```typescript
2121
- * const isPositive = createValidator(
2122
- * (state) => state.count >= 0,
2123
- * 'Count must be positive'
2124
- * );
2125
- *
2126
- * const store = createStore({ count: 0 })
2127
- * .use(validate({ schema: isPositive }));
2128
- * ```
2129
- */
2130
- declare function createValidator<T>(predicate: (state: T) => boolean, message: string): ValidatorFn<T>;
2131
- /**
2132
- * Combine multiple validators into one.
2133
- *
2134
- * @param validators - Array of validator functions
2135
- * @returns Combined validator function
2136
- *
2137
- * @example
2138
- * ```typescript
2139
- * const combinedValidator = combineValidators(
2140
- * createValidator((s) => s.name.length > 0, 'Name required'),
2141
- * createValidator((s) => s.age >= 18, 'Must be 18+'),
2142
- * );
2143
- *
2144
- * const store = createStore({ name: '', age: 0 })
2145
- * .use(validate({ schema: combinedValidator }));
2146
- * ```
2147
- */
2148
- declare function combineValidators<T>(...validators: ValidatorFn<T>[]): ValidatorFn<T>;
2149
- /**
2150
- * Create a field-level validator.
2151
- *
2152
- * @param field - Field name to validate
2153
- * @param predicate - Validation predicate for field value
2154
- * @param message - Error message when validation fails
2155
- * @returns A validator function
2156
- *
2157
- * @example
2158
- * ```typescript
2159
- * const emailValidator = createFieldValidator(
2160
- * 'email',
2161
- * (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email),
2162
- * 'Invalid email format'
2163
- * );
2164
- *
2165
- * const store = createStore({ email: '' })
2166
- * .use(validate({ schema: emailValidator }));
2167
- * ```
2168
- */
2169
- declare function createFieldValidator<T, K extends keyof T>(field: K, predicate: (value: T[K], state: T) => boolean, message: string): ValidatorFn<T>;
2170
- /**
2171
- * Create an async validator (for server-side validation).
2172
- *
2173
- * @param validator - Async validation function
2174
- * @returns A promise that resolves to validation result
2175
- *
2176
- * @example
2177
- * ```typescript
2178
- * const checkUsername = createAsyncValidator(async (state) => {
2179
- * const exists = await api.checkUsername(state.username);
2180
- * return exists
2181
- * ? [{ path: ['username'], message: 'Username already taken' }]
2182
- * : [];
2183
- * });
2184
- *
2185
- * // Manual validation
2186
- * const result = await checkUsername(store.getState());
2187
- * ```
2188
- */
2189
- declare function createAsyncValidator<T>(validator: (state: T) => Promise<ValidationError[]>): (state: T) => Promise<ValidationResult>;
2190
-
2191
- /**
2192
- * Deep clone a value, creating copies of nested objects and arrays.
2193
- *
2194
- * Handles:
2195
- * - Primitives (returned as-is)
2196
- * - null and undefined (returned as-is)
2197
- * - Date objects
2198
- * - Arrays
2199
- * - Plain objects
2200
- * - Circular references
2201
- * - Other objects (returned as-is, not cloned)
2202
- *
2203
- * @typeParam T - The type to clone
2204
- * @param value - The value to clone
2205
- * @param seen - Internal map for tracking circular references
2206
- * @returns A deep clone of the value
2207
- *
2208
- * @example
2209
- * ```typescript
2210
- * const original = { a: 1, b: { c: 2 } };
2211
- * const cloned = deepClone(original);
2212
- * cloned.b.c = 3;
2213
- * console.log(original.b.c); // 2 (unchanged)
2214
- * ```
2215
- */
2216
- declare function deepClone<T>(value: T, seen?: WeakMap<object, unknown>): T;
2217
-
2218
- /**
2219
- * Deep equality check for two values.
2220
- *
2221
- * Recursively compares objects and arrays.
2222
- * Uses Object.is for primitive comparison.
2223
- *
2224
- * @param a - First value
2225
- * @param b - Second value
2226
- * @returns true if values are deeply equal
2227
- *
2228
- * @example
2229
- * ```typescript
2230
- * deepEqual(1, 1); // true
2231
- * deepEqual({ a: { b: 1 } }, { a: { b: 1 } }); // true
2232
- * deepEqual({ a: { b: 1 } }, { a: { b: 2 } }); // false
2233
- * deepEqual([1, 2], [1, 2]); // true
2234
- * deepEqual([1, 2], [1, 2, 3]); // false
2235
- * ```
2236
- */
2237
- declare function deepEqual(a: unknown, b: unknown): boolean;
2238
-
2239
- /**
2240
- * Shallow equality check for two values.
2241
- *
2242
- * Uses Object.is for comparison, which handles NaN correctly
2243
- * and distinguishes between +0 and -0.
2244
- *
2245
- * @param a - First value
2246
- * @param b - Second value
2247
- * @returns true if values are shallowly equal
2248
- *
2249
- * @example
2250
- * ```typescript
2251
- * shallowEqual(1, 1); // true
2252
- * shallowEqual({ a: 1 }, { a: 1 }); // true
2253
- * shallowEqual({ a: 1 }, { a: 2 }); // false
2254
- * shallowEqual(NaN, NaN); // true
2255
- * ```
2256
- */
2257
- declare function shallowEqual(a: unknown, b: unknown): boolean;
2258
-
2259
- /**
2260
- * Deep merge a partial object into a target object.
2261
- *
2262
- * Creates a new object with nested objects merged recursively.
2263
- * Arrays are replaced, not merged.
2264
- *
2265
- * @typeParam T - The target type
2266
- * @param target - The target object
2267
- * @param source - The partial source to merge
2268
- * @returns A new merged object
2269
- *
2270
- * @example
2271
- * ```typescript
2272
- * const target = { a: 1, b: { c: 2, d: 3 } };
2273
- * const source = { b: { c: 10 }, e: 4 };
2274
- * const merged = deepMerge(target, source);
2275
- * // { a: 1, b: { c: 10, d: 3 }, e: 4 }
2276
- * ```
2277
- */
2278
-
2279
- declare function deepMerge<T>(target: T, source: Partial<T> | DeepPartial<T>): T;
2280
-
2281
- /**
2282
- * Type guard to check if a value is a function.
2283
- *
2284
- * @param value - The value to check
2285
- * @returns true if the value is a function
2286
- *
2287
- * @example
2288
- * ```typescript
2289
- * const value: unknown = () => {};
2290
- * if (isFunction(value)) {
2291
- * value(); // TypeScript knows this is a function
2292
- * }
2293
- * ```
2294
- */
2295
- declare function isFunction(value: unknown): value is (...args: any[]) => any;
2296
-
2297
- /**
2298
- * Pick specified properties from an object.
2299
- *
2300
- * Creates a new object with only the specified keys.
2301
- *
2302
- * @typeParam T - The object type
2303
- * @typeParam K - The keys to pick
2304
- * @param obj - The source object
2305
- * @param keys - The keys to pick
2306
- * @returns A new object with only the picked keys
2307
- *
2308
- * @example
2309
- * ```typescript
2310
- * const user = { name: 'John', age: 30, city: 'NYC' };
2311
- * const picked = pick(user, ['name', 'age']);
2312
- * // { name: 'John', age: 30 }
2313
- * ```
2314
- */
2315
- declare function pick<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Pick<T, K>;
2316
-
2317
- /**
2318
- * Omit specified properties from an object.
2319
- *
2320
- * Creates a new object without the specified keys.
2321
- *
2322
- * @typeParam T - The object type
2323
- * @typeParam K - The keys to omit
2324
- * @param obj - The source object
2325
- * @param keys - The keys to omit
2326
- * @returns A new object without the omitted keys
2327
- *
2328
- * @example
2329
- * ```typescript
2330
- * const user = { name: 'John', age: 30, city: 'NYC' };
2331
- * const omitted = omit(user, ['age', 'city']);
2332
- * // { name: 'John' }
2333
- * ```
2334
- */
2335
- declare function omit<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Omit<T, K>;
2336
-
2337
- /**
2338
- * Identity function that returns its input.
2339
- *
2340
- * Useful as a default selector when no transformation is needed.
2341
- *
2342
- * @typeParam T - The value type
2343
- * @param value - The value to return
2344
- * @returns The same value
2345
- *
2346
- * @example
2347
- * ```typescript
2348
- * const selector = identity;
2349
- * selector(42); // 42
2350
- * selector('hello'); // 'hello'
2351
- * ```
2352
- */
2353
- declare function identity<T>(value: T): T;
2354
-
2355
- /**
2356
- * Testing utilities for @oxog/state.
2357
- *
2358
- * Provides helpers for testing stores, state changes,
2359
- * and async effects in unit tests.
2360
- *
2361
- * @module testing
2362
- */
2363
-
2364
- /**
2365
- * Mock storage for testing persist plugin.
2366
- */
2367
- interface MockStorage {
2368
- getItem(key: string): string | null;
2369
- setItem(key: string, value: string): void;
2370
- removeItem(key: string): void;
2371
- clear(): void;
2372
- getAll(): Record<string, string>;
2373
- }
2374
- /**
2375
- * Create a mock storage for testing.
2376
- *
2377
- * @returns A mock storage implementation
2378
- *
2379
- * @example
2380
- * ```typescript
2381
- * import { createMockStorage, persist } from '@oxog/state';
2382
- *
2383
- * const mockStorage = createMockStorage();
2384
- *
2385
- * const store = createStore({ count: 0 })
2386
- * .use(persist({ key: 'test', storage: mockStorage }));
2387
- *
2388
- * store.setState({ count: 5 });
2389
- * expect(mockStorage.getItem('test')).toBe('{"count":5}');
2390
- * ```
2391
- */
2392
- declare function createMockStorage(): MockStorage;
2393
- /**
2394
- * State change record for tracking.
2395
- */
2396
- interface StateChange<TState> {
2397
- state: TState;
2398
- prevState: TState;
2399
- timestamp: number;
2400
- }
2401
- /**
2402
- * Store spy for testing state changes.
2403
- */
2404
- interface StoreSpy<TState> {
2405
- /** All recorded state changes */
2406
- changes: StateChange<TState>[];
2407
- /** Get the last state change */
2408
- lastChange: () => StateChange<TState> | undefined;
2409
- /** Get the last state */
2410
- lastState: () => TState | undefined;
2411
- /** Reset recorded changes */
2412
- reset: () => void;
2413
- /** Unsubscribe from store */
2414
- unsubscribe: () => void;
2415
- /** Wait for a specific state condition */
2416
- waitFor: (predicate: (state: TState) => boolean, timeout?: number) => Promise<TState>;
2417
- /** Wait for a specific number of changes */
2418
- waitForChanges: (count: number, timeout?: number) => Promise<StateChange<TState>[]>;
2419
- }
2420
- /**
2421
- * Create a spy to track store state changes.
2422
- *
2423
- * @param store - The store to spy on
2424
- * @returns A store spy object
2425
- *
2426
- * @example
2427
- * ```typescript
2428
- * import { createStore, spyOnStore } from '@oxog/state';
2429
- *
2430
- * const store = createStore({ count: 0 });
2431
- * const spy = spyOnStore(store);
2432
- *
2433
- * store.setState({ count: 1 });
2434
- * store.setState({ count: 2 });
2435
- *
2436
- * expect(spy.changes).toHaveLength(2);
2437
- * expect(spy.lastState()?.count).toBe(2);
2438
- * ```
2439
- */
2440
- declare function spyOnStore<TState>(store: Store<TState>): StoreSpy<TState>;
2441
- /**
2442
- * Test helper for asserting state values.
2443
- */
2444
- interface StateAssertion<TState> {
2445
- /** Assert the current state equals expected */
2446
- toEqual: (expected: Partial<TState>) => void;
2447
- /** Assert a selector value equals expected */
2448
- toHaveSelected: <T>(selector: Selector<TState, T>, expected: T) => void;
2449
- /** Assert state matches a predicate */
2450
- toMatch: (predicate: (state: TState) => boolean) => void;
2451
- }
2452
- /**
2453
- * Create assertions for a store's state.
2454
- *
2455
- * @param store - The store to assert on
2456
- * @returns State assertion helpers
2457
- *
2458
- * @example
2459
- * ```typescript
2460
- * import { createStore, assertState } from '@oxog/state';
2461
- *
2462
- * const store = createStore({ count: 0, name: 'test' });
2463
- * const assert = assertState(store);
2464
- *
2465
- * assert.toEqual({ count: 0 });
2466
- * assert.toHaveSelected(s => s.name, 'test');
2467
- * assert.toMatch(s => s.count >= 0);
2468
- * ```
2469
- */
2470
- declare function assertState<TState>(store: Store<TState>): StateAssertion<TState>;
2471
- /**
2472
- * Options for test store creation.
2473
- */
2474
- interface TestStoreOptions<TState> {
2475
- /** Initial state */
2476
- initialState: TState;
2477
- /** Whether to enable spy automatically */
2478
- spy?: boolean;
2479
- }
2480
- /**
2481
- * Test store wrapper with built-in utilities.
2482
- */
2483
- interface TestStore<TState> {
2484
- /** The underlying store */
2485
- store: Store<TState>;
2486
- /** State spy (if enabled) */
2487
- spy?: StoreSpy<TState>;
2488
- /** State assertions */
2489
- assert: StateAssertion<TState>;
2490
- /** Reset store to initial state */
2491
- reset: () => void;
2492
- /** Destroy store and cleanup */
2493
- destroy: () => void;
2494
- }
2495
- /**
2496
- * Create a test store with built-in utilities.
2497
- *
2498
- * @param options - Test store options
2499
- * @returns A test store wrapper
2500
- *
2501
- * @example
2502
- * ```typescript
2503
- * import { createTestStore } from '@oxog/state';
2504
- *
2505
- * describe('Counter', () => {
2506
- * let testStore: TestStore<{ count: number }>;
2507
- *
2508
- * beforeEach(() => {
2509
- * testStore = createTestStore({ initialState: { count: 0 }, spy: true });
2510
- * });
2511
- *
2512
- * afterEach(() => {
2513
- * testStore.destroy();
2514
- * });
2515
- *
2516
- * it('should increment count', () => {
2517
- * testStore.store.setState({ count: 1 });
2518
- * testStore.assert.toEqual({ count: 1 });
2519
- * expect(testStore.spy?.changes).toHaveLength(1);
2520
- * });
2521
- * });
2522
- * ```
2523
- */
2524
- declare function createTestStore<TState>(options: TestStoreOptions<TState>): TestStore<TState>;
2525
- /**
2526
- * Wait for a specified amount of time.
2527
- *
2528
- * @param ms - Milliseconds to wait
2529
- * @returns A promise that resolves after the delay
2530
- *
2531
- * @example
2532
- * ```typescript
2533
- * await delay(100);
2534
- * ```
2535
- */
2536
- declare function delay(ms: number): Promise<void>;
2537
- /**
2538
- * Run a function and wait for all pending microtasks.
2539
- *
2540
- * @param fn - Function to run
2541
- * @returns A promise that resolves after microtasks complete
2542
- *
2543
- * @example
2544
- * ```typescript
2545
- * await flushMicrotasks(() => {
2546
- * store.setState({ count: 1 });
2547
- * });
2548
- * ```
2549
- */
2550
- declare function flushMicrotasks(fn?: () => void): Promise<void>;
2551
- /**
2552
- * Wrap a store action for testing with call tracking.
2553
- */
2554
- interface MockedAction<TArgs extends any[], TReturn> {
2555
- /** Call the action */
2556
- (...args: TArgs): TReturn;
2557
- /** Number of times called */
2558
- callCount: number;
2559
- /** Arguments from each call */
2560
- calls: TArgs[];
2561
- /** Reset call tracking */
2562
- reset: () => void;
2563
- }
2564
- /**
2565
- * Create a mocked action for testing.
2566
- *
2567
- * @param fn - The original function
2568
- * @returns A mocked action with call tracking
2569
- *
2570
- * @example
2571
- * ```typescript
2572
- * const mockIncrement = mockAction((amount: number) => {
2573
- * store.setState(s => ({ count: s.count + amount }));
2574
- * });
2575
- *
2576
- * mockIncrement(5);
2577
- * mockIncrement(3);
2578
- *
2579
- * expect(mockIncrement.callCount).toBe(2);
2580
- * expect(mockIncrement.calls).toEqual([[5], [3]]);
2581
- * ```
2582
- */
2583
- declare function mockAction<TArgs extends any[], TReturn>(fn: (...args: TArgs) => TReturn): MockedAction<TArgs, TReturn>;
2584
- /**
2585
- * Create a snapshot of the current store state.
2586
- *
2587
- * @param store - The store to snapshot
2588
- * @returns A deep clone of the current state
2589
- *
2590
- * @example
2591
- * ```typescript
2592
- * const before = snapshot(store);
2593
- * store.setState({ count: 5 });
2594
- * const after = snapshot(store);
2595
- *
2596
- * expect(before.count).toBe(0);
2597
- * expect(after.count).toBe(5);
2598
- * ```
2599
- */
2600
- declare function snapshot<TState>(store: Store<TState>): TState;
2601
- /**
2602
- * Compare two state snapshots and return differences.
2603
- *
2604
- * @param before - State before changes
2605
- * @param after - State after changes
2606
- * @returns Object containing changed keys and their values
2607
- *
2608
- * @example
2609
- * ```typescript
2610
- * const before = { count: 0, name: 'test' };
2611
- * const after = { count: 5, name: 'test' };
2612
- *
2613
- * const diff = stateDiff(before, after);
2614
- * // { count: { before: 0, after: 5 } }
2615
- * ```
2616
- */
2617
- declare function stateDiff<TState extends Record<string, any>>(before: TState, after: TState): Record<string, {
2618
- before: any;
2619
- after: any;
2620
- }>;
2621
-
2622
- /**
2623
- * Middleware Compatibility Layer
2624
- *
2625
- * Provides a generic middleware pattern for state management,
2626
- * enabling compatibility with various middleware ecosystems.
2627
- *
2628
- * @module compat/middleware
2629
- */
2630
-
2631
- /**
2632
- * Middleware-style SetState function.
2633
- */
2634
- type MiddlewareSetState<T> = {
2635
- (partial: Partial<T> | ((state: T) => Partial<T>), replace?: boolean): void;
2636
- };
2637
- /**
2638
- * Middleware-style GetState function.
2639
- */
2640
- type MiddlewareGetState<T> = () => T;
2641
- /**
2642
- * Middleware-style Subscribe function.
2643
- */
2644
- type MiddlewareSubscribe<T> = (listener: (state: T, prevState: T) => void) => () => void;
2645
- /**
2646
- * Generic StoreApi for middleware compatibility.
2647
- */
2648
- interface MiddlewareStoreApi<T> {
2649
- setState: MiddlewareSetState<T>;
2650
- getState: MiddlewareGetState<T>;
2651
- subscribe: MiddlewareSubscribe<T>;
2652
- destroy?: () => void;
2653
- }
2654
- /**
2655
- * State creator function for middleware pattern.
2656
- */
2657
- type StateCreatorFn<T, Mps extends unknown[] = [], Mcs extends unknown[] = []> = (set: MiddlewareSetState<T>, get: MiddlewareGetState<T>, api: MiddlewareStoreApi<T>) => T;
2658
- /**
2659
- * Generic Middleware type.
2660
- */
2661
- type MiddlewareFn<T, Mps extends unknown[] = [], Mcs extends unknown[] = []> = (creator: StateCreatorFn<T, Mps, Mcs>) => StateCreatorFn<T, Mps, Mcs>;
2662
- /**
2663
- * Convert an @oxog/state store to middleware-compatible API.
2664
- *
2665
- * @param store - An @oxog/state store
2666
- * @returns A middleware-compatible store API
2667
- *
2668
- * @example
2669
- * ```typescript
2670
- * import { createStore, toMiddlewareApi } from '@oxog/state';
2671
- *
2672
- * const store = createStore({ count: 0 });
2673
- * const api = toMiddlewareApi(store);
2674
- *
2675
- * // Use middleware-style API
2676
- * api.setState({ count: 1 });
2677
- * api.setState((state) => ({ count: state.count + 1 }));
2678
- * console.log(api.getState()); // { count: 2 }
2679
- * ```
2680
- */
2681
- declare function toMiddlewareApi<T>(store: Store<T>): MiddlewareStoreApi<T>;
2682
- /**
2683
- * Wrap a middleware to work as an @oxog/state plugin.
2684
- *
2685
- * @param middleware - A middleware function
2686
- * @param options - Optional middleware options
2687
- * @returns An @oxog/state plugin
2688
- *
2689
- * @example
2690
- * ```typescript
2691
- * import { createStore, middlewareCompat } from '@oxog/state';
2692
- *
2693
- * // Use external middleware with @oxog/state
2694
- * const store = createStore({ count: 0 })
2695
- * .use(middlewareCompat(someMiddleware, { name: 'MyStore' }));
2696
- * ```
2697
- */
2698
- declare function middlewareCompat<T>(middleware: MiddlewareFn<T>, options?: Record<string, unknown>): Plugin<T>;
2699
- /**
2700
- * Create a store using middleware-style state creator.
2701
- *
2702
- * @param creator - Middleware-style state creator function
2703
- * @returns A store API
2704
- *
2705
- * @example
2706
- * ```typescript
2707
- * import { createWithMiddleware } from '@oxog/state';
2708
- *
2709
- * const store = createWithMiddleware((set, get) => ({
2710
- * count: 0,
2711
- * increment: () => set((state) => ({ count: state.count + 1 })),
2712
- * decrement: () => set((state) => ({ count: state.count - 1 })),
2713
- * reset: () => set({ count: 0 }),
2714
- * getDoubled: () => get().count * 2,
2715
- * }));
2716
- *
2717
- * store.getState().increment();
2718
- * console.log(store.getState().count); // 1
2719
- * ```
2720
- */
2721
- declare function createWithMiddleware<T extends object>(creator: StateCreatorFn<T>): MiddlewareStoreApi<T> & {
2722
- use: <U>(plugin: Plugin<T>) => MiddlewareStoreApi<T>;
2723
- };
2724
- /**
2725
- * Create a simple middleware.
2726
- *
2727
- * @param name - Middleware name
2728
- * @param enhancer - Function that enhances the state creator
2729
- * @returns A middleware function
2730
- *
2731
- * @example
2732
- * ```typescript
2733
- * const loggerMiddleware = createSimpleMiddleware('logger', (creator) => (set, get, api) => {
2734
- * const loggedSet: typeof set = (partial, replace) => {
2735
- * console.log('Before:', get());
2736
- * set(partial, replace);
2737
- * console.log('After:', get());
2738
- * };
2739
- * return creator(loggedSet, get, api);
2740
- * });
2741
- *
2742
- * const store = createStore({ count: 0 })
2743
- * .use(middlewareCompat(loggerMiddleware));
2744
- * ```
2745
- */
2746
- declare function createSimpleMiddleware<T>(name: string, enhancer: (creator: StateCreatorFn<T>) => StateCreatorFn<T>): MiddlewareFn<T>;
2747
- /**
2748
- * Compose multiple middlewares.
2749
- *
2750
- * @param middlewares - Array of middlewares
2751
- * @returns A single composed middleware
2752
- *
2753
- * @example
2754
- * ```typescript
2755
- * import { compose, middlewareCompat } from '@oxog/state';
2756
- *
2757
- * const composedMiddleware = compose(
2758
- * loggerMiddleware,
2759
- * devtoolsMiddleware,
2760
- * persistMiddleware,
2761
- * );
2762
- *
2763
- * const store = createStore({ count: 0 })
2764
- * .use(middlewareCompat(composedMiddleware));
2765
- * ```
2766
- */
2767
- declare function compose<T>(...middlewares: MiddlewareFn<T>[]): MiddlewareFn<T>;
2768
- /**
2769
- * Type helper for extracting state type from a store API.
2770
- */
2771
- type ExtractStateType<S> = S extends MiddlewareStoreApi<infer T> ? T : never;
2772
- /**
2773
- * Type helper for selector function.
2774
- */
2775
- type SelectorFn<T, U> = (state: T) => U;
2776
- /**
2777
- * Type helper for equality function.
2778
- */
2779
- type EqualityCheck<T> = (a: T, b: T) => boolean;
2780
-
2781
- export { type Action, type Actions, type Computed, type ComputedOptions, type DeepPartial, type DevtoolsOptions, type EffectCleanup, type EffectDefinition, type EffectFn, type EffectUtils, type EffectsOptions, type EqualityCheck, type EqualityFn, type ExtractStateType, type FederatedState, type Federation, type FederationListener, type FederationOptions, type GetSlice, type HistoryOptions, type HistoryStore, type Listener, type LogLevel, type LoggerOptions, type MiddlewareFn, type MiddlewareGetState, type MiddlewareSetState, type MiddlewareStoreApi, type MiddlewareSubscribe, type MockStorage, type MockedAction, type PersistOptions, type Plugin, type Selector, type SelectorFn, type SelectorOptions, type SetSlice, type SliceCreator, type SliceDefinition, type StateAssertion, type StateChange, type StateCreatorFn, type StorageLike$1 as StorageLike, type Store, type StoreBuilder, StoreError, StoreError as StoreErrorClass, StoreErrorCode, type StoreOptions, type StoreSpy, type StoreState, type SubscribeOptions, type SyncOptions, type TestStore, type TestStoreOptions, type TransactionFn, type ValidateOptions, type ValidationAPI, type ValidationError, type ValidationResult, type ValidationTiming, type ValidatorFn, assertState, batch, combineComputed, combineEffects, combineSlices, combineValidators, compose, computed, createAsyncValidator, createDebouncedEffect, createEffect, createFederatedComputed, createFederatedSelector, createFederation, createFieldValidator, createLogger, createMockStorage, createNamespacedSlice, createSimpleEffect, createSimpleMiddleware, createSlice, createStorage, createStore, createSubscriber, createTestStore, createValidator, createWithMiddleware, deepClone, deepEqual, deepMerge, delay, devtools, effects, extendStore, flushMicrotasks, hasHistory, history, identity, immer, isFunction, logger, memoizeSelector, middlewareCompat, mockAction, omit, persist, pick, produce, resetSlices, selector, sessionStorage, shallowEqual, snapshot, spyOnStore, stateDiff, subscribeOnce, subscribeToMany, subscribeWithOptions, sync, toMiddlewareApi, triggerSync, useAction, useCreateStore, useSetState, useShallow, useStore, useStoreActions, useStoreSelector, useTransientSubscribe, validate, waitForFederated };
253
+ export { EqualityFn, Selector, Store, useAction, useCreateStore, useSetState, useShallow, useStore, useStoreActions, useStoreSelector, useTransientSubscribe };