@asaidimu/utils-remote-store 1.3.11 → 1.3.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,234 +1,191 @@
1
- interface SimplePersistence<T> {
2
- /**
3
- * Persists data to storage.
4
- *
5
- * @param id The **unique identifier of the *consumer instance*** making the change. This is NOT the ID of the data (`T`) itself.
6
- * Think of it as the ID of the specific browser tab, component, or module that's currently interacting with the persistence layer.
7
- * It should typically be a **UUID** generated once at the consumer instance's instantiation.
8
- * 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.
9
- * @param state The state (of type T) to persist. This state is generally considered the **global or shared state** that all instances interact with.
10
- * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations (like `IndexedDBPersistence`), this returns a `Promise<boolean>`.
11
- */
12
- set(id: string, state: T): boolean | Promise<boolean>;
13
- /**
14
- * Retrieves the global persisted data from storage.
15
- *
16
- * @returns The retrieved state of type `T`, or `null` if no data is found or if an error occurs during retrieval/parsing.
17
- * For asynchronous implementations, this returns a `Promise<T | null>`.
18
- */
19
- get(): (T | null) | Promise<T | null>;
20
- /**
21
- * 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).
22
- *
23
- * @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.
24
- * @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.
25
- * @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.
26
- */
27
- subscribe(id: string, callback: (state: T) => void): () => void;
28
- /**
29
- * Clears (removes) the entire global persisted data from storage.
30
- *
31
- * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations, this returns a `Promise<boolean>`.
32
- */
33
- clear(): boolean | Promise<boolean>;
34
- /**
35
- * Returns metadata about the persistence layer.
36
- *
37
- * This is useful for distinguishing between multiple apps running on the same host
38
- * (e.g., several apps served at `localhost:3000` that share the same storage key).
39
- *
40
- * @returns An object containing:
41
- * - `version`: The semantic version string of the persistence schema or application.
42
- * - `id`: A unique identifier for the application using this persistence instance.
43
- */
44
- stats(): {
45
- version: string;
46
- id: string;
47
- };
48
- }
1
+ import { SimplePersistence } from "@asaidimu/utils-persistence";
49
2
 
3
+ //#region src/cache/types.d.ts
50
4
  interface CacheOptions {
51
- staleTime?: number;
52
- cacheTime?: number;
53
- retryAttempts?: number;
54
- retryDelay?: number;
55
- maxSize?: number;
56
- enableMetrics?: boolean;
57
- persistence?: SimplePersistence<SerializableCacheState>;
58
- persistenceId?: string;
59
- serializeValue?: (value: any) => any;
60
- deserializeValue?: (value: any) => any;
61
- persistenceDebounceTime?: number;
5
+ staleTime?: number;
6
+ cacheTime?: number;
7
+ retryAttempts?: number;
8
+ retryDelay?: number;
9
+ maxSize?: number;
10
+ enableMetrics?: boolean;
11
+ persistence?: SimplePersistence<SerializableCacheState>;
12
+ persistenceId?: string;
13
+ serializeValue?: (value: any) => any;
14
+ deserializeValue?: (value: any) => any;
15
+ persistenceDebounceTime?: number;
62
16
  }
63
17
  interface CacheMetrics {
64
- hits: number;
65
- misses: number;
66
- fetches: number;
67
- errors: number;
68
- evictions: number;
69
- staleHits: number;
18
+ hits: number;
19
+ misses: number;
20
+ fetches: number;
21
+ errors: number;
22
+ evictions: number;
23
+ staleHits: number;
70
24
  }
71
25
  interface SerializableCacheEntry {
72
- data: any;
73
- lastUpdated: number;
74
- lastAccessed: number;
75
- accessCount: number;
76
- error?: {
77
- name: string;
78
- message: string;
79
- stack?: string;
80
- };
26
+ data: any;
27
+ lastUpdated: number;
28
+ lastAccessed: number;
29
+ accessCount: number;
30
+ error?: {
31
+ name: string;
32
+ message: string;
33
+ stack?: string;
34
+ };
81
35
  }
82
36
  type SerializableCacheState = Array<[string, SerializableCacheEntry]>;
83
37
  type CacheEventBase<Type extends string, Payload = {}> = {
84
- type: Type;
85
- key: string;
86
- timestamp: number;
38
+ type: Type;
39
+ key: string;
40
+ timestamp: number;
87
41
  } & Payload;
88
42
  type CacheReadHitEvent<T = any> = CacheEventBase<"cache:read:hit", {
89
- data: T;
90
- isStale: boolean;
43
+ data: T;
44
+ isStale: boolean;
91
45
  }>;
92
46
  type CacheReadMissEvent = CacheEventBase<"cache:read:miss">;
93
47
  type CacheFetchStartEvent = CacheEventBase<"cache:fetch:start", {
94
- attempt: number;
48
+ attempt: number;
95
49
  }>;
96
50
  type CacheFetchSuccessEvent<T = any> = CacheEventBase<"cache:fetch:success", {
97
- data: T;
51
+ data: T;
98
52
  }>;
