@asaidimu/utils-store 6.0.0 → 7.0.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/index.d.mts CHANGED
@@ -50,132 +50,237 @@ interface SimplePersistence<T> {
50
50
  }
51
51
 
52
52
  /**
53
- * Utility type for representing partial updates to the state.
53
+ * Utility type for representing partial updates to the state, allowing deep nesting.
54
+ * It makes all properties optional and applies the same transformation recursively
55
+ * to nested objects and array elements, allowing for selective updates while
56
+ * preserving the original structure. It also includes the original type T and
57
+ * undefined as possibilities for the top level and nested values.
54
58
  */
55
59
  type DeepPartial<T> = T extends object ? T extends readonly (infer U)[] ? readonly (DeepPartial<U> | undefined)[] | undefined | T : T extends (infer U)[] ? (DeepPartial<U> | undefined)[] | undefined | T : {
56
60
  [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> | undefined : T[K] | undefined;
57
61
  } | undefined | T : T | undefined;
58
62
  /**
59
- * Interface for performance metrics of the state.
63
+ * Interface for performance and execution metrics of the state store.
60
64
  */
61
65
  interface StoreMetrics {
66
+ /** The number of times the state has been successfully updated. */
62
67
  updateCount: number;
68
+ /** The total number of listener functions executed in response to state changes. */
63
69
  listenerExecutions: number;
70
+ /** The average time taken for a state update process to complete (in milliseconds). */
64
71
  averageUpdateTime: number;
72
+ /** The size (e.g., number of paths changed) of the largest single state update. */
65
73
  largestUpdateSize: number;
74
+ /** List of state paths that trigger the most listener executions. */
66
75
  mostActiveListenerPaths: string[];
76
+ /** The total number of update attempts (including blocked ones). */
67
77
  totalUpdates: number;
78
+ /** The number of updates that were blocked by blocking middleware. */
68
79
  blockedUpdates: number;
80
+ /** The average duration of a state update cycle (in milliseconds). */
69
81
  averageUpdateDuration: number;
82
+ /** The total number of middleware functions executed. */
70
83
  middlewareExecutions: number;
84
+ /** The total number of transactions initiated. */
71
85
  transactionCount: number;
86
+ /** The total number of store events fired. */
72
87
  totalEventsFired: number;
88
+ /** The total number of actions dispatched. */
73
89
  totalActionsDispatched: number;
90
+ /** The total number of actions that completed successfully. */
74
91
  totalActionsSucceeded: number;
92
+ /** The total number of actions that failed with an error. */
75
93
  totalActionsFailed: number;
94
+ /** The average duration of an action execution (in milliseconds). */
76
95
  averageActionDuration: number;
77
96
  }
78
97
  /**
79
- * Extended store state for monitoring execution status
98
+ * Extended store state for monitoring the current execution status (e.g., if an update is in progress).
80
99
  */
81
100
  interface StoreExecutionState<T> {
101
+ /** Indicates if a state update process is currently executing. */
82
102
  executing: boolean;
103
+ /** The changes (DeepPartial) currently being processed in the execution cycle. Null if none. */
83
104
  changes: DeepPartial<T> | null;
105
+ /** A queue of pending state update functions/objects to be applied sequentially. */
84
106
  pendingChanges: Array<StateUpdater<T>>;
107
+ /** Names of all currently registered middlewares. */
85
108
  middlewares: string[];
109
+ /** Details of the middleware currently running. Null if none. */
86
110
  runningMiddleware: {
87
111
  id: string;
88
112
  name: string;
89
113
  startTime: number;
90
114
  } | null;
115
+ /** Indicates if the store is currently within an active transaction block. */
91
116
  transactionActive: boolean;
92
117
  }
93
118
  /**
94
- * Event types emitted by the state for observability
119
+ * Event types emitted by the state store for observability and debugging.
95
120
  */
96
121
  type StoreEvent = "update:start" | "update:complete" | "middleware:start" | "middleware:complete" | "middleware:error" | "middleware:blocked" | "middleware:executed" | "transaction:start" | "transaction:complete" | "transaction:error" | "persistence:ready" | "persistence:queued" | "persistence:success" | "persistence:retry" | "persistence:failed" | "persistence:queue_cleared" | "persistence:init_error" | "action:start" | "action:complete" | "action:error" | "selector:accessed" | "selector:changed";
122
+ /**
123
+ * Payload for the 'selector:changed' event.
124
+ */
97
125
  interface SelectorChangedPayload<S> {
126
+ /** Unique identifier of the selector. */
98
127
  selectorId: string;
128
+ /** The new computed result of the selector. */
99
129
  newResult: S;
130
+ /** Timestamp of when the change occurred. */
100
131
  timestamp: number;
101
132
  }
133
+ /**
134
+ * Maps each `StoreEvent` type to its corresponding event payload interface.
135
+ * Uses conditional types to ensure type safety for event listeners.
136
+ */
102
137
  type StoreEvents = {
103
138
  [K in StoreEvent]: K extends "update:complete" ? {
139
+ /** List of state changes (deltas) applied in the update. */
104
140
  deltas: StateDelta[];
141
+ /** Total duration of the update process (in milliseconds). */
105
142
  duration: number;
143
+ /** Timestamp of the update completion. */
106
144
  timestamp: number;
145
+ /** Optional ID of the action that triggered the update. */
107
146
  actionId?: string;
147
+ /** The resulting new state after the update (may be a partial/transformed state). */
108
148
  newState: any;
149
+ /** True if the update was blocked by a middleware. */
109
150
  blocked?: boolean;
151
+ /** Any error that occurred during the update. */
110
152
  error?: any;
111
153
  } : K extends "selector:accessed" ? SelectorAccessedPayload : K extends "selector:changed" ? SelectorChangedPayload<any> : K extends "action:start" ? ActionStartPayload : K extends "action:complete" ? ActionCompletePayload : K extends "action:error" ? ActionErrorPayload : K extends "middleware:start" | "middleware:complete" | "middleware:error" | "middleware:blocked" | "middleware:executed" ? MiddlewareExecution : K extends "transaction:start" | "transaction:complete" | "transaction:error" ? {
112
154
  transactionId: string;
113
155
  timestamp: number;
114
156
  } : K extends "persistence:queued" ? PersistenceQueuedPayload : K extends "persistence:success" ? PersistenceSuccessPayload : K extends "persistence:retry" ? PersistenceRetryPayload : K extends "persistence:failed" ? PersistenceFailedPayload : K extends "persistence:queue_cleared" ? PersistenceQueueClearedPayload : K extends "persistence:init_error" ? PersistenceInitErrorPayload : any;
115
157
  };
158
+ /**
159
+ * Payload for the 'selector:accessed' event.
160
+ */
116
161
  interface SelectorAccessedPayload {
162
+ /** Unique identifier of the selector. */
117
163
  selectorId: string;
164
+ /** List of state paths accessed during the selector computation. */
118
165
  accessedPaths: string[];
166
+ /** Duration of the selector computation (in milliseconds). */
119
167
  duration: number;
168
+ /** Timestamp of the access. */
120
169
  timestamp: number;
121
170
  }
171
+ /**
172
+ * Payload for the 'action:start' event.
173
+ */
122
174
  interface ActionStartPayload {
175
+ /** Unique identifier for the action execution. */
123
176
  actionId: string;
177
+ /** Name of the action function. */
124
178
  name: string;
179
+ /** The parameters passed to the action function. */
125
180
  params: any[];
181
+ /** Timestamp of when the action execution started. */
126
182
  timestamp: number;
127
183
  }
184
+ /**
185
+ * Payload for the 'action:complete' event (successful action execution).
186
+ */
128
187
  interface ActionCompletePayload {
188
+ /** Unique identifier for the action execution. */
129
189
  actionId: string;
190
+ /** Name of the action function. */
130
191
  name: string;
192
+ /** The parameters passed to the action function. */
131
193
  params: any[];
194
+ /** Timestamp of when the action execution started. */
132
195
  startTime: number;
196
+ /** Timestamp of when the action execution completed. */
133
197
  endTime: number;
198
+ /** Total duration of the action execution (in milliseconds). */
134
199
  duration: number;
200
+ /** The result returned by the action function. */
135
201
  result: any;
136
202
  }
203
+ /**
204
+ * Payload for the 'action:error' event (failed action execution).
205
+ */
137
206
  interface ActionErrorPayload {
207
+ /** Unique identifier for the action execution. */
138
208
  actionId: string;
209
+ /** Name of the action function. */
139
210
  name: string;
211
+ /** The parameters passed to the action function. */
140
212
  params: any[];
213
+ /** Timestamp of when the action execution started. */
141
214
  startTime: number;
215
+ /** Timestamp of when the action execution ended (with error). */
142
216
  endTime: number;
217
+ /** Total duration of the action execution (in milliseconds). */
143
218
  duration: number;
219
+ /** The error object. */
144
220
  error: any;
145
221
  }
146
222
  /**
147
- * Type for middleware functions. Return a partial state to transform the update.
223
+ * Type for a generic middleware function.
224
+ * It receives the current state and the incoming update, and can return
225
+ * a modified `DeepPartial<T>` (transforming the update) or `void`.
148
226
  */
149
227
  type Middleware<T> = (state: T, update: DeepPartial<T>) => Promise<DeepPartial<T>> | Promise<void> | DeepPartial<T> | void;
150
228
  /**
151
- * Middleware execution information for event emissions
229
+ * Middleware execution information for event emissions and tracking.
152
230
  */
153
231
  interface MiddlewareExecution {
232
+ /** Unique identifier for the middleware instance. */
154
233
  id: string;
234
+ /** Name of the middleware. */
155
235
  name: string;
236
+ /** Timestamp of when the middleware execution started. */
156
237
  startTime: number;
238
+ /** Timestamp of when the middleware execution completed. */
157
239
  endTime: number;
240
+ /** Total duration of the middleware execution (in milliseconds). */
158
241
  duration: number;
242
+ /** True if the middleware blocked the update. */
159
243
  blocked: boolean;
244
+ /** Error object if the middleware failed. */
160
245
  error?: Error;
246
+ /** List of state changes (deltas) that resulted from this middleware's transformation. */
161
247
  deltas: StateDelta[];
162
248
  }
249
+ /**
250
+ * Represents a single change to the state, detailing the path, old value, and new value.
251
+ */
163
252
  interface StateDelta {
253
+ /** Dot-separated path to the changed property (e.g., "user.profile.name"). */
164
254
  path: string;
255
+ /** The value of the property *before* the update. */
165
256
  oldValue: any;
257
+ /** The value of the property *after* the update. */
166
258
  newValue: any;
167
259
  }
168
260
  /**
169
- * Represents a state update, which can be either a partial state object or a function.
261
+ * Represents a state update, which can be:
262
+ * 1. The full new state (`T`).
263
+ * 2. A partial update object (`DeepPartial<T>`).
264
+ * 3. A function that receives the current state and returns a partial update (sync or async).
170
265
  */
171
266
  type StateUpdater<T> = T | DeepPartial<T> | ((state: T) => DeepPartial<T> | Promise<DeepPartial<T>>);
267
+ /**
268
+ * A unique symbol used within DeepPartial objects to explicitly signal that a property
269
+ * should be deleted from the state object.
270
+ */
172
271
  declare const DELETE_SYMBOL: unique symbol;
173
272
  /**
174
273
  * Core types for the reactive data store
175
274
  */
275
+ /**
276
+ * Type for a Transform Middleware function.
277
+ * It modifies (transforms) the incoming changes and must return a `DeepPartial<T>`.
278
+ */
176
279
  type TransformMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<DeepPartial<T>> | DeepPartial<T>;
177
280
  /**
178
- * Type for blocking middleware functions that can prevent updates.
281
+ * Type for a Blocking Middleware function.
282
+ * It determines whether the state update should proceed or be blocked.
283
+ * It returns a boolean or an object containing a `block` boolean and an optional `error`.
179
284
  */
180
285
  type BlockingMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<boolean | {
181
286
  block: boolean;
@@ -185,23 +290,46 @@ type BlockingMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<bool
185
290
  error?: Error;
186
291
  };
187
292
  /**
188
- * Type representing the configuration object passed to `use`.
293
+ * Type representing the configuration object passed to the `use` method to register a middleware.
189
294
  */
190
295
  interface MiddlewareConfig<T> {
296
+ /** The middleware function (can be a transform or blocking middleware). */
191
297
  action: TransformMiddleware<T> | BlockingMiddleware<T>;
298
+ /** An optional, human-readable name for the middleware. */
192
299
  name?: string;
300
+ /** If true, the middleware is treated as a blocking middleware (must return a boolean or `{ block: boolean }`). */
193
301
  block?: boolean;
194
302
  }
303
+ /**
304
+ * Interface for a reactive selector result, providing access to the value and subscription capabilities.
305
+ */
195
306
  interface ReactiveSelector<S> {
307
+ /** Unique identifier for the selector. */
196
308
  id: string;
309
+ /** Function to get the current computed value of the selector. */
197
310
  get: () => S;
311
+ /**
312
+ * Subscribes a callback function to run whenever the selector's result changes.
313
+ * Returns an unsubscribe function.
314
+ */
198
315
  subscribe: (callback: (state: S) => void) => () => void;
199
316
  }
200
317
  /**
201
- * Interface defining the contract for the data state.
318
+ * Interface defining the contract for the core data state store.
319
+ * T must be an object type.
202
320
  */
203
321
  interface DataStore<T extends object> {
322
+ /**
323
+ * Gets the current state of the store.
324
+ * @param clone If true, returns a deep clone of the state; otherwise, returns the internal state reference.
325
+ * @returns The current state T.
326
+ */
204
327
  get(clone?: boolean): T;
328
+ /**
329
+ * Registers a named action function that can modify the state.
330
+ * @param action The action configuration object.
331
+ * @returns A function to unregister the action.
332
+ */
205
333
  register<R extends any[]>(action: {
206
334
  name: string;
207
335
  fn: (state: T, ...args: R) => DeepPartial<T> | Promise<DeepPartial<T>>;
@@ -210,67 +338,144 @@ interface DataStore<T extends object> {
210
338
  condition?: (previous: R, current: R) => boolean;
211
339
  };
212
340
  }): () => void;
341
+ /**
342
+ * Executes (dispatches) a previously registered action by its name.
343
+ * @param name The name of the action.
344
+ * @param args The parameters to pass to the action function.
345
+ * @returns A promise that resolves to the final state after the action and subsequent updates are complete.
346
+ */
213
347
  dispatch<R extends any[]>(name: string, ...args: R): Promise<T>;
348
+ /**
349
+ * Sets or updates the state using a StateUpdater.
350
+ * @param update The new state, partial state, or a function returning a partial state.
351
+ * @param options Configuration options for the set operation.
352
+ * @returns A promise that resolves to the current state when the update is complete.
353
+ */
214
354
  set(update: StateUpdater<T>, options?: {
215
355
  force?: boolean;
216
356
  actionId?: string;
217
- }): Promise<any>;
357
+ }): Promise<T>;
358
+ /**
359
+ * Creates a reactive selector that computes a derived value and tracks dependencies.
360
+ * @param selector A function to compute the derived state value S from the full state T.
361
+ * @returns A `ReactiveSelector<S>` object.
362
+ */
218
363
  select<S>(selector: (state: T) => S): ReactiveSelector<S>;
