@asaidimu/utils-artifacts 8.2.10 → 8.2.12

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 DELETED
@@ -1,842 +0,0 @@
1
- interface SubscribeOptions {
2
- /**
3
- * Debounce delay in milliseconds. When multiple events arrive in quick
4
- * succession, the callback runs only after the quiet period ends, using the
5
- * latest payload. Default = no debouncing.
6
- */
7
- debounce?: number;
8
- }
9
-
10
- /**
11
- * Utility type for representing partial updates to the state, allowing deep nesting.
12
- * It makes all properties optional and applies the same transformation recursively
13
- * to nested objects, allowing for selective updates while
14
- * preserving the original structure. It also includes the original type T and
15
- * undefined as possibilities for the top level and nested values.
16
- */
17
- 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 : {
18
- [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> | undefined : T[K] | undefined;
19
- } | undefined | T : T | undefined | symbol;
20
- /**
21
- * Extended store state for monitoring the current execution status (e.g., if an update is in progress).
22
- */
23
- interface StoreExecutionState<T> {
24
- /** Indicates if a state update process is currently executing. */
25
- executing: boolean;
26
- /** The changes (DeepPartial) currently being processed in the execution cycle. Null if none. */
27
- changes: DeepPartial<T> | null;
28
- /** A queue of pending state update functions/objects to be applied sequentially. */
29
- pendingChanges: Array<StateUpdater<T>>;
30
- /** Names of all currently registered middlewares. */
31
- middlewares: string[];
32
- /** Details of the middleware currently running. Null if none. */
33
- runningMiddleware: {
34
- id: string;
35
- name: string;
36
- startTime: number;
37
- } | null;
38
- /** Indicates if the store is currently within an active transaction block. */
39
- transactionActive: boolean;
40
- }
41
- /**
42
- * Event types emitted by the state store for observability and debugging.
43
- */
44
- 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";
45
- /**
46
- * Represents a state update, which can be:
47
- * 1. The full new state (`T`).
48
- * 2. A partial update object (`DeepPartial<T>`).
49
- * 3. A function that receives the current state and returns a partial update (sync or async).
50
- */
51
- type StateUpdater<T> = T | DeepPartial<T> | ((state: T) => DeepPartial<T> | Promise<DeepPartial<T>>);
52
- /**
53
- * Core types for the reactive data store
54
- */
55
- /**
56
- * Type for a Transform Middleware function.
57
- * It modifies (transforms) the incoming changes and must return a `DeepPartial<T>`.
58
- */
59
- type TransformMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<DeepPartial<T>> | DeepPartial<T>;
60
- /**
61
- * Type for a Blocking Middleware function.
62
- * It determines whether the state update should proceed or be blocked.
63
- * It returns a boolean or an object containing a `block` boolean and an optional `error`.
64
- */
65
- type BlockingMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<boolean | {
66
- block: boolean;
67
- error?: Error;
68
- }> | boolean | {
69
- block: boolean;
70
- error?: Error;
71
- };
72
- /**
73
- * Type representing the configuration object passed to the `use` method to register a middleware.
74
- */
75
- interface MiddlewareConfig<T> {
76
- /** The middleware function (can be a transform or blocking middleware). */
77
- action: TransformMiddleware<T> | BlockingMiddleware<T>;
78
- /** An optional, human-readable name for the middleware. */
79
- name?: string;
80
- /** If true, the middleware is treated as a blocking middleware (must return a boolean or `{ block: boolean }`). */
81
- block?: boolean;
82
- }
83
- /**
84
- * Interface for a reactive selector result, providing access to the value and subscription capabilities.
85
- */
86
- interface ReactiveSelector<S> {
87
- /** Unique identifier for the selector. */
88
- id: string;
89
- /** Function to get the current computed value of the selector. */
90
- get: () => S;
91
- /**
92
- * Subscribes a callback function to run whenever the selector's result changes.
93
- * Returns an unsubscribe function.
94
- */
95
- subscribe: (callback: (state: S) => void) => () => void;
96
- }
97
- interface ActionWatcher {
98
- /** Unique identifier for the action */
99
- name: string;
100
- /** Function to get the current computed value of the action. */
101
- status: () => boolean;
102
- /**
103
- * Subscribes a callback function to run whenever the action's status changes.
104
- * Returns an unsubscribe function.
105
- */
106
- subscribe: (callback: () => void) => () => void;
107
- }
108
- interface TransactionOptions {
109
- /** If true, blocks resolution until changes are fully committed to the database row */
110
- flush?: boolean;
111
- }
112
- /**
113
- * Interface defining the contract for the core data state store.
114
- * T must be an object type.
115
- */
116
- interface DataStore<T extends object> {
117
- /**
118
- * Gets the current state of the store.
119
- * @param clone If true, returns a deep clone of the state; otherwise, returns the internal state reference.
120
- * @returns The current state T.
121
- */
122
- get(clone?: boolean): T;
123
- /**
124
- * Gets a subset of the store.
125
- * @param paths The paths which to include in the returned object.
126
- * @param separator Optional separator for paths. Defaults to `.` .
127
- * @returns An object of the shape K mapping paths to their current values.
128
- */
129
- subset<K extends Record<string, any> = Record<string, any>>(paths: Array<string>, separator?: string): K;
130
- /**
131
- * Registers a named action function that can modify the state.
132
- * @param action The action configuration object.
133
- * @returns A function to unregister the action.
134
- */
135
- register<R extends any[]>(action: {
136
- name: string;
137
- fn: (state: T, ...args: R) => DeepPartial<T> | Promise<DeepPartial<T>>;
138
- debounce?: {
139
- delay: number;
140
- condition?: (previous: R, current: R) => boolean;
141
- };
142
- }): () => void;
143
- /**
144
- * Executes (dispatches) a previously registered action by its name.
145
- * @param name The name of the action.
146
- * @param args The parameters to pass to the action function.
147
- * @returns A promise that resolves to the final state after the action and subsequent updates are complete.
148
- */
149
- dispatch<R extends any[]>(name: string, ...args: R): Promise<T>;
150
- /**
151
- * Sets or updates the state using a StateUpdater.
152
- * @param update The new state, partial state, or a function returning a partial state.
153
- * @param options Configuration options for the set operation.
154
- * @returns A promise that resolves to the current state when the update is complete.
155
- */
156
- set(update: StateUpdater<T>, options?: {
157
- force?: boolean;
158
- actionId?: string;
159
- }): Promise<T>;
160
- /**
161
- * Creates a reactive selector that computes a derived value and tracks dependencies.
162
- * @param selector A function to compute the derived state value S from the full state T.
163
- * @returns A `ReactiveSelector<S>` object.
164
- */
165
- select<S>(selector: (state: T) => S): ReactiveSelector<S>;
166
- /**
167
- * Subscribes a callback to run when the data at the specified path(s) changes.
168
- * @param path A single path string or an array of path strings to watch.
169
- * @param callback The function to execute when a change occurs in the watched path(s).
170
- * @param options Extra options to pass to the event bus
171
- * @returns An unsubscribe function.
172
- */
173
- watch(path: string | Array<string>, callback: (state: T) => void, options?: SubscribeOptions): () => void;
174
- /**
175
- * Subscribes to execution‑status changes of a registered action.
176
- *
177
- * The provided callback is called **every time** the action transitions
178
- * between idle and running (i.e. on `action:start`, `action:complete`, or
179
- * `action:error` for the given name). The current status can also be read
180
- * synchronously with `isActionRunning(name)`.
181
- *
182
- * **Deferred listener teardown**
183
- * To avoid unnecessary churn when subscriptions are rapidly created and
184
- * destroyed, the underlying event listeners are not removed immediately
185
- * on unsubscribe. Instead, a *pending reset* is queued via `queueMicrotask`.
186
- * If a new subscription for the same action arrives before that microtask
187
- * executes, the reset is silently cancelled and the already‑established
188
- * listeners are reused. This keeps the subscription infrastructure stable
189
- * and prevents cascading notifications that could otherwise arise from
190
- * repeated subscribe‑unsubscribe‑subscribe cycles.
191
- *
192
- * @param name - The name of the action to watch.
193
- * @returns An ActionWatcher
194
- */
195
- watchAction(name: string): ActionWatcher;
196
- /**
197
- * Executes an operation function within a transaction block.
198
- * All state updates (`set` or actions) within the transaction are batched and applied atomically (all or nothing).
199
- * @param operation The function containing the state updates.
200
- * @returns A promise that resolves to the return value of the operation function.
201
- */
202
- transaction<R>(operation: () => R | Promise<R>, options?: TransactionOptions): Promise<R>;
203
- /**
204
- * Registers a middleware function to intercept state updates.
205
- * @param props The middleware configuration.
206
- * @returns A function to unregister the middleware.
207
- */
208
- use(props: MiddlewareConfig<T>): () => boolean;
209
- /**
210
- * Subscribes a listener to a specific store event type.
211
- * @param event The type of store event to listen for.
212
- * @param listener The callback function to execute when the event fires.
213
- * @returns An unsubscribe function.
214
- */
215
- on(event: StoreEvent, listener: (data: any) => void): () => void;
216
- /**
217
- * Returns the unique identifier of the store instance.
218
- */
219
- id(): string;
220
- /**
221
- * Checks whether the store is fully initialized and ready for use.
222
- */
223
- isReady(): boolean;
224
- /**
225
- * Returns a promise that resolves once the store is fully initialised.
226
- * Safe to call multiple times — all callers share the same latch.
227
- *
228
- * @param timeout - Optional maximum wait time in milliseconds.
229
- * @throws {TimeoutError} If the store does not become ready within the timeout.
230
- *
231
- * @example
232
- * await store.ready();
233
- * const state = store.get();
234
- */
235
- ready(timeout?: number): Promise<void>;
236
- /**
237
- * Returns a readonly snapshot of the current execution state of the store.
238
- */
239
- state(): Readonly<StoreExecutionState<T>>;
240
- /**
241
- * Releases all resources held by the store and renders it unusable
242
- */
243
- dispose(): Promise<void>;
244
- }
245
-
246
- /**
247
- * Defines the lifecycle and sharing strategy for an artifact within the container.
248
- */
249
-
250
- /**
251
- * Defines the lifecycle and sharing strategy for an artifact.
252
- */
253
- type ArtifactScope =
254
- /**
255
- * **Singleton:** A single instance of the artifact is created and shared across all resolutions
256
- * within the container. It is created once (often lazily) and reused until invalidated.
257
- */
258
- "singleton"
259
- /**
260
- * **Transient:** A new instance of the artifact is created every time it is resolved.
261
- * Transient artifacts do not participate in caching or shared state management.
262
- */
263
- | "transient";
264
- /**
265
- * Enumeration of standard artifact scopes for strongly typed configuration.
266
- */
267
- declare enum ArtifactScopes {
268
- /** A single instance is shared globally. */
269
- Singleton = "singleton",
270
- /** A new instance is created on every resolution. */
271
- Transient = "transient"
272
- }
273
- /**
274
- * Represents a snapshot of an artifact's state and dependencies for debugging purposes.
275
- * Provides insight into the artifact's current status and its position within the dependency graph.
276
- */
277
- interface ArtifactDebugNode {
278
- /** The unique identifier (key) of the artifact. */
279
- id: string;
280
- /** The scope of the artifact (Singleton or Transient). */
281
- scope: ArtifactScope;
282
- /**
283
- * The current status of the artifact, indicating its lifecycle phase.
284
- * - `'active'`: The artifact is successfully built and its instance is available.
285
- * - `'error'`: The artifact failed to build due to an external (runtime) error.
286
- * - `'idle'`: The artifact has not yet been built (for lazy singletons) or has been disposed.
287
- * - `'building'`: The artifact's factory is currently executing.
288
- * - `'pending'`: The artifact is waiting to be built, often after an invalidation and before any debounce.
289
- */
290
- status: "active" | "error" | "idle" | "building" | "pending" | "debouncing";
291
- /** A list of artifact keys that this artifact directly depends on. */
292
- dependencies: string[];
293
- /** A list of artifact keys that directly depend on this artifact (its consumers). */
294
- dependents: string[];
295
- /** A list of state paths (selectors) that this artifact depends on. */
296
- stateDependencies: string[];
297
- /** The number of times this artifact's factory has been successfully executed/rebuilt. */
298
- buildCount: number;
299
- }
300
- /**
301
- * Context provided to the `use` callback within an artifact factory.
302
- * It allows an artifact to declare dependencies on other artifacts and state slices.
303
- * @template TRegistry The type mapping artifact keys to their artifact types.
304
- * @template TState The type of the global state managed by the DataStore.
305
- */
306
- interface UseDependencyContext<TRegistry extends Record<string, any>, TState extends object> {
307
- /**
308
- * Resolves another artifact from the container and registers a dependency on it.
309
- * If the dependency changes, the current artifact will be invalidated and rebuilt.
310
- * @template K The key of the artifact to resolve.
311
- * @param key The key of the artifact to resolve.
312
- * @param params Parameters with which to resolve the artifact
313
- * @returns A Promise that resolves to a `ResolvedArtifact` containing the instance
314
- * or an external error.
315
- * @throws {SystemError} if the key is missing or if resolving creates a circular dependency.
316
- */
317
- resolve<K extends keyof TRegistry>(key: K, params?: any): Promise<ResolvedArtifact<TRegistry[K]>>;
318
- /**
319
- * Resolves another artifact from the container and registers a dependency on it.
320
- * If the dependency changes, the current artifact will be invalidated and rebuilt.
321
- * @template K The key of the artifact to resolve.
322
- * @param key The key of the artifact to resolve.
323
- * @param params Parameters with which to resolve the artifact
324
- * @returns A Promise that resolves to a the resolved instance, unlike
325
- * resolve, this will throw an error if resolution fails.
326
- * @throws {SystemError} if any error occurs during resolution.
327
- */
328
- require<K extends keyof TRegistry>(key: K, params?: any): Promise<TRegistry[K]>;
329
- /**
330
- * Selects a slice of the global state and registers a dependency on it.
331
- * If the selected state slice changes (based on a deep comparison), the current
332
- * artifact will be invalidated and rebuilt.
333
- * @template S The type of the selected state slice.
334
- * @param selector A function that takes the full state and returns a slice of state.
335
- * @returns The selected slice of state.
336
- */
337
- select<S>(selector: (state: TState) => S, options?: SubscribeOptions): S;
338
- }
339
- /**
340
- * Context object provided to an artifact stream producer function (`ctx.stream` callback).
341
- * It contains methods and properties necessary for managing the stream and communicating
342
- * new artifact values to the container and its consumers.
343
- *
344
- * @template TState The type of the global state.
345
- * @template TArtifact The type of the artifact being streamed.
346
- */
347
- type ArtifactStreamContext<TState, TArtifact> = {
348
- /**
349
- * The current value of the artifact. This is `undefined` before the first value is emitted.
350
- * Useful for diffing or migrating state during an update.
351
- * @returns The current artifact value or `undefined`.
352
- */
353
- value: () => TArtifact | undefined;
354
- /**
355
- * An AbortSignal that indicates if the stream has been cancelled or aborted
356
- * from the consumer side (e.g., due to container disposal or artifact invalidation).
357
- * Producers should check this signal and stop processing when it is set to prevent leaks.
358
- */
359
- signal: AbortSignal;
360
- /**
361
- * A function to asynchronously emit a new value of the artifact to the container.
362
- * Calling this function updates the artifact's resolved value, triggers invalidation
363
- * for its dependents, and updates the `value()` property for subsequent emissions.
364
- *
365
- * @param value The new artifact value to emit.
366
- * @returns A Promise that resolves when the value has been sent and dependents have been notified.
367
- */
368
- emit: (value: TArtifact) => Promise<void>;
369
- /**
370
- * Dispatches a state update to the global store, analogous to a standard `setState`.
371
- * **Note:** This does not automatically register a dependency for the current artifact.
372
- * @param update A `StateUpdater` function or a partial state object.
373
- * @param options Optional settings for the update, including `force` and `actionId`.
374
- * @returns A Promise that resolves when the state update is complete.
375
- */
376
- set(update: StateUpdater<TState>, options?: {
377
- force?: boolean;
378
- actionId?: string;
379
- }): Promise<any>;
380
- };
381
- /**
382
- * The full context provided to an artifact's factory function.
383
- * This context allows the artifact to interact with the container,
384
- * declare dependencies, manage its lifecycle, and update its value.
385
- * @template TRegistry The type mapping artifact keys to their artifact types.
386
- * @template TState The type of the global state managed by the DataStore.
387
- * @template TArtifact The type of the artifact being created by the factory.
388
- */
389
- type ArtifactFactoryContext<TRegistry extends Record<string, any>, TState extends object, TArtifact, TExtra extends Record<string, any> = {}> = TExtra & {
390
- /**
391
- * Returns the current global state object. This is a non-reactive read;
392
- * changes to the state will not automatically invalidate the artifact
393
- * unless explicitly selected via `ctx.use` and `ctx.select`.
394
- * @returns The current global state.
395
- */
396
- state(): TState;
397
- /**
398
- * The previous instance of the artifact if it's a Singleton and is being rebuilt
399
- * after an invalidation. This is `undefined` on the initial build.
400
- * Useful for diffing, migrating state, or reusing resources during an update.
401
- */
402
- previous?: TArtifact;
403
- /**
404
- * Executes a callback within a dependency tracking context.
405
- * Any `resolve` or `select` calls made inside this callback will register
406
- * dependencies for the current artifact.
407
- * @template R The return type of the callback.
408
- * @param callback The function to execute to resolve dependencies.
409
- * @returns A Promise resolving to the result of the callback.
410
- */
411
- use<R>(callback: (ctx: UseDependencyContext<TRegistry, TState>) => R | Promise<R>): Promise<R>;
412
- /**
413
- * Registers a cleanup function to be executed when the **current instance** of the
414
- * artifact is invalidated and before its new instance is built. This is useful
415
- * for releasing resources (e.g., event listeners) specific to the *previous* instance.
416
- * @param cleanup The cleanup function.
417
- */
418
- onCleanup(cleanup: ArtifactCleanup): void;
419
- /**
420
- * Registers a dispose function to be executed when the artifact is
421
- * permanently removed from the container or the container itself is disposed.
422
- * This is for final, permanent resource release.
423
- * @param callback The dispose function.
424
- */
425
- onDispose(callback: ArtifactCleanup): void;
426
- /**
427
- * Starts a streaming process for a Singleton artifact.
428
- * The callback receives an `ArtifactStreamContext` to emit values and manage the
429
- * stream's lifecycle. It can return a cleanup function (or a Promise resolving
430
- * to one) to handle resource disposal.
431
- * * @param callback - The streaming logic implementation. Can be synchronous or
432
- * asynchronous, optionally returning a cleanup function.
433
- * @throws {SystemError} If called on a Transient artifact, as they do not
434
- * support persistent streaming states.
435
- */
436
- stream(callback: (ctx: ArtifactStreamContext<TState, TArtifact>) => (void | (() => void | Promise<void>)) | Promise<void | (() => void | Promise<void>)>): void;
437
- stream(callback: (ctx: ArtifactStreamContext<TState, TArtifact>) => (void | (() => void | Promise<void>)) | Promise<void | (() => void | Promise<void>)>): void;
438
- /**
439
- * An AbortSignal that indicates if the artifacts has been unregistered
440
- */
441
- signal: AbortSignal;
442
- /** For parameterized artifacts: the parameters that were passed during resolve/watch. */
443
- params?: any;
444
- };
445
- /**
446
- * A function that performs cleanup or disposal logic for an artifact, potentially asynchronously.
447
- * Used for `onCleanup` and `onDispose` callbacks.
448
- */
449
- type ArtifactCleanup = () => void | Promise<void>;
450
- /**
451
- * Common properties shared across all possible states of a resolved artifact.
452
- * @template TArtifact The type of the resolved artifact instance.
453
- */
454
- interface ResolvedArtifactBase {
455
- /**
456
- * A function to manually trigger cleanup associated with this specific
457
- * resolved instance. This is typically only relevant for Transient artifacts
458
- * where the consumer is responsible for cleanup.
459
- */
460
- cleanup?: ArtifactCleanup;
461
- /**
462
- * Manually invalidates this artifact, triggering its rebuild and
463
- * cascading invalidations to its dependents.
464
- * @param replace If `true`, forces immediate rebuild without debounce delay.
465
- * @param fatal If `true`, the artifact will not be rebuilt until next resolve
466
- * regardless of the lazy option during registration.
467
- */
468
- invalidate(replace?: boolean, fatal?: boolean): Promise<void>;
469
- }
470
- /**
471
- * State of an artifact that is successfully built and ready for use.
472
- * The instance is guaranteed to be present.
473
- * @template TArtifact The type of the resolved artifact instance.
474
- */
475
- interface ReadyArtifact<TArtifact> extends ResolvedArtifactBase {
476
- /** The successfully resolved instance of the artifact. */
477
- instance: TArtifact;
478
- /** Indicates whether the artifact is ready and has an instance. */
479
- ready: true;
480
- error?: undefined;
481
- }
482
- /**
483
- * State of an artifact that failed to build due to an external error.
484
- * The instance is guaranteed to be absent.
485
- */
486
- interface ErrorArtifact extends ResolvedArtifactBase {
487
- instance?: undefined;
488
- ready: false;
489
- /**
490
- * Any runtime or external error that occurred during the artifact's factory
491
- * execution (e.g., network fetch failed).
492
- */
493
- error: any;
494
- }
495
- /**
496
- * State of an artifact that is pending, idle, or currently building.
497
- * Both instance and error are absent.
498
- */
499
- interface PendingArtifact extends ResolvedArtifactBase {
500
- /** The instance is absent while pending or idle. Always undefined. */
501
- instance?: undefined;
502
- ready: false;
503
- error?: undefined;
504
- }
505
- /**
506
- * The result of an artifact resolution. This is a union type representing
507
- * the artifact in one of three possible states: Ready, Error, or Pending/Idle.
508
- *
509
- * This structure allows consuming code to narrow the type based on the
510
- * boolean flag `ready` or the presence of the `error` property.
511
- *
512
- * @template TArtifact The type of the resolved artifact instance.
513
- */
514
- type ResolvedArtifact<TArtifact> = ReadyArtifact<TArtifact> | ErrorArtifact | PendingArtifact;
515
- type KeyedResolvedArtifact<TRegistry, K extends keyof TRegistry> = ResolvedArtifact<TRegistry[K]> & {
516
- [P in K]?: TRegistry[K];
517
- };
518
- /**
519
- * The factory function responsible for creating an artifact's instance.
520
- * It receives an `ArtifactFactoryContext` to interact with the container
521
- * and declare dependencies.
522
- * @template TRegistry The type mapping artifact keys to their artifact types.
523
- * @template TState The type of the global state managed by the DataStore.
524
- * @template TArtifact The type of the artifact this factory produces.
525
- * @param context The context for creating the artifact.
526
- * @returns The artifact instance or a Promise resolving to it.
527
- */
528
- type ArtifactFactory<TRegistry extends Record<string, any>, TState extends object, TArtifact, TExtra extends Record<string, any> = {}> = (context: ArtifactFactoryContext<TRegistry, TState, TArtifact, TExtra>) => TArtifact | Promise<TArtifact>;
529
- type ArtifactInstance<R> = R extends PromiseLike<infer T> ? T : R;
530
- /**
531
- * An interface for observing changes to an artifact without direct resolution,
532
- * typically used for UI binding or monitoring.
533
- * Provides a way to get the current resolved artifact and subscribe to updates.
534
- * @template TArtifact The type of the artifact being watched.
535
- */
536
- interface ArtifactObserver<TRegistry, K extends keyof TRegistry> {
537
- /** The unique identifier (key) of the artifact being watched. */
538
- id: string;
539
- /**
540
- * Number of active references (watchers) to this observer instance.
541
- * Incremented on each `watch()` call, decremented on each `dispose()` call.
542
- */
543
- count: number;
544
- /**
545
- * Retrieves the current `ResolvedArtifact` for the watched key.
546
- * @param resolve Flag indicating whether we should resolve the artifact
547
- * immediately. Defaults to `false`
548
- * @returns The resolved artifact, including its instance and status.
549
- */
550
- get(resolve?: boolean): KeyedResolvedArtifact<TRegistry, K>;
551
- /**
552
- * Subscribes a callback function to be invoked whenever the artifact's
553
- * state (instance, error, or readiness) changes.
554
- * @param callback The function to call on updates. It receives the new `ResolvedArtifact`.
555
- * @param eager a boolean indicating whether we should immediately call the
556
- * callback after subscription. Defaults to `true`
557
- * @returns A function to unsubscribe the callback and stop receiving updates.
558
- */
559
- subscribe(callback: (artifact: KeyedResolvedArtifact<TRegistry, K>) => void, eager?: boolean): () => void;
560
- /**
561
- * Resolves another artifact from the container and registers a dependency on it.
562
- * If the dependency changes, the current artifact will be invalidated and rebuilt.
563
- * @returns A Promise that resolves to a `ResolvedArtifact` containing the instance
564
- * or an external error.
565
- * @throws {SystemError} if resolution fails.
566
- */
567
- resolve(): Promise<KeyedResolvedArtifact<TRegistry, K>>;
568
- }
569
- /**
570
- * Configuration options for defining an artifact. These options control
571
- * its lifecycle, instantiation, and error handling behavior.
572
- * @template TState The type of the global state.
573
- * @template TArtifact The resolved type of the artifact instance.
574
- * @template TRegistry The type mapping of all artifacts in the container.
575
- */
576
- interface ArtifactTemplate<TState extends object, TArtifact, TRegistry extends Record<string, any> = Record<string, any>, TExtra extends Record<string, any> = {}> {
577
- /** The unique key identifying this artifact within the registry. */
578
- key: keyof TRegistry;
579
- /** The factory function responsible for creating the artifact's instance. */
580
- factory: ArtifactFactory<TRegistry, TState, TArtifact, TExtra>;
581
- /**
582
- * The scope of the artifact, determining its lifecycle and sharing strategy.
583
- * Defaults to `ArtifactScopes.Singleton`.
584
- */
585
- scope?: ArtifactScope;
586
- /**
587
- * If `true` (default), the artifact's factory is executed only when the artifact
588
- * is first requested (lazy instantiation). If `false`, the artifact is built
589
- * immediately upon registration (only applies to Singleton scopes).
590
- */
591
- lazy?: boolean;
592
- /**
593
- * Maximum time in milliseconds allowed for the artifact's factory function
594
- * to complete execution. If exceeded, the factory will time out.
595
- */
596
- timeout?: number;
597
- /**
598
- * Number of times to retry the artifact's factory on failure due to an
599
- * external (runtime) error (e.g., an exception in an async dependency).
600
- * SystemErrors (e.g., key not found) are not retried. Defaults to `0`.
601
- */
602
- retries?: number;
603
- /**
604
- * Base debounce time in milliseconds for invalidation events originating
605
- * from this artifact's dependencies. This delays the rebuild process to
606
- * aggregate multiple rapid changes.
607
- */
608
- debounce?: number;
609
- /** If defined, the artifact is parameterized. Receives the user‑supplied params and returns a unique string key. */
610
- paramKey?: (params: Record<string, unknown>) => string;
611
- virtual?: true;
612
- }
613
- /**
614
- * Extracts the global state type (`TState`) from an `ArtifactTemplate`.
615
- */
616
- type ArtifactStateType<T> = T extends ArtifactTemplate<infer TState, any, any> ? TState : never;
617
- /**
618
- * Extracts the full artifact registry type (`TRegistry`) from an `ArtifactTemplate`.
619
- */
620
- type ArtifactRegistryType<T> = T extends ArtifactTemplate<any, any, infer TRegistry> ? TRegistry : never;
621
- /**
622
- * Extracts the key type (`K`) from an `ArtifactTemplate` (as a string literal if possible).
623
- */
624
- type ArtifactKey<T> = T extends {
625
- key: infer K;
626
- } ? K : never;
627
- /**
628
- * Extracts the scope type (`S`) from an `ArtifactTemplate`, defaulting to `ArtifactScope` if undefined.
629
- */
630
- type ArtifactScopeType<T> = T extends {
631
- scope: infer S;
632
- } ? S extends ArtifactScope ? S : ArtifactScope : ArtifactScope;
633
- /**
634
- * Helper type that creates a properly typed template map where keys correspond to artifact names
635
- * and values are their corresponding templates.
636
- * @template TState The type of the global state.
637
- * @template TRegistry The map of all artifact keys to their resolved types.
638
- */
639
- type ArtifactTemplateMap<TState extends object, TRegistry extends Record<string, any> = Record<string, any>> = {
640
- [K in keyof TRegistry]: ArtifactTemplate<TState, TRegistry[K], TRegistry>;
641
- };
642
- /**
643
- * Extracts the artifact's resolved value type (`TArtifact`) from an object that structurally
644
- * resembles an `ArtifactTemplate` (by inspecting the `factory` function's generic arguments).
645
- *
646
- * @template T The type that contains a factory property.
647
- */
648
- type ArtifactValue<T> = T extends {
649
- factory: ArtifactFactory<any, any, infer TArtifact, any>;
650
- } ? TArtifact : never;
651
- /**
652
- * Infers the complete Artifact Registry type from a map of artifact configuration objects.
653
- *
654
- * This utility uses the `ArtifactValue` type to determine the resolved type for each key
655
- * based on the `factory` function defined in the configuration.
656
- *
657
- * @template T A map where keys are artifact names and values are their configurations.
658
- */
659
- type InferRegistry<T extends Record<string, {
660
- factory: (...args: any[]) => any;
661
- [key: string]: any;
662
- }>> = {
663
- [K in keyof T]: ArtifactValue<T[K]>;
664
- };
665
- /**
666
- * State paths grouped by options passed to the store
667
- */
668
- interface StateGroup {
669
- paths: string[];
670
- options?: SubscribeOptions;
671
- }
672
- interface ExportedArtifact {
673
- key: string;
674
- instance: any;
675
- state: {
676
- groups: Array<{
677
- paths: string[];
678
- options?: SubscribeOptions;
679
- }>;
680
- hash: string;
681
- };
682
- dependencies: string[];
683
- }
684
- interface ExportedContainerState {
685
- version: string;
686
- timestamp: number;
687
- artifacts: ExportedArtifact[];
688
- checksum: string;
689
- }
690
-
691
- /**
692
- * A dependency injection container for managing the lifecycle, dependencies,
693
- * and instances of "artifacts" (any JavaScript/TypeScript object or value).
694
- *
695
- * Separated concerns:
696
- * - ArtifactRegistry: Stores artifact templates (factories + options)
697
- * - ArtifactCache: Stores resolved singleton instances
698
- * - ArtifactDependencyGraph: Tracks artifact dependencies using DependencyGraph
699
- * - ArtifactManager: Handles lifecycle (build, invalidate, dispose)
700
- * - ArtifactObserverManager: Manages watchers and subscriptions
701
- *
702
- * @template TRegistry A type that maps artifact keys to their types
703
- * @template TState The type of the global state object
704
- */
705
- declare class ArtifactContainer<TRegistry extends Record<string, any> = Record<string, any>, TState extends object = any> {
706
- private readonly registry;
707
- private readonly cache;
708
- private readonly graph;
709
- private readonly manager;
710
- private readonly observer;
711
- private readonly store;
712
- /**
713
- * Creates a new ArtifactContainer instance.
714
- * @param store An object providing functions to interact with a global data store
715
- */
716
- constructor(store: Pick<DataStore<TState>, "watch" | "get" | "set" | "subset">);
717
- /**
718
- * Provides debug information about all artifacts currently registered in this container.
719
- *
720
- * Status mapping:
721
- * - `"building"` — factory is currently executing (buildOnce.running())
722
- * - `"debouncing"` — invalidation is pending behind a debounce timer
723
- * - `"error"` — last build attempt failed
724
- * - `"active"` — successfully built and instance is available
725
- * - `"idle"` — not yet built (lazy) or has been disposed
726
- *
727
- * @returns An array of ArtifactDebugNode objects
728
- */
729
- debugInfo(): ArtifactDebugNode[];
730
- /**
731
- * Registers a new artifact with the container.
732
- * If an artifact with the same key already exists, it will be overwritten and disposed.
733
- * For Singleton, non-lazy artifacts, the factory will be immediately invoked.
734
- *
735
- * @param params The registration parameters
736
- * @returns A cleanup function that unregisters the artifact
737
- */
738
- register<K extends keyof TRegistry>(params: ArtifactTemplate<TState, TRegistry[K], TRegistry>): () => void;
739
- /**
740
- * Returns a boolean indicating whether a template exists for an artifact.
741
- *
742
- * @param key The unique identifier of the artifact.
743
- * @returns boolean.
744
- */
745
- has<K extends keyof TRegistry>(key: K): boolean;
746
- /**
747
- * Unregisters an artifact from the container, disposing of its current instance
748
- * and removing all associated resources and dependency links.
749
- *
750
- * Also evicts the observer watcher cache entry so singleton watchers do not
751
- * outlive the artifact's registration.
752
- *
753
- * @param key The unique identifier of the artifact
754
- */
755
- unregister<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<void>;
756
- /**
757
- * Resolves an artifact by its key, returning its instance or an error.
758
- * Handles dependency resolution, cycle detection, caching, and retry logic.
759
- *
760
- * The keyed index property (`artifact[key]`) is set inside `cache.package()`
761
- * so it is always consistent with `artifact.instance`. No post-hoc mutation
762
- * is needed here.
763
- *
764
- * @param key The unique identifier for the artifact
765
- * @param params Parameters with which to resolve the artifact
766
- * @returns A Promise that resolves to a ResolvedArtifact
767
- * @throws {ArtifactNotFoundError} if the artifact is not found
768
- */
769
- resolve<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<KeyedResolvedArtifact<TRegistry, K>>;
770
- /**
771
- * Resolves an artifact by its key, returning its instance directly.
772
- * Throws if resolution fails.
773
- *
774
- * @param key The unique identifier for the artifact
775
- * @param params Parameters with which to resolve the artifact
776
- * @returns A Promise that resolves to the artifact instance
777
- * @throws {ArtifactNotFoundError} if the artifact is not found
778
- * @throws the artifact's error if resolution failed
779
- */
780
- require<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<TRegistry[K]>;
781
- /**
782
- * Returns an ArtifactObserver for a given artifact key.
783
- * The observer allows subscribing to changes in the artifact's resolved value.
784
- *
785
- * @param key The unique identifier for the artifact
786
- * @param params Parameters with which to resolve the artifact
787
- * @param ttl Delay before the watcher is cleaned up if we have no subscriber
788
- * @returns An ArtifactObserver instance
789
- */
790
- watch<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>, ttl?: number): ArtifactObserver<TRegistry, K>;
791
- /**
792
- * Peeks at the resolved instance of an artifact without triggering resolution
793
- * or registering a dependency.
794
- *
795
- * @param key The unique identifier for the artifact
796
- * @returns The artifact instance if already built, otherwise undefined
797
- */
798
- peek<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): TRegistry[K] | undefined;
799
- /**
800
- * Invalidates an artifact, triggering rebuild and cascade to dependents.
801
- *
802
- * @param key The artifact key to invalidate
803
- * @param options.replace If true, forces immediate rebuild bypassing debounce
804
- * @param options.params for parametized artifacts
805
- */
806
- invalidate<K extends keyof TRegistry>(key: K, options?: {
807
- replace?: boolean;
808
- params?: Record<string, unknown>;
809
- }): Promise<void>;
810
- /**
811
- * Notifies observers that an artifact has changed.
812
- * Called by ArtifactManager during stream propagation.
813
- *
814
- * @param key The artifact key
815
- */
816
- notifyObservers(key: string): void;
817
- /**
818
- * Checks if an artifact has active watchers.
819
- * Called by ArtifactManager to determine if lazy artifacts should rebuild.
820
- *
821
- * @param key The artifact key
822
- * @returns True if the artifact has active watchers
823
- */
824
- hasWatchers(key: string): boolean;
825
- /**
826
- * Disposes of the entire container and all artifacts registered within it.
827
- * Releases all resources, stops all watchers, and clears all internal state.
828
- *
829
- * Returns a Promise that resolves once all artifact teardowns have settled.
830
- * Callers should await this method to guarantee full resource release.
831
- */
832
- dispose(): Promise<void>;
833
- export(): Promise<ExportedContainerState>;
834
- private restore;
835
- static from<TRegistry extends Record<string, any> = Record<string, any>, TState extends object = any>(options: {
836
- store: Pick<DataStore<TState>, "watch" | "get" | "set" | "subset">;
837
- bundle?: ExportedContainerState;
838
- templates: ArtifactTemplate<TState, any, TRegistry>[];
839
- }): Promise<ArtifactContainer<TRegistry, TState>>;
840
- }
841
-
842
- 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 ExportedArtifact, type ExportedContainerState, type InferRegistry, type KeyedResolvedArtifact, type PendingArtifact, type ReadyArtifact, type ResolvedArtifact, type ResolvedArtifactBase, type StateGroup, type UseDependencyContext };