99
53
  type CacheFetchErrorEvent = CacheEventBase<"cache:fetch:error", {
100
- error: Error;
101
- attempt: number;
54
+ error: Error;
55
+ attempt: number;
102
56
  }>;
103
57
  type CacheDataEvictEvent = CacheEventBase<"cache:data:evict", {
104
- reason?: string;
58
+ reason?: string;
105
59
  }>;
106
60
  type CacheDataInvalidateEvent = CacheEventBase<"cache:data:invalidate">;
107
61
  type CacheDataSetEvent<T = any> = CacheEventBase<"cache:data:set", {
108
- newData: T;
109
- oldData?: T;
62
+ newData: T;
63
+ oldData?: T;
110
64
  }>;
111
65
  type CachePersistenceLoadSuccessEvent = CacheEventBase<"cache:persistence:load:success", {
112
- message?: string;
66
+ message?: string;
113
67
  }>;
114
68
  type CachePersistenceLoadErrorEvent = CacheEventBase<"cache:persistence:load:error", {
115
- message?: string;
116
- error?: any;
69
+ message?: string;
70
+ error?: any;
117
71
  }>;
118
72
  type CachePersistenceSaveSuccessEvent = CacheEventBase<"cache:persistence:save:success">;
119
73
  type CachePersistenceSaveErrorEvent = CacheEventBase<"cache:persistence:save:error", {
120
- message?: string;
121
- error?: any;
74
+ message?: string;
75
+ error?: any;
122
76
  }>;
123
77
  type CachePersistenceClearSuccessEvent = CacheEventBase<"cache:persistence:clear:success">;
124
78
  type CachePersistenceClearErrorEvent = CacheEventBase<"cache:persistence:clear:error", {
125
- message?: string;
126
- error?: any;
79
+ message?: string;
80
+ error?: any;
127
81
  }>;
128
82
  type CachePersistenceSyncEvent = CacheEventBase<"cache:persistence:sync", {
129
- message?: string;
83
+ message?: string;
130
84
  }>;
131
85
  type CacheEvent = CacheReadHitEvent | CacheReadMissEvent | CacheFetchStartEvent | CacheFetchSuccessEvent | CacheFetchErrorEvent | CacheDataEvictEvent | CacheDataInvalidateEvent | CacheDataSetEvent | CachePersistenceLoadSuccessEvent | CachePersistenceLoadErrorEvent | CachePersistenceSaveSuccessEvent | CachePersistenceSaveErrorEvent | CachePersistenceClearSuccessEvent | CachePersistenceClearErrorEvent | CachePersistenceSyncEvent;
132
86
  type CacheEventType = CacheEvent["type"];
