@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
@@ -0,0 +1,389 @@
1
+ const require_isEqual = require("./index2.cjs.js");
2
+ const require_queryDelta = require("./index4.cjs.js");
3
+ const require_getMatchingKeys = require("./index14.cjs.js");
4
+ const require_getIndexInfo = require("./index17.cjs.js");
5
+ const require_deepClone = require("./index18.cjs.js");
6
+ const require_match = require("./index19.cjs.js");
7
+ const require_modify = require("./index20.cjs.js");
8
+ const require_projectItems = require("./index23.cjs.js");
9
+ const require_sortItems = require("./index24.cjs.js");
10
+ const require_incrementalQueryUpdate = require("./index25.cjs.js");
11
+ const require_queryId = require("./index26.cjs.js");
12
+ const require_compact = require("./index35.cjs.js");
13
+ //#region src/WorkerDataAdapterHost.ts
14
+ /**
15
+ * Turns the item states a write produced into the upsert/delete split a query update needs.
16
+ *
17
+ * The two lists are not symmetric: an item that is still there after the write is described by
18
+ * its new state, while an item that is gone — removed, or given a new id — is described by the id
19
+ * it used to have and nothing else. Mixing the states from before and after a write into one list
20
+ * loses exactly that distinction.
21
+ * @template T - The type of the items.
22
+ * @param previousItems - The items as they were before the write.
23
+ * @param modifiedItems - The items as they are after it.
24
+ * @returns The changeset describing the write.
25
+ */
26
+ function toChangeset(previousItems, modifiedItems) {
27
+ const modifiedIds = new Set(modifiedItems.map((item) => item.id));
28
+ return {
29
+ upserts: modifiedItems,
30
+ deletes: previousItems.map((item) => item.id).filter((id) => !modifiedIds.has(id))
31
+ };
32
+ }
33
+ var WorkerDataAdapterHost = class {
34
+ workerContext;
35
+ options;
36
+ id;
37
+ log = () => {};
38
+ storageAdapters = /* @__PURE__ */ new Map();
39
+ storageAdapterReady = /* @__PURE__ */ new Map();
40
+ collectionIndices = /* @__PURE__ */ new Map();
41
+ queries = /* @__PURE__ */ new Map();
42
+ onError = (error) => {
43
+ console.error(error);
44
+ };
45
+ constructor(workerContext, options) {
46
+ this.workerContext = workerContext;
47
+ this.options = options;
48
+ this.id = this.options.id || "default-worker-data-adapter";
49
+ if (this.options.onError) this.onError = this.options.onError;
50
+ if (this.options.log) this.log = this.options.log;
51
+ this.workerContext.addEventListener("message", async (event) => {
52
+ try {
53
+ const { workerId, id, method, args } = event.data;
54
+ await this.handleMessage(workerId, id, method, args);
55
+ } catch (error) {
56
+ this.onError(error);
57
+ }
58
+ });
59
+ this.respond("ready", null, null, "ready");
60
+ }
61
+ respond(id, data, error = null, type = "response") {
62
+ this.workerContext.postMessage({
63
+ id,
64
+ workerId: this.id,
65
+ type,
66
+ data,
67
+ error
68
+ });
69
+ }
70
+ async handleMessage(workerId, id, method, args) {
71
+ if (workerId !== this.id) return;
72
+ const fn = this[method];
73
+ if (typeof fn !== "function") {
74
+ this.respond(id, null, /* @__PURE__ */ new Error(`Method ${method} not found`));
75
+ return;
76
+ }
77
+ this.log(method, ...args);
78
+ await this.isReady(args[0]);
79
+ try {
80
+ const result = await fn.apply(this, args);
81
+ this.respond(id, result);
82
+ } catch (error) {
83
+ this.respond(id, null, error);
84
+ }
85
+ }
86
+ async getIndexInfo(collectionName, selector) {
87
+ const storageAdapter = this.storageAdapters.get(collectionName);
88
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
89
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") return {
90
+ matched: true,
91
+ ids: require_compact.default([selector.id]),
92
+ optimizedSelector: {}
93
+ };
94
+ if (selector == null) return {
95
+ matched: false,
96
+ ids: [],
97
+ optimizedSelector: {}
98
+ };
99
+ return require_getIndexInfo.default((this.collectionIndices.get(collectionName) ?? []).map((field) => async (flatSelector) => {
100
+ if (!Object.hasOwnProperty.call(flatSelector, field)) return { matched: false };
101
+ const index = await storageAdapter.readIndex(field);
102
+ const fieldSelector = flatSelector[field];
103
+ const filteresForNull = fieldSelector == null || fieldSelector.$exists === false;
104
+ const keys = filteresForNull ? {
105
+ include: null,
106
+ exclude: [...index.keys()].filter((key) => key != null)
107
+ } : require_getMatchingKeys.default(field, flatSelector);
108
+ if (keys.include == null && keys.exclude == null) return { matched: false };
109
+ let includedIds = [];
110
+ if (keys.include == null) for (const set of index.values()) for (const pos of set) includedIds.push(pos);
111
+ else for (const key of keys.include) {
112
+ const idSet = index.get(key);
113
+ if (idSet) for (const id of idSet) includedIds.push(id);
114
+ }
115
+ if (keys.exclude != null) {
116
+ const excludeIds = /* @__PURE__ */ new Set();
117
+ for (const key of keys.exclude) {
118
+ const idSet = index.get(key);
119
+ if (idSet) for (const id of idSet) excludeIds.add(id);
120
+ }
121
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
122
+ }
123
+ return {
124
+ matched: true,
125
+ ids: includedIds,
126
+ fields: [field],
127
+ keepSelector: filteresForNull
128
+ };
129
+ }), selector);
130
+ }
131
+ async queryItems(collectionName, selector) {
132
+ const storageAdapter = this.storageAdapters.get(collectionName);
133
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
134
+ const indexInfo = await this.getIndexInfo(collectionName, selector);
135
+ const matchItems = (item) => {
136
+ if (indexInfo.optimizedSelector == null) return true;
137
+ if (Object.keys(indexInfo.optimizedSelector).length <= 0) return true;
138
+ return require_match.default(item, indexInfo.optimizedSelector);
139
+ };
140
+ if (indexInfo.matched) {
141
+ const items = await storageAdapter.readIds(indexInfo.ids);
142
+ if (require_isEqual.default(indexInfo.optimizedSelector, {})) return items;
143
+ return items.filter(matchItems);
144
+ } else {
145
+ const allItems = await storageAdapter.readAll();
146
+ if (require_isEqual.default(selector, {})) return allItems;
147
+ return allItems.filter(matchItems);
148
+ }
149
+ }
150
+ async executeQuery(collectionName, selector, options) {
151
+ if (selector === null) return [];
152
+ const items = await this.queryItems(collectionName, selector || {});
153
+ const { sort, skip, limit, fields } = options || {};
154
+ const sorted = sort ? require_sortItems.default(items, sort) : items;
155
+ const skipped = skip ? sorted.slice(skip) : sorted;
156
+ return require_projectItems.default(limit ? skipped.slice(0, limit) : skipped, fields);
157
+ }
158
+ ensureQuery(collectionName, selector, options) {
159
+ const id = require_queryId.default(selector, options);
160
+ if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
161
+ let query = this.queries.get(collectionName)?.get(id);
162
+ if (!query) {
163
+ query = {
164
+ selector,
165
+ options,
166
+ items: null
167
+ };
168
+ this.queries.get(collectionName)?.set(id, query);
169
+ }
170
+ return query;
171
+ }
172
+ setQueryItems(query, items) {
173
+ query.items = items;
174
+ query.itemIds = void 0;
175
+ }
176
+ queryItemIds(query) {
177
+ if (!query.itemIds) query.itemIds = new Set((query.items ?? []).map((item) => item.id));
178
+ return query.itemIds;
179
+ }
180
+ emitQueryUpdate(collectionName, selector, options, state, error, items, delta) {
181
+ const id = require_queryId.default(selector, options);
182
+ if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
183
+ this.respond(id, {
184
+ collectionName,
185
+ qid: id,
186
+ selector,
187
+ options,
188
+ state,
189
+ error,
190
+ items,
191
+ delta
192
+ }, null, "queryUpdate");
193
+ }
194
+ ensureStorageAdapter(name) {
195
+ if (this.storageAdapters.has(name)) return;
196
+ const adapter = this.options.storage(name);
197
+ if (!adapter) return;
198
+ this.storageAdapters.set(name, adapter);
199
+ }
200
+ async checkQueryUpdates(collectionName, changes) {
201
+ const queries = this.queries.get(collectionName);
202
+ if (!queries) throw new Error(`Collection ${collectionName} not initialized!`);
203
+ if (changes.upserts.length === 0 && changes.deletes.length === 0) return;
204
+ const affectedQueries = [...queries.values()].filter((query) => {
205
+ const ids = this.queryItemIds(query);
206
+ if (changes.deletes.some((id) => ids.has(id))) return true;
207
+ return changes.upserts.some((item) => ids.has(item.id) || require_match.default(item, query.selector));
208
+ });
209
+ if (affectedQueries.length === 0) return;
210
+ await Promise.all(affectedQueries.map(async (query) => {
211
+ const { selector, options } = query;
212
+ const previous = query.items;
213
+ const incremental = previous == null ? null : require_incrementalQueryUpdate.default(previous, selector, options, changes);
214
+ if (incremental != null) {
215
+ const delta = require_queryDelta.diffQueryResults(previous, incremental);
216
+ if (require_queryDelta.isEmptyQueryDelta(delta)) return;
217
+ this.setQueryItems(query, incremental);
218
+ this.emitQueryUpdate(collectionName, selector, options, "complete", null, void 0, delta);
219
+ return;
220
+ }
221
+ this.emitQueryUpdate(collectionName, selector, options, "active", null);
222
+ const queryItems = await this.executeQuery(collectionName, selector, options);
223
+ if (previous == null) {
224
+ this.setQueryItems(query, queryItems);
225
+ this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
226
+ return;
227
+ }
228
+ const delta = require_queryDelta.diffQueryResults(previous, queryItems);
229
+ this.setQueryItems(query, queryItems);
230
+ this.emitQueryUpdate(collectionName, selector, options, "complete", null, void 0, delta);
231
+ }));
232
+ }
233
+ registerCollection = async (collectionName, indices) => {
234
+ this.collectionIndices.set(collectionName, indices);
235
+ this.queries.set(collectionName, /* @__PURE__ */ new Map());
236
+ this.ensureStorageAdapter(collectionName);
237
+ const storageAdapter = this.storageAdapters.get(collectionName);
238
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
239
+ const setupPromise = (async () => {
240
+ await storageAdapter.setup();
241
+ await Promise.all(indices.map((index) => storageAdapter.createIndex(index)));
242
+ })();
243
+ this.storageAdapterReady.set(collectionName, setupPromise);
244
+ await setupPromise;
245
+ };
246
+ unregisterCollection = async (collectionName) => {
247
+ this.storageAdapters.delete(collectionName);
248
+ this.queries.delete(collectionName);
249
+ };
250
+ registerQuery = async (collectionName, selector, options) => {
251
+ const query = this.ensureQuery(collectionName, selector, options);
252
+ const queryItems = await this.executeQuery(collectionName, selector, options);
253
+ this.setQueryItems(query, queryItems);
254
+ this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
255
+ };
256
+ unregisterQuery = async (collectionName, selector, options) => {
257
+ const id = require_queryId.default(selector, options);
258
+ if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
259
+ this.queries.get(collectionName)?.delete(id);
260
+ };
261
+ insert = async (collectionName, input) => {
262
+ const storageAdapter = this.storageAdapters.get(collectionName);
263
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
264
+ const existingItems = await this.executeQuery(collectionName, { id: { $in: input.map((i) => i[0].id) } });
265
+ const result = input.map(([item]) => {
266
+ if (item.id == null) return /* @__PURE__ */ new Error("Item must have an id");
267
+ if (existingItems.some((existing) => existing.id === item.id)) return /* @__PURE__ */ new Error(`Item with id ${item.id} already exists`);
268
+ return item;
269
+ });
270
+ const newItems = result.filter((item) => !(item instanceof Error));
271
+ await storageAdapter.insert(newItems);
272
+ await this.checkQueryUpdates(collectionName, {
273
+ upserts: newItems,
274
+ deletes: []
275
+ });
276
+ return result;
277
+ };
278
+ updateOne = async (collectionName, parameters) => {
279
+ const storageAdapter = this.storageAdapters.get(collectionName);
280
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
281
+ const previousItems = [];
282
+ const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
283
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
284
+ const { $setOnInsert, ...restModifier } = modifier;
285
+ if (item == null) return [];
286
+ previousItems.push(item);
287
+ const modifiedItem = require_modify.default(require_deepClone.default(item), restModifier);
288
+ if (item.id !== modifiedItem.id) {
289
+ if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) return /* @__PURE__ */ new Error(`Item with id ${modifiedItem.id} already exists`);
290
+ }
291
+ return [modifiedItem];
292
+ }));
293
+ const modifiedItems = require_compact.default(result.filter((item) => !(item instanceof Error)).flat());
294
+ if (modifiedItems.length > 0) {
295
+ await storageAdapter.replace(modifiedItems);
296
+ await this.checkQueryUpdates(collectionName, toChangeset(previousItems, modifiedItems));
297
+ }
298
+ return result;
299
+ };
300
+ updateMany = async (collectionName, parameters) => {
301
+ const storageAdapter = this.storageAdapters.get(collectionName);
302
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
303
+ const previousItems = [];
304
+ const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
305
+ const items = await this.executeQuery(collectionName, selector);
306
+ if (items.length === 0) return [];
307
+ const { $setOnInsert, ...restModifier } = modifier;
308
+ try {
309
+ return await Promise.all(items.map(async (item) => {
310
+ const modifiedItem = require_modify.default(require_deepClone.default(item), restModifier);
311
+ if (item.id !== modifiedItem.id) {
312
+ if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${modifiedItem.id} already exists`);
313
+ }
314
+ previousItems.push(item);
315
+ return modifiedItem;
316
+ }));
317
+ } catch (error) {
318
+ return error;
319
+ }
320
+ }));
321
+ const modifiedItems = require_compact.default(result.filter((item) => !(item instanceof Error)).flat());
322
+ if (modifiedItems.length > 0) {
323
+ await storageAdapter.replace(modifiedItems);
324
+ await this.checkQueryUpdates(collectionName, toChangeset(previousItems, modifiedItems));
325
+ }
326
+ return result;
327
+ };
328
+ replaceOne = async (collectionName, parameters) => {
329
+ const storageAdapter = this.storageAdapters.get(collectionName);
330
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
331
+ const previousItems = [];
332
+ const result = await Promise.all(parameters.map(async ([selector, replacement]) => {
333
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
334
+ if (item == null) return [];
335
+ previousItems.push(item);
336
+ const modifiedItem = {
337
+ ...replacement,
338
+ id: replacement.id ?? item.id
339
+ };
340
+ if (item.id !== modifiedItem.id) {
341
+ if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) return /* @__PURE__ */ new Error(`Item with id ${modifiedItem.id} already exists`);
342
+ }
343
+ return [modifiedItem];
344
+ }));
345
+ const modifiedItems = require_compact.default(result.filter((item) => !(item instanceof Error)).flat());
346
+ if (modifiedItems.length > 0) {
347
+ await storageAdapter.replace(modifiedItems);
348
+ await this.checkQueryUpdates(collectionName, toChangeset(previousItems, modifiedItems));
349
+ }
350
+ return result;
351
+ };
352
+ removeOne = async (collectionName, selectors) => {
353
+ const storageAdapter = this.storageAdapters.get(collectionName);
354
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
355
+ const result = await Promise.all(selectors.map(async ([selector]) => {
356
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
357
+ if (item == null) return [];
358
+ return [item];
359
+ }));
360
+ const items = result.flat();
361
+ if (items.length > 0) {
362
+ await storageAdapter.remove(items);
363
+ await this.checkQueryUpdates(collectionName, {
364
+ upserts: [],
365
+ deletes: items.map((item) => item.id)
366
+ });
367
+ }
368
+ return result;
369
+ };
370
+ removeMany = async (collectionName, selectors) => {
371
+ const storageAdapter = this.storageAdapters.get(collectionName);
372
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
373
+ const result = await Promise.all(selectors.map(async ([selector]) => this.executeQuery(collectionName, selector)));
374
+ const items = result.flat();
375
+ if (items.length > 0) {
376
+ await storageAdapter.remove(items);
377
+ await this.checkQueryUpdates(collectionName, {
378
+ upserts: [],
379
+ deletes: items.map((item) => item.id)
380
+ });
381
+ }
382
+ return result;
383
+ };
384
+ isReady = async (collectionName) => {
385
+ return this.storageAdapterReady.get(collectionName);
386
+ };
387
+ };
388
+ //#endregion
389
+ exports.default = WorkerDataAdapterHost;