@signaldb/localstorage 2.0.0-beta.6 → 2.0.0-beta.7
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/dist/base/core/src/AsyncDataAdapter.d.ts +64 -0
- package/dist/base/core/src/AutoFetchDataAdapter.d.ts +112 -0
- package/dist/base/core/src/Collection/Cursor.d.ts +113 -0
- package/dist/base/core/src/Collection/Observer.d.ts +64 -0
- package/dist/base/core/src/Collection/index.d.ts +294 -0
- package/dist/base/core/src/Collection/types.d.ts +28 -0
- package/dist/base/core/src/DataAdapter.d.ts +35 -0
- package/dist/base/core/src/DefaultDataAdapter.d.ts +35 -0
- package/dist/base/core/src/WorkerDataAdapter.d.ts +25 -0
- package/dist/base/core/src/WorkerDataAdapterHost.d.ts +62 -0
- package/dist/base/core/src/createIndex.d.ts +7 -0
- package/dist/base/core/src/createIndexProvider.d.ts +8 -0
- package/dist/base/core/src/createReactivityAdapter.d.ts +8 -0
- package/dist/base/core/src/createStorageAdapter.d.ts +9 -0
- package/dist/base/core/src/getIndexInfo.d.ts +39 -0
- package/dist/base/core/src/index.d.ts +22 -0
- package/dist/base/core/src/types/Dependency.d.ts +4 -0
- package/dist/base/core/src/types/IndexProvider.d.ts +26 -0
- package/dist/base/core/src/types/Modifier.d.ts +46 -0
- package/dist/base/core/src/types/ReactivityAdapter.d.ts +6 -0
- package/dist/base/core/src/types/Selector.d.ts +46 -0
- package/dist/base/core/src/types/Signal.d.ts +4 -0
- package/dist/base/core/src/types/StorageAdapter.d.ts +20 -0
- package/dist/base/core/src/utils/EventEmitter.d.ts +71 -0
- package/dist/base/core/src/utils/batchOnNextTick.d.ts +16 -0
- package/dist/base/core/src/utils/compact.d.ts +9 -0
- package/dist/base/core/src/utils/createSignal.d.ts +14 -0
- package/dist/base/core/src/utils/deepClone.d.ts +17 -0
- package/dist/base/core/src/utils/get.d.ts +9 -0
- package/dist/base/core/src/utils/getMatchingKeys.d.ts +19 -0
- package/dist/base/core/src/utils/intersection.d.ts +9 -0
- package/dist/base/core/src/utils/isEqual.d.ts +14 -0
- package/dist/base/core/src/utils/isFieldExpression.d.ts +11 -0
- package/dist/base/core/src/utils/match.d.ts +12 -0
- package/dist/base/core/src/utils/modify.d.ts +14 -0
- package/dist/base/core/src/utils/project.d.ts +15 -0
- package/dist/base/core/src/utils/queryId.d.ts +9 -0
- package/dist/base/core/src/utils/randomId.d.ts +7 -0
- package/dist/base/core/src/utils/reactiveOrAsync.d.ts +59 -0
- package/dist/base/core/src/utils/serializeValue.d.ts +12 -0
- package/dist/base/core/src/utils/set.d.ts +13 -0
- package/dist/base/core/src/utils/sortItems.d.ts +12 -0
- package/dist/base/core/src/utils/uniqueBy.d.ts +10 -0
- package/dist/index.mjs +151 -165
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +2 -2
- package/dist/index.umd.js.map +1 -1
- package/package.json +2 -2
- /package/dist/{index.d.ts → storage-adapters/localstorage/src/index.d.ts} +0 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { BaseItem } from './Collection';
|
|
2
|
+
import type Collection from './Collection';
|
|
3
|
+
import type DataAdapter from './DataAdapter';
|
|
4
|
+
import type { CollectionBackend } from './DataAdapter';
|
|
5
|
+
import type StorageAdapter from './types/StorageAdapter';
|
|
6
|
+
export interface AsyncDataAdapterOptions {
|
|
7
|
+
/** Factory to obtain a StorageAdapter per collection name */
|
|
8
|
+
storage: (name: string) => StorageAdapter<any, any>;
|
|
9
|
+
/** Optional logical id (handy if you run multiple adapters side-by-side) */
|
|
10
|
+
id?: string;
|
|
11
|
+
/** Optional error hook (mirrors WorkerDataAdapterHost) */
|
|
12
|
+
onError?: (error: Error) => void;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* AsyncDataAdapter
|
|
16
|
+
* Combines WorkerDataAdapter + WorkerDataAdapterHost into a single, transport-free adapter.
|
|
17
|
+
* - Keeps the DataAdapter/CollectionBackend surface identical to the Worker version.
|
|
18
|
+
* - Executes queries and mutations directly against the provided StorageAdapter.
|
|
19
|
+
* - Preserves index-aware query optimization and push-style query updates to listeners.
|
|
20
|
+
*/
|
|
21
|
+
export default class AsyncDataAdapter implements DataAdapter {
|
|
22
|
+
private options;
|
|
23
|
+
private id;
|
|
24
|
+
private onError;
|
|
25
|
+
private storageAdapters;
|
|
26
|
+
private storageAdapterReady;
|
|
27
|
+
private collectionIndices;
|
|
28
|
+
private queries;
|
|
29
|
+
constructor(options: AsyncDataAdapterOptions);
|
|
30
|
+
createCollectionBackend<T extends BaseItem<I>, I = any, E extends BaseItem = T, U = E>(collection: Collection<T, I, E, U>, indices: string[]): CollectionBackend<T, I>;
|
|
31
|
+
private setupStorage;
|
|
32
|
+
private ensureStorageAdapter;
|
|
33
|
+
/**
|
|
34
|
+
* Compute and publish the result for a specific query
|
|
35
|
+
* @param collectionName - name of the collection
|
|
36
|
+
* @param selector - query selector
|
|
37
|
+
* @param options - query options
|
|
38
|
+
*/
|
|
39
|
+
private fulfillQuery;
|
|
40
|
+
/**
|
|
41
|
+
* Notify listeners about state changes and keep the cache updated
|
|
42
|
+
* @param collectionName - name of the collection
|
|
43
|
+
* @param qid - query id
|
|
44
|
+
* @param state - new state
|
|
45
|
+
* @param error - error if state is 'error', null otherwise
|
|
46
|
+
*/
|
|
47
|
+
private publishState;
|
|
48
|
+
private publishResult;
|
|
49
|
+
private getIndexInfo;
|
|
50
|
+
private queryItems;
|
|
51
|
+
private executeQuery;
|
|
52
|
+
/**
|
|
53
|
+
* After mutations, recompute and push updates for affected active queries
|
|
54
|
+
* @param collectionName - name of the collection
|
|
55
|
+
* @param affectedItems - item states before and/or after the mutation
|
|
56
|
+
*/
|
|
57
|
+
private checkQueryUpdates;
|
|
58
|
+
private insert;
|
|
59
|
+
private updateOne;
|
|
60
|
+
private updateMany;
|
|
61
|
+
private replaceOne;
|
|
62
|
+
private removeOne;
|
|
63
|
+
private removeMany;
|
|
64
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type { BaseItem } from './Collection';
|
|
2
|
+
import type Collection from './Collection';
|
|
3
|
+
import type DataAdapter from './DataAdapter';
|
|
4
|
+
import type { CollectionBackend } from './DataAdapter';
|
|
5
|
+
import type StorageAdapter from './types/StorageAdapter';
|
|
6
|
+
import type Selector from './types/Selector';
|
|
7
|
+
/**
|
|
8
|
+
* AutoFetchDataAdapterOptions
|
|
9
|
+
*
|
|
10
|
+
* Merges the core options required to talk to a per-collection StorageAdapter with
|
|
11
|
+
* the auto-fetch behavior inspired by AutoFetchCollection.
|
|
12
|
+
*/
|
|
13
|
+
export interface AutoFetchDataAdapterOptions {
|
|
14
|
+
/** Factory to obtain a StorageAdapter per collection name */
|
|
15
|
+
storage?: (name: string) => StorageAdapter<any, any>;
|
|
16
|
+
/** Optional logical id (handy if you run multiple adapters side-by-side) */
|
|
17
|
+
id?: string;
|
|
18
|
+
/** Optional error hook */
|
|
19
|
+
onError?: (error: Error) => void;
|
|
20
|
+
/**
|
|
21
|
+
* Fetch hook: given a selector, retrieve items from a remote source.
|
|
22
|
+
* Must resolve to an object with an `items` array. Items MUST include an `id`.
|
|
23
|
+
*/
|
|
24
|
+
fetchQueryItems: (collectionName: string, selector: Selector<BaseItem>) => Promise<BaseItem[] | undefined>;
|
|
25
|
+
/**
|
|
26
|
+
* Optional: called once at adapter construction to subscribe to remote changes.
|
|
27
|
+
* When invoked, call the provided callback whenever the remote source changed
|
|
28
|
+
* and all active queries should be re-fetched.
|
|
29
|
+
*/
|
|
30
|
+
registerRemoteChange?: (onChange: () => Promise<void>) => Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* Merge strategy for ingesting freshly fetched items with existing ones.
|
|
33
|
+
* Default is shallow spread (right wins).
|
|
34
|
+
*/
|
|
35
|
+
mergeItems?: <T extends BaseItem<any>>(a: T, b: T) => T;
|
|
36
|
+
/**
|
|
37
|
+
* Delay (ms) before purging auto-fetched items for a query after the query
|
|
38
|
+
* becomes inactive. Set to 0 to purge immediately. Default: 10s.
|
|
39
|
+
*/
|
|
40
|
+
purgeDelay?: number;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* AutoFetchDataAdapter
|
|
44
|
+
*
|
|
45
|
+
* A DataAdapter that:
|
|
46
|
+
* - Mirrors the CollectionBackend surface (CRUD + query registry + lifecycle)
|
|
47
|
+
* - Executes queries against a provided StorageAdapter (local cache)
|
|
48
|
+
* - On first registration of a selector, auto-fetches from a remote source and
|
|
49
|
+
* ingests the result into storage (upsert), then pushes query result updates
|
|
50
|
+
* - Optionally purges auto-fetched items for a selector once no observers remain
|
|
51
|
+
* - Can subscribe to remote change notifications to re-fetch active selectors
|
|
52
|
+
*
|
|
53
|
+
* IMPORTANT: Purging only ever deletes items that were introduced via the
|
|
54
|
+
* auto-fetch path and are no longer referenced by any active selector. Items
|
|
55
|
+
* inserted through CRUD calls are never purged.
|
|
56
|
+
*/
|
|
57
|
+
export default class AutoFetchDataAdapter implements DataAdapter {
|
|
58
|
+
private options;
|
|
59
|
+
private id;
|
|
60
|
+
private onError;
|
|
61
|
+
private fetchQueryItems;
|
|
62
|
+
private mergeItems;
|
|
63
|
+
private purgeDelay;
|
|
64
|
+
private storageAdapters;
|
|
65
|
+
private storageAdapterReady;
|
|
66
|
+
private collectionIndices;
|
|
67
|
+
private queries;
|
|
68
|
+
private activeObservers;
|
|
69
|
+
private observerTimeouts;
|
|
70
|
+
private selectorIds;
|
|
71
|
+
private idRefCounts;
|
|
72
|
+
private autoloadIds;
|
|
73
|
+
constructor(options: AutoFetchDataAdapterOptions);
|
|
74
|
+
createCollectionBackend<T extends BaseItem<I>, I = any, E extends BaseItem = T, U = E>(collection: Collection<T, I, E, U>, indices: string[]): CollectionBackend<T, I>;
|
|
75
|
+
private forceRefetchAll;
|
|
76
|
+
private fetchAndIngest;
|
|
77
|
+
private purgeSelector;
|
|
78
|
+
private setupStorage;
|
|
79
|
+
private ensureStorageAdapter;
|
|
80
|
+
private publishForSelector;
|
|
81
|
+
private publishState;
|
|
82
|
+
private publishResult;
|
|
83
|
+
private fulfillQuery;
|
|
84
|
+
private getIndexInfo;
|
|
85
|
+
private queryItems;
|
|
86
|
+
private executeQuery;
|
|
87
|
+
private checkQueryUpdates;
|
|
88
|
+
private insert;
|
|
89
|
+
private updateOne;
|
|
90
|
+
private updateMany;
|
|
91
|
+
private replaceOne;
|
|
92
|
+
private removeOne;
|
|
93
|
+
private removeMany;
|
|
94
|
+
private upsertMerged;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Usage (example):
|
|
98
|
+
*
|
|
99
|
+
* const adapter = new AutoFetchDataAdapter({
|
|
100
|
+
* storage: (name) => new IndexedDBStorage(name),
|
|
101
|
+
* fetchQueryItems: async (collectionName, selector) => {
|
|
102
|
+
* const res = await fetch(`/api/${collectionName}?q=${encodeURIComponent(JSON.stringify(selector||{}))}`)
|
|
103
|
+
* const items = await res.json()
|
|
104
|
+
* return { items }
|
|
105
|
+
* },
|
|
106
|
+
* registerRemoteChange: (onChange) => subscribeToWS(onChange),
|
|
107
|
+
* mergeItems: (a, b) => ({ ...a, ...b }),
|
|
108
|
+
* purgeDelay: 10_000,
|
|
109
|
+
* })
|
|
110
|
+
*
|
|
111
|
+
* const backend = adapter.createCollectionBackend(myCollection, ['status', 'projectId'])
|
|
112
|
+
*/
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type ReactivityAdapter from '../types/ReactivityAdapter';
|
|
2
|
+
import type { BaseItem, FindOptions, Transform } from './types';
|
|
3
|
+
import type { ObserveCallbacks } from './Observer';
|
|
4
|
+
/**
|
|
5
|
+
* Checks if the current scope is reactive, considering the provided reactivity adapter.
|
|
6
|
+
* @param reactivity - The reactivity adapter or a boolean indicating whether reactivity is enabled.
|
|
7
|
+
* @returns A boolean indicating if the current scope is reactive.
|
|
8
|
+
*/
|
|
9
|
+
export declare function isInReactiveScope(reactivity: ReactivityAdapter | undefined | false): boolean;
|
|
10
|
+
export interface CursorOptions<T extends BaseItem, U = T, Async extends boolean = false> extends FindOptions<T, Async> {
|
|
11
|
+
transform?: Transform<T, U>;
|
|
12
|
+
bindEvents?: (requery: () => void) => () => void;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Represents a cursor for querying and observing a filtered, sorted, and transformed
|
|
16
|
+
* subset of items from a collection. Supports reactivity and field tracking.
|
|
17
|
+
* @template T - The type of the items in the collection.
|
|
18
|
+
* @template U - The transformed item type after applying transform (default is T).
|
|
19
|
+
*/
|
|
20
|
+
export default class Cursor<T extends BaseItem, U = T, Async extends boolean = false> {
|
|
21
|
+
private observer;
|
|
22
|
+
private getItems;
|
|
23
|
+
private options;
|
|
24
|
+
private onCleanupCallbacks;
|
|
25
|
+
/**
|
|
26
|
+
* Creates a new instance of the `Cursor` class.
|
|
27
|
+
* Provides utilities for querying, observing, and transforming items from a collection.
|
|
28
|
+
* @template T - The type of the items in the collection.
|
|
29
|
+
* @template U - The transformed item type after applying transformations (default is T).
|
|
30
|
+
* @param getItems - A function that retrieves the filtered list of items.
|
|
31
|
+
* @param options - Optional configuration for the cursor.
|
|
32
|
+
* @param options.transform - A transformation function to apply to each item when retrieving them.
|
|
33
|
+
* @param options.bindEvents - A function to bind reactivity events for the cursor, which should return a cleanup function.
|
|
34
|
+
* @param options.fields - A projection object defining which fields of the item should be included or excluded.
|
|
35
|
+
* @param options.sort - A sort specifier to determine the order of the items.
|
|
36
|
+
* @param options.skip - The number of items to skip from the beginning of the result set.
|
|
37
|
+
* @param options.limit - The maximum number of items to return in the result set.
|
|
38
|
+
* @param options.reactive - A reactivity adapter to enable observing changes in the cursor's result set.
|
|
39
|
+
* @param options.fieldTracking - A boolean to enable fine-grained field tracking for reactivity.
|
|
40
|
+
* @param options.transformAll - A function that will be able to solve the n+1 problem
|
|
41
|
+
*/
|
|
42
|
+
constructor(getItems: Async extends true ? () => Promise<T[]> : () => T[], options?: CursorOptions<T, U, Async>);
|
|
43
|
+
private addGetters;
|
|
44
|
+
private transform;
|
|
45
|
+
private depend;
|
|
46
|
+
private ensureObserver;
|
|
47
|
+
private observeRawChanges;
|
|
48
|
+
/**
|
|
49
|
+
* Cleans up all resources associated with the cursor, such as reactive bindings
|
|
50
|
+
* and event listeners. This method should be called when the cursor is no longer needed
|
|
51
|
+
* to prevent memory leaks.
|
|
52
|
+
*/
|
|
53
|
+
cleanup(): void;
|
|
54
|
+
/**
|
|
55
|
+
* Registers a cleanup callback to be executed when the `cleanup` method is called.
|
|
56
|
+
* Useful for managing resources and ensuring proper cleanup of bindings or listeners.
|
|
57
|
+
* @param callback - A function to be executed during cleanup.
|
|
58
|
+
*/
|
|
59
|
+
onCleanup(callback: () => void): void;
|
|
60
|
+
/**
|
|
61
|
+
* Iterates over each item in the cursor's result set, applying the provided callback
|
|
62
|
+
* function to each transformed item.
|
|
63
|
+
* ⚡️ this function is reactive!
|
|
64
|
+
* @param callback - A function to execute for each item in the result set.
|
|
65
|
+
* @param callback.item - The transformed item.
|
|
66
|
+
* @returns A promise that resolves when all items have been processed, or void if not in async mode.
|
|
67
|
+
*/
|
|
68
|
+
forEach(callback: (item: U) => void): Async extends true ? Promise<void> : void;
|
|
69
|
+
/**
|
|
70
|
+
* Creates a new array populated with the results of applying the provided callback
|
|
71
|
+
* function to each transformed item in the cursor's result set.
|
|
72
|
+
* ⚡️ this function is reactive!
|
|
73
|
+
* @template V - The type of the items in the resulting array.
|
|
74
|
+
* @param callback - A function to execute for each item in the result set.
|
|
75
|
+
* @param callback.item - The transformed item.
|
|
76
|
+
* @returns An array of results after applying the callback to each item.
|
|
77
|
+
*/
|
|
78
|
+
map<V>(callback: (item: U) => V): Async extends true ? Promise<V[]> : V[];
|
|
79
|
+
/**
|
|
80
|
+
* Fetches all transformed items from the cursor's result set as an array.
|
|
81
|
+
* Automatically applies filtering, sorting, and limiting as per the cursor's options.
|
|
82
|
+
* ⚡️ this function is reactive!
|
|
83
|
+
* @returns An array of transformed items in the result set.
|
|
84
|
+
*/
|
|
85
|
+
fetch(): Async extends true ? Promise<U[]> : U[];
|
|
86
|
+
/**
|
|
87
|
+
* Counts the total number of items in the cursor's result set after applying
|
|
88
|
+
* filtering and other criteria.
|
|
89
|
+
* ⚡️ this function is reactive!
|
|
90
|
+
* @returns The total number of items in the result set.
|
|
91
|
+
*/
|
|
92
|
+
count(): Async extends true ? Promise<number> : number;
|
|
93
|
+
/**
|
|
94
|
+
* Observes changes to the cursor's result set and triggers the specified callbacks
|
|
95
|
+
* when items are added, removed, or updated. Supports reactivity and transformation.
|
|
96
|
+
* @param callbacks - An object containing the callback functions to handle different change events.
|
|
97
|
+
* @param callbacks.added - Triggered when an item is added to the result set.
|
|
98
|
+
* @param callbacks.removed - Triggered when an item is removed from the result set.
|
|
99
|
+
* @param callbacks.changed - Triggered when an item in the result set is modified.
|
|
100
|
+
* @param callbacks.addedBefore - Triggered when an item is added before another item in the result set.
|
|
101
|
+
* @param callbacks.movedBefore - Triggered when an item is moved before another item in the result set.
|
|
102
|
+
* @param callbacks.changedField - Triggered when a specific field of an item changes.
|
|
103
|
+
* @param skipInitial - A boolean indicating whether to skip the initial notification of the current result set.
|
|
104
|
+
* @returns A function to stop observing changes.
|
|
105
|
+
*/
|
|
106
|
+
observeChanges(callbacks: ObserveCallbacks<T>, skipInitial?: boolean): () => void;
|
|
107
|
+
/**
|
|
108
|
+
* Forces the cursor to re-evaluate its result set by re-fetching items
|
|
109
|
+
* from the collection. This is useful when the underlying data or query
|
|
110
|
+
* criteria have changed, and you want to ensure the cursor reflects the latest state.
|
|
111
|
+
*/
|
|
112
|
+
requery(): void;
|
|
113
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
type AddedCallback<T> = (item: T) => void;
|
|
2
|
+
type AddedBeforeCallback<T> = (item: T, before: T) => void;
|
|
3
|
+
type ChangedCallback<T> = (item: T) => void;
|
|
4
|
+
type ChangedFieldCallback<T> = <Field extends keyof T>(item: T, field: Field, oldValue: T[Field], newValue: T[Field]) => void;
|
|
5
|
+
type MovedBeforeCallback<T> = (item: T, before: T) => void;
|
|
6
|
+
type RemovedCallback<T> = (item: T) => void;
|
|
7
|
+
export interface ObserveCallbacks<T> {
|
|
8
|
+
added?: AddedCallback<T>;
|
|
9
|
+
addedBefore?: AddedBeforeCallback<T>;
|
|
10
|
+
changed?: ChangedCallback<T>;
|
|
11
|
+
changedField?: ChangedFieldCallback<T>;
|
|
12
|
+
movedBefore?: MovedBeforeCallback<T>;
|
|
13
|
+
removed?: RemovedCallback<T>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Represents an observer that tracks changes in a collection of items and triggers
|
|
17
|
+
* callbacks for various events such as addition, removal, and modification of items.
|
|
18
|
+
* @template T - The type of the items being observed, which must include an `id` field.
|
|
19
|
+
*/
|
|
20
|
+
export default class Observer<T extends {
|
|
21
|
+
id: any;
|
|
22
|
+
}> {
|
|
23
|
+
private previousItems;
|
|
24
|
+
private callbacks;
|
|
25
|
+
private unbindEvents;
|
|
26
|
+
/**
|
|
27
|
+
* Creates a new instance of the `Observer` class.
|
|
28
|
+
* Sets up event bindings and initializes the callbacks for tracking changes in a collection.
|
|
29
|
+
* @param bindEvents - A function to bind external events to the observer. Must return a cleanup function to unbind those events.
|
|
30
|
+
*/
|
|
31
|
+
constructor(bindEvents: () => () => void);
|
|
32
|
+
private call;
|
|
33
|
+
private hasCallbacks;
|
|
34
|
+
/**
|
|
35
|
+
* Determines if the observer has no active callbacks registered for any events.
|
|
36
|
+
* @returns A boolean indicating whether the observer is empty (i.e., no callbacks are registered).
|
|
37
|
+
*/
|
|
38
|
+
isEmpty(): boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Compares the previous state of items with the new state and triggers the appropriate callbacks
|
|
41
|
+
* for events such as added, removed, changed, or moved items.
|
|
42
|
+
* @param getItems - A function that returns a promise resolving to the new items or the items themselves.
|
|
43
|
+
*/
|
|
44
|
+
runChecks(getItems: () => Promise<T[]> | T[]): void;
|
|
45
|
+
private checkItems;
|
|
46
|
+
private stopped;
|
|
47
|
+
/**
|
|
48
|
+
* Stops the observer by unbinding all events and cleaning up resources.
|
|
49
|
+
* Safe to call multiple times - will only unbind once.
|
|
50
|
+
*/
|
|
51
|
+
stop(): void;
|
|
52
|
+
/**
|
|
53
|
+
* Registers callbacks for specific events to observe changes in the collection.
|
|
54
|
+
* @param callbacks - An object containing the callbacks for various events (e.g., 'added', 'removed').
|
|
55
|
+
* @param skipInitial - A boolean indicating whether to skip invoking the callbacks for the initial state of the collection.
|
|
56
|
+
*/
|
|
57
|
+
addCallbacks(callbacks: ObserveCallbacks<T>, skipInitial?: boolean): void;
|
|
58
|
+
/**
|
|
59
|
+
* Removes the specified callbacks for specific events, unregistering them from the observer.
|
|
60
|
+
* @param callbacks - An object containing the callbacks to be removed for various events.
|
|
61
|
+
*/
|
|
62
|
+
removeCallbacks(callbacks: ObserveCallbacks<T>): void;
|
|
63
|
+
}
|
|
64
|
+
export {};
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import type ReactivityAdapter from '../types/ReactivityAdapter';
|
|
2
|
+
import EventEmitter from '../utils/EventEmitter';
|
|
3
|
+
import type Selector from '../types/Selector';
|
|
4
|
+
import type Modifier from '../types/Modifier';
|
|
5
|
+
import type DataAdapter from '../DataAdapter';
|
|
6
|
+
import type { QueryOptions } from '../DataAdapter';
|
|
7
|
+
import type StorageAdapter from '../types/StorageAdapter';
|
|
8
|
+
import Cursor from './Cursor';
|
|
9
|
+
import type { AsyncFindOptions, BaseItem, FindOptions, SyncFindOptions, Transform, TransformAll } from './types';
|
|
10
|
+
export type { AnyFindOptions, AsyncFindOptions, BaseItem, Transform, TransformAll, SortSpecifier, FieldSpecifier, FindOptions, SyncFindOptions, } from './types';
|
|
11
|
+
export type { CursorOptions } from './Cursor';
|
|
12
|
+
export type { ObserveCallbacks } from './Observer';
|
|
13
|
+
export { default as createIndex } from '../createIndex';
|
|
14
|
+
export interface CollectionOptions<T extends BaseItem<I>, I, E extends BaseItem = T, U = E> {
|
|
15
|
+
/**
|
|
16
|
+
* @deprecated Use new constructor parameters instead.
|
|
17
|
+
*/
|
|
18
|
+
name?: string;
|
|
19
|
+
/**
|
|
20
|
+
* @deprecated Use `DataAdapter` options instead.
|
|
21
|
+
*/
|
|
22
|
+
persistence?: StorageAdapter<T, I>;
|
|
23
|
+
primaryKeyGenerator?: (item: Omit<T, 'id'>) => I;
|
|
24
|
+
reactivity?: ReactivityAdapter;
|
|
25
|
+
transform?: Transform<E, U>;
|
|
26
|
+
transformAll?: TransformAll<T, E>;
|
|
27
|
+
indices?: string[];
|
|
28
|
+
enableDebugMode?: boolean;
|
|
29
|
+
fieldTracking?: boolean;
|
|
30
|
+
}
|
|
31
|
+
interface CollectionEvents<T extends BaseItem, E extends BaseItem = T, U = E> {
|
|
32
|
+
'added': (item: T) => void;
|
|
33
|
+
'changed': (item: T, modifier: Modifier<T>) => void;
|
|
34
|
+
'removed': (item: T) => void;
|
|
35
|
+
'observer.created': <O extends QueryOptions<T>>(selector?: Selector<T>, options?: O) => void;
|
|
36
|
+
'observer.disposed': <O extends QueryOptions<T>>(selector?: Selector<T>, options?: O) => void;
|
|
37
|
+
'getItems': (selector: Selector<T> | undefined) => void;
|
|
38
|
+
'find': <Async extends boolean, O extends FindOptions<T, Async>>(selector: Selector<T> | undefined, options: O | undefined, cursor: Cursor<E, U, Async>) => void;
|
|
39
|
+
'findOne': <O extends QueryOptions<T>>(selector: Selector<T>, options: O | undefined, item: U | undefined) => void;
|
|
40
|
+
'insert': (item: Omit<T, 'id'> & Partial<Pick<T, 'id'>>) => void;
|
|
41
|
+
'updateOne': (selector: Selector<T>, modifier: Modifier<T>) => void;
|
|
42
|
+
'updateMany': (selector: Selector<T>, modifier: Modifier<T>) => void;
|
|
43
|
+
'replaceOne': (selector: Selector<T>, item: Omit<T, 'id'> & Partial<Pick<T, 'id'>>) => void;
|
|
44
|
+
'removeOne': (selector: Selector<T>) => void;
|
|
45
|
+
'removeMany': (selector: Selector<T>) => void;
|
|
46
|
+
'validate': (item: T) => void;
|
|
47
|
+
'_debug.getItems': (callstack: string, selector: Selector<T> | undefined, measuredTime: number) => void;
|
|
48
|
+
'_debug.find': <Async extends boolean, O extends FindOptions<T, Async>>(callstack: string, selector: Selector<T> | undefined, options: O | undefined, cursor: Cursor<E, U, Async>) => void;
|
|
49
|
+
'_debug.findOne': <Async extends boolean, O extends FindOptions<T, Async>>(callstack: string, selector: Selector<T>, options: O | undefined, item: U | undefined) => void;
|
|
50
|
+
'_debug.insert': (callstack: string, item: Omit<T, 'id'> & Partial<Pick<T, 'id'>>) => void;
|
|
51
|
+
'_debug.updateOne': (callstack: string, selector: Selector<T>, modifier: Modifier<T>) => void;
|
|
52
|
+
'_debug.updateMany': (callstack: string, selector: Selector<T>, modifier: Modifier<T>) => void;
|
|
53
|
+
'_debug.replaceOne': (callstack: string, selector: Selector<T>, item: Omit<T, 'id'> & Partial<Pick<T, 'id'>>) => void;
|
|
54
|
+
'_debug.removeOne': (callstack: string, selector: Selector<T>) => void;
|
|
55
|
+
'_debug.removeMany': (callstack: string, selector: Selector<T>) => void;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Represents a collection of data items with support for in-memory operations,
|
|
59
|
+
* persistence, reactivity, and event-based notifications. The collection provides
|
|
60
|
+
* CRUD operations, observer patterns, and batch operations.
|
|
61
|
+
* @template T - The type of the items stored in the collection.
|
|
62
|
+
* @template I - The type of the unique identifier for the items.
|
|
63
|
+
* @template U - The transformed item type after applying transformations (default is T).
|
|
64
|
+
*/
|
|
65
|
+
export default class Collection<T extends BaseItem<I> = BaseItem, I = any, E extends BaseItem = T, U = E> extends EventEmitter<CollectionEvents<T, E, U>> {
|
|
66
|
+
private static collections;
|
|
67
|
+
private static debugMode;
|
|
68
|
+
private static batchOperationInProgress;
|
|
69
|
+
private static fieldTracking;
|
|
70
|
+
private static onCreationCallbacks;
|
|
71
|
+
private static onDisposeCallbacks;
|
|
72
|
+
static getCollections(): Collection<any, any, any, any>[];
|
|
73
|
+
static onCreation(callback: (collection: Collection<any>) => void): void;
|
|
74
|
+
static onDispose(callback: (collection: Collection<any>) => void): void;
|
|
75
|
+
/**
|
|
76
|
+
* Enables debug mode for all collections.
|
|
77
|
+
*/
|
|
78
|
+
static enableDebugMode: () => void;
|
|
79
|
+
/**
|
|
80
|
+
* Enables field tracking for all collections.
|
|
81
|
+
* @param enable - A boolean indicating whether to enable field tracking.
|
|
82
|
+
*/
|
|
83
|
+
static setFieldTracking: (enable: boolean) => void;
|
|
84
|
+
/**
|
|
85
|
+
* Executes a batch operation, allowing multiple modifications to the collection
|
|
86
|
+
* while deferring index rebuilding until all operations in the batch are completed.
|
|
87
|
+
* This improves performance by avoiding repetitive index recalculations and
|
|
88
|
+
* provides atomicity for the batch of operations.
|
|
89
|
+
* Supports both synchronous and asynchronous callbacks.
|
|
90
|
+
* @param callback - The batch operation to execute.
|
|
91
|
+
* @returns A promise if the callback returns a promise, otherwise `void`.
|
|
92
|
+
*/
|
|
93
|
+
static batch<ReturnType>(callback: () => Promise<ReturnType>): Promise<void>;
|
|
94
|
+
static batch<ReturnType>(callback: () => ReturnType): void;
|
|
95
|
+
readonly name: string;
|
|
96
|
+
private backend;
|
|
97
|
+
private options;
|
|
98
|
+
private isPullingSignal;
|
|
99
|
+
private isPushingSignal;
|
|
100
|
+
private readySignal;
|
|
101
|
+
private debugMode;
|
|
102
|
+
private batchOperationInProgress;
|
|
103
|
+
private isDisposed;
|
|
104
|
+
private postBatchCallbacks;
|
|
105
|
+
private fieldTracking;
|
|
106
|
+
private queryListenersMap;
|
|
107
|
+
/**
|
|
108
|
+
* Initializes a new instance of the `Collection` class with optional configuration.
|
|
109
|
+
* Sets up memory, persistence, reactivity, and indices as specified in the options.
|
|
110
|
+
* @template T - The type of the items stored in the collection.
|
|
111
|
+
* @template I - The type of the unique identifier for the items.
|
|
112
|
+
* @template U - The transformed item type after applying transformations (default is T).
|
|
113
|
+
* @param name - The name of the collection.
|
|
114
|
+
* @param dataAdapter - The data adapter for creating the collection backend.
|
|
115
|
+
* @param options - Optional configuration for the collection.
|
|
116
|
+
* @param options.name - An optional name for the collection.
|
|
117
|
+
* @param options.memory - The in-memory adapter for storing items.
|
|
118
|
+
* @param options.reactivity - The reactivity adapter for observing changes in the collection.
|
|
119
|
+
* @param options.transform - A transformation function to apply to items when retrieving them.
|
|
120
|
+
* @param options.persistence - The persistence adapter for saving and loading items.
|
|
121
|
+
* @param options.indices - An array of index providers for optimized querying.
|
|
122
|
+
* @param options.enableDebugMode - A boolean to enable or disable debug mode.
|
|
123
|
+
* @param options.fieldTracking - A boolean to enable or disable field tracking by default.
|
|
124
|
+
* @param options.transformAll - A function that will be able to solve the n+1 problem
|
|
125
|
+
*/
|
|
126
|
+
constructor(options?: CollectionOptions<T, I, E, U>);
|
|
127
|
+
constructor(name: string, dataAdapter: DataAdapter, options?: CollectionOptions<T, I, E, U>);
|
|
128
|
+
isBatchOperationInProgress(): boolean;
|
|
129
|
+
/**
|
|
130
|
+
* Checks whether the collection is currently performing a pull operation
|
|
131
|
+
* ⚡️ this function is reactive!
|
|
132
|
+
* (loading data from the persistence adapter).
|
|
133
|
+
* @returns A boolean indicating if the collection is in the process of pulling data.
|
|
134
|
+
*/
|
|
135
|
+
isPulling(): boolean;
|
|
136
|
+
/**
|
|
137
|
+
* Checks whether the collection is currently performing a push operation
|
|
138
|
+
* ⚡️ this function is reactive!
|
|
139
|
+
* (saving data to the persistence adapter).
|
|
140
|
+
* @returns A boolean indicating if the collection is in the process of pushing data.
|
|
141
|
+
*/
|
|
142
|
+
isPushing(): boolean;
|
|
143
|
+
/**
|
|
144
|
+
* Checks whether the collection is currently performing either a pull or push operation,
|
|
145
|
+
* ⚡️ this function is reactive!
|
|
146
|
+
* indicating that it is loading or saving data.
|
|
147
|
+
* @returns A boolean indicating if the collection is in the process of loading or saving data.
|
|
148
|
+
*/
|
|
149
|
+
isLoading(): boolean;
|
|
150
|
+
/**
|
|
151
|
+
* Retrieves the current debug mode status of the collection.
|
|
152
|
+
* @returns A boolean indicating whether debug mode is enabled for the collection.
|
|
153
|
+
*/
|
|
154
|
+
getDebugMode(): boolean;
|
|
155
|
+
/**
|
|
156
|
+
* Enables or disables debug mode for the collection.
|
|
157
|
+
* When debug mode is enabled, additional debugging information and events are emitted.
|
|
158
|
+
* @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) debug mode.
|
|
159
|
+
*/
|
|
160
|
+
setDebugMode(enable: boolean): void;
|
|
161
|
+
/**
|
|
162
|
+
* Enables or disables field tracking for the collection.
|
|
163
|
+
* @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) field tracking.
|
|
164
|
+
*/
|
|
165
|
+
setFieldTracking(enable: boolean): void;
|
|
166
|
+
/**
|
|
167
|
+
* Resolves when the persistence adapter finished initializing
|
|
168
|
+
* and the collection is ready to be used.
|
|
169
|
+
* @returns A promise that resolves when the collection is ready.
|
|
170
|
+
* @example
|
|
171
|
+
* ```ts
|
|
172
|
+
* const collection = new Collection({
|
|
173
|
+
* persistence: // ...
|
|
174
|
+
* })
|
|
175
|
+
* await collection.isReady()
|
|
176
|
+
*
|
|
177
|
+
* collection.insert({ name: 'Item 1' })
|
|
178
|
+
*/
|
|
179
|
+
ready(): Promise<void>;
|
|
180
|
+
/**
|
|
181
|
+
* Checks if the collection is ready.
|
|
182
|
+
* ⚡️ this function is reactive!
|
|
183
|
+
* @returns A boolean indicating whether the collection is ready.
|
|
184
|
+
*/
|
|
185
|
+
isReady(): boolean;
|
|
186
|
+
private profile;
|
|
187
|
+
private executeInDebugMode;
|
|
188
|
+
private transform;
|
|
189
|
+
private transformAll;
|
|
190
|
+
private getItem;
|
|
191
|
+
private getItems;
|
|
192
|
+
private withPushState;
|
|
193
|
+
private queryListeners;
|
|
194
|
+
/**
|
|
195
|
+
* Disposes the collection, unregisters persistence adapters, clears memory, and
|
|
196
|
+
* cleans up all resources used by the collection.
|
|
197
|
+
* @returns A promise that resolves when the collection is disposed.
|
|
198
|
+
*/
|
|
199
|
+
dispose(): Promise<void>;
|
|
200
|
+
/**
|
|
201
|
+
* Finds multiple items in the collection based on a selector and optional options.
|
|
202
|
+
* Returns a cursor for reactive data queries.
|
|
203
|
+
* @param [selector] - The criteria to select items.
|
|
204
|
+
* @param [options] - Options for the find operation, such as limit and sort.
|
|
205
|
+
* @returns A cursor to fetch and observe the matching items.
|
|
206
|
+
*/
|
|
207
|
+
find(selector?: Selector<T>, options?: SyncFindOptions<T>): Cursor<E, U, false>;
|
|
208
|
+
find(selector: Selector<T> | undefined, options: AsyncFindOptions<T>): Cursor<E, U, true>;
|
|
209
|
+
find(selector?: Selector<T>, options?: FindOptions<T, boolean>): Cursor<E, U, boolean>;
|
|
210
|
+
/**
|
|
211
|
+
* Finds a single item in the collection based on a selector and optional options.
|
|
212
|
+
* ⚡️ this function is reactive!
|
|
213
|
+
* Returns the found item or undefined if no item matches.
|
|
214
|
+
* @param selector - The criteria to select the item.
|
|
215
|
+
* @param [options] - Options for the find operation, such as projection.
|
|
216
|
+
* @returns The found item or `undefined`.
|
|
217
|
+
*/
|
|
218
|
+
findOne(selector: Selector<T>, options?: Omit<SyncFindOptions<T>, 'limit'>): U | undefined;
|
|
219
|
+
findOne(selector: Selector<T>, options: Omit<AsyncFindOptions<T>, 'limit'>): Promise<U | undefined>;
|
|
220
|
+
findOne(selector: Selector<T>, options?: Omit<FindOptions<T, boolean>, 'limit'>): Promise<U | undefined> | U | undefined;
|
|
221
|
+
/**
|
|
222
|
+
* Performs a batch operation, deferring index rebuilds and allowing multiple
|
|
223
|
+
* modifications to be made atomically. Executes any post-batch callbacks afterwards.
|
|
224
|
+
* @param callback - The batch operation to execute.
|
|
225
|
+
* @returns A promise if the callback returns a promise, otherwise void.
|
|
226
|
+
*/
|
|
227
|
+
batch<ReturnType>(callback: () => Promise<ReturnType>): Promise<void>;
|
|
228
|
+
batch<ReturnType>(callback: () => ReturnType): void;
|
|
229
|
+
onPostBatch(callback: () => void): void;
|
|
230
|
+
/**
|
|
231
|
+
* Inserts a single item into the collection. Generates a unique ID if not provided.
|
|
232
|
+
* @param item - The item to insert.
|
|
233
|
+
* @returns The ID of the inserted item.
|
|
234
|
+
* @throws {Error} If the collection is disposed or the item has an invalid ID.
|
|
235
|
+
*/
|
|
236
|
+
insert(item: Omit<T, 'id'> & Partial<Pick<T, 'id'>>): Promise<I>;
|
|
237
|
+
/**
|
|
238
|
+
* Inserts multiple items into the collection. Generates unique IDs for items if not provided.
|
|
239
|
+
* @param items - The items to insert.
|
|
240
|
+
* @returns An array of IDs of the inserted items.
|
|
241
|
+
* @throws {Error} If the collection is disposed or the items are invalid.
|
|
242
|
+
*/
|
|
243
|
+
insertMany(items: Array<Omit<T, 'id'> & Partial<Pick<T, 'id'>>>): Promise<I[]>;
|
|
244
|
+
/**
|
|
245
|
+
* Updates a single item in the collection that matches the given selector.
|
|
246
|
+
* @param selector - The criteria to select the item to update.
|
|
247
|
+
* @param modifier - The modifications to apply to the item.
|
|
248
|
+
* @param [options] - Optional settings for the update operation.
|
|
249
|
+
* @param [options.upsert] - If `true`, creates a new item if no item matches the selector.
|
|
250
|
+
* @returns The number of items updated (0 or 1).
|
|
251
|
+
* @throws {Error} If the collection is disposed or invalid arguments are provided.
|
|
252
|
+
*/
|
|
253
|
+
updateOne(selector: Selector<T>, modifier: Modifier<T>, options?: {
|
|
254
|
+
upsert?: boolean;
|
|
255
|
+
}): Promise<number>;
|
|
256
|
+
/**
|
|
257
|
+
* Updates multiple items in the collection that match the given selector.
|
|
258
|
+
* @param selector - The criteria to select the items to update.
|
|
259
|
+
* @param modifier - The modifications to apply to the items.
|
|
260
|
+
* @param [options] - Optional settings for the update operation.
|
|
261
|
+
* @param [options.upsert] - If `true`, creates new items if no items match the selector.
|
|
262
|
+
* @returns The number of items updated.
|
|
263
|
+
* @throws {Error} If the collection is disposed or invalid arguments are provided.
|
|
264
|
+
*/
|
|
265
|
+
updateMany(selector: Selector<T>, modifier: Modifier<T>, options?: {
|
|
266
|
+
upsert?: boolean;
|
|
267
|
+
}): Promise<number>;
|
|
268
|
+
/**
|
|
269
|
+
* Replaces a single item in the collection that matches the given selector.
|
|
270
|
+
* @param selector - The criteria to select the item to replace.
|
|
271
|
+
* @param replacement - The item to replace the selected item with.
|
|
272
|
+
* @param [options] - Optional settings for the replace operation.
|
|
273
|
+
* @param [options.upsert] - If `true`, creates a new item if no item matches the selector.
|
|
274
|
+
* @returns The number of items replaced (0 or 1).
|
|
275
|
+
* @throws {Error} If the collection is disposed or invalid arguments are provided.
|
|
276
|
+
*/
|
|
277
|
+
replaceOne(selector: Selector<T>, replacement: Omit<T, 'id'> & Partial<Pick<T, 'id'>>, options?: {
|
|
278
|
+
upsert?: boolean;
|
|
279
|
+
}): Promise<number>;
|
|
280
|
+
/**
|
|
281
|
+
* Removes a single item from the collection that matches the given selector.
|
|
282
|
+
* @param selector - The criteria to select the item to remove.
|
|
283
|
+
* @returns The number of items removed (0 or 1).
|
|
284
|
+
* @throws {Error} If the collection is disposed or invalid arguments are provided.
|
|
285
|
+
*/
|
|
286
|
+
removeOne(selector: Selector<T>): Promise<number>;
|
|
287
|
+
/**
|
|
288
|
+
* Removes multiple items from the collection that match the given selector.
|
|
289
|
+
* @param selector - The criteria to select the items to remove.
|
|
290
|
+
* @returns The number of items removed.
|
|
291
|
+
* @throws {Error} If the collection is disposed or invalid arguments are provided.
|
|
292
|
+
*/
|
|
293
|
+
removeMany(selector: Selector<T>): Promise<number>;
|
|
294
|
+
}
|