133
-
87
+ //#endregion
88
+ //#region src/cache/cache.d.ts
134
89
  declare class QueryCache {
135
- private cache;
136
- private queries;
137
- private fetching;
138
- private readonly defaultOptions;
139
- private metrics;
140
- private eventBus;
141
- private gcTimer?;
142
- private readonly persistenceId;
143
- private persistenceUnsubscribe?;
144
- private persistenceDebounceTimer?;
145
- private isHandlingRemoteUpdate;
146
- constructor(defaultOptions?: CacheOptions);
147
- private initializePersistence;
148
- private serializeCache;
149
- private deserializeAndLoadCache;
150
- private schedulePersistState;
151
- private handleRemoteStateChange;
152
- registerQuery<T>(key: string, fetchFunction: () => Promise<T>, options?: CacheOptions): void;
153
- get<T>(key: string, options?: {
154
- waitForFresh?: boolean;
155
- throwOnError?: boolean;
156
- }): Promise<T | undefined>;
157
- peek<T>(key: string): T | undefined;
158
- has(key: string): boolean;
159
- private fetch;
160
- private fetchAndWait;
161
- private performFetchWithRetry;
162
- private isStale;
163
- invalidate(key: string, refetch?: boolean): Promise<void>;
164
- invalidatePattern(pattern: RegExp, refetch?: boolean): Promise<void>;
165
- prefetch(key: string): Promise<void>;
166
- refresh<T>(key: string): Promise<T | undefined>;
167
- setData<T>(key: string, data: T): void;
168
- remove(key: string): boolean;
169
- private enforceSizeLimit;
170
- private startGarbageCollection;
171
- garbageCollect(): number;
172
- getStats(): {
173
- size: number;
174
- metrics: CacheMetrics;
175
- hitRate: number;
176
- staleHitRate: number;
177
- entries: Array<{
178
- key: string;
179
- lastAccessed: number;
180
- lastUpdated: number;
181
- accessCount: number;
182
- isStale: boolean;
183
- isLoading?: boolean;
184
- error?: boolean;
185
- }>;
186
- };
187
- on<EType extends CacheEventType>(event: EType, listener: (ev: Extract<CacheEvent, {
188
- type: EType;
189
- }>) => void): () => void;
190
- private emitEvent;
191
- private updateMetrics;
192
- private delay;
193
- clear(): Promise<void>;
194
- destroy(): void;
90
+ private cache;
91
+ private queries;
92
+ private fetching;
93
+ private readonly defaultOptions;
94
+ private metrics;
95
+ private eventBus;
96
+ private gcTimer?;
97
+ private readonly persistenceId;
98
+ private persistenceUnsubscribe?;
99
+ private persistenceDebounceTimer?;
100
+ private isHandlingRemoteUpdate;
101
+ constructor(defaultOptions?: CacheOptions);
102
+ private initializePersistence;
103
+ private serializeCache;
104
+ private deserializeAndLoadCache;
105
+ private schedulePersistState;
106
+ private handleRemoteStateChange;
107
+ registerQuery<T>(key: string, fetchFunction: () => Promise<T>, options?: CacheOptions): void;
108
+ get<T>(key: string, options?: {
109
+ waitForFresh?: boolean;
110
+ throwOnError?: boolean;
111
+ }): Promise<T | undefined>;
112
+ peek<T>(key: string): T | undefined;
113
+ has(key: string): boolean;
114
+ private fetch;
115
+ private fetchAndWait;
116
+ private performFetchWithRetry;
117
+ private isStale;
118
+ invalidate(key: string, refetch?: boolean): Promise<void>;
119
+ invalidatePattern(pattern: RegExp, refetch?: boolean): Promise<void>;
120
+ prefetch(key: string): Promise<void>;
121
+ refresh<T>(key: string): Promise<T | undefined>;
122
+ setData<T>(key: string, data: T): void;
123
+ remove(key: string): boolean;
124
+ private enforceSizeLimit;
125
+ private startGarbageCollection;
126
+ garbageCollect(): number;
127
+ getStats(): {
128
+ size: number;
129
+ metrics: CacheMetrics;
130
+ hitRate: number;
131
+ staleHitRate: number;
132
+ entries: Array<{
133
+ key: string;
134
+ lastAccessed: number;
135
+ lastUpdated: number;
136
+ accessCount: number;
137
+ isStale: boolean;
138
+ isLoading?: boolean;
139
+ error?: boolean;
140
+ }>;
141
+ };
142
+ on<EType extends CacheEventType>(event: EType, listener: (ev: Extract<CacheEvent, {
143
+ type: EType;
144
+ }>) => void): () => void;
145
+ private emitEvent;
146
+ private updateMetrics;
147
+ private delay;
148
+ clear(): Promise<void>;
149
+ destroy(): void;
195
150
  }
196
-
151
+ //#endregion
152
+ //#region src/remote-store/error.d.ts
197
153
  interface StoreErrorDetails {
198
- code: string;
199
- message: string;
200
- status?: number;
201
- data?: unknown;
202
- isRetryable: boolean;
154
+ code: string;
155
+ message: string;
156
+ status?: number;
157
+ data?: unknown;
158
+ isRetryable: boolean;
203
159
  }
204
160
  declare class StoreError extends Error {
205
- readonly code: string;
206
- readonly status?: number;
207
- readonly data?: unknown;
208
- readonly isRetryable: boolean;
209
- readonly originalError?: Error;
210
- constructor(details: StoreErrorDetails, originalError?: Error);
211
- static fromError(error: any, operation: string): StoreError;
161
+ readonly code: string;
162
+ readonly status?: number;
163
+ readonly data?: unknown;
164
+ readonly isRetryable: boolean;
165
+ readonly originalError?: Error;
166
+ constructor(details: StoreErrorDetails, originalError?: Error);
167
+ static fromError(error: any, operation: string): StoreError;
212
168
  }
213
-
169
+ //#endregion
170
+ //#region src/remote-store/types.d.ts
214
171
  /**
215
172
  * Represents a paginated response containing a list of records and pagination details.
216
173
  * @template T The type of the records in the page.
217
174
  */
218
175
  interface Page<T> {
219
- /** The array of records for the current page. */
220
- data: T[];
221
- /** Pagination metadata. */
222
- page: PaginationInfo;
176
+ /** The array of records for the current page. */
177
+ data: T[];
178
+ /** Pagination metadata. */
179
+ page: PaginationInfo;
223
180
  }
224
181
  /**
225
182
  * Represents an event emitted by the store, typically for notifications or state changes.
226
183
  */
227
184
  interface StoreEvent {
228
- /** The scope of the event, indicating its type and context. Custom scopes are allowed. */
229
- scope: string;
230
- /** Optional payload carrying data related to the event. */
231
- payload?: any;
185
+ /** The scope of the event, indicating its type and context. Custom scopes are allowed. */
186
+ scope: string;
187
+ /** Optional payload carrying data related to the event. */
188
+ payload?: any;
232
189
  }
233
190
  /**
234
191
  * Defines the types of mutation operations that can occur.
@@ -242,8 +199,8 @@ type MutationOperation = "create" | "update" | "delete" | "upload";
242
199
  * @returns An array of query keys to be invalidated.
243
200
  */
