@asaidimu/utils-artifacts 8.2.11 → 8.2.13

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.ts CHANGED
@@ -1,256 +1,13 @@
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
- */
1
+ import { Issue, Severity, SystemError, SystemError as SystemError$1 } from "@asaidimu/utils-error";
2
+ import { SystemLogger } from "@asaidimu/utils-logger";
3
+ import { DataStore, StateUpdater, SubscribeOptions } from "@asaidimu/utils-store/types";
4
+ import { EventBus } from "@asaidimu/utils-events/types";
249
5
 
6
+ //#region src/artifacts/types.d.ts
250
7
  /**
251
8
  * Defines the lifecycle and sharing strategy for an artifact.
252
9
  */
253
- type ArtifactScope =
10
+ type ArtifactScope =
254
11
  /**
255
12
  * **Singleton:** A single instance of the artifact is created and shared across all resolutions
256
13
  * within the container. It is created once (often lazily) and reused until invalidated.
@@ -260,42 +17,42 @@ type ArtifactScope =
260
17
  * **Transient:** A new instance of the artifact is created every time it is resolved.
261
18
  * Transient artifacts do not participate in caching or shared state management.
262
19
  */
263
- | "transient";
20
+ | "transient";
264
21
  /**
265
22
  * Enumeration of standard artifact scopes for strongly typed configuration.
266
23
  */
267
24
  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"
25
+ /** A single instance is shared globally. */
26
+ Singleton = "singleton",
27
+ /** A new instance is created on every resolution. */
28
+ Transient = "transient"
272
29
  }
273
30
  /**
274
31
  * Represents a snapshot of an artifact's state and dependencies for debugging purposes.
275
32
  * Provides insight into the artifact's current status and its position within the dependency graph.
276
33
  */
277
34
  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;
35
+ /** The unique identifier (key) of the artifact. */
36
+ id: string;
37
+ /** The scope of the artifact (Singleton or Transient). */
38
+ scope: ArtifactScope;
39
+ /**
40
+ * The current status of the artifact, indicating its lifecycle phase.
41
+ * - `'active'`: The artifact is successfully built and its instance is available.
42
+ * - `'error'`: The artifact failed to build due to an external (runtime) error.
43
+ * - `'idle'`: The artifact has not yet been built (for lazy singletons) or has been disposed.
44
+ * - `'building'`: The artifact's factory is currently executing.
45
+ * - `'pending'`: The artifact is waiting to be built, often after an invalidation and before any debounce.
46
+ */
47
+ status: "active" | "error" | "idle" | "building" | "pending" | "debouncing";
48
+ /** A list of artifact keys that this artifact directly depends on. */
49
+ dependencies: string[];
50
+ /** A list of artifact keys that directly depend on this artifact (its consumers). */
51
+ dependents: string[];
52
+ /** A list of state paths (selectors) that this artifact depends on. */
53
+ stateDependencies: string[];
54
+ /** The number of times this artifact's factory has been successfully executed/rebuilt. */
55
+ buildCount: number;
299
56
  }
300
57
  /**
301
58
  * Context provided to the `use` callback within an artifact factory.
@@ -304,37 +61,37 @@ interface ArtifactDebugNode {
304
61
  * @template TState The type of the global state managed by the DataStore.
305
62
  */
306
63
  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;
