@asaidimu/utils-persistence 6.1.11 → 6.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ //#region src/persistence/types.d.ts
1
2
  /**
2
3
  * configuration object for initializing a persistence store.
3
4
  *
@@ -11,215 +12,218 @@
11
12
  * @template T the type of data being persisted.
12
13
  */
13
14
  interface StoreConfig<T> {
14
- /**
15
- * the semantic version string (e.g., "1.0.0") of the data schema or application.
16
- *
17
- * this is used for version control and data migrations.
18
- * when the persisted state’s version does not match the current version,
19
- * the `onUpgrade` function will be invoked (if provided).
20
- */
15
+ /**
16
+ * the semantic version string (e.g., "1.0.0") of the data schema or application.
17
+ *
18
+ * this is used for version control and data migrations.
19
+ * when the persisted state’s version does not match the current version,
20
+ * the `onUpgrade` function will be invoked (if provided).
21
+ */
22
+ version: string;
23
+ /**
24
+ * a unique application identifier (e.g., "chat-app" or "my-dashboard").
25
+ *
26
+ * this prevents collisions between different apps or modules
27
+ * that might share the same persistence backend (e.g., localstorage).
28
+ *
29
+ * example: if two apps both persist under the key "user", the `app`
30
+ * value ensures they can be distinguished.
31
+ */
32
+ app: string;
33
+ /**
34
+ * optional handler for upgrading persisted state across versions.
35
+ *
36
+ * this function will be called when the persisted state’s `version`
37
+ * does not match the `version` specified in this config.
38
+ *
39
+ * @param state the existing state object, including:
40
+ * - `data`: the current persisted data (or null if none exists).
41
+ * - `version`: the version string stored with the data.
42
+ * - `app`: the application identifier stored with the data.
43
+ *
44
+ * @returns a new state object with:
45
+ * - `state`: the migrated data (or null if clearing/resetting).
46
+ * - `version`: the new version string (must match `config.version`).
47
+ *
48
+ * example:
49
+ * ```ts
50
+ * onupgrade: async ({ data, version, app }) => {
51
+ * if (version === "1.0.0") {
52
+ * // migrate from 1.0.0 to 2.0.0
53
+ * return { state: { ...data, newfield: "default" }, version: "2.0.0" };
54
+ * }
55
+ * return { state: data, version: "2.0.0" };
56
+ * }
57
+ * ```
58
+ */
59
+ onUpgrade?: (state: {
60
+ data: T | null;
21
61
  version: string;
22
- /**
23
- * a unique application identifier (e.g., "chat-app" or "my-dashboard").
24
- *
25
- * this prevents collisions between different apps or modules
26
- * that might share the same persistence backend (e.g., localstorage).
27
- *
28
- * example: if two apps both persist under the key "user", the `app`
29
- * value ensures they can be distinguished.
30
- */
31
62
  app: string;
32
- /**
33
- * optional handler for upgrading persisted state across versions.
34
- *
35
- * this function will be called when the persisted state’s `version`
36
- * does not match the `version` specified in this config.
37
- *
38
- * @param state the existing state object, including:
39
- * - `data`: the current persisted data (or null if none exists).
40
- * - `version`: the version string stored with the data.
41
- * - `app`: the application identifier stored with the data.
42
- *
43
- * @returns a new state object with:
44
- * - `state`: the migrated data (or null if clearing/resetting).
45
- * - `version`: the new version string (must match `config.version`).
46
- *
47
- * example:
48
- * ```ts
49
- * onupgrade: async ({ data, version, app }) => {
50
- * if (version === "1.0.0") {
51
- * // migrate from 1.0.0 to 2.0.0
52
- * return { state: { ...data, newfield: "default" }, version: "2.0.0" };
53
- * }
54
- * return { state: data, version: "2.0.0" };
55
- * }
56
- * ```
57
- */
58
- onUpgrade?: (state: {
59
- data: T | null;
60
- version: string;
61
- app: string;
62
- }) => Promise<{
63
- state: T | null;
64
- version: string;
65
- }>;
66
- /**
67
- * enables or disables developer mode for the persistence store.
68
- *
69
- * when set to `true`, the store may provide additional logging,
70
- * verbose error reporting, or bypass certain production constraints
71
- * (such as strict cache validation) to aid in debugging.
72
- *
73
- * @default false
74
- */
75
- dev?: boolean;
63
+ }) => Promise<{
64
+ state: T | null;
65
+ version: string;
66
+ }>;
67
+ /**
68
+ * enables or disables developer mode for the persistence store.
69
+ *
70
+ * when set to `true`, the store may provide additional logging,
71
+ * verbose error reporting, or bypass certain production constraints
72
+ * (such as strict cache validation) to aid in debugging.
73
+ *
74
+ * @default false
75
+ */
76
+ dev?: boolean;
76
77
  }
