@asaidimu/utils-store 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.mts ADDED
@@ -0,0 +1,286 @@
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
+
87
+ /**
88
+ * Reactive Data Store Implementation
89
+ * A type-safe reactive data state for managing complex application state.
90
+ * Arrays are treated as primitive values (stored and updated as whole units).
91
+ */
92
+
93
+ /**
94
+ * Main ReactiveDataStore - now acts as a coordinator between components
95
+ */
96
+ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
97
+ private coreState;
98
+ private middlewareEngine;
99
+ private persistenceHandler;
100
+ private transactionManager;
101
+ private metricsCollector;
102
+ private pendingUpdates;
103
+ private isUpdating;
104
+ private updateBus;
105
+ private eventBus;
106
+ private executionState;
107
+ private instanceID;
108
+ private merge;
109
+ private diff;
110
+ constructor(initialData: T, persistence?: SimplePersistence<T>, deleteMarker?: symbol);
111
+ isReady(): boolean;
112
+ state(): Readonly<StoreExecutionState<T>>;
113
+ get(clone?: boolean): T;
114
+ set(update: StateUpdater<T>): Promise<void>;
115
+ subscribe(path: string | Array<string>, callback: (state: T) => void): () => void;
116
+ id(): string;
117
+ transaction<R>(operation: () => R | Promise<R>): Promise<R>;
118
+ use(props: MiddlewareConfig<T>): string;
119
+ unuse(id: string): boolean;
120
+ /** @deprecated WILL BE REMOVED*/
121
+ metrics(): StoreMetrics;
122
+ onStoreEvent(event: StoreEvent, listener: (data: any) => void): () => void;
123
+ }
124
+
125
+ /**
126
+ * Store Observability Module
127
+ * A separate module to add debugging and observability capabilities to the ReactiveDataStore.
128
+ */
129
+
130
+ /**
131
+ * Interface for debug event structure
132
+ */
133
+ interface DebugEvent {
134
+ type: string;
135
+ timestamp: number;
136
+ data: any;
137
+ }
138
+ /**
139
+ * Configuration options for the observability module
140
+ */
141
+ interface ObservabilityOptions {
142
+ /** Maximum number of events to keep in history */
143
+ maxEvents?: number;
144
+ /** Whether to enable console logging */
145
+ enableConsoleLogging?: boolean;
146
+ maxStateHistory?: number;
147
+ /** Options for specific event types to log */
148
+ logEvents?: {
149
+ updates?: boolean;
150
+ middleware?: boolean;
151
+ transactions?: boolean;
152
+ };
153
+ /** Time threshold in ms to highlight slow operations */
154
+ performanceThresholds?: {
155
+ updateTime?: number;
156
+ middlewareTime?: number;
157
+ };
158
+ }
159
+ /**
160
+ * Class for observing and debugging a ReactiveDataStore instance
161
+ */
162
+ declare class StoreObservability<T extends object> {
163
+ protected store: DataStore<T>;
164
+ private eventHistory;
165
+ private maxEvents;
166
+ private enableConsoleLogging;
167
+ private logEvents;
168
+ private performanceThresholds;
169
+ private unsubscribers;
170
+ private stateHistory;
171
+ private maxStateHistory;
172
+ private activeTransactionCount;
173
+ private activeBatches;
174
+ private middlewareExecutions;
175
+ /**
176
+ * Creates a new StoreObservability instance
177
+ * @param store The ReactiveDataStore to observe
178
+ * @param options Configuration options
179
+ */
180
+ constructor(store: DataStore<T>, options?: ObservabilityOptions);
181
+ /**
182
+ * Sets up all event listeners
183
+ */
184
+ private setupEventListeners;
185
+ /**
186
+ * Records a state snapshot
187
+ */
188
+ private recordStateSnapshot;
189
+ /**
190
+ * Records an event to the history
191
+ * @param type Event type
192
+ * @param data Event data
193
+ */
194
+ private recordEvent;
195
+ /**
196
+ * Logs an event to the console with appropriate formatting
197
+ * @param type Event type
198
+ * @param data Event data
199
+ */
200
+ private logEventToConsole;
201
+ /**
202
+ * Checks for performance issues in the events
203
+ * @param type Event type
204
+ * @param data Event data
205
+ */
206
+ private checkPerformance;
207
+ /**
208
+ * Returns the event history
209
+ * @returns Array of debug events
210
+ */
211
+ getEventHistory(): DebugEvent[];
212
+ /**
213
+ * Returns the state history
214
+ * @returns Array of state snapshots
215
+ */
216
+ getStateHistory(): T[];
217
+ /**
218
+ * Returns middleware execution history from the state
219
+ * @returns Array of middleware executions
220
+ */
221
+ getMiddlewareExecutions(): MiddlewareExecution[];
222
+ /**
223
+ * Returns state performance metrics
224
+ * @returns Store metrics object
225
+ */
226
+ getPerformanceMetrics(): StoreMetrics;
227
+ /**
228
+ * Returns current transaction status
229
+ * @returns Object with transaction status information
230
+ */
231
+ getTransactionStatus(): {
232
+ activeTransactions: number;
233
+ activeBatches: string[];
234
+ };
235
+ /**
236
+ * Creates a middleware that logs all updates
237
+ * @param options Options for the logging middleware
238
+ * @returns A middleware function
239
+ */
240
+ createLoggingMiddleware(options?: {
241
+ logLevel?: "debug" | "info" | "warn";
242
+ logUpdates?: boolean;
243
+ }): (state: T, update: DeepPartial<T>) => DeepPartial<T>;
244
+ /**
245
+ * Creates a middleware that validates updates against a schema
246
+ * @param validator Function that validates updates
247
+ * @returns A blocking middleware function
248
+ */
249
+ createValidationMiddleware(validator: (state: T, update: DeepPartial<T>) => boolean | {
250
+ valid: boolean;
251
+ reason?: string;
252
+ }): (state: T, update: DeepPartial<T>) => boolean;
253
+ /**
254
+ * Clears all event and state history
255
+ */
256
+ clearHistory(): void;
257
+ /**
258
+ * Returns a simplified view of recent state changes
259
+ * @param limit Maximum number of state changes to compare
260
+ * @returns Array of state difference objects
261
+ */
262
+ getRecentChanges(limit?: number): Array<{
263
+ timestamp: number;
264
+ changedPaths: string[];
265
+ from: Partial<T>;
266
+ to: Partial<T>;
267
+ }>;
268
+ /**
269
+ * Creates a time-travel debug middleware that lets you undo/redo state changes
270
+ * @returns An object with undo/redo methods and state info
271
+ */
272
+ createTimeTravel(): {
273
+ canUndo: () => boolean;
274
+ canRedo: () => boolean;
275
+ undo: () => void;
276
+ redo: () => void;
277
+ getHistoryLength: () => number;
278
+ clear: () => void;
279
+ };
280
+ /**
281
+ * Disconnects all event listeners and cleans up resources
282
+ */
283
+ disconnect(): void;
284
+ }
285
+
286
+ export { type DebugEvent, type ObservabilityOptions, ReactiveDataStore, StoreObservability };
package/index.d.ts ADDED
@@ -0,0 +1,286 @@
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
+
87
+ /**
88
+ * Reactive Data Store Implementation
89
+ * A type-safe reactive data state for managing complex application state.
90
+ * Arrays are treated as primitive values (stored and updated as whole units).
91
+ */
92
+
93
+ /**
94
+ * Main ReactiveDataStore - now acts as a coordinator between components
95
+ */
96
+ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
97
+ private coreState;
98
+ private middlewareEngine;
99
+ private persistenceHandler;
100
+ private transactionManager;
101
+ private metricsCollector;
102
+ private pendingUpdates;
103
+ private isUpdating;
104
+ private updateBus;
105
+ private eventBus;
106
+ private executionState;
107
+ private instanceID;
108
+ private merge;
109
+ private diff;
110
+ constructor(initialData: T, persistence?: SimplePersistence<T>, deleteMarker?: symbol);
111
+ isReady(): boolean;
112
+ state(): Readonly<StoreExecutionState<T>>;
113
+ get(clone?: boolean): T;
114
+ set(update: StateUpdater<T>): Promise<void>;
115
+ subscribe(path: string | Array<string>, callback: (state: T) => void): () => void;
116
+ id(): string;
117
+ transaction<R>(operation: () => R | Promise<R>): Promise<R>;
118
+ use(props: MiddlewareConfig<T>): string;
119
+ unuse(id: string): boolean;
120
+ /** @deprecated WILL BE REMOVED*/
121
+ metrics(): StoreMetrics;
122
+ onStoreEvent(event: StoreEvent, listener: (data: any) => void): () => void;
123
+ }
124
+
125
+ /**
126
+ * Store Observability Module
127
+ * A separate module to add debugging and observability capabilities to the ReactiveDataStore.
128
+ */
129
+
130
+ /**
131
+ * Interface for debug event structure
132
+ */
133
+ interface DebugEvent {
134
+ type: string;
135
+ timestamp: number;
136
+ data: any;
137
+ }
138
+ /**
139
+ * Configuration options for the observability module
140
+ */
141
+ interface ObservabilityOptions {
142
+ /** Maximum number of events to keep in history */
143
+ maxEvents?: number;
144
+ /** Whether to enable console logging */
145
+ enableConsoleLogging?: boolean;
146
+ maxStateHistory?: number;
147
+ /** Options for specific event types to log */
148
+ logEvents?: {
149
+ updates?: boolean;
150
+ middleware?: boolean;
151
+ transactions?: boolean;
152
+ };
153
+ /** Time threshold in ms to highlight slow operations */
154
+ performanceThresholds?: {
155
+ updateTime?: number;
156
+ middlewareTime?: number;
157
+ };
158
+ }
159
+ /**
160
+ * Class for observing and debugging a ReactiveDataStore instance
161
+ */
162
+ declare class StoreObservability<T extends object> {
163
+ protected store: DataStore<T>;
164
+ private eventHistory;
165
+ private maxEvents;
166
+ private enableConsoleLogging;
167
+ private logEvents;
168
+ private performanceThresholds;
169
+ private unsubscribers;
170
+ private stateHistory;
171
+ private maxStateHistory;
172
+ private activeTransactionCount;
173
+ private activeBatches;
174
+ private middlewareExecutions;
175
+ /**
176
+ * Creates a new StoreObservability instance
177
+ * @param store The ReactiveDataStore to observe
178
+ * @param options Configuration options
179
+ */
180
+ constructor(store: DataStore<T>, options?: ObservabilityOptions);
181
+ /**
182
+ * Sets up all event listeners
183
+ */
184
+ private setupEventListeners;
185
+ /**
186
+ * Records a state snapshot
187
+ */
188
+ private recordStateSnapshot;
189
+ /**
190
+ * Records an event to the history
191
+ * @param type Event type
192
+ * @param data Event data
193
+ */
194
+ private recordEvent;
195
+ /**
196
+ * Logs an event to the console with appropriate formatting
197
+ * @param type Event type
198
+ * @param data Event data
199
+ */
200
+ private logEventToConsole;
201
+ /**
202
+ * Checks for performance issues in the events
203
+ * @param type Event type
204
+ * @param data Event data
205
+ */
206
+ private checkPerformance;
207
+ /**
208
+ * Returns the event history
209
+ * @returns Array of debug events
210
+ */
211
+ getEventHistory(): DebugEvent[];
212
+ /**
213
+ * Returns the state history
214
+ * @returns Array of state snapshots
215
+ */
216
+ getStateHistory(): T[];
217
+ /**
218
+ * Returns middleware execution history from the state
219
+ * @returns Array of middleware executions
220
+ */
221
+ getMiddlewareExecutions(): MiddlewareExecution[];
222
+ /**
223
+ * Returns state performance metrics
224
+ * @returns Store metrics object
225
+ */
226
+ getPerformanceMetrics(): StoreMetrics;
227
+ /**
228
+ * Returns current transaction status
229
+ * @returns Object with transaction status information
230
+ */
231
+ getTransactionStatus(): {
232
+ activeTransactions: number;
233
+ activeBatches: string[];
234
+ };
235
+ /**
236
+ * Creates a middleware that logs all updates
237
+ * @param options Options for the logging middleware
238
+ * @returns A middleware function
239
+ */
240
+ createLoggingMiddleware(options?: {
241
+ logLevel?: "debug" | "info" | "warn";
242
+ logUpdates?: boolean;
243
+ }): (state: T, update: DeepPartial<T>) => DeepPartial<T>;
244
+ /**
245
+ * Creates a middleware that validates updates against a schema
246
+ * @param validator Function that validates updates
247
+ * @returns A blocking middleware function
248
+ */
249
+ createValidationMiddleware(validator: (state: T, update: DeepPartial<T>) => boolean | {
250
+ valid: boolean;
251
+ reason?: string;
252
+ }): (state: T, update: DeepPartial<T>) => boolean;
253
+ /**
254
+ * Clears all event and state history
255
+ */
256
+ clearHistory(): void;
257
+ /**
258
+ * Returns a simplified view of recent state changes
259
+ * @param limit Maximum number of state changes to compare
260
+ * @returns Array of state difference objects
261
+ */
262
+ getRecentChanges(limit?: number): Array<{
263
+ timestamp: number;
264
+ changedPaths: string[];
265
+ from: Partial<T>;
266
+ to: Partial<T>;
267
+ }>;
268
+ /**
269
+ * Creates a time-travel debug middleware that lets you undo/redo state changes
270
+ * @returns An object with undo/redo methods and state info
271
+ */
272
+ createTimeTravel(): {
273
+ canUndo: () => boolean;
274
+ canRedo: () => boolean;
275
+ undo: () => void;
276
+ redo: () => void;
277
+ getHistoryLength: () => number;
278
+ clear: () => void;
279
+ };
280
+ /**
281
+ * Disconnects all event listeners and cleans up resources
282
+ */
283
+ disconnect(): void;
284
+ }
285
+
286
+ export { type DebugEvent, type ObservabilityOptions, ReactiveDataStore, StoreObservability };