64
+ /**
65
+ * Resolves another artifact from the container and registers a dependency on it.
66
+ * If the dependency changes, the current artifact will be invalidated and rebuilt.
67
+ * @template K The key of the artifact to resolve.
68
+ * @param key The key of the artifact to resolve.
69
+ * @param params Parameters with which to resolve the artifact
70
+ * @returns A Promise that resolves to a `ResolvedArtifact` containing the instance
71
+ * or an external error.
72
+ * @throws {SystemError} if the key is missing or if resolving creates a circular dependency.
73
+ */
74
+ resolve<K extends keyof TRegistry>(key: K, params?: any): Promise<ResolvedArtifact<TRegistry[K]>>;
75
+ /**
76
+ * Resolves another artifact from the container and registers a dependency on it.
77
+ * If the dependency changes, the current artifact will be invalidated and rebuilt.
78
+ * @template K The key of the artifact to resolve.
79
+ * @param key The key of the artifact to resolve.
80
+ * @param params Parameters with which to resolve the artifact
81
+ * @returns A Promise that resolves to a the resolved instance, unlike
82
+ * resolve, this will throw an error if resolution fails.
83
+ * @throws {SystemError} if any error occurs during resolution.
84
+ */
85
+ require<K extends keyof TRegistry>(key: K, params?: any): Promise<TRegistry[K]>;
86
+ /**
87
+ * Selects a slice of the global state and registers a dependency on it.
88
+ * If the selected state slice changes (based on a deep comparison), the current
89
+ * artifact will be invalidated and rebuilt.
90
+ * @template S The type of the selected state slice.
91
+ * @param selector A function that takes the full state and returns a slice of state.
92
+ * @returns The selected slice of state.
93
+ */
94
+ select<S>(selector: (state: TState) => S, options?: SubscribeOptions): S;
338
95
  }
339
96
  /**
340
97
  * Context object provided to an artifact stream producer function (`ctx.stream` callback).
@@ -345,38 +102,38 @@ interface UseDependencyContext<TRegistry extends Record<string, any>, TState ext
345
102
  * @template TArtifact The type of the artifact being streamed.
346
103
  */
347
104
  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>;
105
+ /**
106
+ * The current value of the artifact. This is `undefined` before the first value is emitted.
107
+ * Useful for diffing or migrating state during an update.
108
+ * @returns The current artifact value or `undefined`.
109
+ */
110
+ value: () => TArtifact | undefined;
111
+ /**
112
+ * An AbortSignal that indicates if the stream has been cancelled or aborted
113
+ * from the consumer side (e.g., due to container disposal or artifact invalidation).
114
+ * Producers should check this signal and stop processing when it is set to prevent leaks.
115
+ */
116
+ signal: AbortSignal;
117
+ /**
118
+ * A function to asynchronously emit a new value of the artifact to the container.
119
+ * Calling this function updates the artifact's resolved value, triggers invalidation
120
+ * for its dependents, and updates the `value()` property for subsequent emissions.
121
+ *
122
+ * @param value The new artifact value to emit.
123
+ * @returns A Promise that resolves when the value has been sent and dependents have been notified.
124
+ */
125
+ emit: (value: TArtifact) => Promise<void>;
126
+ /**
127
+ * Dispatches a state update to the global store, analogous to a standard `setState`.
128
+ * **Note:** This does not automatically register a dependency for the current artifact.
129
+ * @param update A `StateUpdater` function or a partial state object.
130
+ * @param options Optional settings for the update, including `force` and `actionId`.
131
+ * @returns A Promise that resolves when the state update is complete.
132
+ */
133
+ set(update: StateUpdater<TState>, options?: {
134
+ force?: boolean;
135
+ actionId?: string;
136
+ }): Promise<any>;
380
137
  };
381
138
  /**
382
139
  * The full context provided to an artifact's factory function.
@@ -387,85 +144,115 @@ type ArtifactStreamContext<TState, TArtifact> = {
387
144
  * @template TArtifact The type of the artifact being created by the factory.
388
145
  */
389
146
  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;