77
78
  interface SimplePersistence<T> {
78
- /**
79
- * Persists data to storage.
80
- *
81
- * @param id The **unique identifier of the *consumer instance*** making the change. This is NOT the ID of the data (`T`) itself.
82
- * Think of it as the ID of the specific browser tab, component, or module that's currently interacting with the persistence layer.
83
- * It should typically be a **UUID** generated once at the consumer instance's instantiation.
84
- * 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.
85
- * @param state The state (of type T) to persist. This state is generally considered the **global or shared state** that all instances interact with.
86
- * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations (like `IndexedDBPersistence`), this returns a `Promise<boolean>`.
87
- */
88
- set(id: string, state: T): boolean | Promise<boolean>;
89
- /**
90
- * Retrieves the global persisted data from storage.
91
- *
92
- * @returns The retrieved state of type `T`, or `null` if no data is found or if an error occurs during retrieval/parsing.
93
- * For asynchronous implementations, this returns a `Promise<T | null>`.
94
- */
95
- get(): (T | null) | Promise<T | null>;
96
- /**
97
- * 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).
98
- *
99
- * @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.
100
- * @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.
101
- * @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.
102
- */
103
- subscribe(id: string, callback: (state: T) => void): () => void;
104
- /**
105
- * Clears (removes) the entire global persisted data from storage.
106
- *
107
- * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations, this returns a `Promise<boolean>`.
108
- */
109
- clear(): boolean | Promise<boolean>;
110
- /**
111
- * Returns metadata about the persistence layer.
112
- *
113
- * This is useful for distinguishing between multiple apps running on the same host
114
- * (e.g., several apps served at `localhost:3000` that share the same storage key).
115
- *
116
- * @returns An object containing:
117
- * - `version`: The semantic version string of the persistence schema or application.
118
- * - `id`: A unique identifier for the application using this persistence instance.
119
- */
120
- stats(): {
121
- version: string;
122
- id: string;
123
- };
79
+ /**
80
+ * Persists data to storage.
81
+ *
82
+ * @param id The **unique identifier of the *consumer instance*** making the change. This is NOT the ID of the data (`T`) itself.
83
+ * Think of it as the ID of the specific browser tab, component, or module that's currently interacting with the persistence layer.
84
+ * It should typically be a **UUID** generated once at the consumer instance's instantiation.
85
+ * 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.
86
+ * @param state The state (of type T) to persist. This state is generally considered the **global or shared state** that all instances interact with.
87
+ * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations (like `IndexedDBPersistence`), this returns a `Promise<boolean>`.
88
+ */
89
+ set(id: string, state: T): boolean | Promise<boolean>;
90
+ /**
91
+ * Retrieves the global persisted data from storage.
92
+ *
93
+ * @returns The retrieved state of type `T`, or `null` if no data is found or if an error occurs during retrieval/parsing.
94
+ * For asynchronous implementations, this returns a `Promise<T | null>`.
95
+ */
96
+ get(): (T | null) | Promise<T | null>;
97
+ /**
98
+ * 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).
99
+ *
100
+ * @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.
101
+ * @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.
102
+ * @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.
103
+ */
104
+ subscribe(id: string, callback: (state: T) => void): () => void;
105
+ /**
106
+ * Clears (removes) the entire global persisted data from storage.
107
+ *
108
+ * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations, this returns a `Promise<boolean>`.
109
+ */
110
+ clear(): boolean | Promise<boolean>;
111
+ /**
112
+ * Returns metadata about the persistence layer.
113
+ *
114
+ * This is useful for distinguishing between multiple apps running on the same host
115
+ * (e.g., several apps served at `localhost:3000` that share the same storage key).
116
+ *
117
+ * @returns An object containing:
118
+ * - `version`: The semantic version string of the persistence schema or application.
119
+ * - `id`: A unique identifier for the application using this persistence instance.
120
+ */
121
+ stats(): {
122
+ version: string;
123
+ id: string;
124
+ };
124
125
  }