244
201
  type Correlator = (mutation: {
245
- operation: MutationOperation;
246
- params: any;
202
+ operation: MutationOperation;
203
+ params: any;
247
204
  }, activeQueries: ActiveQuery[]) => string[];
248
205
  /**
249
206
  * A correlator function that determines which active queries should be invalidated
@@ -266,141 +223,138 @@ type StoreEventCorrelator = (event: StoreEvent, activeQueries: ActiveQuery[]) =>
266
223
  * @template TStreamOptions Options for the stream operation.
267
224
  */
268
225
  interface BaseStore<T extends StoreRecord, TFindOptions = Record<string, unknown>, TReadOptions = Record<string, unknown>, TListOptions = Record<string, unknown>, TDeleteOptions = Record<string, unknown>, TUpdateOptions = Record<string, unknown>, TCreateOptions = Record<string, unknown>, TUploadOptions = Record<string, unknown>, TStreamOptions = Record<string, unknown>> {
269
- /**
270
- * Finds records based on provided options, returning a paginated result.
271
- * @param options The options for the find operation.
272
- * @returns A promise that resolves to a Page of records.
273
- */
274
- find: (options: TFindOptions) => Promise<Page<T>>;
275
- /**
276
- * Reads a single record by its identifier or other read options.
277
- * @param options The options for the read operation, typically including an ID.
278
- * @returns A promise that resolves to the record or undefined if not found.
279
- */
280
- read: (options: TReadOptions) => Promise<T | undefined>;
281
- /**
282
- * Lists records based on provided options, returning a paginated result.
283
- * @param options The options for the list operation.
284
- * @returns A promise that resolves to a Page of records.
285
- */
286
- list: (options: TListOptions) => Promise<Page<T>>;
287
- /**
288
- * Deletes a record based on provided options, typically including an ID.
289
- * @param options The options for the delete operation.
290
- * @returns A promise that resolves when the deletion is complete.
291
- */
292
- delete: (options: TDeleteOptions) => Promise<void>;
293
- /**
294
- * Updates an existing record.
295
- * @param props An object containing the ID of the record to update, the partial data, and optional update options.
296
- * @returns A promise that resolves to the updated record or undefined if not found.
297
- */
298
- update: (props: {
299
- data: Partial<T>;
300
- options?: TUpdateOptions;
301
- }) => Promise<T | undefined>;
302
- /**
303
- * Creates a new record.
304
- * @param props An object containing the data for the new record and optional create options.
305
- * @returns A promise that resolves to the newly created record or undefined if creation failed.
306
- */
307
- create: (props: {
308
- data: Partial<T>;
309
- options?: TCreateOptions;
310
- }) => Promise<T | undefined>;
311
- /**
312
- * Uploads a file associated with a record. Optionally updates the record with upload details.
313
- * @param props An object containing the file to upload and optional upload options.
314
- * @returns A promise that resolves to the updated record after upload or undefined if upload failed.
315
- */
316
- upload: (props: {
317
- file: File;
318
- options?: TUploadOptions;
319
- }) => Promise<T | undefined>;
320
- /**
321
- * Subscribes to store events for a given scope.
322
- * @param scope The event scope to subscribe to (e.g., 'todos:created:success', '*').
323
- * @param callback The function to call when an event matching the scope is received.
324
- * @returns A promise that resolves to an unsubscribe function. Call this function to stop receiving events.
325
- */
326
- subscribe(scope: string, callback: (event: StoreEvent) => void): Promise<() => void>;
327
- /**
328
- * Notifies the store of an event, which can then be broadcast to subscribers.
329
- * @param event The StoreEvent to notify.
330
- * @returns A promise that resolves when the notification has been processed.
331
- */
332
- notify: (event: StoreEvent) => Promise<void>;
333
- /**
334
- * Establishes a stream of records based on provided options.
335
- * @param options Options for configuring the stream (e.g., batch size, delay, filters).
336
- * @param onStreamChange A callback function that is called when the stream's status changes.
337
- * @returns An object containing the async iterable stream, a cancel function, and a status getter.
338
- */
339
- stream: (options: TStreamOptions, onStreamChange: () => void) => {
340
- /** An async iterable that yields records as they become available in the stream. */
341
- stream: () => AsyncIterable<T>;
342
- /** A function to call to cancel the ongoing stream. */
343
- cancel: () => void;
344
- /** A getter function that returns the current status of the stream ('active', 'cancelled', or 'completed'). */
345
- status: () => "active" | "cancelled" | "completed";
346
- };
226
+ /**
227
+ * Finds records based on provided options, returning a paginated result.
228
+ * @param options The options for the find operation.
229
+ * @returns A promise that resolves to a Page of records.
230
+ */
231
+ find: (options: TFindOptions) => Promise<Page<T>>;
232
+ /**
233
+ * Reads a single record by its identifier or other read options.
234
+ * @param options The options for the read operation, typically including an ID.
235
+ * @returns A promise that resolves to the record or undefined if not found.
236
+ */
237
+ read: (options: TReadOptions) => Promise<T | undefined>;
238
+ /**
239
+ * Lists records based on provided options, returning a paginated result.
240
+ * @param options The options for the list operation.
241
+ * @returns A promise that resolves to a Page of records.
242
+ */
243
+ list: (options: TListOptions) => Promise<Page<T>>;
244
+ /**
245
+ * Deletes a record based on provided options, typically including an ID.
246
+ * @param options The options for the delete operation.
247
+ * @returns A promise that resolves when the deletion is complete.
248
+ */
249
+ delete: (options: TDeleteOptions) => Promise<void>;
250
+ /**
251
+ * Updates an existing record.
252
+ * @param props An object containing the ID of the record to update, the partial data, and optional update options.
253
+ * @returns A promise that resolves to the updated record or undefined if not found.
254
+ */
255
+ update: (props: {
256
+ data: Partial<T>;
257
+ options?: TUpdateOptions;
258
+ }) => Promise<T | undefined>;
259
+ /**
260
+ * Creates a new record.
261
+ * @param props An object containing the data for the new record and optional create options.
262
+ * @returns A promise that resolves to the newly created record or undefined if creation failed.
263
+ */
264
+ create: (props: {
265
+ data: Partial<T>;
266
+ options?: TCreateOptions;
267
+ }) => Promise<T | undefined>;
268
+ /**
269
+ * Uploads a file associated with a record. Optionally updates the record with upload details.
270
+ * @param props An object containing the file to upload and optional upload options.
271
+ * @returns A promise that resolves to the updated record after upload or undefined if upload failed.
272
+ */
273
+ upload: (props: {
274
+ file: File;
275
+ options?: TUploadOptions;
276
+ }) => Promise<T | undefined>;
277
+ /**
278
+ * Subscribes to store events for a given scope.
279
+ * @param scope The event scope to subscribe to (e.g., 'todos:created:success', '*').
280
+ * @param callback The function to call when an event matching the scope is received.
281
+ * @returns A promise that resolves to an unsubscribe function. Call this function to stop receiving events.
282
+ */
283
+ subscribe(scope: string, callback: (event: StoreEvent) => void): Promise<() => void>;
284
+ /**
285
+ * Notifies the store of an event, which can then be broadcast to subscribers.
286
+ * @param event The StoreEvent to notify.
287
+ * @returns A promise that resolves when the notification has been processed.
288
+ */
289
+ notify: (event: StoreEvent) => Promise<void>;
290
+ /**
291
+ * Establishes a stream of records based on provided options.
292
+ * @param options Options for configuring the stream (e.g., batch size, delay, filters).
293
+ * @param onStreamChange A callback function that is called when the stream's status changes.
294
+ * @returns An object containing the async iterable stream, a cancel function, and a status getter.
295
+ */
296
+ stream: (options: TStreamOptions, onStreamChange: () => void) => {
297
+ /** An async iterable that yields records as they become available in the stream. */stream: () => AsyncIterable<T>; /** A function to call to cancel the ongoing stream. */
298
+ cancel: () => void; /** A getter function that returns the current status of the stream ('active', 'cancelled', or 'completed'). */
299
+ status: () => "active" | "cancelled" | "completed";
300
+ };
347
301
  }