147
+ /**
148
+ * Returns the current global state object. This is a non-reactive read;
149
+ * changes to the state will not automatically invalidate the artifact
150
+ * unless explicitly selected via `ctx.use` and `ctx.select`.
151
+ * @returns The current global state.
152
+ */
153
+ state(): TState;
154
+ /**
155
+ * The previous instance of the artifact if it's a Singleton and is being rebuilt
156
+ * after an invalidation. This is `undefined` on the initial build.
157
+ * Useful for diffing, migrating state, or reusing resources during an update.
158
+ */
159
+ previous?: TArtifact;
160
+ /**
161
+ * Executes a callback within a dependency tracking context.
162
+ * Any `resolve` or `select` calls made inside this callback will register
163
+ * dependencies for the current artifact.
164
+ * @template R The return type of the callback.
165
+ * @param callback The function to execute to resolve dependencies.
166
+ * @returns A Promise resolving to the result of the callback.
167
+ */
168
+ use<R>(callback: (ctx: UseDependencyContext<TRegistry, TState>) => R | Promise<R>): Promise<R>;
169
+ /**
170
+ * Registers a cleanup function to be executed when the **current instance** of the
171
+ * artifact is invalidated and before its new instance is built. This is useful
172
+ * for releasing resources (e.g., event listeners) specific to the *previous* instance.
173
+ * @param cleanup The cleanup function.
174
+ */
175
+ onCleanup(cleanup: ArtifactCleanup): void;
176
+ /**
177
+ * Registers a dispose function to be executed when the artifact is
178
+ * permanently removed from the container or the container itself is disposed.
179
+ * This is for final, permanent resource release.
180
+ * @param callback The dispose function.
181
+ */
182
+ onDispose(callback: ArtifactCleanup): void;
183
+ /**
184
+ * Starts a streaming process for a Singleton artifact.
185
+ * The callback receives an `ArtifactStreamContext` to emit values and manage the
186
+ * stream's lifecycle. It can return a cleanup function (or a Promise resolving
187
+ * to one) to handle resource disposal.
188
+ * * @param callback - The streaming logic implementation. Can be synchronous or
189
+ * asynchronous, optionally returning a cleanup function.
190
+ * @throws {SystemError} If called on a Transient artifact, as they do not
191
+ * support persistent streaming states.
192
+ */
193
+ stream(callback: (ctx: ArtifactStreamContext<TState, TArtifact>) => (void | (() => void | Promise<void>)) | Promise<void | (() => void | Promise<void>)>): void;
194
+ stream(callback: (ctx: ArtifactStreamContext<TState, TArtifact>) => (void | (() => void | Promise<void>)) | Promise<void | (() => void | Promise<void>)>): void;
195
+ /**
196
+ * An AbortSignal that indicates if the artifacts has been unregistered
197
+ */
198
+ signal: AbortSignal; /** For parameterized artifacts: the parameters that were passed during resolve/watch. */
199
+ params?: any;
444
200
  };
445
201
  /**
446
202
  * A function that performs cleanup or disposal logic for an artifact, potentially asynchronously.
447
203
  * Used for `onCleanup` and `onDispose` callbacks.
448
204
  */
449
205
  type ArtifactCleanup = () => void | Promise<void>;
206
+ interface ArtifactLifecycleEventMap {
207
+ "build:start": {
208
+ key: string;
209
+ templateKey?: string;
210
+ };
211
+ "build:complete": {
212
+ key: string;
213
+ instance: unknown;
214
+ };
215
+ "build:error": {
216
+ key: string;
217
+ error: unknown;
218
+ };
219
+ "artifact:invalidated": {
220
+ key: string;
221
+ cascade: boolean;
222
+ replace: boolean;
223
+ };
224
+ "artifact:disposed": {
225
+ key: string;
226
+ };
227
+ "artifact:registered": {
228
+ key: string;
229
+ scope: ArtifactScope;
230
+ };
231
+ "stream:emit": {
232
+ key: string;
233
+ value: unknown;
234
+ };
235
+ "container:dispose": {};
236
+ }
450
237
  /**
451
238
  * Common properties shared across all possible states of a resolved artifact.
452
239
  * @template TArtifact The type of the resolved artifact instance.
453
240
  */
454
241
  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>;
