@signaldb/core 1.7.0 → 2.0.0-beta.0

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 (88) hide show
  1. package/dist/.vite/manifest.json +125 -82
  2. package/dist/AsyncDataAdapter.d.ts +64 -0
  3. package/dist/AutoFetchDataAdapter.d.ts +113 -0
  4. package/dist/Collection/Cursor.d.ts +9 -9
  5. package/dist/Collection/Observer.d.ts +3 -2
  6. package/dist/Collection/index.d.ts +52 -46
  7. package/dist/Collection/types.d.ts +4 -9
  8. package/dist/DataAdapter.d.ts +33 -0
  9. package/dist/DefaultDataAdapter.d.ts +32 -0
  10. package/dist/WorkerDataAdapter.d.ts +22 -0
  11. package/dist/WorkerDataAdapterHost.d.ts +59 -0
  12. package/dist/createIndex.d.ts +7 -0
  13. package/dist/createStorageAdapter.d.ts +9 -0
  14. package/dist/{Collection/getIndexInfo.d.ts → getIndexInfo.d.ts} +17 -19
  15. package/dist/index.cjs.js +21 -17
  16. package/dist/index.cjs10.js +15 -26
  17. package/dist/index.cjs11.js +13 -10
  18. package/dist/index.cjs12.js +337 -3
  19. package/dist/index.cjs13.js +384 -115
  20. package/dist/index.cjs14.js +183 -67
  21. package/dist/index.cjs15.js +339 -8
  22. package/dist/index.cjs16.js +563 -20
  23. package/dist/index.cjs17.js +16 -12
  24. package/dist/index.cjs18.js +24 -5
  25. package/dist/index.cjs2.js +27 -36
  26. package/dist/index.cjs20.js +102 -13
  27. package/dist/index.cjs21.js +124 -21
  28. package/dist/index.cjs22.js +5 -68
  29. package/dist/index.cjs23.js +22 -82
  30. package/dist/index.cjs24.js +5 -16
  31. package/dist/index.cjs25.js +8 -27
  32. package/dist/index.cjs26.js +27 -7
  33. package/dist/index.cjs27.js +3 -5
  34. package/dist/index.cjs28.js +5 -27
  35. package/dist/index.cjs29.js +27 -40
  36. package/dist/index.cjs3.js +242 -497
  37. package/dist/index.cjs30.js +42 -0
  38. package/dist/index.cjs31.js +9 -0
  39. package/dist/index.cjs4.js +3 -170
  40. package/dist/index.cjs5.js +3 -67
  41. package/dist/index.cjs6.js +27 -3
  42. package/dist/index.cjs7.js +10 -3
  43. package/dist/index.cjs8.js +3 -3
  44. package/dist/index.cjs9.js +131 -3
  45. package/dist/index.d.ts +10 -8
  46. package/dist/index.mjs +15 -11
  47. package/dist/index10.mjs +15 -26
  48. package/dist/index11.mjs +13 -10
  49. package/dist/index12.mjs +337 -3
  50. package/dist/index13.mjs +384 -115
  51. package/dist/index14.mjs +183 -66
  52. package/dist/index15.mjs +339 -8
  53. package/dist/index16.mjs +563 -20
  54. package/dist/index17.mjs +16 -12
  55. package/dist/index18.mjs +24 -5
  56. package/dist/index2.mjs +27 -36
  57. package/dist/index20.mjs +102 -13
  58. package/dist/index21.mjs +123 -21
  59. package/dist/index22.mjs +5 -67
  60. package/dist/index23.mjs +22 -81
  61. package/dist/index24.mjs +5 -16
  62. package/dist/index25.mjs +8 -27
  63. package/dist/index26.mjs +27 -7
  64. package/dist/index27.mjs +3 -5
  65. package/dist/index28.mjs +5 -27
  66. package/dist/index29.mjs +27 -40
  67. package/dist/index3.mjs +241 -497
  68. package/dist/index30.mjs +43 -0
  69. package/dist/index31.mjs +10 -0
  70. package/dist/index4.mjs +3 -170
  71. package/dist/index5.mjs +3 -66
  72. package/dist/index6.mjs +27 -3
  73. package/dist/index7.mjs +10 -3
  74. package/dist/index8.mjs +3 -3
  75. package/dist/index9.mjs +131 -3
  76. package/dist/types/IndexProvider.d.ts +12 -7
  77. package/dist/types/StorageAdapter.d.ts +20 -0
  78. package/dist/utils/objectId.d.ts +8 -0
  79. package/dist/utils/queryId.d.ts +9 -0
  80. package/package.json +2 -2
  81. package/dist/AutoFetchCollection.d.ts +0 -60
  82. package/dist/Collection/createIndex.d.ts +0 -15
  83. package/dist/ReplicatedCollection.d.ts +0 -60
  84. package/dist/createMemoryAdapter.d.ts +0 -7
  85. package/dist/persistence/combinePersistenceAdapters.d.ts +0 -32
  86. package/dist/persistence/createPersistenceAdapter.d.ts +0 -9
  87. package/dist/types/MemoryAdapter.d.ts +0 -15
  88. package/dist/types/PersistenceAdapter.d.ts +0 -20