348
302
  /**
349
303
  * Represents an active query in the cache, used for invalidation correlation.
350
304
  */
351
305
  interface ActiveQuery {
352
- /** The unique key identifying the query in the cache. */
353
- queryKey: string;
354
- /** The type of operation this query represents (e.g., 'read', 'list', 'find'). */
355
- operation: string;
356
- /** The parameters used to make this query. */
357
- params: any;
306
+ /** The unique key identifying the query in the cache. */
307
+ queryKey: string;
308
+ /** The type of operation this query represents (e.g., 'read', 'list', 'find'). */
309
+ operation: string;
310
+ /** The parameters used to make this query. */
311
+ params: any;
358
312
  }
359
313
  /**
360
314
  * Represents the result of a single record query.
361
315
  * @template T The type of the data being queried.
362
316
  */
363
317
  interface QueryResult<T> {
364
- /** The data returned by the query, or undefined if not found or still loading. */
365
- data: T | undefined;
366
- /** Indicates if the query is currently loading data. */
367
- loading: boolean;
368
- /** An error object if the query failed, otherwise undefined. */
369
- error: Error | undefined;
370
- /** Indicates if the cached data is stale and a refetch is needed. */
371
- stale: boolean;
372
- /** Timestamp of the last update to the data. */
373
- updated: number;
318
+ /** The data returned by the query, or undefined if not found or still loading. */
319
+ data: T | undefined;
320
+ /** Indicates if the query is currently loading data. */
321
+ loading: boolean;
322
+ /** An error object if the query failed, otherwise undefined. */
323
+ error: Error | undefined;
324
+ /** Indicates if the cached data is stale and a refetch is needed. */
325
+ stale: boolean;
326
+ /** Timestamp of the last update to the data. */
327
+ updated: number;
374
328
  }
