@asaidimu/utils-artifacts 3.1.2 → 3.1.4

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
@@ -1,38 +1,57 @@
1
1
  /**
2
- * Utility type for representing partial updates to the state.
2
+ * Utility type for representing partial updates to the state, allowing deep nesting.
3
+ * It makes all properties optional and applies the same transformation recursively
4
+ * to nested objects and array elements, allowing for selective updates while
5
+ * preserving the original structure. It also includes the original type T and
6
+ * undefined as possibilities for the top level and nested values.
3
7
  */
4
8
  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 : {
5
9
  [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> | undefined : T[K] | undefined;
6
10
  } | undefined | T : T | undefined;
7
11
  /**
8
- * Extended store state for monitoring execution status
12
+ * Extended store state for monitoring the current execution status (e.g., if an update is in progress).
9
13
  */
10
14
  interface StoreExecutionState<T> {
15
+ /** Indicates if a state update process is currently executing. */
11
16
  executing: boolean;
17
+ /** The changes (DeepPartial) currently being processed in the execution cycle. Null if none. */
12
18
  changes: DeepPartial<T> | null;
19
+ /** A queue of pending state update functions/objects to be applied sequentially. */
13
20
  pendingChanges: Array<StateUpdater<T>>;
21
+ /** Names of all currently registered middlewares. */
14
22
  middlewares: string[];
23
+ /** Details of the middleware currently running. Null if none. */
15
24
  runningMiddleware: {
16
25
  id: string;
17
26
  name: string;
18
27
  startTime: number;
19
28
  } | null;
29
+ /** Indicates if the store is currently within an active transaction block. */
20
30
  transactionActive: boolean;
21
31
  }
22
32
  /**
23
- * Event types emitted by the state for observability
33
+ * Event types emitted by the state store for observability and debugging.
24
34
  */
25
35
  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";
26
36
  /**
27
- * Represents a state update, which can be either a partial state object or a function.
37
+ * Represents a state update, which can be:
38
+ * 1. The full new state (`T`).
39
+ * 2. A partial update object (`DeepPartial<T>`).
40
+ * 3. A function that receives the current state and returns a partial update (sync or async).
28
41
  */
29
42
  type StateUpdater<T> = T | DeepPartial<T> | ((state: T) => DeepPartial<T> | Promise<DeepPartial<T>>);
30
43
  /**
31
44
  * Core types for the reactive data store
32
45
  */
46
+ /**
47
+ * Type for a Transform Middleware function.
48
+ * It modifies (transforms) the incoming changes and must return a `DeepPartial<T>`.
49
+ */
33
50
  type TransformMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<DeepPartial<T>> | DeepPartial<T>;
34
51
  /**
35
- * Type for blocking middleware functions that can prevent updates.
52
+ * Type for a Blocking Middleware function.
53
+ * It determines whether the state update should proceed or be blocked.
54
+ * It returns a boolean or an object containing a `block` boolean and an optional `error`.
36
55
  */
37
56
  type BlockingMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<boolean | {
38
57
  block: boolean;
@@ -42,23 +61,46 @@ type BlockingMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<bool
42
61
  error?: Error;
43
62
  };
44
63
  /**
45
- * Type representing the configuration object passed to `use`.
64
+ * Type representing the configuration object passed to the `use` method to register a middleware.
46
65
  */
47
66
  interface MiddlewareConfig<T> {
67
+ /** The middleware function (can be a transform or blocking middleware). */
48
68
  action: TransformMiddleware<T> | BlockingMiddleware<T>;
69
+ /** An optional, human-readable name for the middleware. */
49
70
  name?: string;
71
+ /** If true, the middleware is treated as a blocking middleware (must return a boolean or `{ block: boolean }`). */
50
72
  block?: boolean;
51
73
  }
74
+ /**
75
+ * Interface for a reactive selector result, providing access to the value and subscription capabilities.
76
+ */
52
77
  interface ReactiveSelector<S> {
78
+ /** Unique identifier for the selector. */
53
79
  id: string;
80
+ /** Function to get the current computed value of the selector. */
54
81
  get: () => S;
82
+ /**
83
+ * Subscribes a callback function to run whenever the selector's result changes.
84
+ * Returns an unsubscribe function.
85
+ */
55
86
  subscribe: (callback: (state: S) => void) => () => void;
56
87
  }
57
88
  /**
58
- * Interface defining the contract for the data state.
89
+ * Interface defining the contract for the core data state store.
90
+ * T must be an object type.
59
91
  */
60
92
  interface DataStore<T extends object> {
93
+ /**
94
+ * Gets the current state of the store.
95
+ * @param clone If true, returns a deep clone of the state; otherwise, returns the internal state reference.
96
+ * @returns The current state T.
97
+ */
61
98
  get(clone?: boolean): T;
99
+ /**
100
+ * Registers a named action function that can modify the state.
101
+ * @param action The action configuration object.
102
+ * @returns A function to unregister the action.
103
+ */
62
104
  register<R extends any[]>(action: {
63
105
  name: string;
64
106
  fn: (state: T, ...args: R) => DeepPartial<T> | Promise<DeepPartial<T>>;
@@ -67,46 +109,95 @@ interface DataStore<T extends object> {
67
109
  condition?: (previous: R, current: R) => boolean;
68
110
  };
69
111
  }): () => void;
112
+ /**
113
+ * Executes (dispatches) a previously registered action by its name.
114
+ * @param name The name of the action.
115
+ * @param args The parameters to pass to the action function.
116
+ * @returns A promise that resolves to the final state after the action and subsequent updates are complete.
117
+ */
70
118
  dispatch<R extends any[]>(name: string, ...args: R): Promise<T>;
119
+ /**
120
+ * Sets or updates the state using a StateUpdater.
121
+ * @param update The new state, partial state, or a function returning a partial state.
122
+ * @param options Configuration options for the set operation.
123
+ * @returns A promise that resolves to the current state when the update is complete.
124
+ */
71
125
  set(update: StateUpdater<T>, options?: {
72
126
  force?: boolean;
73
127
  actionId?: string;
74
- }): Promise<any>;
128
+ }): Promise<T>;
129
+ /**
130
+ * Creates a reactive selector that computes a derived value and tracks dependencies.
131
+ * @param selector A function to compute the derived state value S from the full state T.
132
+ * @returns A `ReactiveSelector<S>` object.
133
+ */
75
134
  select<S>(selector: (state: T) => S): ReactiveSelector<S>;
