@signaldb/core 2.0.0-beta.1 → 2.0.0-beta.11

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 (129) hide show
  1. package/dist/.vite/manifest.json +122 -82
  2. package/dist/AsyncDataAdapter.d.ts +44 -7
  3. package/dist/AutoFetchDataAdapter.d.ts +5 -7
  4. package/dist/Collection/Cursor.d.ts +6 -5
  5. package/dist/Collection/Observer.d.ts +2 -0
  6. package/dist/Collection/index.d.ts +34 -25
  7. package/dist/Collection/types.d.ts +10 -2
  8. package/dist/DataAdapter.d.ts +12 -6
  9. package/dist/DefaultDataAdapter.d.ts +6 -6
  10. package/dist/WorkerDataAdapter.d.ts +10 -6
  11. package/dist/WorkerDataAdapterHost.d.ts +7 -7
  12. package/dist/createIndex.d.ts +2 -2
  13. package/dist/createIndexProvider.d.ts +2 -2
  14. package/dist/createReactivityAdapter.d.ts +2 -2
  15. package/dist/createStorageAdapter.d.ts +1 -1
  16. package/dist/getIndexInfo.d.ts +3 -4
  17. package/dist/index.cjs.js +33 -31
  18. package/dist/index.d.ts +4 -1
  19. package/dist/index.mjs +17 -32
  20. package/dist/index10.cjs.js +23 -0
  21. package/dist/index10.mjs +21 -17
  22. package/dist/index11.cjs.js +45 -0
  23. package/dist/index11.mjs +44 -15
  24. package/dist/index12.cjs.js +22 -0
  25. package/dist/index12.mjs +21 -350
  26. package/dist/index13.cjs.js +45 -0
  27. package/dist/index13.mjs +44 -419
  28. package/dist/index14.cjs.js +86 -0
  29. package/dist/index14.mjs +85 -184
  30. package/dist/index15.cjs.js +15 -0
  31. package/dist/index15.mjs +14 -386
  32. package/dist/index16.cjs.js +136 -0
  33. package/dist/index16.mjs +133 -577
  34. package/dist/index17.cjs.js +47 -0
  35. package/dist/index17.mjs +46 -150
  36. package/dist/index18.cjs.js +15 -0
  37. package/dist/index18.mjs +14 -26
  38. package/dist/index19.cjs.js +23 -0
  39. package/dist/index19.mjs +22 -42
  40. package/dist/index2.cjs.js +33 -0
  41. package/dist/index2.mjs +32 -257
  42. package/dist/index20.cjs.js +37 -0
  43. package/dist/index20.mjs +36 -7
  44. package/dist/index21.cjs.js +35 -0
  45. package/dist/index21.mjs +33 -103
  46. package/dist/index22.cjs.js +25 -0
  47. package/dist/index22.mjs +23 -127
  48. package/dist/index23.cjs.js +19 -0
  49. package/dist/index23.mjs +18 -7
  50. package/dist/index24.cjs.js +342 -0
  51. package/dist/index24.mjs +340 -26
  52. package/dist/index25.cjs.js +542 -0
  53. package/dist/index25.mjs +541 -10
  54. package/dist/index26.cjs.js +11 -0
  55. package/dist/index26.mjs +10 -29
  56. package/dist/index27.cjs.js +11 -0
  57. package/dist/index27.mjs +10 -46
  58. package/dist/index28.cjs.js +90 -0
  59. package/dist/index28.mjs +87 -7
  60. package/dist/index29.cjs.js +424 -0
  61. package/dist/index29.mjs +423 -9
  62. package/dist/index3.cjs.js +19 -0
  63. package/dist/index3.mjs +18 -541
  64. package/dist/index30.cjs.js +72 -0
  65. package/dist/index30.mjs +71 -5
  66. package/dist/index31.cjs.js +191 -0
  67. package/dist/index31.mjs +190 -7
  68. package/dist/index32.cjs.js +21 -0
  69. package/dist/index32.mjs +20 -29
  70. package/dist/index33.cjs.js +335 -0
  71. package/dist/index33.mjs +334 -42
  72. package/dist/index34.cjs.js +539 -0
  73. package/dist/index34.mjs +539 -0
  74. package/dist/index4.cjs.js +150 -0
  75. package/dist/index4.mjs +149 -5
  76. package/dist/index5.cjs.js +254 -0
  77. package/dist/index5.mjs +252 -4
  78. package/dist/index6.cjs.js +125 -0
  79. package/dist/index6.mjs +124 -29
  80. package/dist/index7.cjs.js +33 -0
  81. package/dist/index7.mjs +32 -12
  82. package/dist/index8.cjs.js +12 -0
  83. package/dist/index8.mjs +10 -4
  84. package/dist/index9.cjs.js +11 -0
  85. package/dist/index9.mjs +10 -133
  86. package/dist/types/IndexProvider.d.ts +2 -2
  87. package/dist/types/Modifier.d.ts +1 -1
  88. package/dist/types/ReactivityAdapter.d.ts +1 -1
  89. package/dist/utils/createSignal.d.ts +2 -2
  90. package/dist/utils/deepClone.d.ts +1 -1
  91. package/dist/utils/getMatchingKeys.d.ts +2 -2
  92. package/dist/utils/isFieldExpression.d.ts +1 -1
  93. package/dist/utils/match.d.ts +1 -1
  94. package/dist/utils/modify.d.ts +1 -1
  95. package/dist/utils/queryId.d.ts +2 -2
  96. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  97. package/package.json +3 -3
  98. package/dist/index.cjs10.js +0 -18
  99. package/dist/index.cjs11.js +0 -15
  100. package/dist/index.cjs12.js +0 -350
  101. package/dist/index.cjs13.js +0 -419
  102. package/dist/index.cjs14.js +0 -184
  103. package/dist/index.cjs15.js +0 -386
  104. package/dist/index.cjs16.js +0 -579
  105. package/dist/index.cjs17.js +0 -150
  106. package/dist/index.cjs18.js +0 -26
  107. package/dist/index.cjs19.js +0 -43
  108. package/dist/index.cjs2.js +0 -258
  109. package/dist/index.cjs20.js +0 -7
  110. package/dist/index.cjs21.js +0 -104
  111. package/dist/index.cjs22.js +0 -129
  112. package/dist/index.cjs23.js +0 -7
  113. package/dist/index.cjs24.js +0 -27
  114. package/dist/index.cjs25.js +0 -10
  115. package/dist/index.cjs26.js +0 -29
  116. package/dist/index.cjs27.js +0 -46
  117. package/dist/index.cjs28.js +0 -8
  118. package/dist/index.cjs29.js +0 -9
  119. package/dist/index.cjs3.js +0 -542
  120. package/dist/index.cjs30.js +0 -5
  121. package/dist/index.cjs31.js +0 -7
  122. package/dist/index.cjs32.js +0 -29
  123. package/dist/index.cjs33.js +0 -42
  124. package/dist/index.cjs4.js +0 -5
  125. package/dist/index.cjs5.js +0 -5
  126. package/dist/index.cjs6.js +0 -29
  127. package/dist/index.cjs7.js +0 -12
  128. package/dist/index.cjs8.js +0 -5
  129. package/dist/index.cjs9.js +0 -133