219
- /** @deprecated
220
- * Use watch instead will be removed in next major version
221
- * **/
222
- subscribe(path: string | Array<string>, callback: (state: T) => void): () => void;
364
+ /**
365
+ * Subscribes a callback to run when the data at the specified path(s) changes.
366
+ * @param path A single path string or an array of path strings to watch.
367
+ * @param callback The function to execute when a change occurs in the watched path(s).
368
+ * @returns An unsubscribe function.
369
+ */
223
370
  watch(path: string | Array<string>, callback: (state: T) => void): () => void;
371
+ /**
372
+ * Executes an operation function within a transaction block.
373
+ * All state updates (`set` or actions) within the transaction are batched and applied atomically (all or nothing).
374
+ * @param operation The function containing the state updates.
375
+ * @returns A promise that resolves to the return value of the operation function.
376
+ */
224
377
  transaction<R>(operation: () => R | Promise<R>): Promise<R>;
378
+ /**
379
+ * Registers a middleware function to intercept state updates.
380
+ * @param props The middleware configuration.
381
+ * @returns A function to unregister the middleware.
382
+ */
225
383
  use(props: MiddlewareConfig<T>): () => boolean;
226
- /** @deprecated
227
- * Use on instead will be removed in next majow version
228
- * **/
229
- onStoreEvent(event: StoreEvent, listener: (data: any) => void): () => void;
384
+ /**
385
+ * Subscribes a listener to a specific store event type.
386
+ * @param event The type of store event to listen for.
387
+ * @param listener The callback function to execute when the event fires.
388
+ * @returns An unsubscribe function.
389
+ */
230
390
  on(event: StoreEvent, listener: (data: any) => void): () => void;