375
329
  /**
376
330
  * Represents the result of a paginated query (list or find).
377
331
  * @template T The type of the records in the page.
378
332
  */
379
333
  interface PagedQueryResult<T> {
380
- /** The paginated data, or undefined if not found or still loading. */
381
- page: Page<T> | undefined;
382
- /** Indicates if the query is currently loading data. */
383
- loading: boolean;
384
- /** An error object if the query failed, otherwise undefined. */
385
- error: StoreError | undefined;
386
- /** Indicates if the cached data is stale and a refetch is needed. */
387
- stale: boolean;
388
- /** Timestamp of the last update to the data. */
389
- updated: number;
390
- /** True if there is a next page, false otherwise. */
391
- hasNext: boolean;
392
- /** True if there is a previous page, false otherwise. */
393
- hasPrevious: boolean;
394
- /** Function to fetch the next page of data. */
395
- next: () => Promise<void>;
396
- /** Function to fetch the previous page of data. */
397
- previous: () => Promise<void>;
398
- /** Function to fetch a specific page of data.
399
- * @param page The page number to fetch.
400
- */
401
- navigate: (page: number) => Promise<void>;
402
- refresh: (delay?: number) => Promise<void>;
403
- changeParams: (setter: (params: any) => any) => Promise<void>;
334
+ /** The paginated data, or undefined if not found or still loading. */
335
+ page: Page<T> | undefined;
336
+ /** Indicates if the query is currently loading data. */
337
+ loading: boolean;
338
+ /** An error object if the query failed, otherwise undefined. */
339
+ error: StoreError | undefined;
340
+ /** Indicates if the cached data is stale and a refetch is needed. */
341
+ stale: boolean;
342
+ /** Timestamp of the last update to the data. */
343
+ updated: number;
344
+ /** True if there is a next page, false otherwise. */
345
+ hasNext: boolean;
346
+ /** True if there is a previous page, false otherwise. */
347
+ hasPrevious: boolean;
348
+ /** Function to fetch the next page of data. */
349
+ next: () => Promise<void>;
350
+ /** Function to fetch the previous page of data. */
351
+ previous: () => Promise<void>;
352
+ /** Function to fetch a specific page of data.
353
+ * @param page The page number to fetch.
354
+ */
355
+ navigate: (page: number) => Promise<void>;
356
+ refresh: (delay?: number) => Promise<void>;
357
+ changeParams: (setter: (params: any) => any) => Promise<void>;
404
358
  }
405
359
  /**
406
360
  * Represents a basic record in the remote store.
@@ -412,14 +366,10 @@ type StoreRecord<BaseProps extends Record<string, unknown> = Record<string, unkn
412
366
  * Provides pagination information for a collection of records.
413
367
  */
414
368
  type PaginationInfo = {
415
- /** The current page number (1-based). */
416
- number: number;
417
- /** The number of items per page. */
418
- size: number;
419
- /** The total count of items across all pages. */
420
- count: number;
421
- /** The total number of available pages. */
422
- pages: number;
369
+ /** The current page number (1-based). */number: number; /** The number of items per page. */
370
+ size: number; /** The total count of items across all pages. */
371
+ count: number; /** The total number of available pages. */
372
+ pages: number;
423
373
  };
424
374
  /**
425
375
  * Represents the name of a resource in the store, e.g., 'todos', 'users'.
@@ -430,31 +380,32 @@ type ResourceName = string;
430
380
  * @template T The type of the data being queried.
431
381
  */
432
382
  interface QuerySubscription<T> {
433
- /** Callbacks to unsubscribe from cache events. */
434
- unsubscribeCallbacks: (() => void)[];
435
- /** Set of functions to notify when the query data changes. */
436
- subscribers: Set<() => void>;
437
- /** A cached function to subscribe to changes for this query. */
438
- cachedSubscribe: (callback: () => void) => () => void;
439
- /** A cached selector function to get the current query result. */
440
- cachedSelector: () => QueryResult<T> | PagedQueryResult<T>;
441
- /** The operation type of the query (e.g., 'read', 'list'). */
442
- operation: string;
443
- /** The parameters for the query. */
444
- params: any;
445
- /** A stable reference to the operations results. */
446
- result: QueryResult<T> | PagedQueryResult<T>;
383
+ /** Callbacks to unsubscribe from cache events. */
384
+ unsubscribeCallbacks: (() => void)[];
385
+ /** Set of functions to notify when the query data changes. */
386
+ subscribers: Set<() => void>;
387
+ /** A cached function to subscribe to changes for this query. */
388
+ cachedSubscribe: (callback: () => void) => () => void;
389
+ /** A cached selector function to get the current query result. */
390
+ cachedSelector: () => QueryResult<T> | PagedQueryResult<T>;
391
+ /** The operation type of the query (e.g., 'read', 'list'). */
392
+ operation: string;
393
+ /** The parameters for the query. */
394
+ params: any;
395
+ /** A stable reference to the operations results. */
396
+ result: QueryResult<T> | PagedQueryResult<T>;
447
397
  }