package/dist/index29.mjs CHANGED
@@ -1,10 +1,424 @@
1
- function uniqueBy(array, fn) {
2
- const set = /* @__PURE__ */ new Set();
3
- return array.filter((element) => {
4
- const value = typeof fn === "function" ? fn(element) : element[fn];
5
- return !set.has(value) && set.add(value);
6
- });
7
- }
8
- export {
9
- uniqueBy as default
1
+ import isEqual from "./index2.mjs";
2
+ import getMatchingKeys from "./index13.mjs";
3
+ import getIndexInfo from "./index16.mjs";
4
+ import deepClone from "./index17.mjs";
5
+ import match from "./index18.mjs";
6
+ import modify from "./index19.mjs";
7
+ import project from "./index21.mjs";
8
+ import queryId from "./index22.mjs";
9
+ import sortItems from "./index23.mjs";
10
+ //#region src/AsyncDataAdapter.ts
11
+ /**
12
+ * Carries the context needed to act on a failed query. The bare storage error
13
+ * on its own does not say which collection or selector produced it, which made
14
+ * the default `console.error` hook close to useless.
15
+ */
16
+ var QueryError = class extends Error {
17
+ collectionName;
18
+ selector;
19
+ options;
20
+ attempts;
21
+ constructor(collectionName, selector, options, attempts, cause) {
22
+ const reason = cause instanceof Error ? cause.message : String(cause);
23
+ super(`Query on "${collectionName}" failed after ${attempts} attempt(s): ${reason}`);
24
+ this.name = "QueryError";
25
+ this.collectionName = collectionName;
26
+ this.selector = selector;
27
+ this.options = options;
28
+ this.attempts = attempts;
29
+ this.cause = cause;
30
+ }
10
31
  };
32
+ var DEFAULT_RETRY_ATTEMPTS = 3;
33
+ var defaultRetryDelay = (attempt) => 100 * 4 ** (attempt - 1);
34
+ var wait = (ms) => new Promise((resolve) => {
35
+ setTimeout(resolve, ms);
36
+ });
37
+ /**
38
+ * AsyncDataAdapter
39
+ * Combines WorkerDataAdapter + WorkerDataAdapterHost into a single, transport-free adapter.
40
+ * - Keeps the DataAdapter/CollectionBackend surface identical to the Worker version.
41
+ * - Executes queries and mutations directly against the provided StorageAdapter.
42
+ * - Preserves index-aware query optimization and push-style query updates to listeners.
43
+ */
44
+ var AsyncDataAdapter = class {
45
+ options;
46
+ id;
47
+ onError;
48
+ retryAttempts;
49
+ retryDelay;
50
+ storageAdapters = /* @__PURE__ */ new Map();
51
+ storageAdapterReady = /* @__PURE__ */ new Map();
52
+ collectionIndices = /* @__PURE__ */ new Map();
53
+ queries = /* @__PURE__ */ new Map();
54
+ constructor(options) {
55
+ this.options = options;
56
+ this.id = options.id || "async-data-adapter";
57
+ this.onError = options.onError ?? ((error) => {
58
+ console.error(error);
59
+ });
60
+ this.retryAttempts = Math.max(1, options.retry?.attempts ?? DEFAULT_RETRY_ATTEMPTS);
61
+ this.retryDelay = options.retry?.delay ?? defaultRetryDelay;
62
+ }
63
+ createCollectionBackend(collection, indices) {
64
+ this.collectionIndices.set(collection.name, indices);
65
+ this.queries.set(collection.name, /* @__PURE__ */ new Map());
66
+ this.ensureStorageAdapter(collection.name);
67
+ const ready = (async () => {
68
+ try {
69
+ await this.setupStorage(collection.name, indices);
70
+ } catch (error) {
71
+ this.onError(error);
72
+ throw error;
73
+ }
74
+ })();
75
+ this.storageAdapterReady.set(collection.name, ready);
76
+ const registerQuery = (selector, options) => {
77
+ const qid = queryId(selector, options);
78
+ const registry = this.queries.get(collection.name);
79
+ if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
80
+ registry.set(qid, {
81
+ selector,
82
+ options,
83
+ items: [],
84
+ listeners: /* @__PURE__ */ new Set(),
85
+ ...registry.get(qid),
86
+ state: "active",
87
+ error: null
88
+ });
89
+ this.fulfillQuery(collection.name, selector, options).catch(this.onError);
90
+ };
91
+ const unregisterQuery = (selector, options) => {
92
+ const qid = queryId(selector, options);
93
+ this.queries.get(collection.name)?.delete(qid);
94
+ };
95
+ const getQueryState = (selector, options) => {
96
+ return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.state ?? "active";
97
+ };
98
+ const getQueryError = (selector, options) => {
99
+ return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.error ?? null;
100
+ };
101
+ const getQueryResult = (selector, options) => {
102
+ return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.items ?? [];
103
+ };
104
+ const retryQuery = (selector, options) => {
105
+ const qid = queryId(selector, options);
106
+ if (!this.queries.get(collection.name)?.get(qid)) return;
107
+ this.publishState(collection.name, qid, "active", null);
108
+ this.runQuery(collection.name, selector, options);
109
+ };
110
+ const onQueryStateChange = (selector, options, callback) => {
111
+ const qid = queryId(selector, options);
112
+ const registry = this.queries.get(collection.name);
113
+ if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
114
+ if (!registry.has(qid)) registry.set(qid, {
115
+ selector,
116
+ options,
117
+ state: "active",
118
+ error: null,
119
+ items: [],
120
+ listeners: /* @__PURE__ */ new Set()
121
+ });
122
+ registry.get(qid)?.listeners.add(callback);
123
+ if (registry.get(qid)?.state === "error") retryQuery(selector, options);
124
+ return () => registry.get(qid)?.listeners.delete(callback);
125
+ };
126
+ return {
127
+ insert: async (item) => {
128
+ await ready;
129
+ return await this.insert(collection.name, item);
130
+ },
131
+ updateOne: async (selector, modifier) => {
132
+ await ready;
133
+ return this.updateOne(collection.name, selector, modifier);
134
+ },
135
+ updateMany: async (selector, modifier) => {
136
+ await ready;
137
+ return this.updateMany(collection.name, selector, modifier);
138
+ },
139
+ replaceOne: async (selector, replacement) => {
140
+ await ready;
141
+ return this.replaceOne(collection.name, selector, replacement);
142
+ },
143
+ removeOne: async (selector) => {
144
+ await ready;
145
+ return this.removeOne(collection.name, selector);
146
+ },
147
+ removeMany: async (selector) => {
148
+ await ready;
149
+ return this.removeMany(collection.name, selector);
150
+ },
151
+ registerQuery,
152
+ unregisterQuery,
153
+ retryQuery,
154
+ getQueryState,
155
+ getQueryError,
156
+ getQueryResult,
157
+ onQueryStateChange,
158
+ executeQuery: async (selector, options) => {
159
+ await ready;
160
+ return this.executeQuery(collection.name, selector, options);
161
+ },
162
+ dispose: async () => {
163
+ this.storageAdapters.delete(collection.name);
164
+ this.queries.delete(collection.name);
165
+ this.collectionIndices.delete(collection.name);
166
+ this.storageAdapterReady.delete(collection.name);
167
+ },
168
+ isReady: async () => {
169
+ await ready;
170
+ }
171
+ };
172
+ }
173
+ async setupStorage(collectionName, indices) {
174
+ const storage = this.storageAdapters.get(collectionName);
175
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
176
+ await storage.setup();
177
+ await Promise.all(indices.map((index) => storage.createIndex(index)));
178
+ }
179
+ ensureStorageAdapter(name) {
180
+ if (this.storageAdapters.has(name)) return;
181
+ const adapter = this.options.storage(name);
182
+ if (!adapter) return;
183
+ this.storageAdapters.set(name, adapter);
184
+ }
185
+ /**
186
+ * Compute and publish the result for a specific query
187
+ * @param collectionName - name of the collection
188
+ * @param selector - query selector
189
+ * @param options - query options
190
+ */
191
+ async fulfillQuery(collectionName, selector, options) {
192
+ const qid = queryId(selector, options);
193
+ const registry = this.queries.get(collectionName);
194
+ if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
195
+ if (!registry.get(qid)) return;
196
+ this.publishState(collectionName, qid, "active", null);
197
+ await this.runQuery(collectionName, selector, options);
198
+ }
199
+ /**
200
+ * Executes a query, retrying transient failures before giving up. The state
201
+ * stays `'active'` across retries — consumers should see "still loading",
202
+ * not "failed", until we actually stop trying. Only the final failure is
203
+ * published as `'error'` and reported through `onError`; previously that
204
+ * error was swallowed entirely (`fulfillQuery` caught it internally, so the
205
+ * `.catch(this.onError)` on its call site was unreachable) and the query
206
+ * stayed dead for the rest of the session.
207
+ * @param collectionName - name of the collection
208
+ * @param selector - query selector
209
+ * @param options - query options
210
+ */
211
+ async runQuery(collectionName, selector, options) {
212
+ const qid = queryId(selector, options);
213
+ let lastError;
214
+ for (let attempt = 1; attempt <= this.retryAttempts; attempt += 1) {
215
+ if (!this.queries.get(collectionName)?.has(qid)) return;
216
+ try {
217
+ const items = await this.executeQuery(collectionName, selector, options);
218
+ this.publishResult(collectionName, qid, items);
219
+ this.publishState(collectionName, qid, "complete", null);
220
+ return;
221
+ } catch (error) {
222
+ lastError = error;
223
+ if (attempt < this.retryAttempts) await wait(this.retryDelay(attempt));
224
+ }
225
+ }
226
+ const queryError = new QueryError(collectionName, selector, options, this.retryAttempts, lastError);
227
+ this.publishState(collectionName, qid, "error", queryError);
228
+ this.onError(queryError);
229
+ }
230
+ /**
231
+ * Notify listeners about state changes and keep the cache updated
232
+ * @param collectionName - name of the collection
233
+ * @param qid - query id
234
+ * @param state - new state
235
+ * @param error - error if state is 'error', null otherwise
236
+ */
237
+ publishState(collectionName, qid, state, error) {
238
+ const rec = this.queries.get(collectionName)?.get(qid);
239
+ if (!rec) return;
240
+ rec.state = state;
241
+ rec.error = error;
242
+ for (const callback of rec.listeners) try {
243
+ callback(state);
244
+ } catch (error_) {
245
+ this.onError(error_);
246
+ }
247
+ }
248
+ publishResult(collectionName, qid, items) {
249
+ const rec = this.queries.get(collectionName)?.get(qid);
250
+ if (!rec) return;
251
+ rec.items = items;
252
+ }
253
+ async getIndexInfo(collectionName, selector) {
254
+ const storageAdapter = this.storageAdapters.get(collectionName);
255
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
256
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") return {
257
+ matched: true,
258
+ ids: [selector.id].filter(Boolean),
259
+ optimizedSelector: {}
260
+ };
261
+ if (selector == null) return {
262
+ matched: false,
263
+ ids: [],
264
+ optimizedSelector: {}
265
+ };
266
+ return getIndexInfo((this.collectionIndices.get(collectionName) ?? []).map((field) => async (flatSelector) => {
267
+ if (!Object.hasOwnProperty.call(flatSelector, field)) return { matched: false };
268
+ const index = await storageAdapter.readIndex(field);
269
+ const fieldSelector = flatSelector[field];
270
+ const filtersForNull = fieldSelector == null || fieldSelector.$exists === false;
271
+ const keys = filtersForNull ? {
272
+ include: null,
273
+ exclude: [...index.keys()].filter((key) => key != null)
274
+ } : getMatchingKeys(field, flatSelector);
275
+ if (keys.include == null && keys.exclude == null) return { matched: false };
276
+ let includedIds = [];
277
+ if (keys.include == null) for (const set of index.values()) for (const pos of set) includedIds.push(pos);
278
+ else for (const key of keys.include) {
279
+ const idSet = index.get(key);
280
+ if (idSet) for (const id of idSet) includedIds.push(id);
281
+ }
282
+ if (keys.exclude != null) {
283
+ const excludeIds = /* @__PURE__ */ new Set();
284
+ for (const key of keys.exclude) {
285
+ const idSet = index.get(key);
286
+ if (idSet) for (const id of idSet) excludeIds.add(id);
287
+ }
288
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
289
+ }
290
+ return {
291
+ matched: true,
292
+ ids: includedIds,
293
+ fields: [field],
294
+ keepSelector: filtersForNull
295
+ };
296
+ }), selector);
297
+ }
298
+ async queryItems(collectionName, selector) {
299
+ const storage = this.storageAdapters.get(collectionName);
300
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
301
+ const index = await this.getIndexInfo(collectionName, selector);
302
+ const matchItems = (item) => {
303
+ if (index.optimizedSelector == null) return true;
304
+ if (Object.keys(index.optimizedSelector).length <= 0) return true;
305
+ return match(item, index.optimizedSelector);
306
+ };
307
+ if (index.matched) {
308
+ const items = await storage.readIds(index.ids);
309
+ if (isEqual(index.optimizedSelector, {})) return items;
310
+ return items.filter(matchItems);
311
+ } else {
312
+ const allItems = await storage.readAll();
313
+ if (isEqual(selector, {})) return allItems;
314
+ return allItems.filter(matchItems);
315
+ }
316
+ }
317
+ async executeQuery(collectionName, selector, options) {
318
+ const items = await this.queryItems(collectionName, selector || {});
319
+ const { sort, skip, limit, fields } = options || {};
320
+ const sorted = sort ? sortItems(items, sort) : items;
321
+ const skipped = skip ? sorted.slice(skip) : sorted;
322
+ const limited = limit ? skipped.slice(0, limit) : skipped;
323
+ const idExcluded = fields && fields.id === 0;
324
+ return limited.map((item) => {
325
+ if (!fields) return item;
326
+ return {
327
+ ...idExcluded ? {} : { id: item.id },
328
+ ...project(item, fields)
329
+ };
330
+ });
331
+ }
332
+ /**
333
+ * After mutations, recompute and push updates for affected active queries
334
+ * @param collectionName - name of the collection
335
+ * @param affectedItems - item states before and/or after the mutation
336
+ */
337
+ async checkQueryUpdates(collectionName, affectedItems) {
338
+ const registry = this.queries.get(collectionName);
339
+ if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
340
+ if (registry.size === 0) return;
341
+ const affected = [...registry.values()].filter(({ selector }) => affectedItems.some((item) => match(item, selector)));
342
+ if (affected.length === 0) return;
343
+ for (const { selector, options } of affected) {
344
+ const qid = queryId(selector, options);
345
+ this.publishState(collectionName, qid, "active", null);
346
+ }
347
+ await Promise.all(affected.map(({ selector, options }) => this.runQuery(collectionName, selector, options)));
348
+ }
349
+ async insert(collectionName, newItem) {
350
+ const storage = this.storageAdapters.get(collectionName);
351
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
352
+ if ((await storage.readIds([newItem.id])).length > 0) throw new Error(`Item with id ${String(newItem.id)} already exists`);
353
+ await storage.insert([newItem]);
354
+ await this.checkQueryUpdates(collectionName, [newItem]);
355
+ return newItem;
356
+ }
357
+ async updateOne(collectionName, selector, modifier) {
358
+ const storage = this.storageAdapters.get(collectionName);
359
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
360
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
361
+ const { $setOnInsert, ...rest } = modifier;
362
+ if (item == null) return [];
363
+ const modified = modify(deepClone(item), rest);
364
+ if (item.id !== modified.id) {
365
+ if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
366
+ }
367
+ await storage.replace([modified]);
368
+ await this.checkQueryUpdates(collectionName, [item, modified]);
369
+ return [modified];
370
+ }
371
+ async updateMany(collectionName, selector, modifier) {
372
+ const storage = this.storageAdapters.get(collectionName);
373
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
374
+ const items = await this.executeQuery(collectionName, selector);
375
+ if (items.length === 0) return [];
376
+ const { $setOnInsert, ...rest } = modifier;
377
+ const changed = await Promise.all(items.map(async (item) => {
378
+ const modified = modify(deepClone(item), rest);
379
+ if (item.id !== modified.id) {
380
+ if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
381
+ }
382
+ return modified;
383
+ }));
384
+ await storage.replace(changed);
385
+ await this.checkQueryUpdates(collectionName, [...items, ...changed]);
386
+ return changed;
387
+ }
388
+ async replaceOne(collectionName, selector, replacement) {
389
+ const storage = this.storageAdapters.get(collectionName);
390
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
391
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
392
+ if (item == null) return [];
393
+ const modified = {
394
+ ...replacement,
395
+ id: replacement.id ?? item.id
396
+ };
397
+ if (item.id !== modified.id) {
398
+ if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
399
+ }
400
+ await storage.replace([modified]);
401
+ await this.checkQueryUpdates(collectionName, [item, modified]);
402
+ return [modified];
403
+ }
404
+ async removeOne(collectionName, selector) {
405
+ const storage = this.storageAdapters.get(collectionName);
406
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
407
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
408
+ if (item == null) return [];
409
+ await storage.remove([item]);
410
+ await this.checkQueryUpdates(collectionName, [item]);
411
+ return [item];
412
+ }
413
+ async removeMany(collectionName, selector) {
414
+ const storage = this.storageAdapters.get(collectionName);
415
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
416
+ const items = await this.executeQuery(collectionName, selector);
417
+ if (items.length === 0) return [];
418
+ await storage.remove(items);
419
+ await this.checkQueryUpdates(collectionName, items);
420
+ return items;
421
+ }
422
+ };
423
+ //#endregion
424
+ export { AsyncDataAdapter as default };
@@ -0,0 +1,19 @@
1
+ //#region src/utils/uniqueBy.ts
2
+ /**
3
+ * Filters an array to ensure unique values based on a specified key or transformation function.
4
+ * @template T - The type of the elements in the array.
5
+ * @param array - The array to filter for unique values.
6
+ * @param fn - A key or transformation function to determine uniqueness.
7
+ * - If a key is provided, it will use the corresponding property of each element for uniqueness.
8
+ * - If a function is provided, it will use the return value of the function applied to each element for uniqueness.
9
+ * @returns A new array containing only unique elements based on the specified key or transformation.
10
+ */
11
+ function uniqueBy(array, fn) {
12
+ const set = /* @__PURE__ */ new Set();
13
+ return array.filter((element) => {
14
+ const value = typeof fn === "function" ? fn(element) : element[fn];
15
+ return !set.has(value) && set.add(value);
16
+ });
17
+ }
18
+ //#endregion
19
+ exports.default = uniqueBy;