391
+ /**
392
+ * Returns the unique identifier of the store instance.
393
+ */
231
394
  id(): string;
395
+ /**
396
+ * Checks whether the store is fully initialized and ready for use.
397
+ */
232
398
  isReady(): boolean;
399
+ /**
400
+ * Returns a readonly snapshot of the current execution state of the store.
401
+ */
233
402
  state(): Readonly<StoreExecutionState<T>>;
234
403
  }
404
+ /** Payload for the 'persistence:queued' event. */
235
405
  interface PersistenceQueuedPayload {
406
+ /** Unique ID for the persistence task. */
236
407
  taskId: string;
408
+ /** Paths that were changed and triggered persistence. */
237
409
  changedPaths: string[];
410
+ /** The current number of tasks waiting in the persistence queue. */
238
411
  queueSize: number;
412
+ /** Timestamp of when the task was queued. */
239
413
  timestamp: number;
240
414
  }
415
+ /** Payload for the 'persistence:success' event. */
241
416
  interface PersistenceSuccessPayload {
417
+ /** Unique ID for the persistence task. */
242
418
  taskId: string;
419
+ /** Paths that were successfully persisted. */
243
420
  changedPaths: string[];
421
+ /** Duration of the persistence operation (in milliseconds). */
244
422
  duration: number;
423
+ /** Timestamp of the success. */
245
424
  timestamp: number;
246
425
  }