242
+ /**
243
+ * A function to manually trigger cleanup associated with this specific
244
+ * resolved instance. This is typically only relevant for Transient artifacts
245
+ * where the consumer is responsible for cleanup.
246
+ */
247
+ cleanup?: ArtifactCleanup;
248
+ /**
249
+ * Manually invalidates this artifact, triggering its rebuild and
250
+ * cascading invalidations to its dependents.
251
+ * @param replace If `true`, forces immediate rebuild without debounce delay.
252
+ * @param fatal If `true`, the artifact will not be rebuilt until next resolve
253
+ * regardless of the lazy option during registration.
254
+ */
255
+ invalidate(replace?: boolean, fatal?: boolean): Promise<void>;
469
256
  }
470
257
  /**
471
258
  * State of an artifact that is successfully built and ready for use.
@@ -473,34 +260,34 @@ interface ResolvedArtifactBase {
473
260
  * @template TArtifact The type of the resolved artifact instance.
474
261
  */
475
262
  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;
263
+ /** The successfully resolved instance of the artifact. */
264
+ instance: TArtifact;
265
+ /** Indicates whether the artifact is ready and has an instance. */
266
+ ready: true;
267
+ error?: undefined;
481
268
  }
482
269
  /**
483
270
  * State of an artifact that failed to build due to an external error.
484
271
  * The instance is guaranteed to be absent.
485
272
  */
486
273
  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;
274
+ instance?: undefined;
275
+ ready: false;
276
+ /**
277
+ * Any runtime or external error that occurred during the artifact's factory
278
+ * execution (e.g., network fetch failed).
279
+ */
280
+ error: any;
494
281
  }
495
282
  /**
496
283
  * State of an artifact that is pending, idle, or currently building.
497
284
  * Both instance and error are absent.
498
285
  */
499
286
  interface PendingArtifact extends ResolvedArtifactBase {
500
- /** The instance is absent while pending or idle. Always undefined. */
501
- instance?: undefined;
502
- ready: false;
503
- error?: undefined;
287
+ /** The instance is absent while pending or idle. Always undefined. */
288
+ instance?: undefined;
289
+ ready: false;
290
+ error?: undefined;
504
291
  }
505
292
  /**
506
293
  * The result of an artifact resolution. This is a union type representing
@@ -512,9 +299,7 @@ interface PendingArtifact extends ResolvedArtifactBase {
512
299
  * @template TArtifact The type of the resolved artifact instance.
513
300
  */
514
301
  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
- };
302
+ type KeyedResolvedArtifact<TRegistry, K extends keyof TRegistry> = ResolvedArtifact<TRegistry[K]> & { [P in K]?: TRegistry[K] };
518
303
  /**
519
304
  * The factory function responsible for creating an artifact's instance.
520
305
  * It receives an `ArtifactFactoryContext` to interact with the container
@@ -534,37 +319,37 @@ type ArtifactInstance<R> = R extends PromiseLike<infer T> ? T : R;
534
319
  * @template TArtifact The type of the artifact being watched.
535
320
  */
536
321
  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>>;
322
+ /** The unique identifier (key) of the artifact being watched. */
323
+ id: string;
324
+ /**
325
+ * Number of active references (watchers) to this observer instance.
326
+ * Incremented on each `watch()` call, decremented on each `dispose()` call.
327
+ */
328
+ count: number;
329
+ /**
330
+ * Retrieves the current `ResolvedArtifact` for the watched key.
331
+ * @param resolve Flag indicating whether we should resolve the artifact
332
+ * immediately. Defaults to `false`
333
+ * @returns The resolved artifact, including its instance and status.
334
+ */
335
+ get(resolve?: boolean): KeyedResolvedArtifact<TRegistry, K>;
336
+ /**
337
+ * Subscribes a callback function to be invoked whenever the artifact's
338
+ * state (instance, error, or readiness) changes.
339
+ * @param callback The function to call on updates. It receives the new `ResolvedArtifact`.
340
+ * @param eager a boolean indicating whether we should immediately call the
341
+ * callback after subscription. Defaults to `true`
342
+ * @returns A function to unsubscribe the callback and stop receiving updates.
343
+ */
344
+ subscribe(callback: (artifact: KeyedResolvedArtifact<TRegistry, K>) => void, eager?: boolean): () => void;
345
+ /**
346
+ * Resolves another artifact from the container and registers a dependency on it.
347
+ * If the dependency changes, the current artifact will be invalidated and rebuilt.
348
+ * @returns A Promise that resolves to a `ResolvedArtifact` containing the instance
349
+ * or an external error.
350
+ * @throws {SystemError} if resolution fails.
351
+ */
352
+ resolve(): Promise<KeyedResolvedArtifact<TRegistry, K>>;
568
353
  }
