@signaldb/core 2.0.0-beta.2 → 2.0.0-beta.21
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/.vite/manifest.json +183 -80
- package/dist/AsyncDataAdapter.d.ts +53 -7
- package/dist/AutoFetchDataAdapter.d.ts +4 -6
- package/dist/Collection/Cursor.d.ts +56 -4
- package/dist/Collection/Observer.d.ts +33 -0
- package/dist/Collection/index.d.ts +66 -19
- package/dist/Collection/types.d.ts +9 -2
- package/dist/DataAdapter.d.ts +24 -6
- package/dist/DefaultDataAdapter.d.ts +5 -5
- package/dist/WorkerDataAdapter.d.ts +57 -5
- package/dist/WorkerDataAdapterHost.d.ts +9 -7
- package/dist/createIndex.d.ts +2 -2
- package/dist/createIndexProvider.d.ts +2 -2
- package/dist/createReactivityAdapter.d.ts +2 -2
- package/dist/createStorageAdapter.d.ts +1 -1
- package/dist/getIndexInfo.d.ts +3 -4
- package/dist/index.cjs.js +33 -31
- package/dist/index.d.ts +6 -1
- package/dist/index.mjs +17 -32
- package/dist/index10.cjs.js +11 -0
- package/dist/index10.mjs +10 -18
- package/dist/index11.cjs.js +23 -0
- package/dist/index11.mjs +22 -15
- package/dist/index12.cjs.js +45 -0
- package/dist/index12.mjs +44 -353
- package/dist/index13.cjs.js +22 -0
- package/dist/index13.mjs +21 -419
- package/dist/index14.cjs.js +45 -0
- package/dist/index14.mjs +44 -206
- package/dist/index15.cjs.js +86 -0
- package/dist/index15.mjs +85 -388
- package/dist/index16.cjs.js +15 -0
- package/dist/index16.mjs +14 -579
- package/dist/index17.cjs.js +141 -0
- package/dist/index17.mjs +140 -152
- package/dist/index18.cjs.js +47 -0
- package/dist/index18.mjs +46 -26
- package/dist/index19.cjs.js +15 -0
- package/dist/index19.mjs +14 -41
- package/dist/index2.cjs.js +33 -0
- package/dist/index2.mjs +32 -258
- package/dist/index20.cjs.js +23 -0
- package/dist/index20.mjs +22 -16
- package/dist/index21.cjs.js +37 -0
- package/dist/index21.mjs +36 -104
- package/dist/index22.cjs.js +35 -0
- package/dist/index22.mjs +34 -128
- package/dist/index23.cjs.js +21 -0
- package/dist/index23.mjs +20 -7
- package/dist/index24.cjs.js +19 -0
- package/dist/index24.mjs +18 -27
- package/dist/index25.cjs.js +157 -0
- package/dist/index25.mjs +156 -11
- package/dist/index26.cjs.js +38 -0
- package/dist/index26.mjs +37 -29
- package/dist/index27.cjs.js +42 -0
- package/dist/index27.mjs +41 -46
- package/dist/index28.cjs.js +347 -0
- package/dist/index28.mjs +345 -7
- package/dist/index29.cjs.js +602 -0
- package/dist/index29.mjs +601 -7
- package/dist/index3.cjs.js +19 -0
- package/dist/index3.mjs +18 -556
- package/dist/index30.cjs.js +11 -0
- package/dist/index30.mjs +10 -42
- package/dist/index31.cjs.js +11 -0
- package/dist/index31.mjs +10 -29
- package/dist/index32.cjs.js +90 -0
- package/dist/index32.mjs +89 -10
- package/dist/index33.cjs.js +53 -0
- package/dist/index33.mjs +52 -5
- package/dist/index34.cjs.js +453 -0
- package/dist/index34.mjs +453 -0
- package/dist/index35.cjs.js +72 -0
- package/dist/index35.mjs +72 -0
- package/dist/index36.cjs.js +580 -0
- package/dist/index36.mjs +580 -0
- package/dist/index37.cjs.js +21 -0
- package/dist/index37.mjs +21 -0
- package/dist/index38.cjs.js +363 -0
- package/dist/index38.mjs +363 -0
- package/dist/index39.cjs.js +513 -0
- package/dist/index39.mjs +513 -0
- package/dist/index4.cjs.js +209 -0
- package/dist/index4.mjs +204 -5
- package/dist/index5.cjs.js +187 -0
- package/dist/index5.mjs +186 -5
- package/dist/index6.cjs.js +303 -0
- package/dist/index6.mjs +301 -28
- package/dist/index7.cjs.js +125 -0
- package/dist/index7.mjs +124 -12
- package/dist/index8.cjs.js +33 -0
- package/dist/index8.mjs +32 -5
- package/dist/index9.cjs.js +12 -0
- package/dist/index9.mjs +11 -133
- package/dist/types/IndexProvider.d.ts +2 -2
- package/dist/types/Modifier.d.ts +1 -1
- package/dist/types/ReactivityAdapter.d.ts +1 -1
- package/dist/types/StorageAdapter.d.ts +9 -1
- package/dist/utils/applyQueryOptions.d.ts +15 -0
- package/dist/utils/createSignal.d.ts +2 -2
- package/dist/utils/getMatchingKeys.d.ts +2 -2
- package/dist/utils/idIndexQuery.d.ts +20 -0
- package/dist/utils/incrementalQueryUpdate.d.ts +62 -0
- package/dist/utils/isFieldExpression.d.ts +1 -1
- package/dist/utils/match.d.ts +1 -1
- package/dist/utils/modify.d.ts +1 -1
- package/dist/utils/projectItems.d.ts +12 -0
- package/dist/utils/queryDelta.d.ts +83 -0
- package/dist/utils/queryId.d.ts +2 -2
- package/dist/utils/reactiveOrAsync.d.ts +59 -0
- package/dist/utils/storageIndexQuery.d.ts +20 -0
- package/package.json +1 -1
- package/dist/index.cjs10.js +0 -18
- package/dist/index.cjs11.js +0 -15
- package/dist/index.cjs12.js +0 -353
- package/dist/index.cjs13.js +0 -419
- package/dist/index.cjs14.js +0 -206
- package/dist/index.cjs15.js +0 -388
- package/dist/index.cjs16.js +0 -579
- package/dist/index.cjs17.js +0 -152
- package/dist/index.cjs18.js +0 -26
- package/dist/index.cjs19.js +0 -42
- package/dist/index.cjs2.js +0 -259
- package/dist/index.cjs20.js +0 -16
- package/dist/index.cjs21.js +0 -104
- package/dist/index.cjs22.js +0 -129
- package/dist/index.cjs23.js +0 -7
- package/dist/index.cjs24.js +0 -27
- package/dist/index.cjs25.js +0 -10
- package/dist/index.cjs26.js +0 -29
- package/dist/index.cjs27.js +0 -46
- package/dist/index.cjs28.js +0 -8
- package/dist/index.cjs29.js +0 -7
- package/dist/index.cjs3.js +0 -557
- package/dist/index.cjs30.js +0 -42
- package/dist/index.cjs31.js +0 -29
- package/dist/index.cjs32.js +0 -9
- package/dist/index.cjs33.js +0 -5
- package/dist/index.cjs4.js +0 -5
- package/dist/index.cjs5.js +0 -5
- package/dist/index.cjs6.js +0 -29
- package/dist/index.cjs7.js +0 -12
- package/dist/index.cjs8.js +0 -5
- package/dist/index.cjs9.js +0 -133
package/dist/index39.mjs
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
import isEqual from "./index2.mjs";
|
|
2
|
+
import getIndexInfo from "./index17.mjs";
|
|
3
|
+
import deepClone from "./index18.mjs";
|
|
4
|
+
import match from "./index19.mjs";
|
|
5
|
+
import modify from "./index20.mjs";
|
|
6
|
+
import project from "./index22.mjs";
|
|
7
|
+
import sortItems from "./index24.mjs";
|
|
8
|
+
import queryId from "./index26.mjs";
|
|
9
|
+
import idIndexQuery from "./index27.mjs";
|
|
10
|
+
import storageIndexQuery from "./index33.mjs";
|
|
11
|
+
//#region src/AutoFetchDataAdapter.ts
|
|
12
|
+
/**
|
|
13
|
+
* Default merge strategy: shallow spread (right wins)
|
|
14
|
+
* @param a first item
|
|
15
|
+
* @param b second item
|
|
16
|
+
* @returns merged item
|
|
17
|
+
*/
|
|
18
|
+
function defaultMergeItems(a, b) {
|
|
19
|
+
return {
|
|
20
|
+
...a,
|
|
21
|
+
...b
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Generates a stable key for a selector
|
|
26
|
+
* @param selector - the selector
|
|
27
|
+
* @returns the key
|
|
28
|
+
*/
|
|
29
|
+
function selectorId(selector) {
|
|
30
|
+
return JSON.stringify(selector ?? {});
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* AutoFetchDataAdapter
|
|
34
|
+
*
|
|
35
|
+
* A DataAdapter that:
|
|
36
|
+
* - Mirrors the CollectionBackend surface (CRUD + query registry + lifecycle)
|
|
37
|
+
* - Executes queries against a provided StorageAdapter (local cache)
|
|
38
|
+
* - On first registration of a selector, auto-fetches from a remote source and
|
|
39
|
+
* ingests the result into storage (upsert), then pushes query result updates
|
|
40
|
+
* - Optionally purges auto-fetched items for a selector once no observers remain
|
|
41
|
+
* - Can subscribe to remote change notifications to re-fetch active selectors
|
|
42
|
+
*
|
|
43
|
+
* IMPORTANT: Purging only ever deletes items that were introduced via the
|
|
44
|
+
* auto-fetch path and are no longer referenced by any active selector. Items
|
|
45
|
+
* inserted through CRUD calls are never purged.
|
|
46
|
+
*/
|
|
47
|
+
var AutoFetchDataAdapter = class {
|
|
48
|
+
options;
|
|
49
|
+
id;
|
|
50
|
+
onError;
|
|
51
|
+
fetchQueryItems;
|
|
52
|
+
mergeItems;
|
|
53
|
+
purgeDelay;
|
|
54
|
+
storageAdapters = /* @__PURE__ */ new Map();
|
|
55
|
+
storageAdapterReady = /* @__PURE__ */ new Map();
|
|
56
|
+
collectionIndices = /* @__PURE__ */ new Map();
|
|
57
|
+
queries = /* @__PURE__ */ new Map();
|
|
58
|
+
activeObservers = /* @__PURE__ */ new Map();
|
|
59
|
+
observerTimeouts = /* @__PURE__ */ new Map();
|
|
60
|
+
selectorIds = /* @__PURE__ */ new Map();
|
|
61
|
+
idRefCounts = /* @__PURE__ */ new Map();
|
|
62
|
+
autoloadIds = /* @__PURE__ */ new Map();
|
|
63
|
+
constructor(options) {
|
|
64
|
+
this.options = options;
|
|
65
|
+
this.id = options.id || "autofetch-data-adapter";
|
|
66
|
+
this.onError = options.onError ?? ((error) => {
|
|
67
|
+
console.error(error);
|
|
68
|
+
});
|
|
69
|
+
this.fetchQueryItems = options.fetchQueryItems;
|
|
70
|
+
this.mergeItems = options.mergeItems ?? defaultMergeItems;
|
|
71
|
+
this.purgeDelay = options.purgeDelay ?? 1e4;
|
|
72
|
+
if (options.registerRemoteChange) options.registerRemoteChange(async () => {
|
|
73
|
+
await this.forceRefetchAll();
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
createCollectionBackend(collection, indices) {
|
|
77
|
+
this.collectionIndices.set(collection.name, indices);
|
|
78
|
+
this.queries.set(collection.name, /* @__PURE__ */ new Map());
|
|
79
|
+
this.ensureStorageAdapter(collection.name);
|
|
80
|
+
this.activeObservers.set(collection.name, /* @__PURE__ */ new Map());
|
|
81
|
+
this.observerTimeouts.set(collection.name, /* @__PURE__ */ new Map());
|
|
82
|
+
this.selectorIds.set(collection.name, /* @__PURE__ */ new Map());
|
|
83
|
+
this.idRefCounts.set(collection.name, /* @__PURE__ */ new Map());
|
|
84
|
+
this.autoloadIds.set(collection.name, /* @__PURE__ */ new Set());
|
|
85
|
+
const ready = this.setupStorage(collection.name, indices);
|
|
86
|
+
this.storageAdapterReady.set(collection.name, ready);
|
|
87
|
+
const registerQuery = (selector, options) => {
|
|
88
|
+
const qid = queryId(selector, options);
|
|
89
|
+
const registry = this.queries.get(collection.name);
|
|
90
|
+
if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
|
|
91
|
+
registry.set(qid, {
|
|
92
|
+
selector,
|
|
93
|
+
options,
|
|
94
|
+
items: [],
|
|
95
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
96
|
+
...registry.get(qid),
|
|
97
|
+
state: "active",
|
|
98
|
+
error: null
|
|
99
|
+
});
|
|
100
|
+
const key = selectorId(selector);
|
|
101
|
+
const perColObservers = this.activeObservers.get(collection.name);
|
|
102
|
+
const current = perColObservers?.get(key)?.count ?? 0;
|
|
103
|
+
perColObservers?.set(key, {
|
|
104
|
+
selector,
|
|
105
|
+
count: current + 1
|
|
106
|
+
});
|
|
107
|
+
const t = this.observerTimeouts.get(collection.name)?.get(key);
|
|
108
|
+
if (t) clearTimeout(t);
|
|
109
|
+
if (current === 0) this.fetchAndIngest(collection.name, selector).catch(this.onError);
|
|
110
|
+
this.fulfillQuery(collection.name, selector, options).catch(this.onError);
|
|
111
|
+
};
|
|
112
|
+
const unregisterQuery = (selector, options) => {
|
|
113
|
+
const qid = queryId(selector, options);
|
|
114
|
+
this.queries.get(collection.name)?.delete(qid);
|
|
115
|
+
const key = selectorId(selector);
|
|
116
|
+
const perColObservers = this.activeObservers.get(collection.name);
|
|
117
|
+
const current = perColObservers?.get(key)?.count ?? 0;
|
|
118
|
+
const remaining = Math.max(0, current - 1);
|
|
119
|
+
if (remaining > 0) {
|
|
120
|
+
perColObservers?.set(key, {
|
|
121
|
+
selector,
|
|
122
|
+
count: remaining
|
|
123
|
+
});
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const doPurge = () => {
|
|
127
|
+
perColObservers?.delete(key);
|
|
128
|
+
this.purgeSelector(collection.name, selector).catch(this.onError);
|
|
129
|
+
};
|
|
130
|
+
if (this.purgeDelay === 0) doPurge();
|
|
131
|
+
else {
|
|
132
|
+
const timeouts = this.observerTimeouts.get(collection.name);
|
|
133
|
+
const t = timeouts?.get(key);
|
|
134
|
+
if (t) clearTimeout(t);
|
|
135
|
+
timeouts?.set(key, setTimeout(doPurge, this.purgeDelay));
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
const getQueryState = (selector, options) => {
|
|
139
|
+
return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.state ?? "active";
|
|
140
|
+
};
|
|
141
|
+
const getQueryError = (selector, options) => {
|
|
142
|
+
return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.error ?? null;
|
|
143
|
+
};
|
|
144
|
+
const getQueryResult = (selector, options) => {
|
|
145
|
+
return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.items ?? [];
|
|
146
|
+
};
|
|
147
|
+
const onQueryStateChange = (selector, options, callback) => {
|
|
148
|
+
const qid = queryId(selector, options);
|
|
149
|
+
const registry = this.queries.get(collection.name);
|
|
150
|
+
if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
|
|
151
|
+
if (!registry.has(qid)) registry.set(qid, {
|
|
152
|
+
selector,
|
|
153
|
+
options,
|
|
154
|
+
state: "active",
|
|
155
|
+
error: null,
|
|
156
|
+
items: [],
|
|
157
|
+
listeners: /* @__PURE__ */ new Set()
|
|
158
|
+
});
|
|
159
|
+
registry.get(qid)?.listeners.add(callback);
|
|
160
|
+
return () => {
|
|
161
|
+
registry.get(qid)?.listeners.delete(callback);
|
|
162
|
+
};
|
|
163
|
+
};
|
|
164
|
+
return {
|
|
165
|
+
insert: async (item) => {
|
|
166
|
+
await ready;
|
|
167
|
+
return await this.insert(collection.name, item);
|
|
168
|
+
},
|
|
169
|
+
updateOne: async (selector, modifier) => {
|
|
170
|
+
await ready;
|
|
171
|
+
return this.updateOne(collection.name, selector, modifier);
|
|
172
|
+
},
|
|
173
|
+
updateMany: async (selector, modifier) => {
|
|
174
|
+
await ready;
|
|
175
|
+
return this.updateMany(collection.name, selector, modifier);
|
|
176
|
+
},
|
|
177
|
+
replaceOne: async (selector, replacement) => {
|
|
178
|
+
await ready;
|
|
179
|
+
return this.replaceOne(collection.name, selector, replacement);
|
|
180
|
+
},
|
|
181
|
+
removeOne: async (selector) => {
|
|
182
|
+
await ready;
|
|
183
|
+
return this.removeOne(collection.name, selector);
|
|
184
|
+
},
|
|
185
|
+
removeMany: async (selector) => {
|
|
186
|
+
await ready;
|
|
187
|
+
return this.removeMany(collection.name, selector);
|
|
188
|
+
},
|
|
189
|
+
registerQuery,
|
|
190
|
+
unregisterQuery,
|
|
191
|
+
getQueryState,
|
|
192
|
+
getQueryError,
|
|
193
|
+
getQueryResult,
|
|
194
|
+
onQueryStateChange,
|
|
195
|
+
executeQuery: async (selector, options) => {
|
|
196
|
+
await ready;
|
|
197
|
+
registerQuery(selector, options);
|
|
198
|
+
await new Promise((resolve) => {
|
|
199
|
+
let stop = () => {};
|
|
200
|
+
stop = onQueryStateChange(selector, options, (state) => {
|
|
201
|
+
if (state === "active") return;
|
|
202
|
+
resolve();
|
|
203
|
+
stop();
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
const result = getQueryResult(selector, options);
|
|
207
|
+
unregisterQuery(selector, options);
|
|
208
|
+
return result;
|
|
209
|
+
},
|
|
210
|
+
dispose: async () => {
|
|
211
|
+
this.storageAdapters.delete(collection.name);
|
|
212
|
+
this.queries.delete(collection.name);
|
|
213
|
+
this.collectionIndices.delete(collection.name);
|
|
214
|
+
this.storageAdapterReady.delete(collection.name);
|
|
215
|
+
this.activeObservers.delete(collection.name);
|
|
216
|
+
this.observerTimeouts.delete(collection.name);
|
|
217
|
+
this.selectorIds.delete(collection.name);
|
|
218
|
+
this.idRefCounts.delete(collection.name);
|
|
219
|
+
this.autoloadIds.delete(collection.name);
|
|
220
|
+
},
|
|
221
|
+
isReady: async () => {
|
|
222
|
+
await ready;
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
async forceRefetchAll() {
|
|
227
|
+
const tasks = [];
|
|
228
|
+
for (const [collectionName, observers] of this.activeObservers.entries()) for (const { selector, count } of observers.values()) if (count > 0) tasks.push(this.fetchAndIngest(collectionName, selector));
|
|
229
|
+
await Promise.all(tasks);
|
|
230
|
+
}
|
|
231
|
+
async fetchAndIngest(collectionName, selector) {
|
|
232
|
+
this.publishForSelector(collectionName, selector, "active", null);
|
|
233
|
+
try {
|
|
234
|
+
const items = await this.fetchQueryItems(collectionName, selector);
|
|
235
|
+
if (!items || !Array.isArray(items)) throw new Error("AutoFetchDataAdapter: fetchQueryItems must resolve to { items: T[] }");
|
|
236
|
+
const ids = items.map((i) => i.id);
|
|
237
|
+
const selectorKey = selectorId(selector);
|
|
238
|
+
const selMap = this.selectorIds.get(collectionName);
|
|
239
|
+
const previous = selMap?.get(selectorKey) ?? /* @__PURE__ */ new Set();
|
|
240
|
+
ids.forEach((id) => previous.add(id));
|
|
241
|
+
selMap?.set(selectorKey, previous);
|
|
242
|
+
await this.upsertMerged(collectionName, items);
|
|
243
|
+
await this.checkQueryUpdates(collectionName, items);
|
|
244
|
+
} catch (error) {
|
|
245
|
+
this.publishForSelector(collectionName, selector, "error", error);
|
|
246
|
+
this.onError(error);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async purgeSelector(collectionName, selector) {
|
|
250
|
+
const selectorKey = selectorId(selector);
|
|
251
|
+
const selMap = this.selectorIds.get(collectionName);
|
|
252
|
+
const ids = selMap?.get(selectorKey);
|
|
253
|
+
selMap?.delete(selectorKey);
|
|
254
|
+
if (!ids || ids.size === 0) return;
|
|
255
|
+
const referenceMap = this.idRefCounts.get(collectionName);
|
|
256
|
+
const autoload = this.autoloadIds.get(collectionName);
|
|
257
|
+
const toRemove = [];
|
|
258
|
+
for (const id of ids) {
|
|
259
|
+
const current = referenceMap?.get(id) ?? 0;
|
|
260
|
+
const next = Math.max(0, current - 1);
|
|
261
|
+
if (next === 0) {
|
|
262
|
+
referenceMap?.delete(id);
|
|
263
|
+
if (autoload?.has(id)) toRemove.push(id);
|
|
264
|
+
} else referenceMap?.set(id, next);
|
|
265
|
+
}
|
|
266
|
+
if (toRemove.length === 0) return;
|
|
267
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
268
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
269
|
+
const items = await storage.readIds(toRemove);
|
|
270
|
+
if (items.length > 0) {
|
|
271
|
+
await storage.remove(items);
|
|
272
|
+
await this.checkQueryUpdates(collectionName, items);
|
|
273
|
+
}
|
|
274
|
+
toRemove.forEach((id) => autoload?.delete(id));
|
|
275
|
+
}
|
|
276
|
+
async setupStorage(collectionName, indices) {
|
|
277
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
278
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
279
|
+
await storage.setup();
|
|
280
|
+
await Promise.all(indices.map((field) => storage.createIndex(field)));
|
|
281
|
+
}
|
|
282
|
+
ensureStorageAdapter(name) {
|
|
283
|
+
if (this.storageAdapters.has(name)) return;
|
|
284
|
+
const adapter = this.options.storage && this.options.storage(name);
|
|
285
|
+
if (!adapter) return;
|
|
286
|
+
this.storageAdapters.set(name, adapter);
|
|
287
|
+
}
|
|
288
|
+
publishForSelector(collectionName, selector, state, error) {
|
|
289
|
+
const registry = this.queries.get(collectionName);
|
|
290
|
+
if (!registry) return;
|
|
291
|
+
for (const query of registry.values()) {
|
|
292
|
+
if (!isEqual(query.selector, selector)) continue;
|
|
293
|
+
this.publishState(collectionName, queryId(query.selector, query.options), state, error);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
publishState(collectionName, qid, state, error) {
|
|
297
|
+
const query = this.queries.get(collectionName)?.get(qid);
|
|
298
|
+
if (!query) return;
|
|
299
|
+
query.state = state;
|
|
300
|
+
query.error = error;
|
|
301
|
+
for (const callback of query.listeners) try {
|
|
302
|
+
callback(state);
|
|
303
|
+
} catch (error_) {
|
|
304
|
+
this.onError(error_);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
publishResult(collectionName, qid, items) {
|
|
308
|
+
const query = this.queries.get(collectionName)?.get(qid);
|
|
309
|
+
if (!query) return;
|
|
310
|
+
query.items = items;
|
|
311
|
+
this.queries.get(collectionName)?.set(qid, query);
|
|
312
|
+
}
|
|
313
|
+
async fulfillQuery(collectionName, selector, options) {
|
|
314
|
+
const qid = queryId(selector, options);
|
|
315
|
+
const registry = this.queries.get(collectionName);
|
|
316
|
+
if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
|
|
317
|
+
if (!registry.get(qid)) return;
|
|
318
|
+
this.publishState(collectionName, qid, "active", null);
|
|
319
|
+
try {
|
|
320
|
+
const items = await this.executeQuery(collectionName, selector, options);
|
|
321
|
+
this.publishResult(collectionName, qid, items);
|
|
322
|
+
this.publishState(collectionName, qid, "complete", null);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
this.publishState(collectionName, qid, "error", error);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
async getIndexInfo(collectionName, selector) {
|
|
328
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
329
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
330
|
+
if (selector != null && Object.keys(selector).length === 1 && "id" in selector) {
|
|
331
|
+
const idResult = idIndexQuery(selector);
|
|
332
|
+
if (idResult.matched) return {
|
|
333
|
+
matched: true,
|
|
334
|
+
ids: idResult.ids,
|
|
335
|
+
optimizedSelector: {}
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
if (selector == null) return {
|
|
339
|
+
matched: false,
|
|
340
|
+
ids: [],
|
|
341
|
+
optimizedSelector: {}
|
|
342
|
+
};
|
|
343
|
+
return getIndexInfo((this.collectionIndices.get(collectionName) ?? []).map((field) => storageIndexQuery(storage, field)), selector);
|
|
344
|
+
}
|
|
345
|
+
async queryItems(collectionName, selector) {
|
|
346
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
347
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
348
|
+
const index = await this.getIndexInfo(collectionName, selector);
|
|
349
|
+
const matchItems = (item) => {
|
|
350
|
+
if (index.optimizedSelector == null) return true;
|
|
351
|
+
if (Object.keys(index.optimizedSelector).length <= 0) return true;
|
|
352
|
+
return match(item, index.optimizedSelector);
|
|
353
|
+
};
|
|
354
|
+
if (index.matched) {
|
|
355
|
+
const items = await storage.readIds(index.ids);
|
|
356
|
+
if (isEqual(index.optimizedSelector, {})) return items;
|
|
357
|
+
return items.filter(matchItems);
|
|
358
|
+
} else {
|
|
359
|
+
const allItems = await storage.readAll();
|
|
360
|
+
if (isEqual(selector, {})) return allItems;
|
|
361
|
+
return allItems.filter(matchItems);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
async executeQuery(collectionName, selector, options) {
|
|
365
|
+
const items = await this.queryItems(collectionName, selector || {});
|
|
366
|
+
const { sort, skip, limit, fields } = options || {};
|
|
367
|
+
const sorted = sort ? sortItems(items, sort) : items;
|
|
368
|
+
const skipped = skip ? sorted.slice(skip) : sorted;
|
|
369
|
+
const limited = limit ? skipped.slice(0, limit) : skipped;
|
|
370
|
+
const idExcluded = fields && fields.id === 0;
|
|
371
|
+
return limited.map((item) => {
|
|
372
|
+
if (!fields) return item;
|
|
373
|
+
return {
|
|
374
|
+
...idExcluded ? {} : { id: item.id },
|
|
375
|
+
...project(item, fields)
|
|
376
|
+
};
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
async checkQueryUpdates(collectionName, changedItems) {
|
|
380
|
+
const registry = this.queries.get(collectionName);
|
|
381
|
+
if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
|
|
382
|
+
if (registry.size === 0) return;
|
|
383
|
+
const affected = [...registry.values()].filter(({ selector }) => changedItems.some((item) => match(item, selector)));
|
|
384
|
+
if (affected.length === 0) return;
|
|
385
|
+
for (const { selector, options } of affected) {
|
|
386
|
+
const qid = queryId(selector, options);
|
|
387
|
+
this.publishState(collectionName, qid, "active", null);
|
|
388
|
+
}
|
|
389
|
+
await Promise.all(affected.map(async ({ selector, options }) => {
|
|
390
|
+
const qid = queryId(selector, options);
|
|
391
|
+
try {
|
|
392
|
+
const items = await this.executeQuery(collectionName, selector, options);
|
|
393
|
+
this.publishResult(collectionName, qid, items);
|
|
394
|
+
this.publishState(collectionName, qid, "complete", null);
|
|
395
|
+
} catch (error) {
|
|
396
|
+
this.publishState(collectionName, qid, "error", error);
|
|
397
|
+
}
|
|
398
|
+
}));
|
|
399
|
+
}
|
|
400
|
+
async insert(collectionName, newItem) {
|
|
401
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
402
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
403
|
+
if ((await this.executeQuery(collectionName, { id: newItem.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(newItem.id)} already exists`);
|
|
404
|
+
await storage.insert([newItem]);
|
|
405
|
+
await this.checkQueryUpdates(collectionName, [newItem]);
|
|
406
|
+
return newItem;
|
|
407
|
+
}
|
|
408
|
+
async updateOne(collectionName, selector, modifier) {
|
|
409
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
410
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
411
|
+
const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
|
|
412
|
+
const { $setOnInsert, ...rest } = modifier;
|
|
413
|
+
if (item == null) return [];
|
|
414
|
+
const modified = modify(deepClone(item), rest);
|
|
415
|
+
if (item.id !== modified.id) {
|
|
416
|
+
if ((await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
|
|
417
|
+
}
|
|
418
|
+
await storage.replace([modified]);
|
|
419
|
+
await this.checkQueryUpdates(collectionName, [item, modified]);
|
|
420
|
+
return [modified];
|
|
421
|
+
}
|
|
422
|
+
async updateMany(collectionName, selector, modifier) {
|
|
423
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
424
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
425
|
+
const items = await this.executeQuery(collectionName, selector);
|
|
426
|
+
if (items.length === 0) return [];
|
|
427
|
+
const { $setOnInsert, ...rest } = modifier;
|
|
428
|
+
const changed = await Promise.all(items.map(async (item) => {
|
|
429
|
+
const modified = modify(deepClone(item), rest);
|
|
430
|
+
if (item.id !== modified.id) {
|
|
431
|
+
if ((await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
|
|
432
|
+
}
|
|
433
|
+
return modified;
|
|
434
|
+
}));
|
|
435
|
+
await storage.replace(changed);
|
|
436
|
+
await this.checkQueryUpdates(collectionName, [...items, ...changed]);
|
|
437
|
+
return changed;
|
|
438
|
+
}
|
|
439
|
+
async replaceOne(collectionName, selector, replacement) {
|
|
440
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
441
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
442
|
+
const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
|
|
443
|
+
if (item == null) return [];
|
|
444
|
+
const modified = {
|
|
445
|
+
...replacement,
|
|
446
|
+
id: replacement.id ?? item.id
|
|
447
|
+
};
|
|
448
|
+
if (item.id !== modified.id) {
|
|
449
|
+
if ((await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
|
|
450
|
+
}
|
|
451
|
+
await storage.replace([modified]);
|
|
452
|
+
await this.checkQueryUpdates(collectionName, [item, modified]);
|
|
453
|
+
return [modified];
|
|
454
|
+
}
|
|
455
|
+
async removeOne(collectionName, selector) {
|
|
456
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
457
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
458
|
+
const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
|
|
459
|
+
if (item == null) return [];
|
|
460
|
+
await storage.remove([item]);
|
|
461
|
+
await this.checkQueryUpdates(collectionName, [item]);
|
|
462
|
+
return [item];
|
|
463
|
+
}
|
|
464
|
+
async removeMany(collectionName, selector) {
|
|
465
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
466
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
467
|
+
const items = await this.executeQuery(collectionName, selector);
|
|
468
|
+
if (items.length === 0) return [];
|
|
469
|
+
await storage.remove(items);
|
|
470
|
+
await this.checkQueryUpdates(collectionName, items);
|
|
471
|
+
return items;
|
|
472
|
+
}
|
|
473
|
+
async upsertMerged(collectionName, incoming) {
|
|
474
|
+
if (incoming.length === 0) return;
|
|
475
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
476
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
477
|
+
const ids = incoming.map((i) => i.id);
|
|
478
|
+
const existing = await storage.readIds(ids);
|
|
479
|
+
const existingById = new Map(existing.map((it) => [it.id, it]));
|
|
480
|
+
const toInsert = [];
|
|
481
|
+
const toReplace = [];
|
|
482
|
+
const referenceMap = this.idRefCounts.get(collectionName);
|
|
483
|
+
const autoload = this.autoloadIds.get(collectionName);
|
|
484
|
+
for (const item of incoming) {
|
|
485
|
+
const previous = existingById.get(item.id);
|
|
486
|
+
if (previous) toReplace.push(this.mergeItems(previous, item));
|
|
487
|
+
else toInsert.push(item);
|
|
488
|
+
autoload?.add(item.id);
|
|
489
|
+
referenceMap?.set(item.id, (referenceMap?.get(item.id) ?? 0) + 1);
|
|
490
|
+
}
|
|
491
|
+
if (toInsert.length > 0) await storage.insert(toInsert);
|
|
492
|
+
if (toReplace.length > 0) await storage.replace(toReplace);
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
/**
|
|
496
|
+
* Usage (example):
|
|
497
|
+
*
|
|
498
|
+
* const adapter = new AutoFetchDataAdapter({
|
|
499
|
+
* storage: (name) => new IndexedDBStorage(name),
|
|
500
|
+
* fetchQueryItems: async (collectionName, selector) => {
|
|
501
|
+
* const res = await fetch(`/api/${collectionName}?q=${encodeURIComponent(JSON.stringify(selector||{}))}`)
|
|
502
|
+
* const items = await res.json()
|
|
503
|
+
* return { items }
|
|
504
|
+
* },
|
|
505
|
+
* registerRemoteChange: (onChange) => subscribeToWS(onChange),
|
|
506
|
+
* mergeItems: (a, b) => ({ ...a, ...b }),
|
|
507
|
+
* purgeDelay: 10_000,
|
|
508
|
+
* })
|
|
509
|
+
*
|
|
510
|
+
* const backend = adapter.createCollectionBackend(myCollection, ['status', 'projectId'])
|
|
511
|
+
*/
|
|
512
|
+
//#endregion
|
|
513
|
+
export { AutoFetchDataAdapter as default };
|