@asaidimu/utils-store 10.2.16 → 10.2.17

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.cts CHANGED
@@ -1,7 +1,130 @@
1
- import { SimplePersistence } from "@core/persistence";
2
- import { EventBus, SubscribeOptions, SubscribeOptions as SubscribeOptions$1 } from "@core/events";
3
- import { SystemLogger } from "@core/logger";
4
-
1
+ //#region src/persistence/types.d.ts
2
+ interface SimplePersistence<T> {
3
+ /**
4
+ * Persists data to storage.
5
+ *
6
+ * @param id The **unique identifier of the *consumer instance*** making the change. This is NOT the ID of the data (`T`) itself.
7
+ * Think of it as the ID of the specific browser tab, component, or module that's currently interacting with the persistence layer.
8
+ * It should typically be a **UUID** generated once at the consumer instance's instantiation.
9
+ * This `id` is crucial for the `subscribe` method, helping to differentiate updates originating from the current instance versus other instances/tabs, thereby preventing self-triggered notification loops.
10
+ * @param state The state (of type T) to persist. This state is generally considered the **global or shared state** that all instances interact with.
11
+ * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations (like `IndexedDBPersistence`), this returns a `Promise<boolean>`.
12
+ */
13
+ set(id: string, state: T): boolean | Promise<boolean>;
14
+ /**
15
+ * Retrieves the global persisted data from storage.
16
+ *
17
+ * @returns The retrieved state of type `T`, or `null` if no data is found or if an error occurs during retrieval/parsing.
18
+ * For asynchronous implementations, this returns a `Promise<T | null>`.
19
+ */
20
+ get(): (T | null) | Promise<T | null>;
21
+ /**
22
+ * Subscribes to changes in the global persisted data that originate from *other* instances of your application (e.g., other tabs or independent components using the same persistence layer).
23
+ *
24
+ * @param id The **unique identifier of the *consumer instance* subscribing**. This allows the persistence implementation to filter out notifications that were initiated by the subscribing instance itself.
25
+ * @param callback The function to call when the global persisted data changes from *another* source. The new state (`T`) is passed as an argument to this callback.
26
+ * @returns A function that, when called, will unsubscribe the provided callback from future updates. Call this when your component or instance is no longer active to prevent memory leaks.
27
+ */
28
+ subscribe(id: string, callback: (state: T) => void): () => void;
29
+ /**
30
+ * Clears (removes) the entire global persisted data from storage.
31
+ *
32
+ * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations, this returns a `Promise<boolean>`.
33
+ */
34
+ clear(): boolean | Promise<boolean>;
35
+ /**
36
+ * Returns metadata about the persistence layer.
37
+ *
38
+ * This is useful for distinguishing between multiple apps running on the same host
39
+ * (e.g., several apps served at `localhost:3000` that share the same storage key).
40
+ *
41
+ * @returns An object containing:
42
+ * - `version`: The semantic version string of the persistence schema or application.
43
+ * - `id`: A unique identifier for the application using this persistence instance.
44
+ */
45
+ stats(): {
46
+ version: string;
47
+ id: string;
48
+ };
49
+ /**
50
+ * Closes the persistence instance, releasing the file watcher.
51
+ * Call this when shutting down to clean up resources.
52
+ */
53
+ close?: () => Promise<void>;
54
+ }
55
+ //#endregion
56
+ //#region src/events/types.d.ts
57
+ /**
58
+ * Interface defining the shape of the EventBus.
59
+ * @template TEventMap - A record mapping event names to their respective payload types.
60
+ */
61
+ interface EventBus<TEventMap extends Record<string, any>> {
62
+ /**
63
+ * Subscribes to a specific event by name.
64
+ * @param eventName - The name of the event to subscribe to.
65
+ * @param callback - The function to call when the event is emitted.
66
+ * @param options - Extra options to determine the behaviour of the
67
+ * subscription
68
+ * @returns A function to unsubscribe from the event.
69
+ */
70
+ subscribe<TEventName extends keyof TEventMap | "*">(eventName: TEventName, callback: TEventName extends "*" ? (payload: TEventMap[keyof TEventMap], event: keyof TEventMap) => void : (payload: TEventMap[TEventName]) => void, options?: SubscribeOptions): () => void;
71
+ /**
72
+ * Subscribes to an event and automatically unsubscribes after it fires once.
73
+ * @param eventName - The name of the event to subscribe to.
74
+ * @param callback - The function to call when the event is emitted.
75
+ * @returns A function to cancel the one-shot subscription before it fires.
76
+ */
77
+ once<TEventName extends keyof TEventMap | "*">(eventName: TEventName, callback: TEventName extends "*" ? (payload: TEventMap[keyof TEventMap], event: keyof TEventMap) => void : (payload: TEventMap[TEventName]) => void, options?: SubscribeOptions): () => void;
78
+ /**
79
+ * Emits an event with a payload to all subscribed listeners.
80
+ * @param event - An object containing the event name and payload.
81
+ */
82
+ emit: <TEventName extends keyof TEventMap>(event: {
83
+ name: TEventName;
84
+ payload: TEventMap[TEventName];
85
+ }) => void;
86
+ /**
87
+ * Retrieves metrics about event bus usage.
88
+ * @returns An object containing various metrics.
89
+ */
90
+ metrics: () => EventMetrics;
91
+ /**
92
+ * Clears all subscriptions and resets metrics.
93
+ *
94
+ * After calling `clear()`, the bus is fully reset and can be reused
95
+ * cross-tab communication is re-established if it was previously enabled.
96
+ *
97
+ * @param options - Optional configuration object.
98
+ * @param options.permanent - If `true`, the bus becomes permanently unusable after clearing.
99
+ * Defaults to `false`.
100
+ * @returns {void}
101
+ */
102
+ clear: (options?: {
103
+ permanent?: boolean;
104
+ }) => void;
105
+ }
106
+ /**
107
+ * Interface defining the metrics tracked by the EventBus.
108
+ */
109
+ interface EventMetrics {
110
+ /** Total number of events emitted (both sync and deferred paths). */
111
+ totalEvents: number;
112
+ /** Number of active subscriptions across all event names. */
113
+ activeSubscriptions: number;
114
+ /** Map of event names to their emission counts. */
115
+ eventCounts: Map<string, number>;
116
+ /** Average duration of event dispatch in milliseconds. */
117
+ averageEmitDuration: number;
118
+ }
119
+ interface SubscribeOptions {
120
+ /**
121
+ * Debounce delay in milliseconds. When multiple events arrive in quick
122
+ * succession, the callback runs only after the quiet period ends, using the
123
+ * latest payload. Default = no debouncing.
124
+ */
125
+ debounce?: number;
126
+ }
127
+ //#endregion
5
128
  //#region src/store/types.d.ts