569
354
  /**
570
355
  * Configuration options for defining an artifact. These options control
@@ -574,41 +359,41 @@ interface ArtifactObserver<TRegistry, K extends keyof TRegistry> {
574
359
  * @template TRegistry The type mapping of all artifacts in the container.
575
360
  */
576
361
  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;
362
+ /** The unique key identifying this artifact within the registry. */
363
+ key: keyof TRegistry;
364
+ /** The factory function responsible for creating the artifact's instance. */
365
+ factory: ArtifactFactory<TRegistry, TState, TArtifact, TExtra>;
366
+ /**
367
+ * The scope of the artifact, determining its lifecycle and sharing strategy.
368
+ * Defaults to `ArtifactScopes.Singleton`.
369
+ */
370
+ scope?: ArtifactScope;
371
+ /**
372
+ * If `true` (default), the artifact's factory is executed only when the artifact
373
+ * is first requested (lazy instantiation). If `false`, the artifact is built
374
+ * immediately upon registration (only applies to Singleton scopes).
375
+ */
376
+ lazy?: boolean;
377
+ /**
378
+ * Maximum time in milliseconds allowed for the artifact's factory function
379
+ * to complete execution. If exceeded, the factory will time out.
380
+ */
381
+ timeout?: number;
382
+ /**
383
+ * Number of times to retry the artifact's factory on failure due to an
384
+ * external (runtime) error (e.g., an exception in an async dependency).
385
+ * SystemErrors (e.g., key not found) are not retried. Defaults to `0`.
386
+ */
387
+ retries?: number;
388
+ /**
389
+ * Base debounce time in milliseconds for invalidation events originating
390
+ * from this artifact's dependencies. This delays the rebuild process to
391
+ * aggregate multiple rapid changes.
392
+ */
393
+ debounce?: number;
394
+ /** If defined, the artifact is parameterized. Receives the user‑supplied params and returns a unique string key. */
395
+ paramKey?: (params: Record<string, unknown>) => string;
396
+ virtual?: true;
612
397
  }
613
398
  /**
614
399
  * Extracts the global state type (`TState`) from an `ArtifactTemplate`.
@@ -622,13 +407,13 @@ type ArtifactRegistryType<T> = T extends ArtifactTemplate<any, any, infer TRegis
622
407
  * Extracts the key type (`K`) from an `ArtifactTemplate` (as a string literal if possible).
623
408
  */
624
409
  type ArtifactKey<T> = T extends {
625
- key: infer K;
410
+ key: infer K;
626
411
  } ? K : never;
627
412
  /**
628
413
  * Extracts the scope type (`S`) from an `ArtifactTemplate`, defaulting to `ArtifactScope` if undefined.
629
414
  */
630
415
  type ArtifactScopeType<T> = T extends {
631
- scope: infer S;
416
+ scope: infer S;
632
417
  } ? S extends ArtifactScope ? S : ArtifactScope : ArtifactScope;
