@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/index34.mjs
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
import isEqual from "./index2.mjs";
|
|
2
|
+
import { callWithDelta, diffQueryResults, isEmptyQueryDelta } from "./index4.mjs";
|
|
3
|
+
import getIndexInfo from "./index17.mjs";
|
|
4
|
+
import deepClone from "./index18.mjs";
|
|
5
|
+
import match from "./index19.mjs";
|
|
6
|
+
import modify from "./index20.mjs";
|
|
7
|
+
import projectItems from "./index23.mjs";
|
|
8
|
+
import sortItems from "./index24.mjs";
|
|
9
|
+
import incrementalQueryUpdate from "./index25.mjs";
|
|
10
|
+
import queryId from "./index26.mjs";
|
|
11
|
+
import idIndexQuery from "./index27.mjs";
|
|
12
|
+
import storageIndexQuery from "./index33.mjs";
|
|
13
|
+
//#region src/AsyncDataAdapter.ts
|
|
14
|
+
/**
|
|
15
|
+
* Carries the context needed to act on a failed query. The bare storage error
|
|
16
|
+
* on its own does not say which collection or selector produced it, which made
|
|
17
|
+
* the default `console.error` hook close to useless.
|
|
18
|
+
*/
|
|
19
|
+
var QueryError = class extends Error {
|
|
20
|
+
collectionName;
|
|
21
|
+
selector;
|
|
22
|
+
options;
|
|
23
|
+
attempts;
|
|
24
|
+
constructor(collectionName, selector, options, attempts, cause) {
|
|
25
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
26
|
+
super(`Query on "${collectionName}" failed after ${attempts} attempt(s): ${reason}`);
|
|
27
|
+
this.name = "QueryError";
|
|
28
|
+
this.collectionName = collectionName;
|
|
29
|
+
this.selector = selector;
|
|
30
|
+
this.options = options;
|
|
31
|
+
this.attempts = attempts;
|
|
32
|
+
this.cause = cause;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Turns the item states a write produced into the upsert/delete split a query update needs.
|
|
37
|
+
*
|
|
38
|
+
* The two lists are not symmetric: an item that is still there after the write is described by its
|
|
39
|
+
* new state, while an item that is gone — removed, or given a new id — is described by the id it
|
|
40
|
+
* used to have and nothing else. Mixing the states from before and after a write into one list
|
|
41
|
+
* loses exactly that distinction.
|
|
42
|
+
* @template T - The type of the items.
|
|
43
|
+
* @param previousItems - The items as they were before the write.
|
|
44
|
+
* @param modifiedItems - The items as they are after it.
|
|
45
|
+
* @returns The changeset describing the write.
|
|
46
|
+
*/
|
|
47
|
+
function toChangeset(previousItems, modifiedItems) {
|
|
48
|
+
const modifiedIds = new Set(modifiedItems.map((item) => item.id));
|
|
49
|
+
return {
|
|
50
|
+
upserts: modifiedItems,
|
|
51
|
+
deletes: previousItems.map((item) => item.id).filter((id) => !modifiedIds.has(id))
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
var DEFAULT_RETRY_ATTEMPTS = 3;
|
|
55
|
+
var defaultRetryDelay = (attempt) => 100 * 4 ** (attempt - 1);
|
|
56
|
+
var wait = (ms) => new Promise((resolve) => {
|
|
57
|
+
setTimeout(resolve, ms);
|
|
58
|
+
});
|
|
59
|
+
/**
|
|
60
|
+
* AsyncDataAdapter
|
|
61
|
+
* Combines WorkerDataAdapter + WorkerDataAdapterHost into a single, transport-free adapter.
|
|
62
|
+
* - Keeps the DataAdapter/CollectionBackend surface identical to the Worker version.
|
|
63
|
+
* - Executes queries and mutations directly against the provided StorageAdapter.
|
|
64
|
+
* - Preserves index-aware query optimization and push-style query updates to listeners.
|
|
65
|
+
*/
|
|
66
|
+
var AsyncDataAdapter = class {
|
|
67
|
+
options;
|
|
68
|
+
id;
|
|
69
|
+
onError;
|
|
70
|
+
retryAttempts;
|
|
71
|
+
retryDelay;
|
|
72
|
+
storageAdapters = /* @__PURE__ */ new Map();
|
|
73
|
+
storageAdapterReady = /* @__PURE__ */ new Map();
|
|
74
|
+
collectionIndices = /* @__PURE__ */ new Map();
|
|
75
|
+
queries = /* @__PURE__ */ new Map();
|
|
76
|
+
constructor(options) {
|
|
77
|
+
this.options = options;
|
|
78
|
+
this.id = options.id || "async-data-adapter";
|
|
79
|
+
this.onError = options.onError ?? ((error) => {
|
|
80
|
+
console.error(error);
|
|
81
|
+
});
|
|
82
|
+
this.retryAttempts = Math.max(1, options.retry?.attempts ?? DEFAULT_RETRY_ATTEMPTS);
|
|
83
|
+
this.retryDelay = options.retry?.delay ?? defaultRetryDelay;
|
|
84
|
+
}
|
|
85
|
+
createCollectionBackend(collection, indices) {
|
|
86
|
+
this.collectionIndices.set(collection.name, indices);
|
|
87
|
+
this.queries.set(collection.name, /* @__PURE__ */ new Map());
|
|
88
|
+
this.ensureStorageAdapter(collection.name);
|
|
89
|
+
const ready = (async () => {
|
|
90
|
+
try {
|
|
91
|
+
await this.setupStorage(collection.name, indices);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
this.onError(error);
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
})();
|
|
97
|
+
this.storageAdapterReady.set(collection.name, ready);
|
|
98
|
+
const registerQuery = (selector, options) => {
|
|
99
|
+
const qid = queryId(selector, options);
|
|
100
|
+
const registry = this.queries.get(collection.name);
|
|
101
|
+
if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
|
|
102
|
+
registry.set(qid, {
|
|
103
|
+
selector,
|
|
104
|
+
options,
|
|
105
|
+
items: [],
|
|
106
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
107
|
+
...registry.get(qid),
|
|
108
|
+
state: "active",
|
|
109
|
+
error: null
|
|
110
|
+
});
|
|
111
|
+
this.fulfillQuery(collection.name, selector, options).catch(this.onError);
|
|
112
|
+
};
|
|
113
|
+
const unregisterQuery = (selector, options) => {
|
|
114
|
+
const qid = queryId(selector, options);
|
|
115
|
+
this.queries.get(collection.name)?.delete(qid);
|
|
116
|
+
};
|
|
117
|
+
const getQueryState = (selector, options) => {
|
|
118
|
+
return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.state ?? "active";
|
|
119
|
+
};
|
|
120
|
+
const getQueryError = (selector, options) => {
|
|
121
|
+
return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.error ?? null;
|
|
122
|
+
};
|
|
123
|
+
const getQueryResult = (selector, options) => {
|
|
124
|
+
return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.items ?? [];
|
|
125
|
+
};
|
|
126
|
+
const retryQuery = (selector, options) => {
|
|
127
|
+
const qid = queryId(selector, options);
|
|
128
|
+
if (!this.queries.get(collection.name)?.get(qid)) return;
|
|
129
|
+
this.publishState(collection.name, qid, "active", null);
|
|
130
|
+
this.runQuery(collection.name, selector, options);
|
|
131
|
+
};
|
|
132
|
+
const onQueryStateChange = (selector, options, callback) => {
|
|
133
|
+
const qid = queryId(selector, options);
|
|
134
|
+
const registry = this.queries.get(collection.name);
|
|
135
|
+
if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
|
|
136
|
+
if (!registry.has(qid)) registry.set(qid, {
|
|
137
|
+
selector,
|
|
138
|
+
options,
|
|
139
|
+
state: "active",
|
|
140
|
+
error: null,
|
|
141
|
+
items: [],
|
|
142
|
+
listeners: /* @__PURE__ */ new Set()
|
|
143
|
+
});
|
|
144
|
+
registry.get(qid)?.listeners.add(callback);
|
|
145
|
+
if (registry.get(qid)?.state === "error") retryQuery(selector, options);
|
|
146
|
+
return () => registry.get(qid)?.listeners.delete(callback);
|
|
147
|
+
};
|
|
148
|
+
return {
|
|
149
|
+
insert: async (item) => {
|
|
150
|
+
await ready;
|
|
151
|
+
return await this.insert(collection.name, item);
|
|
152
|
+
},
|
|
153
|
+
updateOne: async (selector, modifier) => {
|
|
154
|
+
await ready;
|
|
155
|
+
return this.updateOne(collection.name, selector, modifier);
|
|
156
|
+
},
|
|
157
|
+
updateMany: async (selector, modifier) => {
|
|
158
|
+
await ready;
|
|
159
|
+
return this.updateMany(collection.name, selector, modifier);
|
|
160
|
+
},
|
|
161
|
+
replaceOne: async (selector, replacement) => {
|
|
162
|
+
await ready;
|
|
163
|
+
return this.replaceOne(collection.name, selector, replacement);
|
|
164
|
+
},
|
|
165
|
+
removeOne: async (selector) => {
|
|
166
|
+
await ready;
|
|
167
|
+
return this.removeOne(collection.name, selector);
|
|
168
|
+
},
|
|
169
|
+
removeMany: async (selector) => {
|
|
170
|
+
await ready;
|
|
171
|
+
return this.removeMany(collection.name, selector);
|
|
172
|
+
},
|
|
173
|
+
registerQuery,
|
|
174
|
+
unregisterQuery,
|
|
175
|
+
retryQuery,
|
|
176
|
+
getQueryState,
|
|
177
|
+
getQueryError,
|
|
178
|
+
getQueryResult,
|
|
179
|
+
onQueryStateChange,
|
|
180
|
+
executeQuery: async (selector, options) => {
|
|
181
|
+
await ready;
|
|
182
|
+
return this.executeQuery(collection.name, selector, options);
|
|
183
|
+
},
|
|
184
|
+
dispose: async () => {
|
|
185
|
+
this.storageAdapters.delete(collection.name);
|
|
186
|
+
this.queries.delete(collection.name);
|
|
187
|
+
this.collectionIndices.delete(collection.name);
|
|
188
|
+
this.storageAdapterReady.delete(collection.name);
|
|
189
|
+
},
|
|
190
|
+
isReady: async () => {
|
|
191
|
+
await ready;
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
async setupStorage(collectionName, indices) {
|
|
196
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
197
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
198
|
+
await storage.setup();
|
|
199
|
+
await Promise.all(indices.map((index) => storage.createIndex(index)));
|
|
200
|
+
}
|
|
201
|
+
ensureStorageAdapter(name) {
|
|
202
|
+
if (this.storageAdapters.has(name)) return;
|
|
203
|
+
const adapter = this.options.storage(name);
|
|
204
|
+
if (!adapter) return;
|
|
205
|
+
this.storageAdapters.set(name, adapter);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Compute and publish the result for a specific query
|
|
209
|
+
* @param collectionName - name of the collection
|
|
210
|
+
* @param selector - query selector
|
|
211
|
+
* @param options - query options
|
|
212
|
+
*/
|
|
213
|
+
async fulfillQuery(collectionName, selector, options) {
|
|
214
|
+
const qid = queryId(selector, options);
|
|
215
|
+
const registry = this.queries.get(collectionName);
|
|
216
|
+
if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
|
|
217
|
+
if (!registry.get(qid)) return;
|
|
218
|
+
this.publishState(collectionName, qid, "active", null);
|
|
219
|
+
await this.runQuery(collectionName, selector, options);
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Executes a query, retrying transient failures before giving up. The state
|
|
223
|
+
* stays `'active'` across retries — consumers should see "still loading",
|
|
224
|
+
* not "failed", until we actually stop trying. Only the final failure is
|
|
225
|
+
* published as `'error'` and reported through `onError`; previously that
|
|
226
|
+
* error was swallowed entirely (`fulfillQuery` caught it internally, so the
|
|
227
|
+
* `.catch(this.onError)` on its call site was unreachable) and the query
|
|
228
|
+
* stayed dead for the rest of the session.
|
|
229
|
+
* @param collectionName - name of the collection
|
|
230
|
+
* @param selector - query selector
|
|
231
|
+
* @param options - query options
|
|
232
|
+
*/
|
|
233
|
+
async runQuery(collectionName, selector, options) {
|
|
234
|
+
const qid = queryId(selector, options);
|
|
235
|
+
let lastError;
|
|
236
|
+
for (let attempt = 1; attempt <= this.retryAttempts; attempt += 1) {
|
|
237
|
+
if (!this.queries.get(collectionName)?.has(qid)) return;
|
|
238
|
+
try {
|
|
239
|
+
const items = await this.executeQuery(collectionName, selector, options);
|
|
240
|
+
const rec = this.queries.get(collectionName)?.get(qid);
|
|
241
|
+
const delta = rec?.answered ? diffQueryResults(rec.items, items) : void 0;
|
|
242
|
+
this.publishResult(collectionName, qid, items);
|
|
243
|
+
this.publishState(collectionName, qid, "complete", null, delta);
|
|
244
|
+
return;
|
|
245
|
+
} catch (error) {
|
|
246
|
+
lastError = error;
|
|
247
|
+
if (attempt < this.retryAttempts) await wait(this.retryDelay(attempt));
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const queryError = new QueryError(collectionName, selector, options, this.retryAttempts, lastError);
|
|
251
|
+
this.publishState(collectionName, qid, "error", queryError);
|
|
252
|
+
this.onError(queryError);
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Notify listeners about state changes and keep the cache updated
|
|
256
|
+
* @param collectionName - name of the collection
|
|
257
|
+
* @param qid - query id
|
|
258
|
+
* @param state - new state
|
|
259
|
+
* @param error - error if state is 'error', null otherwise
|
|
260
|
+
* @param delta - what changed about the result, when that is known
|
|
261
|
+
*/
|
|
262
|
+
publishState(collectionName, qid, state, error, delta) {
|
|
263
|
+
const rec = this.queries.get(collectionName)?.get(qid);
|
|
264
|
+
if (!rec) return;
|
|
265
|
+
rec.state = state;
|
|
266
|
+
rec.error = error;
|
|
267
|
+
const subscribers = [...rec.listeners];
|
|
268
|
+
for (const callback of subscribers) try {
|
|
269
|
+
callWithDelta(callback, state, delta);
|
|
270
|
+
} catch (error_) {
|
|
271
|
+
this.onError(error_);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
publishResult(collectionName, qid, items) {
|
|
275
|
+
const rec = this.queries.get(collectionName)?.get(qid);
|
|
276
|
+
if (!rec) return;
|
|
277
|
+
rec.items = items;
|
|
278
|
+
rec.itemIds = void 0;
|
|
279
|
+
rec.answered = true;
|
|
280
|
+
}
|
|
281
|
+
queryItemIds(rec) {
|
|
282
|
+
if (!rec.itemIds) rec.itemIds = new Set(rec.items.map((item) => item.id));
|
|
283
|
+
return rec.itemIds;
|
|
284
|
+
}
|
|
285
|
+
async getIndexInfo(collectionName, selector) {
|
|
286
|
+
const storageAdapter = this.storageAdapters.get(collectionName);
|
|
287
|
+
if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
288
|
+
if (selector != null && Object.keys(selector).length === 1 && "id" in selector) {
|
|
289
|
+
const idResult = idIndexQuery(selector);
|
|
290
|
+
if (idResult.matched) return {
|
|
291
|
+
matched: true,
|
|
292
|
+
ids: idResult.ids.filter(Boolean),
|
|
293
|
+
optimizedSelector: {}
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
if (selector == null) return {
|
|
297
|
+
matched: false,
|
|
298
|
+
ids: [],
|
|
299
|
+
optimizedSelector: {}
|
|
300
|
+
};
|
|
301
|
+
return getIndexInfo((this.collectionIndices.get(collectionName) ?? []).map((field) => storageIndexQuery(storageAdapter, field)), selector);
|
|
302
|
+
}
|
|
303
|
+
async queryItems(collectionName, selector) {
|
|
304
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
305
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
306
|
+
const index = await this.getIndexInfo(collectionName, selector);
|
|
307
|
+
const matchItems = (item) => {
|
|
308
|
+
if (index.optimizedSelector == null) return true;
|
|
309
|
+
if (Object.keys(index.optimizedSelector).length <= 0) return true;
|
|
310
|
+
return match(item, index.optimizedSelector);
|
|
311
|
+
};
|
|
312
|
+
if (index.matched) {
|
|
313
|
+
const items = await storage.readIds(index.ids);
|
|
314
|
+
if (isEqual(index.optimizedSelector, {})) return items;
|
|
315
|
+
return items.filter(matchItems);
|
|
316
|
+
} else {
|
|
317
|
+
const allItems = await storage.readAll();
|
|
318
|
+
if (isEqual(selector, {})) return allItems;
|
|
319
|
+
return allItems.filter(matchItems);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
async executeQuery(collectionName, selector, options) {
|
|
323
|
+
const items = await this.queryItems(collectionName, selector || {});
|
|
324
|
+
const { sort, skip, limit, fields } = options || {};
|
|
325
|
+
const sorted = sort ? sortItems(items, sort) : items;
|
|
326
|
+
const skipped = skip ? sorted.slice(skip) : sorted;
|
|
327
|
+
return projectItems(limit ? skipped.slice(0, limit) : skipped, fields);
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* After mutations, bring every affected active query up to date.
|
|
331
|
+
*
|
|
332
|
+
* A query whose previous result is enough to answer the change is brought up to date from that
|
|
333
|
+
* result alone — no round trip to the storage, and no detour through `'active'`, because there is
|
|
334
|
+
* no window in which the query is stale. Only a query the change cannot be reasoned about
|
|
335
|
+
* locally — a window onto a larger set, or one that has never been answered — goes back to the
|
|
336
|
+
* store, and that one gets the same retry and reporting behaviour a freshly registered query
|
|
337
|
+
* gets: a refresh that fails silently leaves exactly the same dead cursor.
|
|
338
|
+
* @param collectionName - name of the collection
|
|
339
|
+
* @param changes - the items the write created, updated or removed
|
|
340
|
+
*/
|
|
341
|
+
async checkQueryUpdates(collectionName, changes) {
|
|
342
|
+
const registry = this.queries.get(collectionName);
|
|
343
|
+
if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
|
|
344
|
+
if (registry.size === 0) return;
|
|
345
|
+
if (changes.upserts.length === 0 && changes.deletes.length === 0) return;
|
|
346
|
+
const affected = [...registry.values()].filter((rec) => {
|
|
347
|
+
const ids = this.queryItemIds(rec);
|
|
348
|
+
if (changes.deletes.some((id) => ids.has(id))) return true;
|
|
349
|
+
return changes.upserts.some((item) => ids.has(item.id) || match(item, rec.selector));
|
|
350
|
+
});
|
|
351
|
+
if (affected.length === 0) return;
|
|
352
|
+
const needsReExecution = [];
|
|
353
|
+
for (const rec of affected) {
|
|
354
|
+
const { selector, options } = rec;
|
|
355
|
+
const incremental = rec.answered ? incrementalQueryUpdate(rec.items, selector, options, changes) : null;
|
|
356
|
+
if (incremental == null) {
|
|
357
|
+
needsReExecution.push(rec);
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
const qid = queryId(selector, options);
|
|
361
|
+
const delta = diffQueryResults(rec.items, incremental);
|
|
362
|
+
if (isEmptyQueryDelta(delta)) continue;
|
|
363
|
+
this.publishResult(collectionName, qid, incremental);
|
|
364
|
+
this.publishState(collectionName, qid, "complete", null, delta);
|
|
365
|
+
}
|
|
366
|
+
for (const { selector, options } of needsReExecution) this.publishState(collectionName, queryId(selector, options), "active", null);
|
|
367
|
+
await Promise.all(needsReExecution.map(({ selector, options }) => this.runQuery(collectionName, selector, options)));
|
|
368
|
+
}
|
|
369
|
+
async insert(collectionName, newItem) {
|
|
370
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
371
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
372
|
+
if ((await storage.readIds([newItem.id])).length > 0) throw new Error(`Item with id ${String(newItem.id)} already exists`);
|
|
373
|
+
await storage.insert([newItem]);
|
|
374
|
+
await this.checkQueryUpdates(collectionName, {
|
|
375
|
+
upserts: [newItem],
|
|
376
|
+
deletes: []
|
|
377
|
+
});
|
|
378
|
+
return newItem;
|
|
379
|
+
}
|
|
380
|
+
async updateOne(collectionName, selector, modifier) {
|
|
381
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
382
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
383
|
+
const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
|
|
384
|
+
const { $setOnInsert, ...rest } = modifier;
|
|
385
|
+
if (item == null) return [];
|
|
386
|
+
const modified = modify(deepClone(item), rest);
|
|
387
|
+
if (item.id !== modified.id) {
|
|
388
|
+
if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
|
|
389
|
+
}
|
|
390
|
+
await storage.replace([modified]);
|
|
391
|
+
await this.checkQueryUpdates(collectionName, toChangeset([item], [modified]));
|
|
392
|
+
return [modified];
|
|
393
|
+
}
|
|
394
|
+
async updateMany(collectionName, selector, modifier) {
|
|
395
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
396
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
397
|
+
const items = await this.executeQuery(collectionName, selector);
|
|
398
|
+
if (items.length === 0) return [];
|
|
399
|
+
const { $setOnInsert, ...rest } = modifier;
|
|
400
|
+
const changed = await Promise.all(items.map(async (item) => {
|
|
401
|
+
const modified = modify(deepClone(item), rest);
|
|
402
|
+
if (item.id !== modified.id) {
|
|
403
|
+
if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
|
|
404
|
+
}
|
|
405
|
+
return modified;
|
|
406
|
+
}));
|
|
407
|
+
await storage.replace(changed);
|
|
408
|
+
await this.checkQueryUpdates(collectionName, toChangeset(items, changed));
|
|
409
|
+
return changed;
|
|
410
|
+
}
|
|
411
|
+
async replaceOne(collectionName, selector, replacement) {
|
|
412
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
413
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
414
|
+
const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
|
|
415
|
+
if (item == null) return [];
|
|
416
|
+
const modified = {
|
|
417
|
+
...replacement,
|
|
418
|
+
id: replacement.id ?? item.id
|
|
419
|
+
};
|
|
420
|
+
if (item.id !== modified.id) {
|
|
421
|
+
if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
|
|
422
|
+
}
|
|
423
|
+
await storage.replace([modified]);
|
|
424
|
+
await this.checkQueryUpdates(collectionName, toChangeset([item], [modified]));
|
|
425
|
+
return [modified];
|
|
426
|
+
}
|
|
427
|
+
async removeOne(collectionName, selector) {
|
|
428
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
429
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
430
|
+
const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
|
|
431
|
+
if (item == null) return [];
|
|
432
|
+
await storage.remove([item]);
|
|
433
|
+
await this.checkQueryUpdates(collectionName, {
|
|
434
|
+
upserts: [],
|
|
435
|
+
deletes: [item.id]
|
|
436
|
+
});
|
|
437
|
+
return [item];
|
|
438
|
+
}
|
|
439
|
+
async removeMany(collectionName, selector) {
|
|
440
|
+
const storage = this.storageAdapters.get(collectionName);
|
|
441
|
+
if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
|
|
442
|
+
const items = await this.executeQuery(collectionName, selector);
|
|
443
|
+
if (items.length === 0) return [];
|
|
444
|
+
await storage.remove(items);
|
|
445
|
+
await this.checkQueryUpdates(collectionName, {
|
|
446
|
+
upserts: [],
|
|
447
|
+
deletes: items.map((item) => item.id)
|
|
448
|
+
});
|
|
449
|
+
return items;
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
//#endregion
|
|
453
|
+
export { AsyncDataAdapter as default };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
//#region src/utils/batchOnNextTick.ts
|
|
2
|
+
/**
|
|
3
|
+
* Groups multiple calls by key and flushes them on the next tick (macrotask).
|
|
4
|
+
* @param onFlush - Function that will be called with the key and all queued items when flushing.
|
|
5
|
+
* @returns An object with `enqueue` and `flush` methods.
|
|
6
|
+
* @example
|
|
7
|
+
* const batcher = batchOnNextTick<string>(async (key, items) => {
|
|
8
|
+
* // items is an array of { args, resolve, reject }
|
|
9
|
+
* // do something once with all args...
|
|
10
|
+
* })
|
|
11
|
+
*
|
|
12
|
+
* batcher.enqueue("my-key", [arg1, arg2])
|
|
13
|
+
*/
|
|
14
|
+
function batchOnNextTick(onFlush) {
|
|
15
|
+
const queues = /* @__PURE__ */ new Map();
|
|
16
|
+
/**
|
|
17
|
+
* Enqueue a call with the given key and arguments.
|
|
18
|
+
* @param key key to group calls
|
|
19
|
+
* @param args arguments for the call
|
|
20
|
+
* @returns A promise that resolves or rejects when the call is flushed.
|
|
21
|
+
*/
|
|
22
|
+
function enqueue(key, args) {
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
let q = queues.get(key);
|
|
25
|
+
if (!q) {
|
|
26
|
+
q = {
|
|
27
|
+
timer: null,
|
|
28
|
+
items: [],
|
|
29
|
+
flush: () => flush(key)
|
|
30
|
+
};
|
|
31
|
+
queues.set(key, q);
|
|
32
|
+
}
|
|
33
|
+
q.items.push({
|
|
34
|
+
args,
|
|
35
|
+
resolve,
|
|
36
|
+
reject
|
|
37
|
+
});
|
|
38
|
+
if (q.timer == null) q.timer = setTimeout(() => {
|
|
39
|
+
q.timer = null;
|
|
40
|
+
q.flush();
|
|
41
|
+
}, 0);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Flush the queue for the given key immediately.
|
|
46
|
+
* @param key key to flush
|
|
47
|
+
* @returns A promise that resolves when the flush is complete.
|
|
48
|
+
*/
|
|
49
|
+
async function flush(key) {
|
|
50
|
+
const q = queues.get(key);
|
|
51
|
+
if (!q || q.items.length === 0) return;
|
|
52
|
+
if (q.timer != null) {
|
|
53
|
+
clearTimeout(q.timer);
|
|
54
|
+
q.timer = null;
|
|
55
|
+
}
|
|
56
|
+
const items = q.items.splice(0);
|
|
57
|
+
onFlush(key, items.map((i) => i.args)).then((results) => {
|
|
58
|
+
for (const [index, result] of results.entries()) {
|
|
59
|
+
const { resolve } = items[index];
|
|
60
|
+
resolve(result);
|
|
61
|
+
}
|
|
62
|
+
}).catch((error) => {
|
|
63
|
+
for (const { reject } of items) reject(error);
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
enqueue,
|
|
68
|
+
flush
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
//#endregion
|
|
72
|
+
exports.default = batchOnNextTick;
|
package/dist/index35.mjs
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
//#region src/utils/batchOnNextTick.ts
|
|
2
|
+
/**
|
|
3
|
+
* Groups multiple calls by key and flushes them on the next tick (macrotask).
|
|
4
|
+
* @param onFlush - Function that will be called with the key and all queued items when flushing.
|
|
5
|
+
* @returns An object with `enqueue` and `flush` methods.
|
|
6
|
+
* @example
|
|
7
|
+
* const batcher = batchOnNextTick<string>(async (key, items) => {
|
|
8
|
+
* // items is an array of { args, resolve, reject }
|
|
9
|
+
* // do something once with all args...
|
|
10
|
+
* })
|
|
11
|
+
*
|
|
12
|
+
* batcher.enqueue("my-key", [arg1, arg2])
|
|
13
|
+
*/
|
|
14
|
+
function batchOnNextTick(onFlush) {
|
|
15
|
+
const queues = /* @__PURE__ */ new Map();
|
|
16
|
+
/**
|
|
17
|
+
* Enqueue a call with the given key and arguments.
|
|
18
|
+
* @param key key to group calls
|
|
19
|
+
* @param args arguments for the call
|
|
20
|
+
* @returns A promise that resolves or rejects when the call is flushed.
|
|
21
|
+
*/
|
|
22
|
+
function enqueue(key, args) {
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
let q = queues.get(key);
|
|
25
|
+
if (!q) {
|
|
26
|
+
q = {
|
|
27
|
+
timer: null,
|
|
28
|
+
items: [],
|
|
29
|
+
flush: () => flush(key)
|
|
30
|
+
};
|
|
31
|
+
queues.set(key, q);
|
|
32
|
+
}
|
|
33
|
+
q.items.push({
|
|
34
|
+
args,
|
|
35
|
+
resolve,
|
|
36
|
+
reject
|
|
37
|
+
});
|
|
38
|
+
if (q.timer == null) q.timer = setTimeout(() => {
|
|
39
|
+
q.timer = null;
|
|
40
|
+
q.flush();
|
|
41
|
+
}, 0);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Flush the queue for the given key immediately.
|
|
46
|
+
* @param key key to flush
|
|
47
|
+
* @returns A promise that resolves when the flush is complete.
|
|
48
|
+
*/
|
|
49
|
+
async function flush(key) {
|
|
50
|
+
const q = queues.get(key);
|
|
51
|
+
if (!q || q.items.length === 0) return;
|
|
52
|
+
if (q.timer != null) {
|
|
53
|
+
clearTimeout(q.timer);
|
|
54
|
+
q.timer = null;
|
|
55
|
+
}
|
|
56
|
+
const items = q.items.splice(0);
|
|
57
|
+
onFlush(key, items.map((i) => i.args)).then((results) => {
|
|
58
|
+
for (const [index, result] of results.entries()) {
|
|
59
|
+
const { resolve } = items[index];
|
|
60
|
+
resolve(result);
|
|
61
|
+
}
|
|
62
|
+
}).catch((error) => {
|
|
63
|
+
for (const { reject } of items) reject(error);
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
enqueue,
|
|
68
|
+
flush
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
//#endregion
|
|
72
|
+
export { batchOnNextTick as default };
|