426
+ /** Payload for the 'persistence:retry' event. */
247
427
  interface PersistenceRetryPayload {
428
+ /** Unique ID for the persistence task. */
248
429
  taskId: string;
430
+ /** Current retry attempt number. */
249
431
  attempt: number;
432
+ /** Maximum allowed retries. */
250
433
  maxRetries: number;
434
+ /** Time until the next retry attempt (in milliseconds). */
251
435
  nextRetryIn: number;
436
+ /** The error that triggered the retry. */
252
437
  error: any;
438
+ /** Timestamp of the retry event. */
253
439
  timestamp: number;
254
440
  }
441
+ /** Payload for the 'persistence:failed' event. */
255
442
  interface PersistenceFailedPayload {
443
+ /** Unique ID for the persistence task. */
256
444
  taskId: string;
445
+ /** Paths that failed to persist. */
257
446
  changedPaths: string[];
447
+ /** Total number of attempts made. */
258
448
  attempts: number;
449
+ /** The final error object. */
259
450
  error: any;
451
+ /** Timestamp of the final failure. */
260
452
  timestamp: number;
261
453
  }
454
+ /** Payload for the 'persistence:queue_cleared' event. */
262
455
  interface PersistenceQueueClearedPayload {
456
+ /** The number of persistence tasks that were cleared from the queue. */
263
457
  clearedTasks: number;
458
+ /** Timestamp of when the queue was cleared. */
264
459
  timestamp: number;
265
460
  }
461
+ /** Payload for the 'persistence:init_error' event. */
266
462
  interface PersistenceInitErrorPayload {
463
+ /** The error that occurred during persistence initialization. */
267
464
  error: any;
465
+ /** Timestamp of the error. */
268
466
  timestamp: number;
269
467
  }
468
+ /**
469
+ * Interface describing a registered state action, including its metadata and debounce configuration.
470
+ */
270
471
  type StoreAction<T, R extends any[] = any[]> = {
472
+ /** Unique identifier for the action definition. */
271
473
  id: string;
474
+ /** Name of the action, used for dispatching. */
272
475
  name: string;
476
+ /** The actual function that takes state and arguments, and returns a state update. */
273
477
  action: (state: T, ...args: R) => DeepPartial<T> | Promise<DeepPartial<T>>;
478
+ /** Optional configuration for debouncing action execution. */
274
479
  debounce?: {
275
480
  /** Active timer reference, if debouncing */
276
481
  timer?: ReturnType<typeof setTimeout>;
@@ -355,7 +560,7 @@ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
355
560
  set(update: StateUpdater<T>, options?: {
356
561
  force?: boolean;
357
562
  actionId?: string;
358
- }): Promise<any>;
563
+ }): Promise<T>;
359
564
  /**
360
565
  * Internal logic for performing a single, sequential state update.
361
566
  */
@@ -382,490 +587,6 @@ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
382
587
  private emit;
383
588
  }
384
589
 