6
129
  /**
7
130
  * Utility type for representing partial updates to the state, allowing deep nesting.
@@ -333,7 +456,7 @@ interface DataStore<T extends object> {
333
456
  * @param options Extra options to pass to the event bus
334
457
  * @returns An unsubscribe function.
335
458
  */
336
- watch(path: string | Array<string>, callback: (state: T) => void, options?: SubscribeOptions$1): () => void;
459
+ watch(path: string | Array<string>, callback: (state: T) => void, options?: SubscribeOptions): () => void;
337
460
  /**
338
461
  * Subscribes to execution‑status changes of a registered action.
339
462
  *
@@ -486,6 +609,87 @@ type StoreAction<T, R extends any[] = any[]> = {
486
609
  };
487
610
  };
488
611
  //#endregion
612
+ //#region src/logger/logger.d.ts
613
+ /**
614
+ * Represents the severity level of a system log entry.
615
+ * Levels are ordered by increasing severity: trace, debug, info, warn, error.
616
+ */
617
+ type LogLevel = "trace" | "debug" | "info" | "warn" | "error";
618
+ /**
619
+ * Defines a destination where system logs are outputted or processed.
620
+ * Custom sinks (e.g., File, Logstash, Sentry) must implement this interface.
621
+ */
622
+ interface LogSink {
623
+ /**
624
+ * Dispatches a structured log entry to the underlying destination.
625
+ *
626
+ * @param record - The complete log object containing metadata and payload.
627
+ * @returns A void or Promise that resolves when the log has been safely handed off.
628
+ */
629
+ write(record: SystemLog): void | Promise<void>;
630
+ }
631
+ /**
632
+ * Structure representing a fully contextualized system log entry ready for sinking.
633
+ */
634
+ interface SystemLog {
635
+ /** The severity level of the log. */
636
+ level: LogLevel;
637
+ /** A clear, human-readable string identifying the distinct event (e.g., "user_login_failed"). */
638
+ event: string;
639
+ /** Additional structured data specific to this log instantiation. */
640
+ data?: object;
641
+ /** Contextual data shared across the logger instance (e.g., traceIds, environment). */
642
+ context?: object;
643
+ /** Epoch timestamp in milliseconds denoting when the log event occurred. */
644
+ timestamp: number;
645
+ }
646
+ /**
647
+ * Primary logger interface providing level-specific log dispatching, context-chaining,
648
+ * and dynamic sink management.
649
+ */
650
+ interface SystemLogger {
651
+ /** Logs high-volume, extremely fine-grained diagnostic details. */
652
+ trace(event: string, data?: object): void;
653
+ /** Logs diagnostic information useful during local development or debugging. */
654
+ debug(event: string, data?: object): void;
655
+ /** Logs standard operational events that track the healthy flow of the system. */
656
+ info(event: string, data?: object): void;
657
+ /** Alias for the `info` logging method. */
658
+ log(event: string, data?: object): void;
659
+ /** Logs non-fatal operational anomalies or conditions that deserve attention. */
660
+ warn(event: string, data?: object): void;
661
+ /** Logs critical errors, failures, or exceptions preventing a transaction/process. */
662
+ error(event: string, data?: unknown): void;
663
+ /**
664
+ * Directly forwards a pre-constructed `SystemLog` record through the logger's pipeline.
665
+ * Combines instance context before outputting.
666
+ */
667
+ write(record: SystemLog): void;
668
+ /**
669
+ * Generates a new `SystemLogger` instance that shares the existing sinks and parent
670
+ * context, deeply merging the newly provided context on top.
671
+ *
672
+ * @param context - The metadata to append to all subsequent logs emitted by the child logger.
673
+ */
674
+ child(context: object): SystemLogger;
675
+ /**
676
+ * Adds a new sink to this logger instance.
677
+ * The sink will receive all logs emitted by this logger and its descendants (unless
678
+ * a descendant removes it). This operation does not affect the parent logger.
679
+ *
680
+ * @param sink - The LogSink to add.
681
+ */
682
+ addSink(sink: LogSink): void;
683
+ /**
684
+ * Removes a previously added sink from this logger instance.
685
+ * Returns `true` if the sink was found and removed, otherwise `false`.
686
+ * This operation does not affect the parent logger.
687
+ *
688
+ * @param sink - The LogSink to remove.
689
+ */
690
+ removeSink(sink: LogSink): boolean;
691
+ }
692
+ //#endregion
489
693
  //#region src/store/logger.d.ts