76
- /** @deprecated
77
- * Use watch instead will be removed in next major version
78
- * **/
79
- subscribe(path: string | Array<string>, callback: (state: T) => void): () => void;
135
+ /**
136
+ * Subscribes a callback to run when the data at the specified path(s) changes.
137
+ * @param path A single path string or an array of path strings to watch.
138
+ * @param callback The function to execute when a change occurs in the watched path(s).
139
+ * @returns An unsubscribe function.
140
+ */
80
141
  watch(path: string | Array<string>, callback: (state: T) => void): () => void;
142
+ /**
143
+ * Executes an operation function within a transaction block.
144
+ * All state updates (`set` or actions) within the transaction are batched and applied atomically (all or nothing).
145
+ * @param operation The function containing the state updates.
146
+ * @returns A promise that resolves to the return value of the operation function.
147
+ */
81
148
  transaction<R>(operation: () => R | Promise<R>): Promise<R>;
149
+ /**
150
+ * Registers a middleware function to intercept state updates.
151
+ * @param props The middleware configuration.
152
+ * @returns A function to unregister the middleware.
153
+ */
82
154
  use(props: MiddlewareConfig<T>): () => boolean;
83
- /** @deprecated
84
- * Use on instead will be removed in next majow version
85
- * **/
86
- onStoreEvent(event: StoreEvent, listener: (data: any) => void): () => void;
155
+ /**
156
+ * Subscribes a listener to a specific store event type.
157
+ * @param event The type of store event to listen for.
158
+ * @param listener The callback function to execute when the event fires.
159
+ * @returns An unsubscribe function.
160
+ */
87
161
  on(event: StoreEvent, listener: (data: any) => void): () => void;
162
+ /**
163
+ * Returns the unique identifier of the store instance.
164
+ */
88
165
  id(): string;
166
+ /**
167
+ * Checks whether the store is fully initialized and ready for use.
168
+ */
89
169
  isReady(): boolean;