125
126
  interface StorageEvents {
126
- "store:updated": {
127
- storageKey: string;
128
- instanceId: string;
129
- state: any;
130
- timestamp?: number;
131
- version: string;
132
- app: string;
133
- };
127
+ "store:updated": {
128
+ storageKey: string;
129
+ instanceId: string;
130
+ state: any;
131
+ timestamp?: number;
132
+ version: string;
133
+ app: string;
134
+ };
134
135
  }
135
-
136
+ //#endregion
137
+ //#region src/persistence/webstorage.d.ts
136
138
  /**
137
139
  * Configuration options specific to the WebStoragePersistence adapter.
138
140
  */
139
141
  interface WebStoragePersistenceConfig {
140
- /**
141
- * The key under which data is stored in web storage (e.g., 'user-profile').
142
- */
143
- storageKey: string;
144
- /**
145
- * If true, uses sessionStorage instead of localStorage. Defaults to false.
146
- */
147
- session?: boolean;
142
+ /**
143
+ * The key under which data is stored in web storage (e.g., 'user-profile').
144
+ */
145
+ storageKey: string;
146
+ /**
147
+ * If true, uses sessionStorage instead of localStorage. Defaults to false.
148
+ */
149
+ session?: boolean;
148
150
  }
149
151
  /**
150
152
  * Implements SimplePersistence using web storage (localStorage or sessionStorage).
151
153
  * Supports cross-tab synchronization and data versioning with upgrade handlers.
152
154
  */
153
155
  declare class WebStoragePersistence<T> implements SimplePersistence<T> {
154
- private readonly eventBus;
155
- private readonly storage;
156
- private readonly config;
157
- private initialized;
158
- private initializationCallbacks;
159
- constructor(config: StoreConfig<T> & WebStoragePersistenceConfig);
160
- private initialize;
161
- private _onInitialized;
162
- private initializeEventBus;
163
- private getStoreName;
164
- private setupStorageEventListener;
165
- set(instanceId: string, state: T): boolean;
166
- private _get;
167
- get(): Promise<T | null>;
168
- subscribe(instanceId: string, onStateChange: (state: T) => void): () => void;
169
- clear(): boolean;
170
- stats(): {
171
- version: string;
172
- id: string;
173
- };
156
+ private readonly eventBus;
157
+ private readonly storage;
158
+ private readonly config;
159
+ private initialized;
160
+ private initializationCallbacks;
161
+ constructor(config: StoreConfig<T> & WebStoragePersistenceConfig);
162
+ private initialize;
163
+ private _onInitialized;
164
+ private initializeEventBus;
165
+ private getStoreName;
166
+ private setupStorageEventListener;
167
+ set(instanceId: string, state: T): boolean;
168
+ private _get;
169
+ get(): Promise<T | null>;
170
+ subscribe(instanceId: string, onStateChange: (state: T) => void): () => void;
171
+ clear(): boolean;
172
+ stats(): {
173
+ version: string;
174
+ id: string;
175
+ };
174
176
  }
175
-
177
+ //#endregion
178
+ //#region src/persistence/indexedb.d.ts
176
179
  interface IndexedDBPersistenceConfig {
177
- store: string;
178
- database: string;
179
- collection: string;
180
- enableTelemetry?: boolean;
180
+ store: string;
181
+ database: string;
182
+ collection: string;
183
+ enableTelemetry?: boolean;
181
184
  }