633
418
  /**
634
419
  * Helper type that creates a properly typed template map where keys correspond to artifact names
@@ -636,9 +421,7 @@ type ArtifactScopeType<T> = T extends {
636
421
  * @template TState The type of the global state.
637
422
  * @template TRegistry The map of all artifact keys to their resolved types.
638
423
  */
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
- };
424
+ type ArtifactTemplateMap<TState extends object, TRegistry extends Record<string, any> = Record<string, any>> = { [K in keyof TRegistry]: ArtifactTemplate<TState, TRegistry[K], TRegistry> };
642
425
  /**
643
426
  * Extracts the artifact's resolved value type (`TArtifact`) from an object that structurally
644
427
  * resembles an `ArtifactTemplate` (by inspecting the `factory` function's generic arguments).
@@ -646,7 +429,7 @@ type ArtifactTemplateMap<TState extends object, TRegistry extends Record<string,
646
429
  * @template T The type that contains a factory property.
647
430
  */
648
431
  type ArtifactValue<T> = T extends {
649
- factory: ArtifactFactory<any, any, infer TArtifact, any>;
432
+ factory: ArtifactFactory<any, any, infer TArtifact, any>;
650
433
  } ? TArtifact : never;
651
434
  /**
652
435
  * Infers the complete Artifact Registry type from a map of artifact configuration objects.
@@ -657,186 +440,99 @@ type ArtifactValue<T> = T extends {
657
440
  * @template T A map where keys are artifact names and values are their configurations.
658
441
  */
659
442
  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
- };
443
+ factory: (...args: any[]) => any;
444
+ [key: string]: any;
445
+ }>> = { [K in keyof T]: ArtifactValue<T[K]> };
665
446
  /**
666
447
  * State paths grouped by options passed to the store
667
448
  */
668
449
  interface StateGroup {
669
- paths: string[];
670
- options?: SubscribeOptions;
450
+ paths: string[];
451
+ options?: SubscribeOptions;
671
452
  }
672
453
  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[];
454
+ key: string;
455
+ instance: any;
456
+ state: {
457
+ groups: Array<{
458
+ paths: string[];
459
+ options?: SubscribeOptions;
460
+ }>;
461
+ hash: string;
462
+ };
463
+ dependencies: string[];
683
464
  }
684
465
  interface ExportedContainerState {
685
- version: string;
686
- timestamp: number;
687
- artifacts: ExportedArtifact[];
688
- checksum: string;
466
+ version: string;
467
+ timestamp: number;
468
+ artifacts: ExportedArtifact[];
469
+ checksum: string;
689
470
  }
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
- */
471
+ //#endregion
472
+ //#region src/artifacts/container.d.ts
705
473
  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>>;