170
+ /**
171
+ * Returns a readonly snapshot of the current execution state of the store.
172
+ */
90
173
  state(): Readonly<StoreExecutionState<T>>;
91
174
  }
92
175
 
93
176
  /**
94
- * Defines the lifecycle and sharing strategy for an artifact.
177
+ * Defines the lifecycle and sharing strategy for an artifact within the container.
95
178
  */
96
179
 
180
+ /**
181
+ * Defines the lifecycle and sharing strategy for an artifact.
182
+ */
97
183
  type ArtifactScope =
98
184
  /**
99
- * A single instance of the artifact is created and shared across all resolutions
100
- * within the container. It is created once and reused.
185
+ * **Singleton:** A single instance of the artifact is created and shared across all resolutions
186
+ * within the container. It is created once (often lazily) and reused until invalidated.
101
187
  */
102
188
  "singleton"
103
189
  /**
104
- * A new instance of the artifact is created every time it is resolved.
105
- * Transient artifacts do not participate in caching or shared state.
190
+ * **Transient:** A new instance of the artifact is created every time it is resolved.
191
+ * Transient artifacts do not participate in caching or shared state management.
106
192
  */
107
193
  | "transient";
194
+ /**
195
+ * Enumeration of standard artifact scopes for strongly typed configuration.
196
+ */
108
197
  declare enum ArtifactScopes {
198
+ /** A single instance is shared globally. */
109
199
  Singleton = "singleton",
200
+ /** A new instance is created on every resolution. */
110
201
  Transient = "transient"
111
202
  }
112
203
  /**
@@ -120,19 +211,20 @@ interface ArtifactDebugNode {
120
211
  scope: ArtifactScope;
121
212
  /**
122
213
  * The current status of the artifact, indicating its lifecycle phase.
123
- * - 'active': The artifact is built and available.
124
- * - 'error': The artifact failed to build due to an external error.
125
- * - 'idle': The artifact has not yet been built (lazy singleton) or has been disposed.
126
- * - 'building': The artifact's factory is currently executing.
127
- * - 'debouncing': The artifact is currently in a debounced invalidation state.
128
- */
129
- status: "active" | "error" | "idle" | "pending" /** A list of artifact keys that this artifact directly depends on. */;
214
+ * - `'active'`: The artifact is successfully built and its instance is available.
215
+ * - `'error'`: The artifact failed to build due to an external (runtime) error.
216
+ * - `'idle'`: The artifact has not yet been built (for lazy singletons) or has been disposed.
217
+ * - `'building'`: The artifact's factory is currently executing.
218
+ * - `'pending'`: The artifact is waiting to be built, often after an invalidation and before any debounce.
219
+ */
220
+ status: "active" | "error" | "idle" | "building" | "pending" | "debouncing";
221
+ /** A list of artifact keys that this artifact directly depends on. */
130
222
  dependencies: string[];
131
- /** A list of artifact keys that directly depend on this artifact. */
223
+ /** A list of artifact keys that directly depend on this artifact (its consumers). */
132
224
  dependents: string[];
133
225
  /** A list of state paths (selectors) that this artifact depends on. */
134
226
  stateDependencies: string[];
135
- /** The number of times this artifact's factory has been successfully executed. */
227
+ /** The number of times this artifact's factory has been successfully executed/rebuilt. */
136
228
  renderCount: number;
137
229
  }
138
230
  /**
@@ -143,54 +235,62 @@ interface ArtifactDebugNode {
143
235
  */