182
185
  declare class IndexedDBPersistence<T> implements SimplePersistence<T> {
183
- private collection;
184
- private collectionPromise;
185
- private config;
186
- private eventBus;
187
- private initialized;
188
- private _initializing;
189
- private initializationCallbacks;
190
- private doc;
191
- private getStoreName;
192
- constructor(config: StoreConfig<T> & IndexedDBPersistenceConfig);
193
- private initialize;
194
- private _onInitialized;
195
- private getCollection;
196
- /**
197
- * Writes state. Waits for initialisation (migration) to complete first.
198
- */
199
- set(id: string, state: T): Promise<boolean>;
200
- private _read;
201
- /**
202
- * Returns the stored document data (after ensuring it has been
203
- * fully read from the underlying store). The `document.read()`
204
- * call populates internal state and we then return the document
205
- * itself which has all fields available.
206
- */
207
- private _get;
208
- get(): Promise<T | null>;
209
- subscribe(id: string, callback: (state: T) => void): () => void;
210
- clear(): Promise<boolean>;
211
- stats(): {
212
- version: string;
213
- id: string;
214
- };
215
- /**
216
- * Closes this persistence instance, releasing our reference on the
217
- * shared database. The actual database connection is closed only
218
- * when every active store has been released.
219
- */
220
- close(): Promise<void>;
186
+ private collection;
187
+ private collectionPromise;
188
+ private config;
189
+ private eventBus;
190
+ private initialized;
191
+ private _initializing;
192
+ private initializationCallbacks;
193
+ private doc;
194
+ private getStoreName;
195
+ constructor(config: StoreConfig<T> & IndexedDBPersistenceConfig);
196
+ private initialize;
197
+ private _onInitialized;
198
+ private getCollection;
199
+ /**
200
+ * Writes state. Waits for initialisation (migration) to complete first.
201
+ */
202
+ set(id: string, state: T): Promise<boolean>;
203
+ private _read;
204
+ /**
205
+ * Returns the stored document data (after ensuring it has been
206
+ * fully read from the underlying store). The `document.read()`
207
+ * call populates internal state and we then return the document
208
+ * itself which has all fields available.
209
+ */
210
+ private _get;
211
+ get(): Promise<T | null>;
212
+ subscribe(id: string, callback: (state: T) => void): () => void;
213
+ clear(): Promise<boolean>;
214
+ stats(): {
215
+ version: string;
216
+ id: string;
217
+ };
218
+ /**
219
+ * Closes this persistence instance, releasing our reference on the
220
+ * shared database. The actual database connection is closed only
221
+ * when every active store has been released.
222
+ */
223
+ close(): Promise<void>;
221
224
  }
222
-
225
+ //#endregion
226
+ //#region src/persistence/ephemeral.d.ts
223
227
  /**
224
228
  * Implements SimplePersistence using an in-memory store.
225
229
  * Data is NOT persisted across page loads or application restarts.
@@ -236,65 +240,65 @@ declare class IndexedDBPersistence<T> implements SimplePersistence<T> {
236
240
  * SimplePersistence is required.
237
241
  */
