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