@asaidimu/utils-store 4.0.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.mts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { EventBus } from '@asaidimu/events';
2
- import { SimplePersistence as SimplePersistence$1 } from '@asaidimu/utils-persistence';
3
2
 
4
3
  interface SimplePersistence<T> {
5
4
  /**
@@ -384,116 +383,487 @@ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
384
383
  }
385
384
 
386
385
  /**
387
- * Defines the lifecycle scope of an artifact.
386
+ * Base class for structural/configuration errors within the ArtifactContainer.
387
+ * These errors indicate fundamental issues (e.g., circular dependencies, missing artifacts)
388
+ * that prevent successful resolution and should bypass any retry mechanisms,
389
+ * causing an immediate strict failure.
390
+ */
391
+ declare class SystemError extends Error {
392
+ constructor(message: string);
393
+ }
394
+ /**
395
+ * Error thrown when a circular dependency is detected during artifact resolution.
396
+ * This indicates a structural problem in the artifact graph.
397
+ */
398
+ declare class CircularDependencyError extends SystemError {
399
+ /**
400
+ * Creates an instance of CircularDependencyError.
401
+ * @param path The dependency path that caused the cycle.
402
+ */
403
+ constructor(path: string[]);
404
+ }
405
+ /**
406
+ * Error thrown when an artifact requested for resolution is not found
407
+ * within the current container or its parent hierarchy.
408
+ */
409
+ declare class ArtifactNotFoundError extends SystemError {
410
+ /**
411
+ * Creates an instance of ArtifactNotFoundError.
412
+ * @param key The key of the artifact that was not found.
413
+ */
414
+ constructor(key: string);
415
+ }
416
+ /**
417
+ * Error thrown when an operation is attempted that is not permitted
418
+ * due to the artifact's scope or current state (e.g., calling `yield` on a Transient artifact).
419
+ */
420
+ declare class IllegalScopeError extends SystemError {
421
+ /**
422
+ * Creates an instance of IllegalScopeError.
423
+ * @param message A descriptive message about the illegal operation.
424
+ */
425
+ constructor(message: string);
426
+ }
427
+ /**
428
+ * Defines the lifecycle and sharing strategy for an artifact.
388
429
  */
389
430
  declare enum ArtifactScope {
390
- Singleton = "singleton",// Created once, cached, tracks dependencies
431
+ /**
432
+ * A single instance of the artifact is created and shared across all resolutions
433
+ * within the container. It is created once and reused.
434
+ */
435
+ Singleton = "singleton",
436
+ /**
437
+ * A new instance of the artifact is created every time it is resolved.
438
+ * Transient artifacts do not participate in caching or shared state.
439
+ */
391
440
  Transient = "transient"
392
441
  }
393
442
  /**
394
- * Dependency resolution context provided to the use() callback.
443
+ * Configuration options for defining an artifact. These options control
444
+ * its lifecycle, instantiation, and error handling behavior.
395
445
  */
396
- interface UseDependencyContext<TState extends object> {
446
+ interface ArtifactOptions {
447
+ /**
448
+ * The scope of the artifact, determining its lifecycle and sharing strategy.
449
+ * Defaults to `ArtifactScope.Singleton`.
450
+ */
451
+ scope?: ArtifactScope;
452
+ /**
453
+ * If `true` (default), the artifact's factory is executed only when the artifact
454
+ * is first requested. If `false`, the artifact is built immediately upon registration
455
+ * (only applies to Singleton scopes).
456
+ */
457
+ lazy?: boolean;
458
+ /**
459
+ * Maximum time in milliseconds allowed for the artifact's factory function
460
+ * to complete execution. If exceeded, the factory will time out.
461
+ */
462
+ timeoutMs?: number;
397
463
  /**
398
- * Resolve another artifact.
399
- * This records a dependency between the caller and the requested artifact.
464
+ * Number of times to retry the artifact's factory on failure due to an
465
+ * external (runtime) error. SystemErrors are not retried. Defaults to `0`.
400
466
  */
401
- resolve<TArtifact>(key: string): Promise<TArtifact>;
467
+ retries?: number;
402
468
  /**
403
- * Select a slice of state.
404
- * This records a dependency between the artifact and the specific state paths.
469
+ * Base debounce time in milliseconds for invalidation events originating
470
+ * from this artifact. This can be overridden by `UseOptions.debounce`.
471
+ */
472
+ debounce?: number;
473
+ }
474
+ /**
475
+ * Options that can be applied to dependency resolutions within an artifact's factory,
476
+ * allowing for fine-grained control over how dependencies affect the current artifact.
477
+ */
478
+ interface UseOptions {
479
+ /**
480
+ * Applies a specific debounce time in milliseconds to dependencies resolved
481
+ * within the `use` block. If this value is higher than the artifact's
482
+ * `baseDebounceMs` (or `activeDebounceMs`), it will be used for subsequent invalidations.
483
+ */
484
+ debounce?: number;
485
+ }
486
+ /**
487
+ * Represents a snapshot of an artifact's state and dependencies for debugging purposes.
488
+ * Provides insight into the artifact's current status and its position within the dependency graph.
489
+ */
490
+ interface ArtifactDebugNode {
491
+ /** The unique identifier (key) of the artifact. */
492
+ id: string;
493
+ /** The scope of the artifact (Singleton or Transient). */
494
+ scope: ArtifactScope;
495
+ /**
496
+ * The current status of the artifact, indicating its lifecycle phase.
497
+ * - 'active': The artifact is built and available.
498
+ * - 'error': The artifact failed to build due to an external error.
499
+ * - 'idle': The artifact has not yet been built (lazy singleton) or has been disposed.
500
+ * - 'building': The artifact's factory is currently executing.
501
+ * - 'debouncing': The artifact is currently in a debounced invalidation state.
502
+ */
503
+ status: "active" | "error" | "idle" | "building" | "debouncing";
504
+ /** A list of artifact keys that this artifact directly depends on. */
505
+ dependencies: string[];
506
+ /** A list of artifact keys that directly depend on this artifact. */
507
+ dependents: string[];
508
+ /** A list of state paths (selectors) that this artifact depends on. */
509
+ stateDependencies: string[];
510
+ /** The number of times this artifact's factory has been successfully executed. */
511
+ renderCount: number;
512
+ }
513
+ /**
514
+ * Context provided to the `use` callback within an artifact factory.
515
+ * It allows an artifact to declare dependencies on other artifacts and state slices.
516
+ * @template TRegistry The type mapping artifact keys to their artifact types.
517
+ * @template TState The type of the global state managed by the DataStore.
518
+ */
519
+ interface UseDependencyContext<TRegistry extends Record<string, any>, TState extends object> {
520
+ /**
521
+ * Resolves another artifact from the container.
522
+ * Declares a dependency on the resolved artifact, meaning that if the dependency
523
+ * changes, this artifact will be invalidated and rebuilt.
524
+ * @template K The key of the artifact to resolve.
525
+ * @param key The key of the artifact to resolve.
526
+ * @returns A Promise that resolves to a `ResolvedArtifact` containing the instance
527
+ * or an external error.
528
+ * @throws {SystemError} if the key is missing or if resolving creates a circular dependency.
529
+ */
530
+ resolve<K extends keyof TRegistry>(key: K): Promise<ResolvedArtifact<TRegistry[K]>>;
531
+ /**
532
+ * Selects a slice of the global state.
533
+ * Declares a dependency on the selected state paths, meaning that if the selected
534
+ * state changes, this artifact will be invalidated and rebuilt.
535
+ * @template S The type of the selected state slice.
536
+ * @param selector A function that takes the full state and returns a slice.
537
+ * @returns The selected slice of state.
405
538
  */
406
539
  select<S>(selector: (state: TState) => S): S;
407
540
  }
408
541
  /**
409
- * The context object provided to an artifact's factory function.
542
+ * The full context provided to an artifact's factory function.
543
+ * This context allows the artifact to interact with the container,
544
+ * declare dependencies, manage its lifecycle, and update its value.
545
+ * @template TRegistry The type mapping artifact keys to their artifact types.
546
+ * @template TState The type of the global state managed by the DataStore.
547
+ * @template TArtifact The type of the artifact being created by the factory.
410
548
  */
411
- interface ArtifactFactoryContext<TState extends object> {
549
+ interface ArtifactFactoryContext<TRegistry extends Record<string, any>, TState extends object, TArtifact> {
412
550
  /**
413
- * Get the current state snapshot immediately.
414
- * WARNING: Calling this does NOT create a subscription.
415
- * Use ctx.use(c => c.select(...)) for reactive behavior.
551
+ * Returns the current global state object. This is a non-reactive read;
552
+ * changes to the state will not automatically invalidate the artifact
553
+ * unless explicitly selected via `ctx.select in use()`.
554
+ * @returns The current global state.
416
555
  */
417
556
  state(): TState;
418
557
  /**
419
- * The existing instance if being re-evaluated.
420
- * Useful for preserving internal state (like connections) during hot-swaps.
558
+ * The previous instance of the artifact if it's a Singleton and is being rebuilt.
559
+ * Useful for diffing or migrating state during an update.
560
+ */
561
+ current?: TArtifact;
562
+ /**
563
+ * Executes a callback within a dependency tracking context.
564
+ * Any `resolve` or `select` calls made inside this callback will register
565
+ * dependencies for the current artifact.
566
+ * @template R The return type of the callback.
567
+ * @param callback The function to execute to resolve dependencies.
568
+ * @param options Optional settings for this dependency block, like debounce.
569
+ * @returns A Promise resolving to the result of the callback.
570
+ */
571
+ use<R>(callback: (ctx: UseDependencyContext<TRegistry, TState>) => R | Promise<R>, options?: UseOptions): Promise<R>;
572
+ /**
573
+ * Registers a cleanup function to be executed when the artifact is
574
+ * invalidated and before its new instance is built. This is useful
575
+ * for releasing resources specific to the *previous* instance.
576
+ * @param cleanup The cleanup function.
421
577
  */
422
- current?: unknown;
578
+ onCleanup(cleanup: ArtifactCleanup): void;
423
579
  /**
424
- * Execute a callback to capture dependencies.
425
- * All resolve() and select() calls inside this callback are recorded
426
- * to build the dependency graph for this artifact.
580
+ * Registers a dispose function to be executed when the artifact is
581
+ * permanently removed from the container or the container itself is disposed.
582
+ * This is for final resource release.
583
+ * @param callback The dispose function.
427
584
  */
428
- use<K>(callback: (ctx: UseDependencyContext<TState>) => K | Promise<K>): Promise<K>;
585
+ onDispose(callback: ArtifactCleanup): void;
586
+ /**
587
+ * Updates the value of a Singleton artifact from within its own factory.
588
+ * This immediately makes the new value available and triggers invalidation
589
+ * for all dependents. Can be used for long-running processes that produce
590
+ * intermediate results.
591
+ * @param value The new value for the artifact.
592
+ * @throws {SystemError} if called on a Transient artifact, as Transient artifacts
593
+ * do not maintain a persistent value.
594
+ */
595
+ yield(value: TArtifact): void;
429
596
  }
430
597
  /**
431
- * Cleanup function type.
598
+ * A function that performs cleanup logic for an artifact, potentially asynchronously.
599
+ * Used for `onCleanup` and `onDispose` callbacks.
432
600
  */
433
601
  type ArtifactCleanup = () => void | Promise<void>;
434
602
  /**
435
- * Represents the output of an artifact factory:
436
- * either the artifact instance itself, or a tuple [instance, cleanup].
603
+ * The result of an artifact resolution, providing the instance,
604
+ * cleanup functionality, and details about any external errors.
605
+ * @template TArtifact The type of the resolved artifact instance.
437
606
  */
438
- type ArtifactResult<T> = T | [T, ArtifactCleanup];
607
+ interface ResolvedArtifact<TArtifact> {
608
+ /** The successfully resolved instance of the artifact, if no error occurred. */
609
+ instance?: TArtifact;
610
+ /**
611
+ * A function to manually trigger cleanup associated with this specific
612
+ * resolved instance. This is typically only relevant for Transient artifacts.
613
+ */
614
+ cleanup?: ArtifactCleanup;
615
+ /**
616
+ * Any runtime or external error that occurred during the artifact's factory
617
+ * execution (e.g., fetch failed, timeout). SystemErrors are explicitly
618
+ * thrown and will not appear here.
619
+ */
620
+ error?: any;
621
+ /**
622
+ * Manually invalidates this artifact, triggering its rebuild and
623
+ * cascading invalidations to its dependents.
624
+ * @param replace If `true`, forces immediate rebuild without debounce.
625
+ */
626
+ invalidate(replace?: boolean): Promise<void>;
627
+ }
628
+ /**
629
+ * The factory function responsible for creating an artifact's instance.
630
+ * It receives an `ArtifactFactoryContext` to interact with the container
631
+ * and declare dependencies.
632
+ * @template TRegistry The type mapping artifact keys to their artifact types.
633
+ * @template TState The type of the global state managed by the DataStore.
634
+ * @template K The key of the artifact this factory produces.
635
+ * @param context The context for creating the artifact.
636
+ * @returns The artifact instance or a Promise resolving to it.
637
+ */
638
+ type ArtifactFactory<TRegistry extends Record<string, any>, TState extends object, K extends keyof TRegistry> = (context: ArtifactFactoryContext<TRegistry, TState, TRegistry[K]>) => TRegistry[K] | Promise<TRegistry[K]>;
439
639
  /**
440
- * A factory function that creates an instance of an artifact.
640
+ * An interface for observing changes to an artifact without direct resolution.
641
+ * Provides a way to get the current resolved artifact and subscribe to updates.
642
+ * @template TArtifact The type of the artifact being watched.
441
643
  */
442
- type ArtifactFactory<TState extends object, TArtifact> = (context: ArtifactFactoryContext<TState>) => ArtifactResult<TArtifact> | Promise<ArtifactResult<TArtifact>>;
443
- declare class ArtifactContainer<TState extends object> {
644
+ interface ArtifactWatcher<TArtifact> {
645
+ /** The unique identifier (key) of the artifact being watched. */
646
+ id: string;
647
+ /**
648
+ * Retrieves the current `ResolvedArtifact` for the watched key.
649
+ * Returns `null` if the artifact has not yet been built or has no instance/error.
650
+ * @returns The resolved artifact or `null`.
651
+ */
652
+ get(): ResolvedArtifact<TArtifact> | null;
653
+ /**
654
+ * Subscribes a callback function to be invoked whenever the artifact's
655
+ * state (instance or error) changes.
656
+ * @param callback The function to call on updates.
657
+ * @returns A function to unsubscribe the callback.
658
+ */
659
+ subscribe(callback: () => void): () => void;
660
+ }
661
+ /**
662
+ * A dependency injection container for managing the lifecycle, dependencies,
663
+ * and instances of "artifacts" (any JavaScript/TypeScript object or value).
664
+ * It supports hierarchical containers, different scopes (singleton, transient),
665
+ * dependency resolution, state-based invalidation, and debounced rebuilding.
666
+ *
667
+ * @template TRegistry A type that maps artifact keys (strings) to their
668
+ * corresponding artifact types. This provides strong
669
+ * typing for `resolve`, `register`, and other operations.
670
+ * @template TState The type of the global state object that artifacts can depend on.
671
+ */
672
+ declare class ArtifactContainer<TRegistry extends Record<string, any> = Record<string, any>, TState extends object = any> {
444
673
  private readonly artifacts;
445
674
  private readonly resolvingStack;
446
675
  private readonly listeners;
447
- private readonly getState;
448
- private readonly subscribe;
676
+ private readonly watcherCache;
677
+ private readonly props;
678
+ private readonly parent?;
679
+ private isDisposed;
449
680
  /**
450
- * @param getState Function to retrieve current state snapshot
451
- * @param subscribe Function to subscribe to path changes. Must return an unsubscribe function.
681
+ * Creates a new ArtifactContainer instance.
682
+ * @param props An object providing functions to interact with a global data store,
683
+ * specifically `watch` for state changes and `get` for current state.
684
+ * @param parent An optional parent `ArtifactContainer`. If provided, this container
685
+ * can resolve artifacts registered in its parent.
452
686
  */
453
- constructor(props: Pick<DataStore<TState>, "watch" | "get">);
454
- subscribeToArtifact(key: string, callback: () => void): () => void;
455
- get(key: string): any | undefined;
456
- private notifyListeners;
687
+ constructor({ watch, get }: Pick<DataStore<TState>, "watch" | "get">, parent?: ArtifactContainer<TRegistry, TState>);
457
688
  /**
458
- * Registers an artifact.
459
- * @returns A function to unregister the artifact.
689
+ * Creates a new child `ArtifactContainer` that inherits from the current container.
690
+ * Child containers can resolve artifacts registered in their parent, but
691
+ * artifacts registered in the child are local to that child.
692
+ * @returns A new `ArtifactContainer` instance.
460
693
  */
461
- register<TArtifact>(options: {
462
- key: string;
463
- factory: ArtifactFactory<TState, TArtifact>;
464
- scope?: ArtifactScope;
465
- lazy?: boolean;
466
- }): () => void;
467
- unregister(key: string): Promise<void>;
694
+ createChild(): ArtifactContainer<TRegistry, TState>;
468
695
  /**
469
- * Resolves an artifact instance.
696
+ * Provides debug information about all artifacts currently registered in this container.
697
+ * This is useful for inspecting the state, scope, dependencies, and activity of artifacts.
698
+ * @returns An array of `ArtifactDebugNode` objects, each representing a registered artifact.
470
699
  */
471
- resolve<TArtifact>(key: string): Promise<TArtifact>;
700
+ getDebugInfo(): ArtifactDebugNode[];
472
701
  /**
473
- * Internal: Executes the factory and captures dependencies into provided Sets.
702
+ * Registers a new artifact with the container.
703
+ * If an artifact with the same key already exists, it will be overwritten and disposed.
704
+ * For Singleton, non-lazy artifacts, the factory will be immediately invoked.
705
+ * @template K The key of the artifact to register.
706
+ * @param {object} params The registration parameters.
707
+ * @param {K} params.key The unique identifier for the artifact.
708
+ * @param {ArtifactFactory<TRegistry, TState, K>} params.factory The function that creates the artifact instance.
709
+ * @param {ArtifactOptions} params.options Optional configuration for the artifact's lifecycle.
710
+ * @returns A cleanup function that, when called, unregisters the artifact.
711
+ */
712
+ register<K extends keyof TRegistry>({ key, factory, ...options }: {
713
+ key: K;
714
+ factory: ArtifactFactory<TRegistry, TState, K>;
715
+ } & ArtifactOptions): () => void;
716
+ /**
717
+ * Unregisters an artifact from the container, disposing of its current instance
718
+ * and removing all associated resources and dependency links.
719
+ * @template K The key of the artifact to unregister.
720
+ * @param key The unique identifier of the artifact.
721
+ * @returns A Promise that resolves when the artifact has been fully unregistered and disposed.
722
+ */
723
+ unregister<K extends keyof TRegistry>(key: K): Promise<void>;
724
+ /**
725
+ * Resolves an artifact by its key, returning its instance or an error.
726
+ * This method handles dependency resolution, cycle detection, caching,
727
+ * and retry logic. It traverses the container hierarchy if the artifact
728
+ * is not found locally.
729
+ * @template K The key of the artifact to resolve.
730
+ * @param key The unique identifier for the artifact.
731
+ * @returns A Promise that resolves to a `ResolvedArtifact`. This object
732
+ * will contain either the `instance` (if successful) or an `error`
733
+ * (if an external error occurred during factory execution).
734
+ * @throws {CircularDependencyError} if a circular dependency is detected during resolution.
735
+ * @throws {ArtifactNotFoundError} if the artifact with the given key is not found
736
+ * in the current container or any parent containers.
737
+ * @throws {SystemError} for any other critical structural or configuration issues.
738
+ */
739
+ resolve<K extends keyof TRegistry>(key: K): Promise<ResolvedArtifact<TRegistry[K]>>;
740
+ /**
741
+ * Returns an `ArtifactWatcher` for a given artifact key.
742
+ * The watcher allows subscribing to changes in the artifact's resolved value
743
+ * without directly resolving it or becoming a direct dependent.
744
+ * @template K The key of the artifact to watch.
745
+ * @param key The unique identifier for the artifact.
746
+ * @returns An `ArtifactWatcher` instance.
747
+ */
748
+ watch<K extends keyof TRegistry>(key: K): ArtifactWatcher<TRegistry[K]>;
749
+ /**
750
+ * Peeks at the resolved instance of an artifact without triggering its resolution
751
+ * if it's lazy, or registering a dependency. It simply returns the currently
752
+ * available instance (if any).
753
+ * @template K The key of the artifact to peek at.
754
+ * @param key The unique identifier for the artifact.
755
+ * @returns The artifact instance if it's already built, otherwise `undefined`.
756
+ */
757
+ peek<K extends keyof TRegistry>(key: K): TRegistry[K] | undefined;
758
+ private findDefinition;
759
+ /**
760
+ * Packages an `ArtifactDefinition` into a `ResolvedArtifact` for public consumption.
761
+ * This abstracts away internal details and provides the external API for interacting
762
+ * with a resolved artifact (e.g., `invalidate`).
763
+ * @template T The expected type of the artifact instance.
764
+ * @param def The internal `ArtifactDefinition`.
765
+ * @returns A `ResolvedArtifact` object.
766
+ */
767
+ private packageArtifact;
768
+ /**
769
+ * Core logic for executing an artifact's factory and capturing its dependencies.
770
+ * This method is responsible for setting up the factory context, running the
771
+ * factory (with retries and timeouts), and collecting all declared dependencies
772
+ * (both artifact and state).
773
+ * @template K The key of the artifact being created.
774
+ * @param def The `ArtifactDefinition` for the artifact.
775
+ * @param outArtifactDeps A Set to capture discovered artifact dependencies.
776
+ * @param outStateDeps A Set to capture discovered state dependencies.
777
+ * @returns A Promise resolving to an object containing the instance, cleanup function, and any external error.
778
+ * @throws {SystemError} if a critical internal error occurs (e.g., circular dependency detected).
474
779
  */
475
780
  private createArtifactInstance;
476
781
  /**
477
- * Updates the dependency graph and state subscriptions after a successful creation.
782
+ * Handles the propagation of a `yield` event from a Singleton artifact.
783
+ * This involves invalidating all direct dependents and notifying any listeners.
784
+ * @param key The key of the artifact that yielded a new value.
478
785
  */
479
- private updateGraph;
786
+ private processYieldPropagation;
787
+ /**
788
+ * Registers a dependency from a `dependent` artifact on a `target` artifact.
789
+ * This builds the inverse dependency graph, allowing for efficient cascade invalidations.
790
+ * This method is public so that child containers can register dependents on artifacts
791
+ * owned by a parent container.
792
+ * @param targetKey The key of the artifact being depended upon.
793
+ * @param dependentKey The key of the artifact that depends on the target.
794
+ * @param dependentContainer The container instance where the dependent artifact is registered.
795
+ */
796
+ registerDependent(targetKey: string, dependentKey: string, dependentContainer: ArtifactContainer<any, any>): void;
797
+ /**
798
+ * Removes a previously registered dependency link.
799
+ * This method is public so that child containers can remove dependents on artifacts
800
+ * owned by a parent container when their artifacts are disposed.
801
+ * @param targetKey The key of the artifact that was depended upon.
802
+ * @param dependentKey The key of the artifact that previously depended on the target.
803
+ * @param dependentContainer The container instance where the dependent artifact was registered.
804
+ */
805
+ removeDependent(targetKey: string, dependentKey: string, dependentContainer: ArtifactContainer<any, any>): void;
480
806
  /**
481
- * Cascading invalidation logic.
482
- * Destroys the artifact, destroys dependents, then rebuilds eager artifacts.
807
+ * Initiates the invalidation process for an artifact, potentially debouncing the rebuild.
808
+ * Invalidation marks an artifact as needing to be rebuilt on its next resolution.
809
+ * @template K The key of the artifact to invalidate.
810
+ * @param key The unique identifier for the artifact.
811
+ * @param replace If `true`, bypasses debouncing and forces an immediate execution of `executeInvalidation`.
812
+ * @returns A Promise that resolves when the invalidation (and potential debounced rebuild) is complete.
483
813
  */
484
814
  private invalidate;
485
815
  /**
486
- * Cleans up a specific artifact definition's instance and subscriptions.
487
- * Keeps the definition registered.
816
+ * Executes the actual invalidation and rebuild logic for an artifact.
817
+ * This includes disposing the old instance, invalidating dependents, and (optionally) resolving a new instance.
818
+ * @template K The key of the artifact to invalidate.
819
+ * @param key The unique identifier for the artifact.
820
+ * @param replace If `true`, forces immediate disposal and rebuild without waiting for existing rebuild promises.
821
+ * @returns A Promise that resolves when the invalidation and rebuild process is complete.
822
+ */
823
+ private executeInvalidation;
824
+ /**
825
+ * Disposes of an artifact's instance by running its cleanup and dispose functions,
826
+ * unsubscribing from state changes, and clearing its cached instance and error.
827
+ * This prepares the artifact for a rebuild or removal.
828
+ * @param def The `ArtifactDefinition` of the instance to dispose.
488
829
  */
489
830
  private disposeInstance;
490
831
  /**
491
- * Fully removes an artifact from the system.
832
+ * Fully disposes of an artifact, including its instance and all its associated
833
+ * dependency graph links and resources. This is typically called when an artifact
834
+ * is unregistered or the container itself is disposed.
835
+ * @param key The unique identifier of the artifact to dispose.
492
836
  */
493
837
  private disposeArtifact;
494
- private detectCycles;
838
+ /**
839
+ * Updates the dependency graph for an artifact based on newly discovered dependencies
840
+ * during its factory execution. This involves adding and removing dependent links,
841
+ * and setting up or tearing down state subscriptions.
842
+ * @param def The `ArtifactDefinition` whose graph is being updated.
843
+ * @param newArtifactDeps The set of artifact dependencies discovered during the latest build.
844
+ * @param newStateDeps The set of state path dependencies discovered during the latest build.
845
+ */
846
+ private updateGraph;
847
+ /**
848
+ * Creates a single composite cleanup function from an array of individual cleanup functions.
849
+ * The composite function executes all provided cleanups in reverse order of registration,
850
+ * ensuring proper resource release, and handles potential asynchronous cleanups.
851
+ * @param fns An array of `ArtifactCleanup` functions.
852
+ * @returns A composite `ArtifactCleanup` function, or `undefined` if the array is empty.
853
+ */
854
+ private createCompositeCleanup;
855
+ /**
856
+ * Notifies all registered listeners (watchers) for a specific artifact that
857
+ * its state (instance or error) has potentially changed.
858
+ * @param key The key of the artifact whose listeners should be notified.
859
+ */
860
+ private notifyListeners;
861
+ /**
862
+ * Disposes of the entire `ArtifactContainer` and all artifacts registered within it.
863
+ * This releases all resources, stops all watchers, and clears all internal state.
864
+ * After disposal, the container should no longer be used.
865
+ */
495
866
  dispose(): void;
496
- isLoading(key: string): boolean;
497
867
  }
498
868
 
499
869
  /**
@@ -824,65 +1194,4 @@ declare class ActionManager<T extends object> {
824
1194
  private emit;
825
1195
  }
826
1196
 
827
- interface ActionContext<TState extends object, TResolvedArtifacts extends object> {
828
- /**
829
- * Resolve an artifact.
830
- * This records a dependency between the caller and the requested artifact.
831
- */
832
- resolve<K extends keyof TResolvedArtifacts>(key: K): Promise<TResolvedArtifacts[K]>;
833
- state: TState;
834
- }
835
- type ActionImplementation<TState extends object, TResolvedArtifacts extends object, TArgs extends any[]> = (ctx: ActionContext<TState, TResolvedArtifacts>, ...args: TArgs) => DeepPartial<TState> | Promise<DeepPartial<TState>>;
836
- type ArtifactDefinition<TState extends Object, R> = {
837
- factory: ArtifactFactory<TState, R>;
838
- scope?: ArtifactScope;
839
- lazy?: boolean;
840
- };
841
- type ArtifactsMap<TState extends object> = Record<string, ArtifactDefinition<TState, any>>;
842
- type ExtractArtifactInstanceFromConfig<T> = T extends {
843
- factory: ArtifactFactory<any, infer I>;
844
- } ? I : never;
845
- type ExtractInstanceFromMap<TMap extends ArtifactsMap<any>, TKey extends keyof TMap> = ExtractArtifactInstanceFromConfig<TMap[TKey]>;
846
- type ResolvedArtifactsMap<TArtifactsMap extends ArtifactsMap<any>> = {
847
- [K in keyof TArtifactsMap]: ExtractInstanceFromMap<TArtifactsMap, K>;
848
- };
849
- type ActionMap<TState extends object, TArtifactsMap extends ArtifactsMap<TState>> = Record<string, ActionImplementation<TState, ResolvedArtifactsMap<TArtifactsMap>, any[]>>;
850
- /**
851
- * Bounds the actions for the resulting store hook, removing the context argument.
852
- */
853
- type BoundActions<TState extends object, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>> = {
854
- [K in keyof TActions]: (...args: Parameters<TActions[K]> extends [ActionContext<any, any>, ...infer R] ? R : never) => Promise<TState>;
855
- };
856
- type LoadingState<TActions> = Partial<Record<keyof TActions, boolean>>;
857
- type StoreOptions<T> = ObserverOptions & {
858
- enableMetrics?: boolean;
859
- persistence?: SimplePersistence$1<T>;
860
- };
861
- interface StoreDefinition<TState extends object, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>> {
862
- state: TState;
863
- actions: TActions;
864
- artifacts?: TArtifactsMap;
865
- loading?: LoadingState<TActions>;
866
- sync?: (args: TState) => void;
867
- blockingMiddleware?: Record<string, BlockingMiddleware<TState>>;
868
- middleware?: Record<string, Middleware<TState>>;
869
- }
870
- type StoreHook<TState extends object, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>> = () => {
871
- store: any;
872
- observer: any;
873
- select: <S>(selector: (state: TState) => S) => S;
874
- actions: BoundActions<TState, TArtifactsMap, TActions>;
875
- /**
876
- * Reactive Artifact Resolver.
877
- * Returns [instance, isReady].
878
- */
879
- resolve: <K extends keyof TArtifactsMap>(key: K) => readonly [ExtractInstanceFromMap<TArtifactsMap, K>, true] | readonly [ExtractInstanceFromMap<TArtifactsMap, K> | undefined, false];
880
- isReady: boolean;
881
- actionTracker: any;
882
- watch: (action: keyof TActions) => boolean;
883
- state: () => TState;
884
- };
885
-
886
- declare function createStore<TState extends Record<string, unknown>, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>>(definition: StoreDefinition<TState, TArtifactsMap, TActions>, { enableMetrics, ...options }?: StoreOptions<TState>): StoreHook<TState, TArtifactsMap, TActions>;
887
-
888
- export { type ActionCompletePayload, type ActionContext, type ActionErrorPayload, type ActionImplementation, ActionManager, type ActionMap, type ActionStartPayload, type ArtifactCleanup, ArtifactContainer, type ArtifactDefinition, type ArtifactFactory, type ArtifactFactoryContext, type ArtifactResult, ArtifactScope, type ArtifactsMap, type BlockingMiddleware, type BoundActions, DELETE_SYMBOL, type DataStore, type DeepPartial, type DiffFunction, type ExtractArtifactInstanceFromConfig, type ExtractInstanceFromMap, type LoadingState, type MergeFunction, type Middleware, type MiddlewareConfig, type MiddlewareExecution, type ObserverOptions, type PersistenceFailedPayload, type PersistenceInitErrorPayload, type PersistenceQueueClearedPayload, type PersistenceQueuedPayload, type PersistenceRetryPayload, type PersistenceSuccessPayload, ReactiveDataStore, type ReactiveSelector, type ResolvedArtifactsMap, type SelectorAccessedPayload, type SelectorChangedPayload, type StateDelta, type StateUpdater, type StoreAction, type StoreDefinition, type StoreEvent, type StoreEvents, type StoreExecutionState, type StoreHook, type StoreMetrics, StoreObserver, type StoreOptions, type TransformMiddleware, type UseDependencyContext, createDerivePaths, createDiff, createMerge, createStore, derivePaths, diff, merge, shallowClone };
1197
+ export { type ActionCompletePayload, type ActionErrorPayload, ActionManager, type ActionStartPayload, type ArtifactCleanup, ArtifactContainer, type ArtifactDebugNode, type ArtifactFactory, type ArtifactFactoryContext, ArtifactNotFoundError, type ArtifactOptions, ArtifactScope, type ArtifactWatcher, type BlockingMiddleware, CircularDependencyError, DELETE_SYMBOL, type DataStore, type DeepPartial, type DiffFunction, IllegalScopeError, type MergeFunction, type Middleware, type MiddlewareConfig, type MiddlewareExecution, type ObserverOptions, type PersistenceFailedPayload, type PersistenceInitErrorPayload, type PersistenceQueueClearedPayload, type PersistenceQueuedPayload, type PersistenceRetryPayload, type PersistenceSuccessPayload, ReactiveDataStore, type ReactiveSelector, type ResolvedArtifact, type SelectorAccessedPayload, type SelectorChangedPayload, type StateDelta, type StateUpdater, type StoreAction, type StoreEvent, type StoreEvents, type StoreExecutionState, type StoreMetrics, StoreObserver, SystemError, type TransformMiddleware, type UseDependencyContext, type UseOptions, createDerivePaths, createDiff, createMerge, derivePaths, diff, merge, shallowClone };