238
242
  declare class EphemeralPersistence<T> implements SimplePersistence<T> {
239
- private readonly eventBus;
240
- private inMemoryState;
241
- private readonly config;
242
- /**
243
- * Initializes a new instance of EphemeralPersistence.
244
- * @param config Configuration object for the persistence adapter.
245
- */
246
- constructor(config: StoreConfig<T> & {
247
- storageKey: string;
248
- });
249
- /**
250
- * Initializes the event bus with configured settings for cross-tab communication.
251
- * @returns Configured event bus instance.
252
- */
253
- private initializeEventBus;
254
- /**
255
- * Sets up an internal listener to synchronize the in-memory state
256
- * using the Last Write Wins (LWW) strategy.
257
- */
258
- private setupLwwSynchronizationListener;
259
- /**
260
- * Persists the provided state to in-memory storage and notifies all subscribers
261
- * across tabs. The state is synchronized using LWW.
262
- * @param instanceId Unique identifier of the instance making the update.
263
- * @param state The state to persist.
264
- * @returns True if successful, false if an error occurs.
265
- */
266
- set(instanceId: string, state: T): boolean;
267
- /**
268
- * Retrieves the current synchronized state from in-memory storage.
269
- * @returns The synchronized state, or null if not set or if cleared.
270
- */
271
- get(): T | null;
272
- /**
273
- * Subscribes to updates in the in-memory state.
274
- * The callback is invoked when the state is updated by any instance
275
- * (including other tabs) *excluding the subscribing instance's own 'set' or 'clear' calls*.
276
- * @param instanceId Unique identifier of the subscribing instance.
277
- * @param onStateChange Callback to invoke with the updated state.
278
- * @returns Function to unsubscribe from updates.
279
- */
280
- subscribe(instanceId: string, onStateChange: (state: T) => void): () => void;
281
- /**
282
- * Clears the in-memory state of this instance and synchronizes this clear
283
- * across all tabs using the LWW strategy.
284
- * @returns True if successful, false if an error occurs.
285
- */
286
- clear(): boolean;
287
- /**
288
- * Returns metadata about the persistence layer.
289
- *
290
- * @returns An object containing:
291
- * - `version`: The semantic version string of the persistence schema or application.
292
- * - `id`: A unique identifier for the application using this persistence instance.
293
- */
294
- stats(): {
295
- version: string;
296
- id: string;
297
- };
243
+ private readonly eventBus;
244
+ private inMemoryState;
245
+ private readonly config;
246
+ /**
247
+ * Initializes a new instance of EphemeralPersistence.
248
+ * @param config Configuration object for the persistence adapter.
249
+ */
250
+ constructor(config: StoreConfig<T> & {
251
+ storageKey: string;
252
+ });
253
+ /**
254
+ * Initializes the event bus with configured settings for cross-tab communication.
255
+ * @returns Configured event bus instance.
256
+ */
257
+ private initializeEventBus;
258
+ /**
259
+ * Sets up an internal listener to synchronize the in-memory state
260
+ * using the Last Write Wins (LWW) strategy.
261
+ */
262
+ private setupLwwSynchronizationListener;
263
+ /**
264
+ * Persists the provided state to in-memory storage and notifies all subscribers
265
+ * across tabs. The state is synchronized using LWW.
266
+ * @param instanceId Unique identifier of the instance making the update.
267
+ * @param state The state to persist.
268
+ * @returns True if successful, false if an error occurs.
269
+ */
270
+ set(instanceId: string, state: T): boolean;
271
+ /**
272
+ * Retrieves the current synchronized state from in-memory storage.
273
+ * @returns The synchronized state, or null if not set or if cleared.
274
+ */
275
+ get(): T | null;
276
+ /**
277
+ * Subscribes to updates in the in-memory state.
278
+ * The callback is invoked when the state is updated by any instance
279
+ * (including other tabs) *excluding the subscribing instance's own 'set' or 'clear' calls*.
280
+ * @param instanceId Unique identifier of the subscribing instance.
281
+ * @param onStateChange Callback to invoke with the updated state.
282
+ * @returns Function to unsubscribe from updates.
283
+ */
284
+ subscribe(instanceId: string, onStateChange: (state: T) => void): () => void;
285
+ /**
286
+ * Clears the in-memory state of this instance and synchronizes this clear
287
+ * across all tabs using the LWW strategy.
288
+ * @returns True if successful, false if an error occurs.
289
+ */
290
+ clear(): boolean;
291
+ /**
292
+ * Returns metadata about the persistence layer.
293
+ *
294
+ * @returns An object containing:
295
+ * - `version`: The semantic version string of the persistence schema or application.
296
+ * - `id`: A unique identifier for the application using this persistence instance.
297
+ */
298
+ stats(): {
299
+ version: string;
300
+ id: string;
301
+ };
298
302
  }
299
-
300
- export { EphemeralPersistence, IndexedDBPersistence, type IndexedDBPersistenceConfig, type SimplePersistence, type StorageEvents, type StoreConfig, WebStoragePersistence, type WebStoragePersistenceConfig };
303
+ //#endregion
304
+ export { EphemeralPersistence, IndexedDBPersistence, IndexedDBPersistenceConfig, SimplePersistence, StorageEvents, StoreConfig, WebStoragePersistence, WebStoragePersistenceConfig };