490
694
  type StoreLogger = SystemLogger;
491
695
  declare function createStoreLogger(logger?: StoreLogger): StoreLogger;
@@ -557,7 +761,7 @@ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
557
761
  /**
558
762
  * Creates a new ReactiveDataStore instance.
559
763
  */
560
- constructor(initialData: T, persistence?: SimplePersistence<T>, deleteMarker?: symbol, options?: {
764
+ constructor(initialData: T | {}, persistence?: SimplePersistence<T>, deleteMarker?: symbol, options?: {
561
765
  persistenceMaxRetries?: number;
562
766
  persistenceRetryDelay?: number;
563
767
  broadcastChannel?: string;
@@ -762,56 +966,6 @@ declare class StoreRegistry<S extends object> {
762
966
  get size(): number;
763
967
  }
764
968
  //#endregion
765
- //#region src/persistence/types.d.ts
766
- interface SimplePersistence$1<T> {
767
- /**
768
- * Persists data to storage.
769
- *
770
- * @param id The **unique identifier of the *consumer instance*** making the change. This is NOT the ID of the data (`T`) itself.
771
- * Think of it as the ID of the specific browser tab, component, or module that's currently interacting with the persistence layer.
772
- * It should typically be a **UUID** generated once at the consumer instance's instantiation.
773
- * This `id` is crucial for the `subscribe` method, helping to differentiate updates originating from the current instance versus other instances/tabs, thereby preventing self-triggered notification loops.
774
- * @param state The state (of type T) to persist. This state is generally considered the **global or shared state** that all instances interact with.
775
- * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations (like `IndexedDBPersistence`), this returns a `Promise<boolean>`.
776
- */
777
- set(id: string, state: T): boolean | Promise<boolean>;
778
- /**
779
- * Retrieves the global persisted data from storage.
780
- *
781
- * @returns The retrieved state of type `T`, or `null` if no data is found or if an error occurs during retrieval/parsing.
782
- * For asynchronous implementations, this returns a `Promise<T | null>`.
783
- */
784
- get(): (T | null) | Promise<T | null>;
785
- /**
786
- * Subscribes to changes in the global persisted data that originate from *other* instances of your application (e.g., other tabs or independent components using the same persistence layer).
787
- *
788
- * @param id The **unique identifier of the *consumer instance* subscribing**. This allows the persistence implementation to filter out notifications that were initiated by the subscribing instance itself.
789
- * @param callback The function to call when the global persisted data changes from *another* source. The new state (`T`) is passed as an argument to this callback.
790
- * @returns A function that, when called, will unsubscribe the provided callback from future updates. Call this when your component or instance is no longer active to prevent memory leaks.
791
- */
792
- subscribe(id: string, callback: (state: T) => void): () => void;
793
- /**
794
- * Clears (removes) the entire global persisted data from storage.
795
- *
796
- * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations, this returns a `Promise<boolean>`.
797
- */
798
- clear(): boolean | Promise<boolean>;
799
- /**
800
- * Returns metadata about the persistence layer.
801
- *
802
- * This is useful for distinguishing between multiple apps running on the same host
803
- * (e.g., several apps served at `localhost:3000` that share the same storage key).
804
- *
805
- * @returns An object containing:
806
- * - `version`: The semantic version string of the persistence schema or application.
807
- * - `id`: A unique identifier for the application using this persistence instance.
808
- */
809
- stats(): {
810
- version: string;
811
- id: string;
812
- };
813
- }
814
- //#endregion
815
969
  //#region src/store/observer.d.ts
816
970
  /**
817
971
  * @interface DebugEvent
@@ -1015,13 +1169,13 @@ declare class StoreObserver<T extends object> {
1015
1169
  * @param persistence An object implementing the SimplePersistence interface.
1016
1170
  * @returns A promise that resolves to true if the session was saved successfully.
1017
1171
  */
1018
- saveSession(persistence: SimplePersistence$1<ObserverSessionData<T>>): Promise<boolean>;
1172
+ saveSession(persistence: SimplePersistence<ObserverSessionData<T>>): Promise<boolean>;
1019
1173
  /**
1020
1174
  * Loads a previously saved observer session and restores the state to the latest saved snapshot.
1021
1175
  * @param persistence An object implementing the SimplePersistence interface.
1022
1176
  * @returns A promise that resolves to true if a session was loaded.
1023
1177
  */
1024
- loadSession(persistence: SimplePersistence$1<ObserverSessionData<T>>): Promise<boolean>;
1178
+ loadSession(persistence: SimplePersistence<ObserverSessionData<T>>): Promise<boolean>;
1025
1179
  /**
1026
1180
  * Exports the current session data as a JSON file, initiating a browser download.
1027
1181
  */
package/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { EventBus, SubscribeOptions, SubscribeOptions as SubscribeOptions$1 } from "@core/events";
2
- import { SystemLogger } from "@core/logger";
3
- import { SimplePersistence } from "@core/persistence";
4
- import { SimplePersistence as SimplePersistence$1 } from "@asaidimu/utils-persistence";
1
+ import { EventBus, SubscribeOptions, SubscribeOptions as SubscribeOptions$1 } from "@asaidimu/utils-events";
2
+ import { SystemLogger } from "@asaidimu/utils-logger";
3
+ import { SimplePersistence } from "@asaidimu/utils-persistence";
5
4
 
6
5
  //#region src/store/types.d.ts
7
6
  /**
@@ -558,7 +557,7 @@ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
558
557
  /**
559
558
  * Creates a new ReactiveDataStore instance.
560
559
  */
561
- constructor(initialData: T, persistence?: SimplePersistence<T>, deleteMarker?: symbol, options?: {
560
+ constructor(initialData: T | {}, persistence?: SimplePersistence<T>, deleteMarker?: symbol, options?: {
562
561
  persistenceMaxRetries?: number;
563
562
  persistenceRetryDelay?: number;
564
563
  broadcastChannel?: string;
@@ -966,13 +965,13 @@ declare class StoreObserver<T extends object> {
966
965
  * @param persistence An object implementing the SimplePersistence interface.
967
966
  * @returns A promise that resolves to true if the session was saved successfully.
968
967
  */
969
- saveSession(persistence: SimplePersistence$1<ObserverSessionData<T>>): Promise<boolean>;
968
+ saveSession(persistence: SimplePersistence<ObserverSessionData<T>>): Promise<boolean>;
970
969
  /**
971
970
  * Loads a previously saved observer session and restores the state to the latest saved snapshot.
972
971
  * @param persistence An object implementing the SimplePersistence interface.
973
972
  * @returns A promise that resolves to true if a session was loaded.
974
973
  */
975
- loadSession(persistence: SimplePersistence$1<ObserverSessionData<T>>): Promise<boolean>;
974
+ loadSession(persistence: SimplePersistence<ObserverSessionData<T>>): Promise<boolean>;
976
975
  /**
977
976
  * Exports the current session data as a JSON file, initiating a browser download.
978
977
  */