144
236
  interface UseDependencyContext<TRegistry extends Record<string, any>, TState extends object> {
145
237
  /**
146
- * Resolves another artifact from the container.
147
- * Declares a dependency on the resolved artifact, meaning that if the dependency
148
- * changes, this artifact will be invalidated and rebuilt.
238
+ * Resolves another artifact from the container and registers a dependency on it.
239
+ * If the dependency changes, the current artifact will be invalidated and rebuilt.
149
240
  * @template K The key of the artifact to resolve.
150
241
  * @param key The key of the artifact to resolve.
151
242
  * @returns A Promise that resolves to a `ResolvedArtifact` containing the instance
152
- * or an external error.
243
+ * or an external error.
153
244
  * @throws {SystemError} if the key is missing or if resolving creates a circular dependency.
154
245
  */
155
246
  resolve<K extends keyof TRegistry>(key: K): Promise<ResolvedArtifact<TRegistry[K]>>;
156
247
  /**
157
- * Selects a slice of the global state.
158
- * Declares a dependency on the selected state paths, meaning that if the selected
159
- * state changes, this artifact will be invalidated and rebuilt.
248
+ * Selects a slice of the global state and registers a dependency on it.
249
+ * If the selected state slice changes (based on a deep comparison), the current
250
+ * artifact will be invalidated and rebuilt.
160
251
  * @template S The type of the selected state slice.
161
- * @param selector A function that takes the full state and returns a slice.
252
+ * @param selector A function that takes the full state and returns a slice of state.
162
253
  * @returns The selected slice of state.
163
254
  */
164
255
  select<S>(selector: (state: TState) => S): S;
165
256
  }
166
257
  /**
167
- * Context object provided to an artifact stream producer function.
168
- * It contains methods and properties necessary for managing the stream
169
- * and communicating new artifact values.
258
+ * Context object provided to an artifact stream producer function (`ctx.stream` callback).
259
+ * It contains methods and properties necessary for managing the stream and communicating
260
+ * new artifact values to the container and its consumers.
170
261
  *
262
+ * @template TState The type of the global state.
171
263
  * @template TArtifact The type of the artifact being streamed.
172
264
  */