474
+ private readonly registry;
475
+ private readonly cache;
476
+ private readonly graph;
477
+ private readonly manager;
478
+ private readonly observer;
479
+ private readonly logger;
480
+ private readonly store;
481
+ readonly events: EventBus<ArtifactLifecycleEventMap>;
482
+ constructor(store: Pick<DataStore<TState>, "watch" | "get" | "set" | "subset">, options?: {
483
+ logger?: SystemLogger;
484
+ });
485
+ debugInfo(): ArtifactDebugNode[];
486
+ register<K extends keyof TRegistry>(params: ArtifactTemplate<TState, TRegistry[K], TRegistry>): () => void;
487
+ has<K extends keyof TRegistry>(key: K): boolean;
488
+ unregister<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<void>;
489
+ resolve<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<KeyedResolvedArtifact<TRegistry, K>>;
490
+ require<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<TRegistry[K]>;
491
+ watch<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>, ttl?: number): ArtifactObserver<TRegistry, K>;
492
+ peek<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): TRegistry[K] | undefined;
493
+ invalidate<K extends keyof TRegistry>(key: K, options?: {
494
+ replace?: boolean;
495
+ params?: Record<string, unknown>;
496
+ }): Promise<void>;
497
+ on<TEventName extends keyof ArtifactLifecycleEventMap>(eventName: TEventName, callback: (payload: ArtifactLifecycleEventMap[TEventName]) => void): () => void;
498
+ on(eventName: "*", callback: (payload: ArtifactLifecycleEventMap[keyof ArtifactLifecycleEventMap], event: keyof ArtifactLifecycleEventMap) => void): () => void;
499
+ once<TEventName extends keyof ArtifactLifecycleEventMap>(eventName: TEventName, callback: (payload: ArtifactLifecycleEventMap[TEventName]) => void): () => void;
500
+ once(eventName: "*", callback: (payload: ArtifactLifecycleEventMap[keyof ArtifactLifecycleEventMap], event: keyof ArtifactLifecycleEventMap) => void): () => void;
501
+ notifyObservers(key: string): void;
502
+ hasWatchers(key: string): boolean;
503
+ dispose(): Promise<void>;
504
+ export(): Promise<ExportedContainerState>;
505
+ private restore;
506
+ static from<TRegistry extends Record<string, any> = Record<string, any>, TState extends object = any>(options: {
507
+ store: Pick<DataStore<TState>, "watch" | "get" | "set" | "subset">;
508
+ bundle?: ExportedContainerState;
509
+ templates: ArtifactTemplate<TState, any, TRegistry>[];
510
+ logger?: SystemLogger;
511
+ }): Promise<ArtifactContainer<TRegistry, TState>>;
840
512
  }
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 };
513
+ //#endregion
514
+ //#region src/artifacts/errors.d.ts
515
+ declare const ErrorCodes: {
516
+ readonly NOT_FOUND: "DB-001-NF";
517
+ readonly DUPLICATE_KEY: "DB-002-DUP";
518
+ readonly INVALID_COMMAND: "BUS-001";
519
+ readonly INTERNAL_ERROR: "SYS-001";
520
+ readonly CONCURRENCY_ERROR: "CON-001";
521
+ };
522
+ declare function artifactNotFound(key: string): SystemError$1;
523
+ declare function cycleDetected(path: string[]): SystemError$1;
524
+ declare function illegalScope(message: string): SystemError$1;
525
+ declare function watcherDisposed(key: string): SystemError$1;
526
+ declare function timeoutError(message?: string): SystemError$1;
527
+ declare function keyConflict(key?: string): SystemError$1;
528
+ declare function notParameterized(key: string): SystemError$1;
529
+ declare function paramKeyCollision(key: string, computedKey: string): SystemError$1;
530
+ declare function selfDependency(key: string): SystemError$1;
531
+ declare function buildStaleAfterRetries(depKey: string): SystemError$1;
532
+ declare function invalidImport(message: string): SystemError$1;
533
+ declare function invalidExport(key: string): SystemError$1;
534
+ declare class SupersededBuildError extends Error {
535
+ constructor();
536
+ }
537
+ //#endregion
538
+ export { ArtifactCleanup, ArtifactContainer, ArtifactDebugNode, ArtifactFactory, ArtifactFactoryContext, ArtifactInstance, ArtifactKey, ArtifactLifecycleEventMap, ArtifactObserver, ArtifactRegistryType, ArtifactScope, ArtifactScopeType, ArtifactScopes, ArtifactStateType, ArtifactStreamContext, ArtifactTemplate, ArtifactTemplateMap, ArtifactValue, ErrorArtifact, ErrorCodes, ExportedArtifact, ExportedContainerState, InferRegistry, type Issue, KeyedResolvedArtifact, PendingArtifact, ReadyArtifact, ResolvedArtifact, ResolvedArtifactBase, type Severity, StateGroup, SupersededBuildError, SystemError, UseDependencyContext, artifactNotFound, buildStaleAfterRetries, cycleDetected, illegalScope, invalidExport, invalidImport, keyConflict, notParameterized, paramKeyCollision, selfDependency, timeoutError, watcherDisposed };