385
- /**
386
- * Base class for structural/configuration errors within the ArtifactContainer.
387
- * These errors indicate fundamental issues (e.g., circular dependencies, missing artifacts)
388
- * that prevent successful resolution and should bypass any retry mechanisms,
389
- * causing an immediate strict failure.
390
- */
391
- declare class SystemError extends Error {
392
- constructor(message: string);
393
- }
394
- /**
395
- * Error thrown when a circular dependency is detected during artifact resolution.
396
- * This indicates a structural problem in the artifact graph.
397
- */
398
- declare class CircularDependencyError extends SystemError {
399
- /**
400
- * Creates an instance of CircularDependencyError.
401
- * @param path The dependency path that caused the cycle.
402
- */
403
- constructor(path: string[]);
404
- }
405
- /**
406
- * Error thrown when an artifact requested for resolution is not found
407
- * within the current container or its parent hierarchy.
408
- */
409
- declare class ArtifactNotFoundError extends SystemError {
410
- /**
411
- * Creates an instance of ArtifactNotFoundError.
412
- * @param key The key of the artifact that was not found.
413
- */
414
- constructor(key: string);
415
- }
416
- /**
417
- * Error thrown when an operation is attempted that is not permitted
418
- * due to the artifact's scope or current state (e.g., calling `yield` on a Transient artifact).
419
- */
420
- declare class IllegalScopeError extends SystemError {
421
- /**
422
- * Creates an instance of IllegalScopeError.
423
- * @param message A descriptive message about the illegal operation.
424
- */
425
- constructor(message: string);
426
- }
427
- /**
428
- * Defines the lifecycle and sharing strategy for an artifact.
429
- */
430
- declare enum ArtifactScope {
431
- /**
432
- * A single instance of the artifact is created and shared across all resolutions
433
- * within the container. It is created once and reused.
434
- */
435
- Singleton = "singleton",
436
- /**
437
- * A new instance of the artifact is created every time it is resolved.
438
- * Transient artifacts do not participate in caching or shared state.
439
- */
440
- Transient = "transient"
441
- }
442
- /**
443
- * Configuration options for defining an artifact. These options control
444
- * its lifecycle, instantiation, and error handling behavior.
445
- */
446
- interface ArtifactOptions {
447
- /**
448
- * The scope of the artifact, determining its lifecycle and sharing strategy.
449
- * Defaults to `ArtifactScope.Singleton`.
450
- */
451
- scope?: ArtifactScope;
452
- /**
453
- * If `true` (default), the artifact's factory is executed only when the artifact
454
- * is first requested. If `false`, the artifact is built immediately upon registration
455
- * (only applies to Singleton scopes).
456
- */
457
- lazy?: boolean;
458
- /**
459
- * Maximum time in milliseconds allowed for the artifact's factory function
460
- * to complete execution. If exceeded, the factory will time out.
461
- */
462
- timeoutMs?: number;
463
- /**
464
- * Number of times to retry the artifact's factory on failure due to an
465
- * external (runtime) error. SystemErrors are not retried. Defaults to `0`.
466
- */
467
- retries?: number;
468
- /**
469
- * Base debounce time in milliseconds for invalidation events originating
470
- * from this artifact. This can be overridden by `UseOptions.debounce`.
471
- */
472
- debounce?: number;
473
- }
474
- /**
475
- * Options that can be applied to dependency resolutions within an artifact's factory,
476
- * allowing for fine-grained control over how dependencies affect the current artifact.
477
- */
478
- interface UseOptions {
479
- /**
480
- * Applies a specific debounce time in milliseconds to dependencies resolved
481
- * within the `use` block. If this value is higher than the artifact's
482
- * `baseDebounceMs` (or `activeDebounceMs`), it will be used for subsequent invalidations.
483
- */
484
- debounce?: number;
485
- }
486
- /**
487
- * Represents a snapshot of an artifact's state and dependencies for debugging purposes.
488
- * Provides insight into the artifact's current status and its position within the dependency graph.
489
- */
490
- interface ArtifactDebugNode {
491
- /** The unique identifier (key) of the artifact. */
492
- id: string;
493
- /** The scope of the artifact (Singleton or Transient). */
494
- scope: ArtifactScope;
495
- /**
496
- * The current status of the artifact, indicating its lifecycle phase.
497
- * - 'active': The artifact is built and available.
498
- * - 'error': The artifact failed to build due to an external error.
499
- * - 'idle': The artifact has not yet been built (lazy singleton) or has been disposed.
500
- * - 'building': The artifact's factory is currently executing.
501
- * - 'debouncing': The artifact is currently in a debounced invalidation state.
502
- */
503
- status: "active" | "error" | "idle" | "building" | "debouncing";
504
- /** A list of artifact keys that this artifact directly depends on. */
505
- dependencies: string[];
506
- /** A list of artifact keys that directly depend on this artifact. */
507
- dependents: string[];
508
- /** A list of state paths (selectors) that this artifact depends on. */
509
- stateDependencies: string[];
510
- /** The number of times this artifact's factory has been successfully executed. */
511
- renderCount: number;
512
- }
513
- /**
514
- * Context provided to the `use` callback within an artifact factory.
515
- * It allows an artifact to declare dependencies on other artifacts and state slices.
516
- * @template TRegistry The type mapping artifact keys to their artifact types.
517
- * @template TState The type of the global state managed by the DataStore.
518
- */
519
- interface UseDependencyContext<TRegistry extends Record<string, any>, TState extends object> {
520
- /**
521
- * Resolves another artifact from the container.
522
- * Declares a dependency on the resolved artifact, meaning that if the dependency
523
- * changes, this artifact will be invalidated and rebuilt.
524
- * @template K The key of the artifact to resolve.
525
- * @param key The key of the artifact to resolve.
526
- * @returns A Promise that resolves to a `ResolvedArtifact` containing the instance
527
- * or an external error.
528
- * @throws {SystemError} if the key is missing or if resolving creates a circular dependency.
529
- */
530
- resolve<K extends keyof TRegistry>(key: K): Promise<ResolvedArtifact<TRegistry[K]>>;
531
- /**
532
- * Selects a slice of the global state.
533
- * Declares a dependency on the selected state paths, meaning that if the selected
534
- * state changes, this artifact will be invalidated and rebuilt.
535
- * @template S The type of the selected state slice.
536
- * @param selector A function that takes the full state and returns a slice.
537
- * @returns The selected slice of state.
538
- */
539
- select<S>(selector: (state: TState) => S): S;
540
- }
541
- /**
542
- * The full context provided to an artifact's factory function.
543
- * This context allows the artifact to interact with the container,
544
- * declare dependencies, manage its lifecycle, and update its value.
545
- * @template TRegistry The type mapping artifact keys to their artifact types.
546
- * @template TState The type of the global state managed by the DataStore.
547
- * @template TArtifact The type of the artifact being created by the factory.
548
- */
549
- interface ArtifactFactoryContext<TRegistry extends Record<string, any>, TState extends object, TArtifact> {
550
- /**
551
- * Returns the current global state object. This is a non-reactive read;
552
- * changes to the state will not automatically invalidate the artifact
553
- * unless explicitly selected via `ctx.select in use()`.
554
- * @returns The current global state.
555
- */
556
- state(): TState;
557
- /**
558
- * The previous instance of the artifact if it's a Singleton and is being rebuilt.
559
- * Useful for diffing or migrating state during an update.
560
- */
561
- current?: TArtifact;
562
- /**
563
- * Executes a callback within a dependency tracking context.
564
- * Any `resolve` or `select` calls made inside this callback will register
565
- * dependencies for the current artifact.
566
- * @template R The return type of the callback.
567
- * @param callback The function to execute to resolve dependencies.
568
- * @param options Optional settings for this dependency block, like debounce.
569
- * @returns A Promise resolving to the result of the callback.
570
- */
571
- use<R>(callback: (ctx: UseDependencyContext<TRegistry, TState>) => R | Promise<R>, options?: UseOptions): Promise<R>;
572
- /**
573
- * Registers a cleanup function to be executed when the artifact is
574
- * invalidated and before its new instance is built. This is useful
575
- * for releasing resources specific to the *previous* instance.
576
- * @param cleanup The cleanup function.
577
- */
578
- onCleanup(cleanup: ArtifactCleanup): void;
579
- /**
580
- * Registers a dispose function to be executed when the artifact is
581
- * permanently removed from the container or the container itself is disposed.
582
- * This is for final resource release.
583
- * @param callback The dispose function.
584
- */
585
- onDispose(callback: ArtifactCleanup): void;
586
- /**
587
- * Updates the value of a Singleton artifact from within its own factory.
588
- * This immediately makes the new value available and triggers invalidation
589
- * for all dependents. Can be used for long-running processes that produce
590
- * intermediate results.
591
- * @param value The new value for the artifact.
592
- * @throws {SystemError} if called on a Transient artifact, as Transient artifacts
593
- * do not maintain a persistent value.
594
- */
595
- yield(value: TArtifact): void;
596
- }
597
- /**
598
- * A function that performs cleanup logic for an artifact, potentially asynchronously.
599
- * Used for `onCleanup` and `onDispose` callbacks.
600
- */
601
- type ArtifactCleanup = () => void | Promise<void>;
602
- /**
603
- * The result of an artifact resolution, providing the instance,
604
- * cleanup functionality, and details about any external errors.
605
- * @template TArtifact The type of the resolved artifact instance.
606
- */
607
- interface ResolvedArtifact<TArtifact> {
608
- /** The successfully resolved instance of the artifact, if no error occurred. */
609
- instance?: TArtifact;
610
- /**
611
- * A function to manually trigger cleanup associated with this specific
612
- * resolved instance. This is typically only relevant for Transient artifacts.
613
- */
614
- cleanup?: ArtifactCleanup;
615
- /**
616
- * Any runtime or external error that occurred during the artifact's factory
617
- * execution (e.g., fetch failed, timeout). SystemErrors are explicitly
618
- * thrown and will not appear here.
619
- */
620
- error?: any;
621
- /**
622
- * Manually invalidates this artifact, triggering its rebuild and
623
- * cascading invalidations to its dependents.
624
- * @param replace If `true`, forces immediate rebuild without debounce.
625
- */
626
- invalidate(replace?: boolean): Promise<void>;
627
- }
628
- /**
629
- * The factory function responsible for creating an artifact's instance.
630
- * It receives an `ArtifactFactoryContext` to interact with the container
631
- * and declare dependencies.
632
- * @template TRegistry The type mapping artifact keys to their artifact types.
633
- * @template TState The type of the global state managed by the DataStore.
634
- * @template K The key of the artifact this factory produces.
635
- * @param context The context for creating the artifact.
636
- * @returns The artifact instance or a Promise resolving to it.
637
- */
638
- type ArtifactFactory<TRegistry extends Record<string, any>, TState extends object, K extends keyof TRegistry> = (context: ArtifactFactoryContext<TRegistry, TState, TRegistry[K]>) => TRegistry[K] | Promise<TRegistry[K]>;
639
- /**
640
- * An interface for observing changes to an artifact without direct resolution.
641
- * Provides a way to get the current resolved artifact and subscribe to updates.
642
- * @template TArtifact The type of the artifact being watched.
643
- */
644
- interface ArtifactWatcher<TArtifact> {
645
- /** The unique identifier (key) of the artifact being watched. */
646
- id: string;
647
- /**
648
- * Retrieves the current `ResolvedArtifact` for the watched key.
649
- * Returns `null` if the artifact has not yet been built or has no instance/error.
650
- * @returns The resolved artifact or `null`.
651
- */
652
- get(): ResolvedArtifact<TArtifact> | null;
653
- /**
654
- * Subscribes a callback function to be invoked whenever the artifact's
655
- * state (instance or error) changes.
656
- * @param callback The function to call on updates.
657
- * @returns A function to unsubscribe the callback.
658
- */
659
- subscribe(callback: () => void): () => void;
660
- }
661
- /**
662
- * A dependency injection container for managing the lifecycle, dependencies,
663
- * and instances of "artifacts" (any JavaScript/TypeScript object or value).
664
- * It supports hierarchical containers, different scopes (singleton, transient),
665
- * dependency resolution, state-based invalidation, and debounced rebuilding.
666
- *
667
- * @template TRegistry A type that maps artifact keys (strings) to their
668
- * corresponding artifact types. This provides strong
669
- * typing for `resolve`, `register`, and other operations.
670
- * @template TState The type of the global state object that artifacts can depend on.
671
- */
672
- declare class ArtifactContainer<TRegistry extends Record<string, any> = Record<string, any>, TState extends object = any> {
673
- private readonly artifacts;
674
- private readonly resolvingStack;
675
- private readonly listeners;
676
- private readonly watcherCache;
677
- private readonly props;
678
- private readonly parent?;
679
- private isDisposed;
680
- /**
681
- * Creates a new ArtifactContainer instance.
682
- * @param props An object providing functions to interact with a global data store,
683
- * specifically `watch` for state changes and `get` for current state.
684
- * @param parent An optional parent `ArtifactContainer`. If provided, this container
685
- * can resolve artifacts registered in its parent.
686
- */
687
- constructor({ watch, get }: Pick<DataStore<TState>, "watch" | "get">, parent?: ArtifactContainer<TRegistry, TState>);
688
- /**
689
- * Creates a new child `ArtifactContainer` that inherits from the current container.
690
- * Child containers can resolve artifacts registered in their parent, but
691
- * artifacts registered in the child are local to that child.
692
- * @returns A new `ArtifactContainer` instance.
693
- */
694
- createChild(): ArtifactContainer<TRegistry, TState>;
695
- /**
696
- * Provides debug information about all artifacts currently registered in this container.
697
- * This is useful for inspecting the state, scope, dependencies, and activity of artifacts.
698
- * @returns An array of `ArtifactDebugNode` objects, each representing a registered artifact.
699
- */
700
- getDebugInfo(): ArtifactDebugNode[];
701
- /**
702
- * Registers a new artifact with the container.
703
- * If an artifact with the same key already exists, it will be overwritten and disposed.
704
- * For Singleton, non-lazy artifacts, the factory will be immediately invoked.
705
- * @template K The key of the artifact to register.
706
- * @param {object} params The registration parameters.
707
- * @param {K} params.key The unique identifier for the artifact.
708
- * @param {ArtifactFactory<TRegistry, TState, K>} params.factory The function that creates the artifact instance.
709
- * @param {ArtifactOptions} params.options Optional configuration for the artifact's lifecycle.
710
- * @returns A cleanup function that, when called, unregisters the artifact.
711
- */
712
- register<K extends keyof TRegistry>({ key, factory, ...options }: {
713
- key: K;
714
- factory: ArtifactFactory<TRegistry, TState, K>;
715
- } & ArtifactOptions): () => void;
716
- /**
717
- * Unregisters an artifact from the container, disposing of its current instance
718
- * and removing all associated resources and dependency links.
719
- * @template K The key of the artifact to unregister.
720
- * @param key The unique identifier of the artifact.
721
- * @returns A Promise that resolves when the artifact has been fully unregistered and disposed.
722
- */
723
- unregister<K extends keyof TRegistry>(key: K): Promise<void>;
724
- /**
725
- * Resolves an artifact by its key, returning its instance or an error.
726
- * This method handles dependency resolution, cycle detection, caching,
727
- * and retry logic. It traverses the container hierarchy if the artifact
728
- * is not found locally.
729
- * @template K The key of the artifact to resolve.
730
- * @param key The unique identifier for the artifact.
731
- * @returns A Promise that resolves to a `ResolvedArtifact`. This object
732
- * will contain either the `instance` (if successful) or an `error`
733
- * (if an external error occurred during factory execution).
734
- * @throws {CircularDependencyError} if a circular dependency is detected during resolution.
735
- * @throws {ArtifactNotFoundError} if the artifact with the given key is not found
736
- * in the current container or any parent containers.
737
- * @throws {SystemError} for any other critical structural or configuration issues.
738
- */
739
- resolve<K extends keyof TRegistry>(key: K): Promise<ResolvedArtifact<TRegistry[K]>>;
740
- /**
741
- * Returns an `ArtifactWatcher` for a given artifact key.
742
- * The watcher allows subscribing to changes in the artifact's resolved value
743
- * without directly resolving it or becoming a direct dependent.
744
- * @template K The key of the artifact to watch.
745
- * @param key The unique identifier for the artifact.
746
- * @returns An `ArtifactWatcher` instance.
747
- */
748
- watch<K extends keyof TRegistry>(key: K): ArtifactWatcher<TRegistry[K]>;
749
- /**
750
- * Peeks at the resolved instance of an artifact without triggering its resolution
751
- * if it's lazy, or registering a dependency. It simply returns the currently
752
- * available instance (if any).
753
- * @template K The key of the artifact to peek at.
754
- * @param key The unique identifier for the artifact.
755
- * @returns The artifact instance if it's already built, otherwise `undefined`.
756
- */
757
- peek<K extends keyof TRegistry>(key: K): TRegistry[K] | undefined;
758
- private findDefinition;
759
- /**
760
- * Packages an `ArtifactDefinition` into a `ResolvedArtifact` for public consumption.
761
- * This abstracts away internal details and provides the external API for interacting
762
- * with a resolved artifact (e.g., `invalidate`).
763
- * @template T The expected type of the artifact instance.
764
- * @param def The internal `ArtifactDefinition`.
765
- * @returns A `ResolvedArtifact` object.
766
- */
767
- private packageArtifact;
768
- /**
769
- * Core logic for executing an artifact's factory and capturing its dependencies.
770
- * This method is responsible for setting up the factory context, running the
771
- * factory (with retries and timeouts), and collecting all declared dependencies
772
- * (both artifact and state).
773
- * @template K The key of the artifact being created.
774
- * @param def The `ArtifactDefinition` for the artifact.
775
- * @param outArtifactDeps A Set to capture discovered artifact dependencies.
776
- * @param outStateDeps A Set to capture discovered state dependencies.
777
- * @returns A Promise resolving to an object containing the instance, cleanup function, and any external error.
778
- * @throws {SystemError} if a critical internal error occurs (e.g., circular dependency detected).
779
- */
780
- private createArtifactInstance;
781
- /**
782
- * Handles the propagation of a `yield` event from a Singleton artifact.
783
- * This involves invalidating all direct dependents and notifying any listeners.
784
- * @param key The key of the artifact that yielded a new value.
785
- */
786
- private processYieldPropagation;
787
- /**
788
- * Registers a dependency from a `dependent` artifact on a `target` artifact.
789
- * This builds the inverse dependency graph, allowing for efficient cascade invalidations.
790
- * This method is public so that child containers can register dependents on artifacts
791
- * owned by a parent container.
792
- * @param targetKey The key of the artifact being depended upon.
793
- * @param dependentKey The key of the artifact that depends on the target.
794
- * @param dependentContainer The container instance where the dependent artifact is registered.
795
- */
796
- registerDependent(targetKey: string, dependentKey: string, dependentContainer: ArtifactContainer<any, any>): void;
797
- /**
798
- * Removes a previously registered dependency link.
799
- * This method is public so that child containers can remove dependents on artifacts
800
- * owned by a parent container when their artifacts are disposed.
801
- * @param targetKey The key of the artifact that was depended upon.
802
- * @param dependentKey The key of the artifact that previously depended on the target.
803
- * @param dependentContainer The container instance where the dependent artifact was registered.
804
- */
805
- removeDependent(targetKey: string, dependentKey: string, dependentContainer: ArtifactContainer<any, any>): void;
806
- /**
807
- * Initiates the invalidation process for an artifact, potentially debouncing the rebuild.
808
- * Invalidation marks an artifact as needing to be rebuilt on its next resolution.
809
- * @template K The key of the artifact to invalidate.
810
- * @param key The unique identifier for the artifact.
811
- * @param replace If `true`, bypasses debouncing and forces an immediate execution of `executeInvalidation`.
812
- * @returns A Promise that resolves when the invalidation (and potential debounced rebuild) is complete.
813
- */
814
- private invalidate;
815
- /**
816
- * Executes the actual invalidation and rebuild logic for an artifact.
817
- * This includes disposing the old instance, invalidating dependents, and (optionally) resolving a new instance.
818
- * @template K The key of the artifact to invalidate.
819
- * @param key The unique identifier for the artifact.
820
- * @param replace If `true`, forces immediate disposal and rebuild without waiting for existing rebuild promises.
821
- * @returns A Promise that resolves when the invalidation and rebuild process is complete.
822
- */
823
- private executeInvalidation;
824
- /**
825
- * Disposes of an artifact's instance by running its cleanup and dispose functions,
826
- * unsubscribing from state changes, and clearing its cached instance and error.
827
- * This prepares the artifact for a rebuild or removal.
828
- * @param def The `ArtifactDefinition` of the instance to dispose.
829
- */
830
- private disposeInstance;
831
- /**
832
- * Fully disposes of an artifact, including its instance and all its associated
833
- * dependency graph links and resources. This is typically called when an artifact
834
- * is unregistered or the container itself is disposed.
835
- * @param key The unique identifier of the artifact to dispose.
836
- */
837
- private disposeArtifact;
838
- /**
839
- * Updates the dependency graph for an artifact based on newly discovered dependencies
840
- * during its factory execution. This involves adding and removing dependent links,
841
- * and setting up or tearing down state subscriptions.
842
- * @param def The `ArtifactDefinition` whose graph is being updated.
843
- * @param newArtifactDeps The set of artifact dependencies discovered during the latest build.
844
- * @param newStateDeps The set of state path dependencies discovered during the latest build.
845
- */
846
- private updateGraph;
847
- /**
848
- * Creates a single composite cleanup function from an array of individual cleanup functions.
849
- * The composite function executes all provided cleanups in reverse order of registration,
850
- * ensuring proper resource release, and handles potential asynchronous cleanups.
851
- * @param fns An array of `ArtifactCleanup` functions.
852
- * @returns A composite `ArtifactCleanup` function, or `undefined` if the array is empty.
853
- */
854
- private createCompositeCleanup;
855
- /**
856
- * Notifies all registered listeners (watchers) for a specific artifact that
857
- * its state (instance or error) has potentially changed.
858
- * @param key The key of the artifact whose listeners should be notified.
859
- */
860
- private notifyListeners;
861
- /**
862
- * Disposes of the entire `ArtifactContainer` and all artifacts registered within it.
863
- * This releases all resources, stops all watchers, and clears all internal state.
864
- * After disposal, the container should no longer be used.
865
- */
866
- dispose(): void;
867
- }
868
-
869
590
  /**
870
591
  * @fileoverview Store Observer Module
871
592
  * @description A comprehensive module to add advanced debugging, observability, and time-travel
@@ -1194,4 +915,4 @@ declare class ActionManager<T extends object> {
1194
915
  private emit;
1195
916
  }
1196
917
 
1197
- export { type ActionCompletePayload, type ActionErrorPayload, ActionManager, type ActionStartPayload, type ArtifactCleanup, ArtifactContainer, type ArtifactDebugNode, type ArtifactFactory, type ArtifactFactoryContext, ArtifactNotFoundError, type ArtifactOptions, ArtifactScope, type ArtifactWatcher, type BlockingMiddleware, CircularDependencyError, DELETE_SYMBOL, type DataStore, type DeepPartial, type DiffFunction, IllegalScopeError, type MergeFunction, type Middleware, type MiddlewareConfig, type MiddlewareExecution, type ObserverOptions, type PersistenceFailedPayload, type PersistenceInitErrorPayload, type PersistenceQueueClearedPayload, type PersistenceQueuedPayload, type PersistenceRetryPayload, type PersistenceSuccessPayload, ReactiveDataStore, type ReactiveSelector, type ResolvedArtifact, type SelectorAccessedPayload, type SelectorChangedPayload, type StateDelta, type StateUpdater, type StoreAction, type StoreEvent, type StoreEvents, type StoreExecutionState, type StoreMetrics, StoreObserver, SystemError, type TransformMiddleware, type UseDependencyContext, type UseOptions, createDerivePaths, createDiff, createMerge, derivePaths, diff, merge, shallowClone };
918
+ export { type ActionCompletePayload, type ActionErrorPayload, ActionManager, type ActionStartPayload, type BlockingMiddleware, DELETE_SYMBOL, type DataStore, type DeepPartial, type DiffFunction, type MergeFunction, type Middleware, type MiddlewareConfig, type MiddlewareExecution, type ObserverOptions, type PersistenceFailedPayload, type PersistenceInitErrorPayload, type PersistenceQueueClearedPayload, type PersistenceQueuedPayload, type PersistenceRetryPayload, type PersistenceSuccessPayload, ReactiveDataStore, type ReactiveSelector, type SelectorAccessedPayload, type SelectorChangedPayload, type StateDelta, type StateUpdater, type StoreAction, type StoreEvent, type StoreEvents, type StoreExecutionState, type StoreMetrics, StoreObserver, type TransformMiddleware, createDerivePaths, createDiff, createMerge, derivePaths, diff, merge, shallowClone };