448
-
398
+ //#endregion
399
+ //#region src/remote-store/store.d.ts
449
400
  /**
450
401
  * Represents the result of a store query with stable React integration.
451
402
  * @template T The type of the result data.
452
403
  */
453
404
  interface StoreResult<T extends Record<string, any> = Record<string, any>, V = QueryResult<T> | PagedQueryResult<T>> {
454
- /** Function that returns the current query state */
455
- value: () => V;
456
- /** Function to subscribe to state changes */
457
- onValueChange: (callback: () => void) => () => void;
405
+ /** Function that returns the current query state */
406
+ value: () => V;
407
+ /** Function to subscribe to state changes */
408
+ onValueChange: (callback: () => void) => () => void;
458
409
  }
459
410
  /**
460
411
  * A reactive remote store that provides cached and observable access to data
@@ -462,88 +413,89 @@ interface StoreResult<T extends Record<string, any> = Record<string, any>, V = Q
462
413
  * via server-sent events (SSE).
463
414
  */
464
415
  declare class ReactiveRemoteStore<T extends StoreRecord, TFindOptions = Record<string, unknown>, TReadOptions = Record<string, unknown>, TListOptions = Record<string, unknown>, TDeleteOptions = Record<string, unknown>, TUpdateOptions = Record<string, unknown>, TCreateOptions = Record<string, unknown>, TUploadOptions = Record<string, unknown>, TStreamOptions = Record<string, unknown>> {
465
- private cache;
466
- private baseStore;
467
- private correlator?;
468
- private storeEventCorrelator?;
469
- private queryStates;
470
- private stableResults;
471
- private stablePaginationMethods;
472
- private errorCache;
473
- private keyCache;
474
- private unsubscribeFromBaseStore;
475
- private cacheEventCleanups;
476
- constructor(cache: QueryCache, baseStore: BaseStore<T, TFindOptions, TReadOptions, TListOptions, TDeleteOptions, TUpdateOptions, TCreateOptions, TUploadOptions, TStreamOptions>, correlator?: Correlator | undefined, storeEventCorrelator?: StoreEventCorrelator | undefined);
477
- private setupCacheEventListeners;
478
- private handleCacheEvent;
479
- private buildKey;
480
- private getOrCreateError;
481
- private getOrCreateStoreError;
482
- private computeResult;
483
- private scheduleBackgroundFetch;
484
- private getCurrentPageForQuery;
485
- private getOrCreatePaginationMethods;
486
- private computeResultForParams;
487
- hasActiveQuery(operation: string, params: any): boolean;
488
- getActiveQuery<TResult extends Record<string, unknown> = T>(operation: string, params: any): StoreResult<TResult> | undefined;
489
- read(params: TReadOptions): StoreResult<T, QueryResult<T>>;
490
- list(params: TListOptions): StoreResult<T, PagedQueryResult<T>>;
491
- find(params: TFindOptions): StoreResult<T, PagedQueryResult<T>>;
492
- private setupPagedQuery;
493
- private invalidateQueries;
494
- private handleStoreEvent;
495
- create(params: {
496
- data: Partial<T>;
497
- options?: TCreateOptions;
498
- }): Promise<T | undefined>;
499
- update(params: {
500
- data: Partial<T>;
501
- options?: TUpdateOptions;
502
- }): Promise<T | undefined>;
503
- delete(params: TDeleteOptions): Promise<void>;
504
- notify(event: StoreEvent): Promise<void>;
505
- stream(options: TStreamOptions, onStreamChange: () => void): {
506
- stream: () => AsyncIterable<T>;
507
- cancel: () => void;
508
- status: () => "active" | "cancelled" | "completed";
509
- };
510
- subscribe(scope: string, callback: (event: StoreEvent) => void): Promise<() => void>;
511
- upload(params: {
512
- file: File;
513
- options?: TUploadOptions;
514
- }): Promise<T | undefined>;
515
- refresh(operation: "read", params: TReadOptions): Promise<T | undefined>;
516
- refresh(operation: "list", params: TListOptions): Promise<Page<T> | undefined>;
517
- refresh(operation: "find", query: TFindOptions): Promise<Page<T> | undefined>;
518
- prefetch(operation: "read", params: TReadOptions): void;
519
- prefetch(operation: "list", params: TListOptions): void;
520
- prefetch(operation: "find", params: TFindOptions): void;
521
- invalidate(operation: string, params: any): Promise<void>;
522
- invalidateAll(): Promise<void>;
523
- getStats(): {
524
- activeSubscriptions: number;
525
- size: number;
526
- metrics: CacheMetrics;
527
- hitRate: number;
528
- staleHitRate: number;
529
- entries: Array<{
530
- key: string;
531
- lastAccessed: number;
532
- lastUpdated: number;
533
- accessCount: number;
534
- isStale: boolean;
535
- isLoading?: boolean;
536
- error?: boolean;
537
- }>;
538
- };
539
- destroy(): void;
416
+ private cache;
417
+ private baseStore;
418
+ private correlator?;
419
+ private storeEventCorrelator?;
420
+ private queryStates;
421
+ private stableResults;
422
+ private stablePaginationMethods;
423
+ private errorCache;
424
+ private keyCache;
425
+ private unsubscribeFromBaseStore;
426
+ private cacheEventCleanups;
427
+ constructor(cache: QueryCache, baseStore: BaseStore<T, TFindOptions, TReadOptions, TListOptions, TDeleteOptions, TUpdateOptions, TCreateOptions, TUploadOptions, TStreamOptions>, correlator?: Correlator | undefined, storeEventCorrelator?: StoreEventCorrelator | undefined);
428
+ private setupCacheEventListeners;
429
+ private handleCacheEvent;
430
+ private buildKey;
431
+ private getOrCreateError;
432
+ private getOrCreateStoreError;
433
+ private computeResult;
434
+ private scheduleBackgroundFetch;
435
+ private getCurrentPageForQuery;
436
+ private getOrCreatePaginationMethods;
437
+ private computeResultForParams;
438
+ hasActiveQuery(operation: string, params: any): boolean;
439
+ getActiveQuery<TResult extends Record<string, unknown> = T>(operation: string, params: any): StoreResult<TResult> | undefined;
440
+ read(params: TReadOptions): StoreResult<T, QueryResult<T>>;
441
+ list(params: TListOptions): StoreResult<T, PagedQueryResult<T>>;
442
+ find(params: TFindOptions): StoreResult<T, PagedQueryResult<T>>;
443
+ private setupPagedQuery;
444
+ private invalidateQueries;
445
+ private handleStoreEvent;
446
+ create(params: {
447
+ data: Partial<T>;
448
+ options?: TCreateOptions;
449
+ }): Promise<T | undefined>;
450
+ update(params: {
451
+ data: Partial<T>;
452
+ options?: TUpdateOptions;
453
+ }): Promise<T | undefined>;
454
+ delete(params: TDeleteOptions): Promise<void>;
455
+ notify(event: StoreEvent): Promise<void>;
456
+ stream(options: TStreamOptions, onStreamChange: () => void): {
457
+ stream: () => AsyncIterable<T>;
458
+ cancel: () => void;
459
+ status: () => "active" | "cancelled" | "completed";
460
+ };
461
+ subscribe(scope: string, callback: (event: StoreEvent) => void): Promise<() => void>;
462
+ upload(params: {
463
+ file: File;
464
+ options?: TUploadOptions;
465
+ }): Promise<T | undefined>;
466
+ refresh(operation: "read", params: TReadOptions): Promise<T | undefined>;
467
+ refresh(operation: "list", params: TListOptions): Promise<Page<T> | undefined>;
468
+ refresh(operation: "find", query: TFindOptions): Promise<Page<T> | undefined>;
469
+ prefetch(operation: "read", params: TReadOptions): void;
470
+ prefetch(operation: "list", params: TListOptions): void;
471
+ prefetch(operation: "find", params: TFindOptions): void;
472
+ invalidate(operation: string, params: any): Promise<void>;
473
+ invalidateAll(): Promise<void>;
474
+ getStats(): {
475
+ activeSubscriptions: number;
476
+ size: number;
477
+ metrics: CacheMetrics;
478
+ hitRate: number;
479
+ staleHitRate: number;
480
+ entries: Array<{
481
+ key: string;
482
+ lastAccessed: number;
483
+ lastUpdated: number;
484
+ accessCount: number;
485
+ isStale: boolean;
486
+ isLoading?: boolean;
487
+ error?: boolean;
488
+ }>;
489
+ };
490
+ destroy(): void;
540
491
  }
541
-
492
+ //#endregion
493
+ //#region src/remote-store/hash.d.ts
542
494
  /**
543
495
  * Computes the FNV-1a 64-bit hash of the given data.
544
496
  * @param {any} data - The data to hash. Can be any type that can be serialized.
545
497
  * @returns {string} The FNV-1a 64-bit hash as a hexadecimal string.
546
498
  */
547
499
  declare function hash(data: any): string;
548
-
549
- export { type ActiveQuery, type BaseStore, type Correlator, type MutationOperation, type Page, type PagedQueryResult, type PaginationInfo, type QueryResult, type QuerySubscription, ReactiveRemoteStore, type ResourceName, StoreError, type StoreErrorDetails, type StoreEvent, type StoreEventCorrelator, type StoreRecord, type StoreResult, hash };
500
+ //#endregion
501
+ export { ActiveQuery, BaseStore, Correlator, MutationOperation, Page, PagedQueryResult, PaginationInfo, QueryResult, QuerySubscription, ReactiveRemoteStore, ResourceName, StoreError, StoreErrorDetails, StoreEvent, StoreEventCorrelator, StoreRecord, StoreResult, hash };