@asaidimu/utils-store 2.0.0 → 2.0.2

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/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Saidimu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/index.d.mts ADDED
@@ -0,0 +1,287 @@
1
+ import { S as SimplePersistence } from '../types-D26luDbE.js';
2
+
3
+ /**
4
+ * Utility type for representing partial updates to the state.
5
+ */
6
+ type DeepPartial<T> = {
7
+ [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P] | symbol;
8
+ };
9
+ /**
10
+ * Interface for performance metrics of the state.
11
+ */
12
+ interface StoreMetrics {
13
+ updateCount: number;
14
+ listenerExecutions: number;
15
+ averageUpdateTime: number;
16
+ largestUpdateSize: number;
17
+ mostActiveListenerPaths: string[];
18
+ }
19
+ /**
20
+ * Extended store state for monitoring execution status
21
+ */
22
+ interface StoreExecutionState<T> {
23
+ executing: boolean;
24
+ changes: DeepPartial<T> | null;
25
+ pendingChanges: Array<StateUpdater<T>>;
26
+ middlewares: string[];
27
+ runningMiddleware: {
28
+ id: string;
29
+ name: string;
30
+ startTime: number;
31
+ } | null;
32
+ transactionActive: boolean;
33
+ }
34
+ /**
35
+ * Event types emitted by the state for observability
36
+ */
37
+ type StoreEvent = "update:start" | "update:complete" | "middleware:start" | "middleware:complete" | "middleware:error" | "middleware:blocked" | "middleware:executed" | "transaction:start" | "transaction:complete" | "transaction:error" | "persistence:ready";
38
+ /**
39
+ * Type for middleware functions. Return a partial state to transform the update.
40
+ */
41
+ type Middleware<T> = (state: T, update: DeepPartial<T>) => Promise<DeepPartial<T>> | Promise<void> | DeepPartial<T> | void;
42
+ /**
43
+ * Type for blocking middleware functions that can prevent updates.
44
+ */
45
+ type BlockingMiddleware<T> = (state: T, update: DeepPartial<T>) => boolean | Promise<boolean>;
46
+ /**
47
+ * Middleware execution information for event emissions
48
+ */
49
+ interface MiddlewareExecution {
50
+ id: string;
51
+ name: string;
52
+ startTime: number;
53
+ endTime: number;
54
+ duration: number;
55
+ blocked: boolean;
56
+ error?: Error;
57
+ changedPaths: string[];
58
+ }
59
+ /**
60
+ * Represents a state update, which can be either a partial state object or a function.
61
+ */
62
+ type StateUpdater<T> = DeepPartial<T> | ((state: T) => DeepPartial<T> | Promise<DeepPartial<T>>);
63
+ /**
64
+ * Interface defining the contract for the data state.
65
+ */
66
+ interface DataStore<T extends object> {
67
+ get(clone?: boolean): T;
68
+ set(update: StateUpdater<T>): Promise<void>;
69
+ subscribe(path: string, listener: (state: T) => void): () => void;
70
+ transaction<R>(operation: () => R | Promise<R>): Promise<R>;
71
+ metrics(): StoreMetrics;
72
+ onStoreEvent(event: StoreEvent, listener: (data: any) => void): () => void;
73
+ }
74
+ /**
75
+ * Type representing the configuration object passed to `use`.
76
+ */
77
+ type MiddlewareConfig<T> = {
78
+ name?: string;
79
+ } & ({
80
+ block: true;
81
+ action: BlockingMiddleware<T>;
82
+ } | {
83
+ block?: false;
84
+ action: Middleware<T>;
85
+ });
86
+ declare const DELETE_SYMBOL: unique symbol;
87
+
88
+ /**
89
+ * Reactive Data Store Implementation
90
+ * A type-safe reactive data state for managing complex application state.
91
+ * Arrays are treated as primitive values (stored and updated as whole units).
92
+ */
93
+
94
+ /**
95
+ * Main ReactiveDataStore - now acts as a coordinator between components
96
+ */
97
+ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
98
+ private coreState;
99
+ private middlewareEngine;
100
+ private persistenceHandler;
101
+ private transactionManager;
102
+ private metricsCollector;
103
+ private pendingUpdates;
104
+ private isUpdating;
105
+ private updateBus;
106
+ private eventBus;
107
+ private executionState;
108
+ private instanceID;
109
+ private merge;
110
+ private diff;
111
+ constructor(initialData: T, persistence?: SimplePersistence<T>, deleteMarker?: symbol);
112
+ isReady(): boolean;
113
+ state(): Readonly<StoreExecutionState<T>>;
114
+ get(clone?: boolean): T;
115
+ set(update: StateUpdater<T>): Promise<void>;
116
+ subscribe(path: string | Array<string>, callback: (state: T) => void): () => void;
117
+ id(): string;
118
+ transaction<R>(operation: () => R | Promise<R>): Promise<R>;
119
+ use(props: MiddlewareConfig<T>): string;
120
+ unuse(id: string): boolean;
121
+ /** @deprecated WILL BE REMOVED*/
122
+ metrics(): StoreMetrics;
123
+ onStoreEvent(event: StoreEvent, listener: (data: any) => void): () => void;
124
+ }
125
+
126
+ /**
127
+ * Store Observability Module
128
+ * A separate module to add debugging and observability capabilities to the ReactiveDataStore.
129
+ */
130
+
131
+ /**
132
+ * Interface for debug event structure
133
+ */
134
+ interface DebugEvent {
135
+ type: string;
136
+ timestamp: number;
137
+ data: any;
138
+ }
139
+ /**
140
+ * Configuration options for the observability module
141
+ */
142
+ interface ObservabilityOptions {
143
+ /** Maximum number of events to keep in history */
144
+ maxEvents?: number;
145
+ /** Whether to enable console logging */
146
+ enableConsoleLogging?: boolean;
147
+ maxStateHistory?: number;
148
+ /** Options for specific event types to log */
149
+ logEvents?: {
150
+ updates?: boolean;
151
+ middleware?: boolean;
152
+ transactions?: boolean;
153
+ };
154
+ /** Time threshold in ms to highlight slow operations */
155
+ performanceThresholds?: {
156
+ updateTime?: number;
157
+ middlewareTime?: number;
158
+ };
159
+ }
160
+ /**
161
+ * Class for observing and debugging a ReactiveDataStore instance
162
+ */
163
+ declare class StoreObserver<T extends object> {
164
+ protected store: DataStore<T>;
165
+ private eventHistory;
166
+ private maxEvents;
167
+ private enableConsoleLogging;
168
+ private logEvents;
169
+ private performanceThresholds;
170
+ private unsubscribers;
171
+ private stateHistory;
172
+ private maxStateHistory;
173
+ private activeTransactionCount;
174
+ private activeBatches;
175
+ private middlewareExecutions;
176
+ /**
177
+ * Creates a new StoreObservability instance
178
+ * @param store The ReactiveDataStore to observe
179
+ * @param options Configuration options
180
+ */
181
+ constructor(store: DataStore<T>, options?: ObservabilityOptions);
182
+ /**
183
+ * Sets up all event listeners
184
+ */
185
+ private setupEventListeners;
186
+ /**
187
+ * Records a state snapshot
188
+ */
189
+ private recordStateSnapshot;
190
+ /**
191
+ * Records an event to the history
192
+ * @param type Event type
193
+ * @param data Event data
194
+ */
195
+ private recordEvent;
196
+ /**
197
+ * Logs an event to the console with appropriate formatting
198
+ * @param type Event type
199
+ * @param data Event data
200
+ */
201
+ private logEventToConsole;
202
+ /**
203
+ * Checks for performance issues in the events
204
+ * @param type Event type
205
+ * @param data Event data
206
+ */
207
+ private checkPerformance;
208
+ /**
209
+ * Returns the event history
210
+ * @returns Array of debug events
211
+ */
212
+ getEventHistory(): DebugEvent[];
213
+ /**
214
+ * Returns the state history
215
+ * @returns Array of state snapshots
216
+ */
217
+ getStateHistory(): T[];
218
+ /**
219
+ * Returns middleware execution history from the state
220
+ * @returns Array of middleware executions
221
+ */
222
+ getMiddlewareExecutions(): MiddlewareExecution[];
223
+ /**
224
+ * Returns state performance metrics
225
+ * @returns Store metrics object
226
+ */
227
+ getPerformanceMetrics(): StoreMetrics;
228
+ /**
229
+ * Returns current transaction status
230
+ * @returns Object with transaction status information
231
+ */
232
+ getTransactionStatus(): {
233
+ activeTransactions: number;
234
+ activeBatches: string[];
235
+ };
236
+ /**
237
+ * Creates a middleware that logs all updates
238
+ * @param options Options for the logging middleware
239
+ * @returns A middleware function
240
+ */
241
+ createLoggingMiddleware(options?: {
242
+ logLevel?: "debug" | "info" | "warn";
243
+ logUpdates?: boolean;
244
+ }): (state: T, update: DeepPartial<T>) => DeepPartial<T>;
245
+ /**
246
+ * Creates a middleware that validates updates against a schema
247
+ * @param validator Function that validates updates
248
+ * @returns A blocking middleware function
249
+ */
250
+ createValidationMiddleware(validator: (state: T, update: DeepPartial<T>) => boolean | {
251
+ valid: boolean;
252
+ reason?: string;
253
+ }): (state: T, update: DeepPartial<T>) => boolean;
254
+ /**
255
+ * Clears all event and state history
256
+ */
257
+ clearHistory(): void;
258
+ /**
259
+ * Returns a simplified view of recent state changes
260
+ * @param limit Maximum number of state changes to compare
261
+ * @returns Array of state difference objects
262
+ */
263
+ getRecentChanges(limit?: number): Array<{
264
+ timestamp: number;
265
+ changedPaths: string[];
266
+ from: Partial<T>;
267
+ to: Partial<T>;
268
+ }>;
269
+ /**
270
+ * Creates a time-travel debug middleware that lets you undo/redo state changes
271
+ * @returns An object with undo/redo methods and state info
272
+ */
273
+ createTimeTravel(): {
274
+ canUndo: () => boolean;
275
+ canRedo: () => boolean;
276
+ undo: () => void;
277
+ redo: () => void;
278
+ getHistoryLength: () => number;
279
+ clear: () => void;
280
+ };
281
+ /**
282
+ * Disconnects all event listeners and cleans up resources
283
+ */
284
+ disconnect(): void;
285
+ }
286
+
287
+ export { type BlockingMiddleware, DELETE_SYMBOL, type DataStore, type DebugEvent, type DeepPartial, type Middleware, type MiddlewareConfig, type MiddlewareExecution, type ObservabilityOptions, ReactiveDataStore, type StateUpdater, type StoreEvent, type StoreExecutionState, type StoreMetrics, StoreObserver };
package/index.d.ts ADDED
@@ -0,0 +1,287 @@
1
+ import { S as SimplePersistence } from '../types-D26luDbE.js';
2
+
3
+ /**
4
+ * Utility type for representing partial updates to the state.
5
+ */
6
+ type DeepPartial<T> = {
7
+ [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P] | symbol;
8
+ };
9
+ /**
10
+ * Interface for performance metrics of the state.
11
+ */
12
+ interface StoreMetrics {
13
+ updateCount: number;
14
+ listenerExecutions: number;
15
+ averageUpdateTime: number;
16
+ largestUpdateSize: number;
17
+ mostActiveListenerPaths: string[];
18
+ }
19
+ /**
20
+ * Extended store state for monitoring execution status
21
+ */
22
+ interface StoreExecutionState<T> {
23
+ executing: boolean;
24
+ changes: DeepPartial<T> | null;
25
+ pendingChanges: Array<StateUpdater<T>>;
26
+ middlewares: string[];
27
+ runningMiddleware: {
28
+ id: string;
29
+ name: string;
30
+ startTime: number;
31
+ } | null;
32
+ transactionActive: boolean;
33
+ }
34
+ /**
35
+ * Event types emitted by the state for observability
36
+ */
37
+ type StoreEvent = "update:start" | "update:complete" | "middleware:start" | "middleware:complete" | "middleware:error" | "middleware:blocked" | "middleware:executed" | "transaction:start" | "transaction:complete" | "transaction:error" | "persistence:ready";
38
+ /**
39
+ * Type for middleware functions. Return a partial state to transform the update.
40
+ */
41
+ type Middleware<T> = (state: T, update: DeepPartial<T>) => Promise<DeepPartial<T>> | Promise<void> | DeepPartial<T> | void;
42
+ /**
43
+ * Type for blocking middleware functions that can prevent updates.
44
+ */
45
+ type BlockingMiddleware<T> = (state: T, update: DeepPartial<T>) => boolean | Promise<boolean>;
46
+ /**
47
+ * Middleware execution information for event emissions
48
+ */
49
+ interface MiddlewareExecution {
50
+ id: string;
51
+ name: string;
52
+ startTime: number;
53
+ endTime: number;
54
+ duration: number;
55
+ blocked: boolean;
56
+ error?: Error;
57
+ changedPaths: string[];
58
+ }
59
+ /**
60
+ * Represents a state update, which can be either a partial state object or a function.
61
+ */
62
+ type StateUpdater<T> = DeepPartial<T> | ((state: T) => DeepPartial<T> | Promise<DeepPartial<T>>);
63
+ /**
64
+ * Interface defining the contract for the data state.
65
+ */
66
+ interface DataStore<T extends object> {
67
+ get(clone?: boolean): T;
68
+ set(update: StateUpdater<T>): Promise<void>;
69
+ subscribe(path: string, listener: (state: T) => void): () => void;
70
+ transaction<R>(operation: () => R | Promise<R>): Promise<R>;
71
+ metrics(): StoreMetrics;
72
+ onStoreEvent(event: StoreEvent, listener: (data: any) => void): () => void;
73
+ }
74
+ /**
75
+ * Type representing the configuration object passed to `use`.
76
+ */
77
+ type MiddlewareConfig<T> = {
78
+ name?: string;
79
+ } & ({
80
+ block: true;
81
+ action: BlockingMiddleware<T>;
82
+ } | {
83
+ block?: false;
84
+ action: Middleware<T>;
85
+ });
86
+ declare const DELETE_SYMBOL: unique symbol;
87
+
88
+ /**
89
+ * Reactive Data Store Implementation
90
+ * A type-safe reactive data state for managing complex application state.
91
+ * Arrays are treated as primitive values (stored and updated as whole units).
92
+ */
93
+
94
+ /**
95
+ * Main ReactiveDataStore - now acts as a coordinator between components
96
+ */
97
+ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
98
+ private coreState;
99
+ private middlewareEngine;
100
+ private persistenceHandler;
101
+ private transactionManager;
102
+ private metricsCollector;
103
+ private pendingUpdates;
104
+ private isUpdating;
105
+ private updateBus;
106
+ private eventBus;
107
+ private executionState;
108
+ private instanceID;
109
+ private merge;
110
+ private diff;
111
+ constructor(initialData: T, persistence?: SimplePersistence<T>, deleteMarker?: symbol);
112
+ isReady(): boolean;
113
+ state(): Readonly<StoreExecutionState<T>>;
114
+ get(clone?: boolean): T;
115
+ set(update: StateUpdater<T>): Promise<void>;
116
+ subscribe(path: string | Array<string>, callback: (state: T) => void): () => void;
117
+ id(): string;
118
+ transaction<R>(operation: () => R | Promise<R>): Promise<R>;
119
+ use(props: MiddlewareConfig<T>): string;
120
+ unuse(id: string): boolean;
121
+ /** @deprecated WILL BE REMOVED*/
122
+ metrics(): StoreMetrics;
123
+ onStoreEvent(event: StoreEvent, listener: (data: any) => void): () => void;
124
+ }
125
+
126
+ /**
127
+ * Store Observability Module
128
+ * A separate module to add debugging and observability capabilities to the ReactiveDataStore.
129
+ */
130
+
131
+ /**
132
+ * Interface for debug event structure
133
+ */
134
+ interface DebugEvent {
135
+ type: string;
136
+ timestamp: number;
137
+ data: any;
138
+ }
139
+ /**
140
+ * Configuration options for the observability module
141
+ */
142
+ interface ObservabilityOptions {
143
+ /** Maximum number of events to keep in history */
144
+ maxEvents?: number;
145
+ /** Whether to enable console logging */
146
+ enableConsoleLogging?: boolean;
147
+ maxStateHistory?: number;
148
+ /** Options for specific event types to log */
149
+ logEvents?: {
150
+ updates?: boolean;
151
+ middleware?: boolean;
152
+ transactions?: boolean;
153
+ };
154
+ /** Time threshold in ms to highlight slow operations */
155
+ performanceThresholds?: {
156
+ updateTime?: number;
157
+ middlewareTime?: number;
158
+ };
159
+ }
160
+ /**
161
+ * Class for observing and debugging a ReactiveDataStore instance
162
+ */
163
+ declare class StoreObserver<T extends object> {
164
+ protected store: DataStore<T>;
165
+ private eventHistory;
166
+ private maxEvents;
167
+ private enableConsoleLogging;
168
+ private logEvents;
169
+ private performanceThresholds;
170
+ private unsubscribers;
171
+ private stateHistory;
172
+ private maxStateHistory;
173
+ private activeTransactionCount;
174
+ private activeBatches;
175
+ private middlewareExecutions;
176
+ /**
177
+ * Creates a new StoreObservability instance
178
+ * @param store The ReactiveDataStore to observe
179
+ * @param options Configuration options
180
+ */
181
+ constructor(store: DataStore<T>, options?: ObservabilityOptions);
182
+ /**
183
+ * Sets up all event listeners
184
+ */
185
+ private setupEventListeners;
186
+ /**
187
+ * Records a state snapshot
188
+ */
189
+ private recordStateSnapshot;
190
+ /**
191
+ * Records an event to the history
192
+ * @param type Event type
193
+ * @param data Event data
194
+ */
195
+ private recordEvent;
196
+ /**
197
+ * Logs an event to the console with appropriate formatting
198
+ * @param type Event type
199
+ * @param data Event data
200
+ */
201
+ private logEventToConsole;
202
+ /**
203
+ * Checks for performance issues in the events
204
+ * @param type Event type
205
+ * @param data Event data
206
+ */
207
+ private checkPerformance;
208
+ /**
209
+ * Returns the event history
210
+ * @returns Array of debug events
211
+ */
212
+ getEventHistory(): DebugEvent[];
213
+ /**
214
+ * Returns the state history
215
+ * @returns Array of state snapshots
216
+ */
217
+ getStateHistory(): T[];
218
+ /**
219
+ * Returns middleware execution history from the state
220
+ * @returns Array of middleware executions
221
+ */
222
+ getMiddlewareExecutions(): MiddlewareExecution[];
223
+ /**
224
+ * Returns state performance metrics
225
+ * @returns Store metrics object
226
+ */
227
+ getPerformanceMetrics(): StoreMetrics;
228
+ /**
229
+ * Returns current transaction status
230
+ * @returns Object with transaction status information
231
+ */
232
+ getTransactionStatus(): {
233
+ activeTransactions: number;
234
+ activeBatches: string[];
235
+ };
236
+ /**
237
+ * Creates a middleware that logs all updates
238
+ * @param options Options for the logging middleware
239
+ * @returns A middleware function
240
+ */
241
+ createLoggingMiddleware(options?: {
242
+ logLevel?: "debug" | "info" | "warn";
243
+ logUpdates?: boolean;
244
+ }): (state: T, update: DeepPartial<T>) => DeepPartial<T>;
245
+ /**
246
+ * Creates a middleware that validates updates against a schema
247
+ * @param validator Function that validates updates
248
+ * @returns A blocking middleware function
249
+ */
250
+ createValidationMiddleware(validator: (state: T, update: DeepPartial<T>) => boolean | {
251
+ valid: boolean;
252
+ reason?: string;
253
+ }): (state: T, update: DeepPartial<T>) => boolean;
254
+ /**
255
+ * Clears all event and state history
256
+ */
257
+ clearHistory(): void;
258
+ /**
259
+ * Returns a simplified view of recent state changes
260
+ * @param limit Maximum number of state changes to compare
261
+ * @returns Array of state difference objects
262
+ */
263
+ getRecentChanges(limit?: number): Array<{
264
+ timestamp: number;
265
+ changedPaths: string[];
266
+ from: Partial<T>;
267
+ to: Partial<T>;
268
+ }>;
269
+ /**
270
+ * Creates a time-travel debug middleware that lets you undo/redo state changes
271
+ * @returns An object with undo/redo methods and state info
272
+ */
273
+ createTimeTravel(): {
274
+ canUndo: () => boolean;
275
+ canRedo: () => boolean;
276
+ undo: () => void;
277
+ redo: () => void;
278
+ getHistoryLength: () => number;
279
+ clear: () => void;
280
+ };
281
+ /**
282
+ * Disconnects all event listeners and cleans up resources
283
+ */
284
+ disconnect(): void;
285
+ }
286
+
287
+ export { type BlockingMiddleware, DELETE_SYMBOL, type DataStore, type DebugEvent, type DeepPartial, type Middleware, type MiddlewareConfig, type MiddlewareExecution, type ObservabilityOptions, ReactiveDataStore, type StateUpdater, type StoreEvent, type StoreExecutionState, type StoreMetrics, StoreObserver };