@signaldb/svelte 2.0.0-beta.21 → 2.0.0-beta.22
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/package.json +3 -3
- package/dist/base/core/src/AsyncDataAdapter.d.ts +0 -112
- package/dist/base/core/src/AsyncDataAdapter.js +0 -549
- package/dist/base/core/src/AutoFetchDataAdapter.d.ts +0 -112
- package/dist/base/core/src/AutoFetchDataAdapter.js +0 -612
- package/dist/base/core/src/Collection/Cursor.d.ts +0 -165
- package/dist/base/core/src/Collection/Cursor.js +0 -352
- package/dist/base/core/src/Collection/Observer.d.ts +0 -95
- package/dist/base/core/src/Collection/Observer.js +0 -227
- package/dist/base/core/src/Collection/index.d.ts +0 -341
- package/dist/base/core/src/Collection/index.js +0 -761
- package/dist/base/core/src/Collection/types.d.ts +0 -28
- package/dist/base/core/src/Collection/types.js +0 -2
- package/dist/base/core/src/DataAdapter.d.ts +0 -54
- package/dist/base/core/src/DataAdapter.js +0 -2
- package/dist/base/core/src/DefaultDataAdapter.d.ts +0 -35
- package/dist/base/core/src/DefaultDataAdapter.js +0 -408
- package/dist/base/core/src/WorkerDataAdapter.d.ts +0 -79
- package/dist/base/core/src/WorkerDataAdapter.js +0 -749
- package/dist/base/core/src/WorkerDataAdapterHost.d.ts +0 -64
- package/dist/base/core/src/WorkerDataAdapterHost.js +0 -430
- package/dist/base/core/src/createIndex.d.ts +0 -7
- package/dist/base/core/src/createIndex.js +0 -120
- package/dist/base/core/src/createIndexProvider.d.ts +0 -8
- package/dist/base/core/src/createIndexProvider.js +0 -11
- package/dist/base/core/src/createReactivityAdapter.d.ts +0 -8
- package/dist/base/core/src/createReactivityAdapter.js +0 -11
- package/dist/base/core/src/createStorageAdapter.d.ts +0 -9
- package/dist/base/core/src/createStorageAdapter.js +0 -11
- package/dist/base/core/src/getIndexInfo.d.ts +0 -39
- package/dist/base/core/src/getIndexInfo.js +0 -188
- package/dist/base/core/src/index.d.ts +0 -26
- package/dist/base/core/src/index.js +0 -39
- package/dist/base/core/src/types/Dependency.d.ts +0 -4
- package/dist/base/core/src/types/Dependency.js +0 -2
- package/dist/base/core/src/types/IndexProvider.d.ts +0 -26
- package/dist/base/core/src/types/IndexProvider.js +0 -2
- package/dist/base/core/src/types/Modifier.d.ts +0 -46
- package/dist/base/core/src/types/Modifier.js +0 -3
- package/dist/base/core/src/types/ReactivityAdapter.d.ts +0 -6
- package/dist/base/core/src/types/ReactivityAdapter.js +0 -2
- package/dist/base/core/src/types/Selector.d.ts +0 -46
- package/dist/base/core/src/types/Selector.js +0 -3
- package/dist/base/core/src/types/Signal.d.ts +0 -4
- package/dist/base/core/src/types/Signal.js +0 -2
- package/dist/base/core/src/types/StorageAdapter.d.ts +0 -28
- package/dist/base/core/src/types/StorageAdapter.js +0 -2
- package/dist/base/core/src/utils/EventEmitter.d.ts +0 -71
- package/dist/base/core/src/utils/EventEmitter.js +0 -144
- package/dist/base/core/src/utils/applyQueryOptions.d.ts +0 -15
- package/dist/base/core/src/utils/applyQueryOptions.js +0 -36
- package/dist/base/core/src/utils/batchOnNextTick.d.ts +0 -16
- package/dist/base/core/src/utils/batchOnNextTick.js +0 -72
- package/dist/base/core/src/utils/compact.d.ts +0 -9
- package/dist/base/core/src/utils/compact.js +0 -21
- package/dist/base/core/src/utils/createSignal.d.ts +0 -14
- package/dist/base/core/src/utils/createSignal.js +0 -38
- package/dist/base/core/src/utils/deepClone.d.ts +0 -17
- package/dist/base/core/src/utils/deepClone.js +0 -68
- package/dist/base/core/src/utils/get.d.ts +0 -9
- package/dist/base/core/src/utils/get.js +0 -27
- package/dist/base/core/src/utils/getMatchingKeys.d.ts +0 -19
- package/dist/base/core/src/utils/getMatchingKeys.js +0 -49
- package/dist/base/core/src/utils/idIndexQuery.d.ts +0 -20
- package/dist/base/core/src/utils/idIndexQuery.js +0 -49
- package/dist/base/core/src/utils/incrementalQueryUpdate.d.ts +0 -62
- package/dist/base/core/src/utils/incrementalQueryUpdate.js +0 -197
- package/dist/base/core/src/utils/intersection.d.ts +0 -9
- package/dist/base/core/src/utils/intersection.js +0 -16
- package/dist/base/core/src/utils/isEqual.d.ts +0 -14
- package/dist/base/core/src/utils/isEqual.js +0 -43
- package/dist/base/core/src/utils/isFieldExpression.d.ts +0 -11
- package/dist/base/core/src/utils/isFieldExpression.js +0 -52
- package/dist/base/core/src/utils/match.d.ts +0 -12
- package/dist/base/core/src/utils/match.js +0 -16
- package/dist/base/core/src/utils/modify.d.ts +0 -14
- package/dist/base/core/src/utils/modify.js +0 -29
- package/dist/base/core/src/utils/project.d.ts +0 -15
- package/dist/base/core/src/utils/project.js +0 -43
- package/dist/base/core/src/utils/projectItems.d.ts +0 -12
- package/dist/base/core/src/utils/projectItems.js +0 -25
- package/dist/base/core/src/utils/queryDelta.d.ts +0 -83
- package/dist/base/core/src/utils/queryDelta.js +0 -231
- package/dist/base/core/src/utils/queryId.d.ts +0 -9
- package/dist/base/core/src/utils/queryId.js +0 -61
- package/dist/base/core/src/utils/randomId.d.ts +0 -7
- package/dist/base/core/src/utils/randomId.js +0 -12
- package/dist/base/core/src/utils/reactiveOrAsync.d.ts +0 -59
- package/dist/base/core/src/utils/reactiveOrAsync.js +0 -93
- package/dist/base/core/src/utils/serializeValue.d.ts +0 -12
- package/dist/base/core/src/utils/serializeValue.js +0 -27
- package/dist/base/core/src/utils/set.d.ts +0 -13
- package/dist/base/core/src/utils/set.js +0 -43
- package/dist/base/core/src/utils/sortItems.d.ts +0 -12
- package/dist/base/core/src/utils/sortItems.js +0 -23
- package/dist/base/core/src/utils/storageIndexQuery.d.ts +0 -20
- package/dist/base/core/src/utils/storageIndexQuery.js +0 -75
- package/dist/base/core/src/utils/uniqueBy.d.ts +0 -10
- package/dist/base/core/src/utils/uniqueBy.js +0 -19
- package/dist/index.cjs +0 -38
- package/dist/index.cjs.map +0 -1
- package/dist/index.mjs +0 -38
- package/dist/index.mjs.map +0 -1
- package/dist/reactivity-adapters/svelte/index.svelte.d.ts +0 -10
- package/dist/reactivity-adapters/svelte/index.svelte.js +0 -36
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import type { QueryOptions } from '../DataAdapter';
|
|
2
|
-
import type ReactivityAdapter from '../types/ReactivityAdapter';
|
|
3
|
-
export type BaseItem<I = any> = {
|
|
4
|
-
id: I;
|
|
5
|
-
} & Record<string, any>;
|
|
6
|
-
export type Transform<T, U = T> = ((document: T) => U) | null | undefined;
|
|
7
|
-
export type TransformAll<T extends BaseItem, O extends BaseItem = T> = ((items: T[], fields: FieldSpecifier<O> | undefined) => O[]) | null | undefined;
|
|
8
|
-
export type SortSpecifier<T> = {
|
|
9
|
-
[P in keyof T]?: -1 | 1;
|
|
10
|
-
} & Record<string, -1 | 1>;
|
|
11
|
-
export type FieldSpecifier<T> = {
|
|
12
|
-
[P in keyof T]?: 0 | 1;
|
|
13
|
-
} & Record<string, 0 | 1>;
|
|
14
|
-
export interface FindOptions<T extends BaseItem, Async extends boolean> extends QueryOptions<T> {
|
|
15
|
-
/** pass `false` to disable reactivity */
|
|
16
|
-
reactive?: ReactivityAdapter | false;
|
|
17
|
-
/** pass `true` to enable automatic field-level reactitivy */
|
|
18
|
-
fieldTracking?: boolean;
|
|
19
|
-
/** pass `true` to execute the query asynchronously */
|
|
20
|
-
async?: Async;
|
|
21
|
-
}
|
|
22
|
-
export type AsyncFindOptions<T extends BaseItem> = Omit<FindOptions<T, true>, 'async'> & {
|
|
23
|
-
async: true;
|
|
24
|
-
};
|
|
25
|
-
export type SyncFindOptions<T extends BaseItem> = Omit<FindOptions<T, false>, 'async'> & {
|
|
26
|
-
async?: false;
|
|
27
|
-
};
|
|
28
|
-
export type AnyFindOptions<T extends BaseItem> = AsyncFindOptions<T> | SyncFindOptions<T>;
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import type { BaseItem, FieldSpecifier, SortSpecifier } from './Collection';
|
|
2
|
-
import type Collection from './Collection';
|
|
3
|
-
import type Modifier from './types/Modifier';
|
|
4
|
-
import type Selector from './types/Selector';
|
|
5
|
-
import type { QueryDelta } from './utils/queryDelta';
|
|
6
|
-
export interface QueryOptions<T extends BaseItem> {
|
|
7
|
-
/** Sort order (default: natural order) */
|
|
8
|
-
sort?: SortSpecifier<T> | undefined;
|
|
9
|
-
/** Number of results to skip at the beginning */
|
|
10
|
-
skip?: number | undefined;
|
|
11
|
-
/** Maximum number of results to return */
|
|
12
|
-
limit?: number | undefined;
|
|
13
|
-
/** Dictionary of fields to return or exclude. */
|
|
14
|
-
fields?: FieldSpecifier<T> | undefined;
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* Notified when a query's state changes.
|
|
18
|
-
*
|
|
19
|
-
* A `'complete'` notification may carry a delta describing how the result changed since the last
|
|
20
|
-
* one. An adapter that can produce one saves its listeners from rediscovering the change by
|
|
21
|
-
* comparing the whole result against the whole previous result; one that cannot simply omits it,
|
|
22
|
-
* and its listeners fall back to exactly that comparison.
|
|
23
|
-
*
|
|
24
|
-
* A delta is only ever passed when it is relative to what `getQueryResult` returned the last time
|
|
25
|
-
* it was asked. An adapter that layers anything on top of its stored result — an optimistic write
|
|
26
|
-
* still in flight, for instance — must omit the delta for as long as it does.
|
|
27
|
-
*/
|
|
28
|
-
export type StateChangeCallback<T extends BaseItem = BaseItem> = (state: 'active' | 'complete' | 'error', delta?: QueryDelta<T>) => void;
|
|
29
|
-
export interface CollectionBackend<T extends BaseItem<I>, I> {
|
|
30
|
-
insert(item: T): Promise<T>;
|
|
31
|
-
updateOne(selector: Selector<T>, modifier: Modifier<T>): Promise<T[]>;
|
|
32
|
-
updateMany(selector: Selector<T>, modifier: Modifier<T>): Promise<T[]>;
|
|
33
|
-
replaceOne(selector: Selector<T>, replacement: Omit<T, 'id'> & Partial<Pick<T, 'id'>>): Promise<T[]>;
|
|
34
|
-
removeOne(selector: Selector<T>): Promise<T[]>;
|
|
35
|
-
removeMany(selector: Selector<T>): Promise<T[]>;
|
|
36
|
-
registerQuery<O extends QueryOptions<T>>(selector: Selector<T>, options: O): void;
|
|
37
|
-
unregisterQuery<O extends QueryOptions<T>>(selector: Selector<T>, options: O): void;
|
|
38
|
-
/**
|
|
39
|
-
* Re-runs a query that is currently in the `'error'` state. Optional so
|
|
40
|
-
* existing custom adapters keep compiling — an adapter that never surfaces
|
|
41
|
-
* an error state has nothing to implement.
|
|
42
|
-
*/
|
|
43
|
-
retryQuery?<O extends QueryOptions<T>>(selector: Selector<T>, options: O): void;
|
|
44
|
-
getQueryState<O extends QueryOptions<T>>(selector: Selector<T>, options: O): 'active' | 'complete' | 'error';
|
|
45
|
-
getQueryError<O extends QueryOptions<T>>(selector: Selector<T>, options: O): Error | null;
|
|
46
|
-
getQueryResult<O extends QueryOptions<T>>(selector: Selector<T>, options: O): T[];
|
|
47
|
-
executeQuery<O extends QueryOptions<T>>(selector: Selector<T>, options: O): Promise<T[]>;
|
|
48
|
-
onQueryStateChange<O extends QueryOptions<T>>(selector: Selector<T>, options: O, callback: StateChangeCallback<T>): () => void;
|
|
49
|
-
dispose(): Promise<void>;
|
|
50
|
-
isReady(): Promise<void>;
|
|
51
|
-
}
|
|
52
|
-
export default interface DataAdapter {
|
|
53
|
-
createCollectionBackend<T extends BaseItem<I>, I = any, E extends BaseItem = T, U = E>(collection: Collection<T, I, E, U>, indices: string[]): CollectionBackend<T, I>;
|
|
54
|
-
}
|
|
@@ -1,35 +0,0 @@
|
|
|
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
|
-
interface DefaultDataAdapterOptions {
|
|
7
|
-
storage?: (name: string) => StorageAdapter<any, any> | undefined;
|
|
8
|
-
onError?: (name: string, error: Error) => void;
|
|
9
|
-
}
|
|
10
|
-
export default class DefaultDataAdapter implements DataAdapter {
|
|
11
|
-
private items;
|
|
12
|
-
private options;
|
|
13
|
-
private storageAdapters;
|
|
14
|
-
private collections;
|
|
15
|
-
private indices;
|
|
16
|
-
private activeQueries;
|
|
17
|
-
private queryEmitters;
|
|
18
|
-
private queuedQueryUpdates;
|
|
19
|
-
private cachedQueryResults;
|
|
20
|
-
constructor(options?: DefaultDataAdapterOptions);
|
|
21
|
-
private ensureStorageAdapter;
|
|
22
|
-
private rebuildIndices;
|
|
23
|
-
private setupStorageAdapter;
|
|
24
|
-
private getIndexInfo;
|
|
25
|
-
private applyIndexDeltas;
|
|
26
|
-
private getItem;
|
|
27
|
-
private queryItems;
|
|
28
|
-
private executeQuery;
|
|
29
|
-
private flushQueuedQueryUpdates;
|
|
30
|
-
private executeAndCacheQuery;
|
|
31
|
-
private updateQueries;
|
|
32
|
-
createCollectionBackend<T extends BaseItem<I>, I = any, E extends BaseItem = T, U = E>(collection: Collection<T, I, E, U>, indices: string[]): CollectionBackend<T, I>;
|
|
33
|
-
fetchItemsFromStorage<T extends BaseItem<I>, I = any, E extends BaseItem = T, U = E>(collection?: Collection<T, I, E, U>): Promise<void>;
|
|
34
|
-
}
|
|
35
|
-
export {};
|
|
@@ -1,408 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
const createIndex_1 = __importDefault(require("./createIndex"));
|
|
7
|
-
const getIndexInfo_1 = __importDefault(require("./getIndexInfo"));
|
|
8
|
-
const deepClone_1 = __importDefault(require("./utils/deepClone"));
|
|
9
|
-
const EventEmitter_1 = __importDefault(require("./utils/EventEmitter"));
|
|
10
|
-
const isEqual_1 = __importDefault(require("./utils/isEqual"));
|
|
11
|
-
const match_1 = __importDefault(require("./utils/match"));
|
|
12
|
-
const modify_1 = __importDefault(require("./utils/modify"));
|
|
13
|
-
const projectItems_1 = __importDefault(require("./utils/projectItems"));
|
|
14
|
-
const incrementalQueryUpdate_1 = __importDefault(require("./utils/incrementalQueryUpdate"));
|
|
15
|
-
const queryDelta_1 = require("./utils/queryDelta");
|
|
16
|
-
const queryId_1 = __importDefault(require("./utils/queryId"));
|
|
17
|
-
const serializeValue_1 = __importDefault(require("./utils/serializeValue"));
|
|
18
|
-
const idIndexQuery_1 = __importDefault(require("./utils/idIndexQuery"));
|
|
19
|
-
const sortItems_1 = __importDefault(require("./utils/sortItems"));
|
|
20
|
-
/**
|
|
21
|
-
* Checks if there are any pending updates in the given changeset.
|
|
22
|
-
* @template T - The type of the items in the changeset.
|
|
23
|
-
* @param pendingUpdates - The changeset to check for pending updates.
|
|
24
|
-
* @returns `true` if there are pending updates, otherwise `false`.
|
|
25
|
-
*/
|
|
26
|
-
function hasPendingUpdates(pendingUpdates) {
|
|
27
|
-
return pendingUpdates.added.length > 0
|
|
28
|
-
|| pendingUpdates.modified.length > 0
|
|
29
|
-
|| pendingUpdates.removed.length > 0;
|
|
30
|
-
}
|
|
31
|
-
class DefaultDataAdapter {
|
|
32
|
-
items = new Map();
|
|
33
|
-
options;
|
|
34
|
-
storageAdapters = new Map();
|
|
35
|
-
collections = new Set();
|
|
36
|
-
indices = new Map();
|
|
37
|
-
activeQueries = new Map();
|
|
38
|
-
queryEmitters = new Map();
|
|
39
|
-
queuedQueryUpdates = new Map();
|
|
40
|
-
cachedQueryResults = new Map();
|
|
41
|
-
constructor(options) {
|
|
42
|
-
this.options = options || {};
|
|
43
|
-
}
|
|
44
|
-
ensureStorageAdapter(name) {
|
|
45
|
-
if (this.storageAdapters.get(name))
|
|
46
|
-
return; // already created
|
|
47
|
-
if (!this.options.storage)
|
|
48
|
-
return; // no storage function provided
|
|
49
|
-
const adapter = this.options.storage(name);
|
|
50
|
-
if (!adapter)
|
|
51
|
-
return; // no adapter returned
|
|
52
|
-
this.storageAdapters.set(name, adapter);
|
|
53
|
-
}
|
|
54
|
-
rebuildIndices(collection) {
|
|
55
|
-
const items = this.items.get(collection.name);
|
|
56
|
-
if (!items)
|
|
57
|
-
throw new Error(`Items not found for collection ${collection.name}`);
|
|
58
|
-
const indices = this.indices.get(collection.name);
|
|
59
|
-
if (!indices)
|
|
60
|
-
throw new Error(`Indices not found for collection ${collection.name}`);
|
|
61
|
-
indices.forEach(index => index.rebuild([...items.values()]));
|
|
62
|
-
}
|
|
63
|
-
async setupStorageAdapter(collection) {
|
|
64
|
-
const storageAdapter = this.storageAdapters.get(collection.name);
|
|
65
|
-
if (!storageAdapter)
|
|
66
|
-
return; // no persistence adapter available
|
|
67
|
-
return storageAdapter.setup()
|
|
68
|
-
.then(async () => {
|
|
69
|
-
await this.fetchItemsFromStorage(collection);
|
|
70
|
-
})
|
|
71
|
-
.catch((error) => {
|
|
72
|
-
if (!this.options.onError) {
|
|
73
|
-
// eslint-disable-next-line no-console
|
|
74
|
-
console.error(`Error during data persistence operation in collection ${collection.name}`, error);
|
|
75
|
-
return;
|
|
76
|
-
}
|
|
77
|
-
this.options.onError(collection.name, error instanceof Error ? error : new Error(error));
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
getIndexInfo(collection, selector) {
|
|
81
|
-
if (selector != null && Object.keys(selector).length === 1 && 'id' in selector) {
|
|
82
|
-
const idResult = (0, idIndexQuery_1.default)(selector);
|
|
83
|
-
if (idResult.matched) {
|
|
84
|
-
return {
|
|
85
|
-
// This adapter keys its in-memory map by `serializeValue(id)`.
|
|
86
|
-
matched: true,
|
|
87
|
-
ids: idResult.ids.map(id => (0, serializeValue_1.default)(id)),
|
|
88
|
-
optimizedSelector: {},
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
if (selector == null) {
|
|
93
|
-
return {
|
|
94
|
-
matched: false,
|
|
95
|
-
ids: [],
|
|
96
|
-
optimizedSelector: {},
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
return (0, getIndexInfo_1.default)((this.indices.get(collection.name) ?? []).map(i => i.query.bind(i)), selector);
|
|
100
|
-
}
|
|
101
|
-
applyIndexDeltas(collection, changes) {
|
|
102
|
-
const indices = this.indices.get(collection.name) ?? [];
|
|
103
|
-
for (const index of indices) {
|
|
104
|
-
if (changes.modified)
|
|
105
|
-
index.update(changes.modified);
|
|
106
|
-
if (changes.added && changes.added.length > 0)
|
|
107
|
-
index.insert(changes.added);
|
|
108
|
-
if (changes.removed && changes.removed.length > 0)
|
|
109
|
-
index.remove(changes.removed);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
getItem(collection, selector) {
|
|
113
|
-
const memory = this.items.get(collection.name) ?? new Map();
|
|
114
|
-
const indexInfo = this.getIndexInfo(collection, selector);
|
|
115
|
-
const items = indexInfo.matched
|
|
116
|
-
? indexInfo.ids.map(id => memory.get((0, serializeValue_1.default)(id))).filter(i => i != null)
|
|
117
|
-
: [...memory.values()];
|
|
118
|
-
const item = items.find(document => (0, match_1.default)(document, selector));
|
|
119
|
-
return item;
|
|
120
|
-
}
|
|
121
|
-
queryItems(collection, selector) {
|
|
122
|
-
const indexInfo = this.getIndexInfo(collection, selector);
|
|
123
|
-
const matchItems = (item) => {
|
|
124
|
-
if (indexInfo.optimizedSelector == null)
|
|
125
|
-
return true; // if no selector is given, return all items
|
|
126
|
-
if (Object.keys(indexInfo.optimizedSelector).length <= 0)
|
|
127
|
-
return true; // if selector is empty, return all items
|
|
128
|
-
const matches = (0, match_1.default)(item, indexInfo.optimizedSelector);
|
|
129
|
-
return matches;
|
|
130
|
-
};
|
|
131
|
-
const items = this.items.get(collection.name);
|
|
132
|
-
// no index available, use complete memory
|
|
133
|
-
if (!indexInfo.matched) {
|
|
134
|
-
if ((0, isEqual_1.default)(selector, {}))
|
|
135
|
-
return [...items.values()];
|
|
136
|
-
return [...items.values()].filter(matchItems);
|
|
137
|
-
}
|
|
138
|
-
const foundItems = indexInfo.ids.map(ids => items.get((0, serializeValue_1.default)(ids))).filter(i => i != null);
|
|
139
|
-
if ((0, isEqual_1.default)(indexInfo.optimizedSelector, {}))
|
|
140
|
-
return foundItems;
|
|
141
|
-
return foundItems.filter(matchItems);
|
|
142
|
-
}
|
|
143
|
-
executeQuery(collection, selector, options) {
|
|
144
|
-
const items = this.queryItems(collection, selector || {});
|
|
145
|
-
const { sort, skip, limit, fields } = options || {};
|
|
146
|
-
const sorted = sort ? (0, sortItems_1.default)(items, sort) : items;
|
|
147
|
-
const skipped = skip ? sorted.slice(skip) : sorted;
|
|
148
|
-
const limited = limit ? skipped.slice(0, limit) : skipped;
|
|
149
|
-
return (0, projectItems_1.default)(limited, fields);
|
|
150
|
-
}
|
|
151
|
-
flushQueuedQueryUpdates(collection) {
|
|
152
|
-
if (!this.queuedQueryUpdates.get(collection.name))
|
|
153
|
-
return;
|
|
154
|
-
const changes = this.queuedQueryUpdates.get(collection.name);
|
|
155
|
-
if (!changes || !hasPendingUpdates(changes))
|
|
156
|
-
return;
|
|
157
|
-
this.queuedQueryUpdates.set(collection.name, { added: [], modified: [], removed: [] });
|
|
158
|
-
const changeset = {
|
|
159
|
-
upserts: [...changes.added, ...changes.modified],
|
|
160
|
-
deletes: changes.removed.map(item => item.id),
|
|
161
|
-
};
|
|
162
|
-
const flatItems = [...changes.added, ...changes.modified, ...changes.removed];
|
|
163
|
-
const itemIds = new Set(flatItems.map(i => i.id));
|
|
164
|
-
const queries = [
|
|
165
|
-
...this.activeQueries.get(collection.name)?.values() ?? [],
|
|
166
|
-
].filter(({ selector, options }) => {
|
|
167
|
-
const idsInQuery = this.cachedQueryResults.get(collection.name)
|
|
168
|
-
?.get((0, queryId_1.default)(selector, options))
|
|
169
|
-
?.map(i => i.id) ?? [];
|
|
170
|
-
// update queries that contained changed items previously
|
|
171
|
-
if (idsInQuery.some(id => itemIds.has(id)))
|
|
172
|
-
return true;
|
|
173
|
-
return flatItems.some(item => (0, match_1.default)(item, selector));
|
|
174
|
-
});
|
|
175
|
-
queries.forEach(({ selector, options }) => {
|
|
176
|
-
this.executeAndCacheQuery(collection, selector, options, changeset);
|
|
177
|
-
});
|
|
178
|
-
}
|
|
179
|
-
executeAndCacheQuery(collection, selector, options, changes) {
|
|
180
|
-
const cached = this.cachedQueryResults.get(collection.name)?.get((0, queryId_1.default)(selector, options));
|
|
181
|
-
// With the change in hand and the previous result cached, the query can be brought up to date
|
|
182
|
-
// without walking every item this collection holds — and the listeners can be told what
|
|
183
|
-
// changed instead of being left to compare the two results themselves.
|
|
184
|
-
const incremental = changes && cached
|
|
185
|
-
? (0, incrementalQueryUpdate_1.default)(cached, selector, options, changes)
|
|
186
|
-
: null;
|
|
187
|
-
const result = incremental ?? this.executeQuery(collection, selector, options);
|
|
188
|
-
const delta = cached ? (0, queryDelta_1.diffQueryResults)(cached, result) : undefined;
|
|
189
|
-
this.cachedQueryResults.set(collection.name, this.cachedQueryResults.get(collection.name) || new Map());
|
|
190
|
-
this.cachedQueryResults.get(collection.name)?.set((0, queryId_1.default)(selector, options), result);
|
|
191
|
-
const emitter = this.queryEmitters.get(collection.name);
|
|
192
|
-
if (!emitter)
|
|
193
|
-
return;
|
|
194
|
-
if (delta && (0, queryDelta_1.isEmptyQueryDelta)(delta))
|
|
195
|
-
return;
|
|
196
|
-
emitter.emit('change', selector, options, 'complete', delta);
|
|
197
|
-
}
|
|
198
|
-
updateQueries(collection, changes) {
|
|
199
|
-
this.queuedQueryUpdates.set(collection.name, this.queuedQueryUpdates.get(collection.name) || { added: [], modified: [], removed: [] });
|
|
200
|
-
this.queuedQueryUpdates.get(collection.name)?.added.push(...changes.added);
|
|
201
|
-
this.queuedQueryUpdates.get(collection.name)?.modified.push(...changes.modified);
|
|
202
|
-
this.queuedQueryUpdates.get(collection.name)?.removed.push(...changes.removed);
|
|
203
|
-
this.flushQueuedQueryUpdates(collection);
|
|
204
|
-
}
|
|
205
|
-
createCollectionBackend(collection, indices) {
|
|
206
|
-
this.collections.add(collection);
|
|
207
|
-
this.ensureStorageAdapter(collection.name);
|
|
208
|
-
this.items.set(collection.name, this.items.get(collection.name) ?? new Map());
|
|
209
|
-
this.queryEmitters.set(collection.name, this.queryEmitters.get(collection.name) ?? new EventEmitter_1.default());
|
|
210
|
-
// we might have many active queries
|
|
211
|
-
this.queryEmitters.get(collection.name)?.setMaxListeners(Infinity);
|
|
212
|
-
this.activeQueries.set(collection.name, this.activeQueries.get(collection.name) || new Map());
|
|
213
|
-
this.indices.set(collection.name, indices.map(field => (0, createIndex_1.default)(field)));
|
|
214
|
-
this.rebuildIndices(collection);
|
|
215
|
-
const persistenceReadyPromise = this.setupStorageAdapter(collection);
|
|
216
|
-
const backend = {
|
|
217
|
-
// CRUD operations
|
|
218
|
-
insert: async (newItem) => {
|
|
219
|
-
const items = this.items.get(collection.name);
|
|
220
|
-
if (!items)
|
|
221
|
-
throw new Error(`Items not found for collection ${collection.name}`);
|
|
222
|
-
if (items.has((0, serializeValue_1.default)(newItem.id))) {
|
|
223
|
-
throw new Error(`Item with id '${newItem.id}' already exists`);
|
|
224
|
-
}
|
|
225
|
-
this.items.get(collection.name)?.set((0, serializeValue_1.default)(newItem.id), newItem);
|
|
226
|
-
await this.storageAdapters.get(collection.name)?.insert([newItem]);
|
|
227
|
-
this.applyIndexDeltas(collection, { added: [newItem] });
|
|
228
|
-
this.updateQueries(collection, {
|
|
229
|
-
added: [],
|
|
230
|
-
modified: [newItem],
|
|
231
|
-
removed: [],
|
|
232
|
-
});
|
|
233
|
-
return newItem;
|
|
234
|
-
},
|
|
235
|
-
updateOne: async (selector, modifier) => {
|
|
236
|
-
const { $setOnInsert, ...restModifier } = modifier;
|
|
237
|
-
const item = this.getItem(collection, selector);
|
|
238
|
-
if (item == null)
|
|
239
|
-
return []; // no item found
|
|
240
|
-
const modifiedItem = (0, modify_1.default)((0, deepClone_1.default)(item), restModifier);
|
|
241
|
-
const hasItemWithSameId = item.id !== modifiedItem.id
|
|
242
|
-
&& this.getItem(collection, { id: modifiedItem.id }) != null;
|
|
243
|
-
if (hasItemWithSameId) {
|
|
244
|
-
throw new Error(`Item with id '${modifiedItem.id}' already exists`);
|
|
245
|
-
}
|
|
246
|
-
this.items.get(collection.name)?.set((0, serializeValue_1.default)(modifiedItem.id), modifiedItem);
|
|
247
|
-
await this.storageAdapters.get(collection.name)?.replace([modifiedItem]);
|
|
248
|
-
this.applyIndexDeltas(collection, { modified: [{ oldItem: item, newItem: modifiedItem }] });
|
|
249
|
-
this.updateQueries(collection, {
|
|
250
|
-
added: [],
|
|
251
|
-
modified: [modifiedItem],
|
|
252
|
-
removed: [],
|
|
253
|
-
});
|
|
254
|
-
return [modifiedItem];
|
|
255
|
-
},
|
|
256
|
-
updateMany: async (selector, modifier) => {
|
|
257
|
-
const { $setOnInsert, ...restModifier } = modifier;
|
|
258
|
-
const items = this.executeQuery(collection, selector, {});
|
|
259
|
-
const changedItems = items.map((item) => {
|
|
260
|
-
const modifiedItem = (0, modify_1.default)((0, deepClone_1.default)(item), restModifier);
|
|
261
|
-
const hasItemWithSameId = item.id !== modifiedItem.id
|
|
262
|
-
&& this.getItem(collection, { id: modifiedItem.id }) != null;
|
|
263
|
-
if (hasItemWithSameId) {
|
|
264
|
-
throw new Error(`Item with id '${modifiedItem.id}' already exists`);
|
|
265
|
-
}
|
|
266
|
-
return modifiedItem;
|
|
267
|
-
});
|
|
268
|
-
changedItems.forEach((item) => {
|
|
269
|
-
this.items.get(collection.name)?.set((0, serializeValue_1.default)(item.id), item);
|
|
270
|
-
});
|
|
271
|
-
await this.storageAdapters.get(collection.name)?.replace(changedItems);
|
|
272
|
-
const pairs = items.map((oldItem, index) => ({ oldItem, newItem: changedItems[index] }));
|
|
273
|
-
this.applyIndexDeltas(collection, { modified: pairs });
|
|
274
|
-
this.updateQueries(collection, {
|
|
275
|
-
added: [],
|
|
276
|
-
modified: changedItems,
|
|
277
|
-
removed: [],
|
|
278
|
-
});
|
|
279
|
-
return changedItems;
|
|
280
|
-
},
|
|
281
|
-
replaceOne: async (selector, replacement) => {
|
|
282
|
-
const item = this.getItem(collection, selector);
|
|
283
|
-
if (item == null)
|
|
284
|
-
return []; // no item found
|
|
285
|
-
const hasItemWithSameId = item.id !== replacement.id
|
|
286
|
-
&& replacement.id != null
|
|
287
|
-
&& this.getItem(collection, { id: replacement.id }) != null;
|
|
288
|
-
if (hasItemWithSameId) {
|
|
289
|
-
throw new Error(`Item with id '${replacement.id}' already exists`);
|
|
290
|
-
}
|
|
291
|
-
const modifiedItem = { id: item.id, ...replacement };
|
|
292
|
-
this.items.get(collection.name)?.set((0, serializeValue_1.default)(modifiedItem.id), modifiedItem);
|
|
293
|
-
await this.storageAdapters.get(collection.name)?.replace([modifiedItem]);
|
|
294
|
-
this.applyIndexDeltas(collection, { modified: [{ oldItem: item, newItem: modifiedItem }] });
|
|
295
|
-
this.updateQueries(collection, {
|
|
296
|
-
added: [],
|
|
297
|
-
modified: [modifiedItem],
|
|
298
|
-
removed: [],
|
|
299
|
-
});
|
|
300
|
-
return [modifiedItem];
|
|
301
|
-
},
|
|
302
|
-
removeOne: async (selector) => {
|
|
303
|
-
const item = this.getItem(collection, selector);
|
|
304
|
-
if (item == null)
|
|
305
|
-
return []; // no item found
|
|
306
|
-
this.items.get(collection.name)?.delete((0, serializeValue_1.default)(item.id));
|
|
307
|
-
await this.storageAdapters.get(collection.name)?.remove([item]);
|
|
308
|
-
this.applyIndexDeltas(collection, { removed: [item] });
|
|
309
|
-
this.updateQueries(collection, {
|
|
310
|
-
added: [],
|
|
311
|
-
modified: [],
|
|
312
|
-
removed: [item],
|
|
313
|
-
});
|
|
314
|
-
return [item];
|
|
315
|
-
},
|
|
316
|
-
removeMany: async (selector) => {
|
|
317
|
-
const items = backend.getQueryResult(selector, {});
|
|
318
|
-
items.forEach((item) => {
|
|
319
|
-
this.items.get(collection.name)?.delete((0, serializeValue_1.default)(item.id));
|
|
320
|
-
});
|
|
321
|
-
await this.storageAdapters.get(collection.name)?.remove(items);
|
|
322
|
-
this.applyIndexDeltas(collection, { removed: items });
|
|
323
|
-
this.updateQueries(collection, {
|
|
324
|
-
added: [],
|
|
325
|
-
modified: [],
|
|
326
|
-
removed: items,
|
|
327
|
-
});
|
|
328
|
-
return items;
|
|
329
|
-
},
|
|
330
|
-
// methods for registering and unregistering queries that will be called from the collection during find/findOne
|
|
331
|
-
registerQuery: (selector, options) => {
|
|
332
|
-
this.activeQueries.set(collection.name, this.activeQueries.get(collection.name) || new Map());
|
|
333
|
-
this.activeQueries.get(collection.name)?.set((0, queryId_1.default)(selector, options), {
|
|
334
|
-
selector,
|
|
335
|
-
options,
|
|
336
|
-
});
|
|
337
|
-
this.executeAndCacheQuery(collection, selector, options);
|
|
338
|
-
},
|
|
339
|
-
unregisterQuery: (selector, options) => {
|
|
340
|
-
if (!this.activeQueries.get(collection.name))
|
|
341
|
-
return;
|
|
342
|
-
this.activeQueries.get(collection.name)?.delete((0, queryId_1.default)(selector, options));
|
|
343
|
-
},
|
|
344
|
-
getQueryState: () => 'complete',
|
|
345
|
-
onQueryStateChange: (selector, options, callback) => {
|
|
346
|
-
const emitter = this.queryEmitters.get(collection.name);
|
|
347
|
-
if (!emitter)
|
|
348
|
-
throw new Error(`Query emitter not found for collection ${collection.name}`);
|
|
349
|
-
const handler = (querySelector, queryOptions, state, delta) => {
|
|
350
|
-
if ((0, queryId_1.default)(querySelector, queryOptions) !== (0, queryId_1.default)(selector, options))
|
|
351
|
-
return;
|
|
352
|
-
(0, queryDelta_1.callWithDelta)(callback, state, delta);
|
|
353
|
-
};
|
|
354
|
-
emitter.on('change', handler);
|
|
355
|
-
return () => {
|
|
356
|
-
emitter.off('change', handler);
|
|
357
|
-
};
|
|
358
|
-
},
|
|
359
|
-
getQueryError: () => null,
|
|
360
|
-
getQueryResult: (selector, options) => {
|
|
361
|
-
const isQueryActive = this.activeQueries.get(collection.name)
|
|
362
|
-
?.has((0, queryId_1.default)(selector, options));
|
|
363
|
-
if (isQueryActive) {
|
|
364
|
-
const results = this.cachedQueryResults
|
|
365
|
-
.get(collection.name)
|
|
366
|
-
?.get((0, queryId_1.default)(selector, options));
|
|
367
|
-
if (!results)
|
|
368
|
-
throw new Error('Cached query results are not defined!');
|
|
369
|
-
return results;
|
|
370
|
-
}
|
|
371
|
-
return this.executeQuery(collection, selector, options);
|
|
372
|
-
},
|
|
373
|
-
executeQuery: (selector, options) => Promise.resolve(this.executeQuery(collection, selector, options)),
|
|
374
|
-
// lifecycle methods
|
|
375
|
-
dispose: async () => {
|
|
376
|
-
const adapter = this.storageAdapters.get(collection.name);
|
|
377
|
-
if (adapter?.teardown)
|
|
378
|
-
await adapter.teardown();
|
|
379
|
-
this.storageAdapters.delete(collection.name);
|
|
380
|
-
this.items.delete(collection.name);
|
|
381
|
-
this.indices.delete(collection.name);
|
|
382
|
-
this.activeQueries.delete(collection.name);
|
|
383
|
-
this.queryEmitters.delete(collection.name);
|
|
384
|
-
this.queuedQueryUpdates.delete(collection.name);
|
|
385
|
-
this.cachedQueryResults.delete(collection.name);
|
|
386
|
-
},
|
|
387
|
-
isReady: () => persistenceReadyPromise,
|
|
388
|
-
};
|
|
389
|
-
return backend;
|
|
390
|
-
}
|
|
391
|
-
async fetchItemsFromStorage(collection) {
|
|
392
|
-
if (!collection) {
|
|
393
|
-
await Promise.all([...this.collections]
|
|
394
|
-
.map(currentCollection => this.fetchItemsFromStorage(currentCollection)));
|
|
395
|
-
return;
|
|
396
|
-
}
|
|
397
|
-
const storageAdapter = this.storageAdapters.get(collection.name);
|
|
398
|
-
if (!storageAdapter)
|
|
399
|
-
return; // no persistence adapter available
|
|
400
|
-
const items = await storageAdapter.readAll();
|
|
401
|
-
this.items.set(collection.name, items.reduce((map, item) => {
|
|
402
|
-
map.set((0, serializeValue_1.default)(item.id), item);
|
|
403
|
-
return map;
|
|
404
|
-
}, new Map()));
|
|
405
|
-
this.rebuildIndices(collection);
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
exports.default = DefaultDataAdapter;
|
|
@@ -1,79 +0,0 @@
|
|
|
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
|
-
interface WorkerDataAdapterOptions {
|
|
6
|
-
id?: string;
|
|
7
|
-
log?: (message: string, ...args: any[]) => void;
|
|
8
|
-
}
|
|
9
|
-
export interface WorkerDataAdapterEndpoint {
|
|
10
|
-
addEventListener: (type: 'message', listener: (event: MessageEvent) => void) => void;
|
|
11
|
-
removeEventListener: (type: 'message', listener: (event: MessageEvent) => void) => void;
|
|
12
|
-
postMessage: (message: unknown) => void;
|
|
13
|
-
terminate?: () => void;
|
|
14
|
-
}
|
|
15
|
-
export default class WorkerDataAdapter implements DataAdapter {
|
|
16
|
-
private worker;
|
|
17
|
-
private options;
|
|
18
|
-
private id;
|
|
19
|
-
private isDisposed;
|
|
20
|
-
private workerReady;
|
|
21
|
-
private log;
|
|
22
|
-
private collectionReady;
|
|
23
|
-
private batchExecutionHelpers;
|
|
24
|
-
private queries;
|
|
25
|
-
private pendingRequests;
|
|
26
|
-
private pendingWrites;
|
|
27
|
-
private pendingWriteSeq;
|
|
28
|
-
private pendingWriteVersions;
|
|
29
|
-
private bumpPendingWriteVersion;
|
|
30
|
-
constructor(worker: WorkerDataAdapterEndpoint, options: WorkerDataAdapterOptions);
|
|
31
|
-
private resolveWorkerReady;
|
|
32
|
-
private handleWorkerMessage;
|
|
33
|
-
private handleQueryUpdate;
|
|
34
|
-
private exec;
|
|
35
|
-
/**
|
|
36
|
-
* Issues a call whose result nobody is waiting for, and makes sure a failure has somewhere to
|
|
37
|
-
* go. A bare rejection here would surface as an uncaught error — which is what a disposed
|
|
38
|
-
* collection produced every time a cursor was cleaned up after it.
|
|
39
|
-
* @param method - The method to call on the worker.
|
|
40
|
-
* @param collectionName - The collection it applies to.
|
|
41
|
-
* @param args - The remaining arguments.
|
|
42
|
-
* @param onError - Called when the call fails, in place of merely logging it.
|
|
43
|
-
*/
|
|
44
|
-
private execInBackground;
|
|
45
|
-
private queryItemsById;
|
|
46
|
-
private flattenPendingWrites;
|
|
47
|
-
private static pushPendingEntry;
|
|
48
|
-
private static dropPendingEntry;
|
|
49
|
-
private static writeFlatEntry;
|
|
50
|
-
private static providesFullItems;
|
|
51
|
-
private observableItems;
|
|
52
|
-
private observableItemsByIds;
|
|
53
|
-
private servedResult;
|
|
54
|
-
private advanceServedResult;
|
|
55
|
-
private changesetForIds;
|
|
56
|
-
private computeServedResult;
|
|
57
|
-
/**
|
|
58
|
-
* Registers a write's effect locally and notifies every active query it
|
|
59
|
-
* touches, then returns a function that drops it again once the write
|
|
60
|
-
* settles.
|
|
61
|
-
* @param collectionName - The collection the write targets.
|
|
62
|
-
* @param upserts - Items inserted or updated by the write.
|
|
63
|
-
* @param deletes - Ids removed by the write.
|
|
64
|
-
* @returns A function that drops the pending write and re-notifies.
|
|
65
|
-
*/
|
|
66
|
-
private applyPendingWrite;
|
|
67
|
-
private affectedQueries;
|
|
68
|
-
private servedResults;
|
|
69
|
-
private notifyWithDeltas;
|
|
70
|
-
private matchObservableItems;
|
|
71
|
-
private resolveUpdate;
|
|
72
|
-
private resolveRemoval;
|
|
73
|
-
private resolveReplacement;
|
|
74
|
-
private withPendingWrite;
|
|
75
|
-
private enqueueBatched;
|
|
76
|
-
private updateQuery;
|
|
77
|
-
createCollectionBackend<T extends BaseItem<I>, I = any, E extends BaseItem = T, U = E>(collection: Collection<T, I, E, U>, indices: string[]): CollectionBackend<T, I>;
|
|
78
|
-
}
|
|
79
|
-
export {};
|