@signaldb/core 2.0.0-beta.13 → 2.0.0-beta.14

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