173
265
  type ArtifactStreamContext<TState, TArtifact> = {
174
266
  /**
175
267
  * The current value of the artifact. This is `undefined` before the first value is emitted.
176
268
  * Useful for diffing or migrating state during an update.
269
+ * @returns The current artifact value or `undefined`.
177
270
  */
178
271
  value: () => TArtifact | undefined;
179
272
  /**
180
273
  * An AbortSignal that indicates if the stream has been cancelled or aborted
181
- * from the consumer side. Producers should check this signal and stop
182
- * processing when it is set.
274
+ * from the consumer side (e.g., due to container disposal or artifact invalidation).
275
+ * Producers should check this signal and stop processing when it is set to prevent leaks.
183
276
  */
184
277
  signal: AbortSignal;
185
278
  /**
186
- * A function to asynchronously emit a new value of the artifact to the consumer.
187
- * Calling this function updates the `value` and `previous` properties in the
188
- * context for subsequent emissions.
279
+ * A function to asynchronously emit a new value of the artifact to the container.
280
+ * Calling this function updates the artifact's resolved value, triggers invalidation
281
+ * for its dependents, and updates the `value()` property for subsequent emissions.
189
282
  *
190
283
  * @param value The new artifact value to emit.
191
- * @returns A Promise that resolves when the value has been sent.
284
+ * @returns A Promise that resolves when the value has been sent and dependents have been notified.
192
285
  */
193
286
  emit: (value: TArtifact) => Promise<void>;
287
+ /**
288
+ * Dispatches a state update to the global store, analogous to a standard `setState`.
289
+ * **Note:** This does not automatically register a dependency for the current artifact.
290
+ * @param update A `StateUpdater` function or a partial state object.
291
+ * @param options Optional settings for the update, including `force` and `actionId`.
292
+ * @returns A Promise that resolves when the state update is complete.
293
+ */
194
294
  set(update: StateUpdater<TState>, options?: {
195
295
  force?: boolean;
196
296
  actionId?: string;
@@ -208,13 +308,14 @@ interface ArtifactFactoryContext<TRegistry extends Record<string, any>, TState e
208
308
  /**
209
309
  * Returns the current global state object. This is a non-reactive read;
210
310
  * changes to the state will not automatically invalidate the artifact
211
- * unless explicitly selected via `ctx.select in use()`.
311
+ * unless explicitly selected via `ctx.use` and `ctx.select`.
212
312
  * @returns The current global state.
213
313
  */
214
314
  state(): TState;
215
315
  /**
216
- * The previous instance of the artifact if it's a Singleton and is being rebuilt.
217
- * Useful for diffing or migrating state during an update.
316
+ * The previous instance of the artifact if it's a Singleton and is being rebuilt
317
+ * after an invalidation. This is `undefined` on the initial build.
318
+ * Useful for diffing, migrating state, or reusing resources during an update.
218
319
  */
219
320
  previous?: TArtifact;
220
321
  /**
@@ -223,81 +324,123 @@ interface ArtifactFactoryContext<TRegistry extends Record<string, any>, TState e
223
324
  * dependencies for the current artifact.
224
325
  * @template R The return type of the callback.
225
326
  * @param callback The function to execute to resolve dependencies.
226
- * @param options Optional settings for this dependency block, like debounce.
227
327
  * @returns A Promise resolving to the result of the callback.
228
328
  */
229
329
  use<R>(callback: (ctx: UseDependencyContext<TRegistry, TState>) => R | Promise<R>): Promise<R>;
230
330
  /**
231
- * Registers a cleanup function to be executed when the artifact is
232
- * invalidated and before its new instance is built. This is useful
233
- * for releasing resources specific to the *previous* instance.
331
+ * Registers a cleanup function to be executed when the **current instance** of the
332
+ * artifact is invalidated and before its new instance is built. This is useful
333
+ * for releasing resources (e.g., event listeners) specific to the *previous* instance.
234
334
  * @param cleanup The cleanup function.
235
335
  */
236
336
  onCleanup(cleanup: ArtifactCleanup): void;
237
337
  /**
238
338
  * Registers a dispose function to be executed when the artifact is
239
339
  * permanently removed from the container or the container itself is disposed.
240
- * This is for final resource release.
340
+ * This is for final, permanent resource release.
241
341
  * @param callback The dispose function.
242
342
  */
243
343
  onDispose(callback: ArtifactCleanup): void;
244
344
  /**
245
- * Updates the value of a Singleton artifact from within its own factory.
246
- * This immediately makes the new value available and triggers invalidation
247
- * for all dependents. Can be used for long-running processes that produce
248
- * intermediate results.
249
- * @param value The new value for the artifact.
345
+ * Starts a stream process for a Singleton artifact, allowing it to emit
346
+ * multiple values over time. The callback receives an `ArtifactStreamContext`
347
+ * for emitting values and managing the stream lifecycle.
348
+ * @param callback The function that implements the streaming logic.
250
349
  * @throws {SystemError} if called on a Transient artifact, as Transient artifacts
251
- * do not maintain a persistent value.
350
+ * do not maintain a persistent value.
252
351
  */
253
352
  stream(callback: (ctx: ArtifactStreamContext<TState, TArtifact>) => void | Promise<void>): void;
254
353
  }
255
354
  /**
256
- * A function that performs cleanup logic for an artifact, potentially asynchronously.
355
+ * A function that performs cleanup or disposal logic for an artifact, potentially asynchronously.
257
356
  * Used for `onCleanup` and `onDispose` callbacks.
258
357
  */
259
358
  type ArtifactCleanup = () => void | Promise<void>;
260
359
  /**
261
- * The result of an artifact resolution, providing the instance,
262
- * cleanup functionality, and details about any external errors.
360
+ * Common properties shared across all possible states of a resolved artifact.
263
361
  * @template TArtifact The type of the resolved artifact instance.
264
362
  */
265
- interface ResolvedArtifact<TArtifact> {
266
- /** The successfully resolved instance of the artifact, if no error occurred. */
267
- instance?: TArtifact;
363
+ interface ResolvedArtifactBase {
268
364
  /**
269
365
  * A function to manually trigger cleanup associated with this specific
270
- * resolved instance. This is typically only relevant for Transient artifacts.
366
+ * resolved instance. This is typically only relevant for Transient artifacts
367
+ * where the consumer is responsible for cleanup.
271
368
  */
272
369
  cleanup?: ArtifactCleanup;
273
- /**
274
- * Any runtime or external error that occurred during the artifact's factory
275
- * execution (e.g., fetch failed, timeout). SystemErrors are explicitly
276
- * thrown and will not appear here.
277
- */
278
- error?: any;
279
- ready: boolean;
280
370
  /**
281
371
  * Manually invalidates this artifact, triggering its rebuild and
282
372
  * cascading invalidations to its dependents.
283
- * @param replace If `true`, forces immediate rebuild without debounce.
373
+ * @param replace If `true`, forces immediate rebuild without debounce delay.
374
+ * @param fatal If `true`, the artifact will not be rebuilt until next resolve
375
+ * regardless of the lazy option during registration.
284
376
  */
285
- invalidate(replace?: boolean): Promise<void>;
377
+ invalidate(replace?: boolean, fatal?: boolean): Promise<void>;
378
+ }
379
+ /**
380
+ * State of an artifact that is successfully built and ready for use.
381
+ * The instance is guaranteed to be present.
382
+ * @template TArtifact The type of the resolved artifact instance.
383
+ */
384
+ interface ReadyArtifact<TArtifact> extends ResolvedArtifactBase {
385
+ /** The successfully resolved instance of the artifact. */
386
+ instance: TArtifact;
387
+ /** Indicates that the artifact is ready and has an instance. Always true. */
388
+ ready: true;
389
+ /** Must be undefined in a ready state. */
390
+ error?: undefined;
286
391
  }
392
+ /**
393
+ * State of an artifact that failed to build due to an external error.
394
+ * The instance is guaranteed to be absent.
395
+ */
396
+ interface ErrorArtifact extends ResolvedArtifactBase {
397
+ /** The instance is absent when an error occurs. Always undefined. */
398
+ instance?: undefined;
399
+ /** Indicates that the artifact failed to build. Always false. */
400
+ ready: false;
401
+ /**
402
+ * Any runtime or external error that occurred during the artifact's factory
403
+ * execution (e.g., network fetch failed).
404
+ */
405
+ error: any;
406
+ }
407
+ /**
408
+ * State of an artifact that is pending, idle, or currently building.
409
+ * Both instance and error are absent.
410
+ */
411
+ interface PendingArtifact extends ResolvedArtifactBase {
412
+ /** The instance is absent while pending or idle. Always undefined. */
413
+ instance?: undefined;
414
+ /** Indicates that the artifact is not yet ready. Always false. */
415
+ ready: false;
416
+ /** Must be undefined in a pending state. */
417
+ error?: undefined;
418
+ }
419
+ /**
420
+ * The result of an artifact resolution. This is a union type representing
421
+ * the artifact in one of three possible states: Ready, Error, or Pending/Idle.
422
+ *
423
+ * This structure allows consuming code to narrow the type based on the
424
+ * boolean flag `ready` or the presence of the `error` property.
425
+ *
426
+ * @template TArtifact The type of the resolved artifact instance.
427
+ */
428
+ type ResolvedArtifact<TArtifact> = ReadyArtifact<TArtifact> | ErrorArtifact | PendingArtifact;
287
429
  /**
288
430
  * The factory function responsible for creating an artifact's instance.
289
431
  * It receives an `ArtifactFactoryContext` to interact with the container
290
432
  * and declare dependencies.
291
433
  * @template TRegistry The type mapping artifact keys to their artifact types.
292
434
  * @template TState The type of the global state managed by the DataStore.
293
- * @template K The key of the artifact this factory produces.
435
+ * @template TArtifact The type of the artifact this factory produces.
294
436
  * @param context The context for creating the artifact.
295
437
  * @returns The artifact instance or a Promise resolving to it.
296
438
  */
297
439
  type ArtifactFactory<TRegistry extends Record<string, any>, TState extends object, TArtifact> = (context: ArtifactFactoryContext<TRegistry, TState, TArtifact>) => TArtifact | Promise<TArtifact>;
298
440
  type ArtifactInstance<R> = R extends PromiseLike<infer T> ? T : R;
299
441
  /**
300
- * An interface for observing changes to an artifact without direct resolution.
442
+ * An interface for observing changes to an artifact without direct resolution,
443
+ * typically used for UI binding or monitoring.
301
444
  * Provides a way to get the current resolved artifact and subscribe to updates.
302
445
  * @template TArtifact The type of the artifact being watched.
303
446
  */
@@ -305,36 +448,38 @@ interface ArtifactObserver<TArtifact> {
305
448
  /** The unique identifier (key) of the artifact being watched. */
306
449
  id: string;
307
450
  /**
308
- * Number of active references to this watcher.
451
+ * Number of active references (watchers) to this observer instance.
309
452
  * Incremented on each `watch()` call, decremented on each `dispose()` call.
310
453
  */
311
454
  count: number;
312
455
  /**
313
456
  * Retrieves the current `ResolvedArtifact` for the watched key.
314
- * @returns The resolved artifact.
457
+ * @returns The resolved artifact, including its instance and status.
315
458
  */
316
459
  get(): ResolvedArtifact<TArtifact>;
317
460
  /**
318
461
  * Subscribes a callback function to be invoked whenever the artifact's
319
- * state (instance or error) changes.
320
- * @param callback The function to call on updates.
321
- * @returns A function to unsubscribe the callback.
462
+ * state (instance, error, or readiness) changes.
463
+ * @param callback The function to call on updates. It receives the new `ResolvedArtifact`.
464
+ * @returns A function to unsubscribe the callback and stop receiving updates.
322
465
  */
323
466
  subscribe(callback: (artifact: ResolvedArtifact<TArtifact>) => void): () => void;
324
467
  /**
325
- * Disposes of this watcher reference, decrementing the reference count.
326
- * When the count reaches zero, cleans up all associated resources.
327
- * For transient artifacts that were cloned to singletons for watching,
328
- * this will unregister the cloned singleton when the last reference is disposed.
468
+ * Disposes of this specific observer reference, decrementing the reference count.
469
+ * When the count reaches zero, associated resources (like cloned singletons for Transient artifacts)
470
+ * are cleaned up.
329
471
  */
330
472
  dispose(): Promise<void>;
331
473
  }
332
474
  /**
333
475
  * Configuration options for defining an artifact. These options control
334
476
  * its lifecycle, instantiation, and error handling behavior.
477
+ * @template TState The type of the global state.
478
+ * @template TArtifact The resolved type of the artifact instance.
479
+ * @template TRegistry The type mapping of all artifacts in the container.
335
480
  */
336
481
  interface ArtifactTemplate<TState extends object, TArtifact, TRegistry extends object = any> {
337
- /** The unique key identifying this artifact. */
482
+ /** The unique key identifying this artifact within the registry. */
338
483
  key: keyof TRegistry;
339
484
  /** The factory function responsible for creating the artifact's instance. */
340
485
  factory: ArtifactFactory<TRegistry, TState, TArtifact>;
@@ -345,8 +490,8 @@ interface ArtifactTemplate<TState extends object, TArtifact, TRegistry extends o
345
490
  scope?: ArtifactScope;
346
491
  /**
347
492
  * If `true` (default), the artifact's factory is executed only when the artifact
348
- * is first requested. If `false`, the artifact is built immediately upon registration
349
- * (only applies to Singleton scopes).
493
+ * is first requested (lazy instantiation). If `false`, the artifact is built
494
+ * immediately upon registration (only applies to Singleton scopes).
350
495
  */
351
496
  lazy?: boolean;
352
497
  /**
@@ -356,60 +501,60 @@ interface ArtifactTemplate<TState extends object, TArtifact, TRegistry extends o
356
501
  timeout?: number;
357
502
  /**
358
503
  * Number of times to retry the artifact's factory on failure due to an
359
- * external (runtime) error. SystemErrors are not retried. Defaults to `0`.
504
+ * external (runtime) error (e.g., an exception in an async dependency).
505
+ * SystemErrors (e.g., key not found) are not retried. Defaults to `0`.
360
506
  */
361
507
  retries?: number;
362
508
  /**
363
509
  * Base debounce time in milliseconds for invalidation events originating
364
- * from this artifact. This can be overridden by `UseOptions.debounce`.
510
+ * from this artifact's dependencies. This delays the rebuild process to
511
+ * aggregate multiple rapid changes.
365
512
  */
366
513
  debounce?: number;
367
514
  }
368
515
  /**
369
- * Extracts the state type from an ArtifactTemplate
516
+ * Extracts the global state type (`TState`) from an `ArtifactTemplate`.
370
517
  */
371
518
  type ArtifactStateType<T> = T extends ArtifactTemplate<infer TState, any, any> ? TState : never;
372
519
  /**
373
- * Extracts the registry type from an ArtifactTemplate
520
+ * Extracts the full artifact registry type (`TRegistry`) from an `ArtifactTemplate`.
374
521
  */
375
522
  type ArtifactRegistryType<T> = T extends ArtifactTemplate<any, any, infer TRegistry> ? TRegistry : never;
376
523
  /**
377
- * Extracts the key from an ArtifactTemplate (as a string literal if possible)
524
+ * Extracts the key type (`K`) from an `ArtifactTemplate` (as a string literal if possible).
378
525
  */
379
526
  type ArtifactKey<T> = T extends {
380
527
  key: infer K;
381
528
  } ? K : never;
382
529
  /**
383
- * Extracts the scope from an ArtifactTemplate
530
+ * Extracts the scope type (`S`) from an `ArtifactTemplate`, defaulting to `ArtifactScope` if undefined.
384
531
  */
385
532
  type ArtifactScopeType<T> = T extends {
386
533
  scope: infer S;
387
534
  } ? S extends ArtifactScope ? S : ArtifactScope : ArtifactScope;
388
535
  /**
389
- * Helper type that creates a properly typed template map.
390
- * Use this as a type annotation when defining your templates object.
536
+ * Helper type that creates a properly typed template map where keys correspond to artifact names
537
+ * and values are their corresponding templates.
538
+ * @template TState The type of the global state.
539
+ * @template TRegistry The map of all artifact keys to their resolved types.
391
540
  */
392
541
  type ArtifactTemplateMap<TState extends object, TRegistry extends Record<string, any> = any> = {
393
542
  [K in keyof TRegistry]: ArtifactTemplate<TState, TRegistry[K], TRegistry>;
394
543
  };
395
544
  /**
396
- * Extracts the artifact's resolved value type from an object that structurally
397
- * resembles an ArtifactTemplate (or a variation where properties are omitted).
398
- *
399
- * It infers TArtifact from the second generic argument of the factory function,
400
- * which is the resolved artifact type.
545
+ * Extracts the artifact's resolved value type (`TArtifact`) from an object that structurally
546
+ * resembles an `ArtifactTemplate` (by inspecting the `factory` function's generic arguments).
401
547
  *
402
- * @template T The type that is structurally an ArtifactTemplate or an omitted version of it.
548
+ * @template T The type that contains a factory property.
403
549
  */
404
550
  type ArtifactValue<T> = T extends {
405
551
  factory: ArtifactFactory<any, any, infer TArtifact>;
406
552
  } ? TArtifact : never;
407
553
  /**
408
- * Infers the complete Artifact Registry type from a map of artifact configurations.
554
+ * Infers the complete Artifact Registry type from a map of artifact configuration objects.
409
555
  *
410
- * This works for both the full ArtifactTemplate (if key is present) or
411
- * ArtifactDefinition (if key is omitted), as it only relies on the presence
412
- * of the 'factory' property to determine the final type.
556
+ * This utility uses the `ArtifactValue` type to determine the resolved type for each key
557
+ * based on the `factory` function defined in the configuration.
413
558
  *
414
559
  * @template T A map where keys are artifact names and values are their configurations.
415
560
  */
@@ -527,4 +672,4 @@ declare class ArtifactContainer<TRegistry extends Record<string, any> = Record<s
527
672
  dispose(): void;
528
673
  }
529
674
 
530
- export { type ArtifactCleanup, ArtifactContainer, type ArtifactDebugNode, type ArtifactFactory, type ArtifactFactoryContext, type ArtifactInstance, type ArtifactKey, type ArtifactObserver, type ArtifactRegistryType, type ArtifactScope, type ArtifactScopeType, ArtifactScopes, type ArtifactStateType, type ArtifactStreamContext, type ArtifactTemplate, type ArtifactTemplateMap, type ArtifactValue, type InferRegistry, type ResolvedArtifact, type UseDependencyContext };
675
+ export { type ArtifactCleanup, ArtifactContainer, type ArtifactDebugNode, type ArtifactFactory, type ArtifactFactoryContext, type ArtifactInstance, type ArtifactKey, type ArtifactObserver, type ArtifactRegistryType, type ArtifactScope, type ArtifactScopeType, ArtifactScopes, type ArtifactStateType, type ArtifactStreamContext, type ArtifactTemplate, type ArtifactTemplateMap, type ArtifactValue, type ErrorArtifact, type InferRegistry, type PendingArtifact, type ReadyArtifact, type ResolvedArtifact, type ResolvedArtifactBase, type UseDependencyContext };