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