package/dist/index13.mjs CHANGED
@@ -1,139 +1,408 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- class EventEmitter {
5
- constructor() {
6
- __publicField(this, "_maxListeners", 100);
7
- /**
8
- * We store a set of the listeners for each event.
9
- */
10
- __publicField(this, "_listenerStore", /* @__PURE__ */ new Map());
11
- }
12
- setMaxListeners(max) {
13
- this._maxListeners = max;
14
- return this;
1
+ import deepClone from "./index19.mjs";
2
+ import match from "./index22.mjs";
3
+ import modify from "./index7.mjs";
4
+ import queryId from "./index24.mjs";
5
+ import isEqual from "./index6.mjs";
6
+ import getIndexInfo from "./index21.mjs";
7
+ import getMatchingKeys from "./index26.mjs";
8
+ import sortItems from "./index25.mjs";
9
+ import project from "./index23.mjs";
10
+ class AsyncDataAdapter {
11
+ options;
12
+ id;
13
+ onError;
14
+ // Per-collection resources
15
+ storageAdapters = /* @__PURE__ */ new Map();
16
+ storageAdapterReady = /* @__PURE__ */ new Map();
17
+ collectionIndices = /* @__PURE__ */ new Map();
18
+ // Per-collection query registries
19
+ queries = /* @__PURE__ */ new Map();
20
+ constructor(options) {
21
+ this.options = options;
22
+ this.id = options.id || "async-data-adapter";
23
+ this.onError = options.onError ?? ((error) => {
24
+ console.error(error);
25
+ });
26
+ }
27
+ createCollectionBackend(collection, indices) {
28
+ this.collectionIndices.set(collection.name, indices);
29
+ this.queries.set(collection.name, /* @__PURE__ */ new Map());
30
+ this.ensureStorageAdapter(collection.name);
31
+ const ready = (async () => {
32
+ try {
33
+ await this.setupStorage(collection.name, indices);
34
+ } catch (error) {
35
+ this.onError(error);
36
+ throw error;
37
+ }
38
+ })();
39
+ this.storageAdapterReady.set(collection.name, ready);
40
+ const registerQuery = (selector, options) => {
41
+ const qid = queryId(selector, options);
42
+ const registry = this.queries.get(collection.name);
43
+ if (!registry)
44
+ throw new Error(`Collection ${collection.name} not initialized!`);
45
+ registry.set(qid, {
46
+ selector,
47
+ options,
48
+ items: [],
49
+ listeners: /* @__PURE__ */ new Set(),
50
+ ...registry.get(qid),
51
+ state: "active",
52
+ error: null
53
+ });
54
+ void this.fulfillQuery(collection.name, selector, options).catch(this.onError);
55
+ };
56
+ const unregisterQuery = (selector, options) => {
57
+ const qid = queryId(selector, options);
58
+ this.queries.get(collection.name)?.delete(qid);
59
+ };
60
+ const getQueryState = (selector, options) => {
61
+ const q = this.queries.get(collection.name)?.get(queryId(selector, options));
62
+ return q?.state ?? "active";
63
+ };
64
+ const getQueryError = (selector, options) => {
65
+ const q = this.queries.get(collection.name)?.get(queryId(selector, options));
66
+ return q?.error ?? null;
67
+ };
68
+ const getQueryResult = (selector, options) => {
69
+ const q = this.queries.get(collection.name)?.get(queryId(selector, options));
70
+ return q?.items ?? [];
71
+ };
72
+ const onQueryStateChange = (selector, options, callback) => {
73
+ const qid = queryId(selector, options);
74
+ const registry = this.queries.get(collection.name);
75
+ if (!registry)
76
+ throw new Error(`Collection ${collection.name} not initialized!`);
77
+ if (!registry.has(qid)) {
78
+ registry.set(qid, {
79
+ selector,
80
+ options,
81
+ state: "active",
82
+ error: null,
83
+ items: [],
84
+ listeners: /* @__PURE__ */ new Set()
85
+ });
86
+ }
87
+ registry.get(qid)?.listeners.add(callback);
88
+ return () => registry.get(qid)?.listeners.delete(callback);
89
+ };
90
+ return {
91
+ insert: async (item) => {
92
+ await ready;
93
+ const inserted = await this.insert(collection.name, item);
94
+ return inserted;
95
+ },
96
+ updateOne: async (selector, modifier) => {
97
+ await ready;
98
+ return this.updateOne(collection.name, selector, modifier);
99
+ },
100
+ updateMany: async (selector, modifier) => {
101
+ await ready;
102
+ return this.updateMany(collection.name, selector, modifier);
103
+ },
104
+ replaceOne: async (selector, replacement) => {
105
+ await ready;
106
+ return this.replaceOne(collection.name, selector, replacement);
107
+ },
108
+ removeOne: async (selector) => {
109
+ await ready;
110
+ return this.removeOne(collection.name, selector);
111
+ },
112
+ removeMany: async (selector) => {
113
+ await ready;
114
+ return this.removeMany(collection.name, selector);
115
+ },
116
+ registerQuery,
117
+ unregisterQuery,
118
+ getQueryState,
119
+ getQueryError,
120
+ getQueryResult,
121
+ onQueryStateChange,
122
+ dispose: async () => {
123
+ this.storageAdapters.delete(collection.name);
124
+ this.queries.delete(collection.name);
125
+ this.collectionIndices.delete(collection.name);
126
+ this.storageAdapterReady.delete(collection.name);
127
+ },
128
+ isReady: async () => {
129
+ await ready;
130
+ }
131
+ };
132
+ }
133
+ async setupStorage(collectionName, indices) {
134
+ const storage = this.storageAdapters.get(collectionName);
135
+ if (!storage)
136
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
137
+ await Promise.all([
138
+ storage.createIndex("id"),
139
+ ...indices.map((index) => storage.createIndex(index))
140
+ ]);
141
+ await storage.setup();
142
+ }
143
+ ensureStorageAdapter(name) {
144
+ if (this.storageAdapters.has(name))
145
+ return;
146
+ const adapter = this.options.storage(name);
147
+ if (!adapter)
148
+ return;
149
+ this.storageAdapters.set(name, adapter);
15
150
  }
16
151
  /**
17
- * Subscribe to an event with a listener function.
18
- * @param eventName The event name (key of E).
19
- * @param listener A function that receives the emitted arguments.
20
- * @returns The emitter instance (for chaining).
152
+ * Compute and publish the result for a specific query
153
+ * @param collectionName - name of the collection
154
+ * @param selector - query selector
155
+ * @param options - query options
21
156
  */
22
- on(eventName, listener) {
23
- let listenersSet = this._listenerStore.get(eventName);
24
- if (!listenersSet) {
25
- listenersSet = /* @__PURE__ */ new Set();
26
- this._listenerStore.set(eventName, listenersSet);
157
+ async fulfillQuery(collectionName, selector, options) {
158
+ const qid = queryId(selector, options);
159
+ const registry = this.queries.get(collectionName);
160
+ if (!registry)
161
+ throw new Error(`Collection ${collectionName} not initialized!`);
162
+ const rec = registry.get(qid);
163
+ if (!rec)
164
+ return;
165
+ this.publishState(collectionName, qid, "active", null);
166
+ try {
167
+ const items = await this.executeQuery(collectionName, selector, options);
168
+ this.publishResult(collectionName, qid, items);
169
+ this.publishState(collectionName, qid, "complete", null);
170
+ } catch (error) {
171
+ this.publishState(collectionName, qid, "error", error);
27
172
  }
28
- listenersSet.add(listener);
29
- if (listenersSet.size > this._maxListeners) {
30
- console.warn(`Possible EventEmitter memory leak detected. ${listenersSet.size} ${String(eventName)} listeners added. Use emitter.setMaxListeners() to increase limit.`);
31
- }
32
- return this;
33
173
  }
34
174
  /**
35
- * Subscribe to an event with a listener function.
36
- * @param eventName The event name (key of E).
37
- * @param listener A function that receives the emitted arguments.
38
- * @returns The emitter instance (for chaining).
175
+ * Notify listeners about state changes and keep the cache updated
176
+ * @param collectionName - name of the collection
177
+ * @param qid - query id
178
+ * @param state - new state
179
+ * @param error - error if state is 'error', null otherwise
39
180
  */
40
- addListener(eventName, listener) {
41
- return this.on(eventName, listener);
181
+ publishState(collectionName, qid, state, error) {
182
+ const rec = this.queries.get(collectionName)?.get(qid);
183
+ if (!rec)
184
+ return;
185
+ rec.state = state;
186
+ rec.error = error;
187
+ for (const callback of rec.listeners) {
188
+ try {
189
+ callback(state);
190
+ } catch (error_) {
191
+ this.onError(error_);
192
+ }
193
+ }
42
194
  }
43
- /**
44
- * Subscribe to an event, handling it only once. Automatically removes
45
- * the listener after it fires the first time.
46
- * @param eventName The event name (key of E).
47
- * @param listener A function that receives the emitted arguments.
48
- * @returns The emitter instance (for chaining).
49
- */
50
- once(eventName, listener) {
51
- const onceWrapper = (...args) => {
52
- listener(...args);
53
- this.off(eventName, onceWrapper);
54
- };
55
- return this.on(eventName, onceWrapper);
195
+ publishResult(collectionName, qid, items) {
196
+ const rec = this.queries.get(collectionName)?.get(qid);
197
+ if (!rec)
198
+ return;
199
+ rec.items = items;
56
200
  }
57
- /**
58
- * Unsubscribe a previously subscribed listener.
59
- * @param eventName The event name (key of E).
60
- * @param listener The original function passed to `on` or `once`.
61
- * @returns The emitter instance (for chaining).
62
- */
63
- off(eventName, listener) {
64
- const listenersSet = this._listenerStore.get(eventName);
65
- if (!listenersSet)
66
- return this;
67
- listenersSet.delete(listener);
68
- if (listenersSet.size === 0) {
69
- this._listenerStore.delete(eventName);
201
+ async getIndexInfo(collectionName, selector) {
202
+ const storage = this.storageAdapters.get(collectionName);
203
+ if (!storage)
204
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
205
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
206
+ return { matched: true, ids: [selector.id], optimizedSelector: {} };
207
+ }
208
+ if (selector == null) {
209
+ return { matched: false, ids: [], optimizedSelector: {} };
70
210
  }
71
- return this;
211
+ const indices = this.collectionIndices.get(collectionName) ?? [];
212
+ return getIndexInfo(indices.map((field) => async (flatSelector) => {
213
+ if (!Object.hasOwnProperty.call(flatSelector, field))
214
+ return { matched: false };
215
+ const index = await storage.readIndex(field);
216
+ const fieldSelector = flatSelector[field];
217
+ const filtersForNull = fieldSelector == null || fieldSelector.$exists === false;
218
+ const keys = filtersForNull ? { include: null, exclude: [...index.keys()].filter((key) => key != null) } : getMatchingKeys(field, flatSelector);
219
+ if (keys.include == null && keys.exclude == null)
220
+ return { matched: false };
221
+ let includedIds = [];
222
+ if (keys.include == null) {
223
+ for (const set of index.values())
224
+ for (const pos of set)
225
+ includedIds.push(pos);
226
+ } else {
227
+ for (const key of keys.include) {
228
+ const idSet = index.get(key);
229
+ if (idSet)
230
+ for (const id of idSet)
231
+ includedIds.push(id);
232
+ }
233
+ }
234
+ if (keys.exclude != null) {
235
+ const excludeIds = /* @__PURE__ */ new Set();
236
+ for (const key of keys.exclude) {
237
+ const idSet = index.get(key);
238
+ if (idSet)
239
+ for (const id of idSet)
240
+ excludeIds.add(id);
241
+ }
242
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
243
+ }
244
+ return { matched: true, ids: includedIds, fields: [field], keepSelector: filtersForNull };
245
+ }), selector);
72
246
  }
73
- /**
74
- * Unsubscribe a previously subscribed listener.
75
- * @param eventName The event name (key of E).
76
- * @param listener The original function passed to `on` or `once`.
77
- * @returns The emitter instance (for chaining).
78
- */
79
- removeListener(eventName, listener) {
80
- return this.off(eventName, listener);
247
+ async queryItems(collectionName, selector) {
248
+ const storage = this.storageAdapters.get(collectionName);
249
+ if (!storage)
250
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
251
+ const index = await this.getIndexInfo(collectionName, selector);
252
+ const matchItems = (item) => {
253
+ if (index.optimizedSelector == null)
254
+ return true;
255
+ if (Object.keys(index.optimizedSelector).length <= 0)
256
+ return true;
257
+ return match(item, index.optimizedSelector);
258
+ };
259
+ if (index.matched) {
260
+ const items = await storage.readIds(index.ids);
261
+ if (isEqual(index.optimizedSelector, {}))
262
+ return items;
263
+ return items.filter(matchItems);
264
+ } else {
265
+ const allItems = await storage.readAll();
266
+ if (isEqual(selector, {}))
267
+ return allItems;
268
+ return allItems.filter(matchItems);
269
+ }
81
270
  }
82
- /**
83
- * Emit (dispatch) an event with a variable number of arguments.
84
- * @param eventName The event name (key of E).
85
- * @param args The arguments to pass to subscribed listeners.
86
- */
87
- emit(eventName, ...args) {
88
- this.listeners(eventName).forEach((listener) => {
89
- listener(...args);
271
+ async executeQuery(collectionName, selector, options) {
272
+ const items = await this.queryItems(collectionName, selector || {});
273
+ const { sort, skip, limit, fields } = options || {};
274
+ const sorted = sort ? sortItems(items, sort) : items;
275
+ const skipped = skip ? sorted.slice(skip) : sorted;
276
+ const limited = limit ? skipped.slice(0, limit) : skipped;
277
+ const idExcluded = fields && fields.id === 0;
278
+ return limited.map((item) => {
279
+ if (!fields)
280
+ return item;
281
+ return { ...idExcluded ? {} : { id: item.id }, ...project(item, fields) };
90
282
  });
91
283
  }
92
284
  /**
93
- * Returns the array of listener functions currently registered for a given event.
94
- * @param eventName The event name (key of E).
95
- * @returns An array of listener functions.
285
+ * After mutations, recompute and push updates for affected active queries
286
+ * @param collectionName - name of the collection
287
+ * @param changedItems - items that were inserted/updated/replaced/removed
96
288
  */
97
- listeners(eventName) {
98
- const listenersSet = this._listenerStore.get(eventName);
99
- if (!listenersSet)
100
- return [];
101
- return [...listenersSet.values()];
289
+ async checkQueryUpdates(collectionName, changedItems) {
290
+ const registry = this.queries.get(collectionName);
291
+ if (!registry)
292
+ throw new Error(`Collection ${collectionName} not initialized!`);
293
+ if (registry.size === 0)
294
+ return;
295
+ const affected = [...registry.values()].filter(({ selector }) => changedItems.some((item) => match(item, selector)));
296
+ if (affected.length === 0)
297
+ return;
298
+ for (const { selector, options } of affected) {
299
+ const qid = queryId(selector, options);
300
+ this.publishState(collectionName, qid, "active", null);
301
+ }
302
+ await Promise.all(affected.map(async ({ selector, options }) => {
303
+ const qid = queryId(selector, options);
304
+ try {
305
+ const items = await this.executeQuery(collectionName, selector, options);
306
+ this.publishResult(collectionName, qid, items);
307
+ this.publishState(collectionName, qid, "complete", null);
308
+ } catch (error) {
309
+ this.publishState(collectionName, qid, "error", error);
310
+ }
311
+ }));
102
312
  }
103
- /**
104
- * Returns the number of listeners for a given event.
105
- * @param eventName The event name (key of E).
106
- * @returns The number of listeners.
107
- */
108
- listenerCount(eventName) {
109
- const listenersSet = this._listenerStore.get(eventName);
110
- return listenersSet ? listenersSet.size : 0;
313
+ async insert(collectionName, newItem) {
314
+ const storage = this.storageAdapters.get(collectionName);
315
+ if (!storage)
316
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
317
+ const existing = await this.executeQuery(collectionName, { id: newItem.id }, { limit: 1 });
318
+ if (existing.length > 0)
319
+ throw new Error(`Item with id ${String(newItem.id)} already exists`);
320
+ await storage.insert([newItem]);
321
+ await this.checkQueryUpdates(collectionName, [newItem]);
322
+ return newItem;
111
323
  }
112
- /**
113
- * Removes all listeners for a given event, or all events if none is specified.
114
- * @param eventName Optional. If omitted, clears all events’ listeners.
115
- * @returns The emitter instance (for chaining).
116
- */
117
- removeAllListeners(eventName) {
118
- if (eventName === void 0) {
119
- for (const [eventName_, listenersSet] of this._listenerStore.entries()) {
120
- for (const listener of listenersSet.values()) {
121
- this.off(eventName_, listener);
122
- }
123
- }
124
- this._listenerStore.clear();
125
- } else {
126
- const listenersSet = this._listenerStore.get(eventName);
127
- if (listenersSet) {
128
- for (const listener of listenersSet.values()) {
129
- this.off(eventName, listener);
130
- }
131
- this._listenerStore.delete(eventName);
324
+ async updateOne(collectionName, selector, modifier) {
325
+ const storage = this.storageAdapters.get(collectionName);
326
+ if (!storage)
327
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
328
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
329
+ const [item] = items;
330
+ const { $setOnInsert, ...rest } = modifier;
331
+ if (item == null)
332
+ return [];
333
+ const modified = modify(deepClone(item), rest);
334
+ if (item.id !== modified.id) {
335
+ const existing = await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 });
336
+ if (existing.length > 0)
337
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
338
+ }
339
+ await storage.replace([modified]);
340
+ await this.checkQueryUpdates(collectionName, [modified]);
341
+ return [modified];
342
+ }
343
+ async updateMany(collectionName, selector, modifier) {
344
+ const storage = this.storageAdapters.get(collectionName);
345
+ if (!storage)
346
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
347
+ const items = await this.executeQuery(collectionName, selector);
348
+ if (items.length === 0)
349
+ return [];
350
+ const { $setOnInsert, ...rest } = modifier;
351
+ const changed = await Promise.all(items.map(async (item) => {
352
+ const modified = modify(deepClone(item), rest);
353
+ if (item.id !== modified.id) {
354
+ const existing = await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 });
355
+ if (existing.length > 0)
356
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
132
357
  }
358
+ return modified;
359
+ }));
360
+ await storage.replace(changed);
361
+ await this.checkQueryUpdates(collectionName, changed);
362
+ return changed;
363
+ }
364
+ async replaceOne(collectionName, selector, replacement) {
365
+ const storage = this.storageAdapters.get(collectionName);
366
+ if (!storage)
367
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
368
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
369
+ const [item] = items;
370
+ if (item == null)
371
+ return [];
372
+ const modified = { ...replacement, id: replacement.id ?? item.id };
373
+ if (item.id !== modified.id) {
374
+ const existing = await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 });
375
+ if (existing.length > 0)
376
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
133
377
  }
134
- return this;
378
+ await storage.replace([modified]);
379
+ await this.checkQueryUpdates(collectionName, [modified]);
380
+ return [modified];
381
+ }
382
+ async removeOne(collectionName, selector) {
383
+ const storage = this.storageAdapters.get(collectionName);
384
+ if (!storage)
385
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
386
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
387
+ const [item] = items;
388
+ if (item == null)
389
+ return [];
390
+ await storage.remove([item]);
391
+ await this.checkQueryUpdates(collectionName, [item]);
392
+ return [item];
393
+ }
394
+ async removeMany(collectionName, selector) {
395
+ const storage = this.storageAdapters.get(collectionName);
396
+ if (!storage)
397
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
398
+ const items = await this.executeQuery(collectionName, selector);
399
+ if (items.length === 0)
400
+ return [];
401
+ await storage.remove(items);
402
+ await this.checkQueryUpdates(collectionName, items);
403
+ return items;
135
404
  }
136
405
  }
137
406
  export {
138
- EventEmitter as default
407
+ AsyncDataAdapter as default
139
408
  };