@signaldb/core 2.0.0-beta.5 → 2.0.0-beta.7

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 (104) hide show
  1. package/dist/.vite/manifest.json +118 -84
  2. package/dist/AsyncDataAdapter.d.ts +1 -1
  3. package/dist/index.cjs.js +33 -34
  4. package/dist/index.mjs +17 -35
  5. package/dist/index10.cjs.js +23 -0
  6. package/dist/index10.mjs +21 -17
  7. package/dist/index11.cjs.js +45 -0
  8. package/dist/index11.mjs +44 -15
  9. package/dist/index12.cjs.js +22 -0
  10. package/dist/index12.mjs +21 -47
  11. package/dist/index13.cjs.js +45 -0
  12. package/dist/index13.mjs +44 -365
  13. package/dist/index14.cjs.js +86 -0
  14. package/dist/index14.mjs +85 -416
  15. package/dist/index15.cjs.js +15 -0
  16. package/dist/index15.mjs +14 -206
  17. package/dist/index16.cjs.js +136 -0
  18. package/dist/index16.mjs +135 -388
  19. package/dist/index17.cjs.js +47 -0
  20. package/dist/index17.mjs +45 -578
  21. package/dist/index18.cjs.js +15 -0
  22. package/dist/index18.mjs +14 -157
  23. package/dist/index19.cjs.js +23 -0
  24. package/dist/index19.mjs +22 -26
  25. package/dist/index2.cjs.js +33 -0
  26. package/dist/index2.mjs +32 -258
  27. package/dist/index20.cjs.js +37 -0
  28. package/dist/index20.mjs +36 -41
  29. package/dist/index21.cjs.js +35 -0
  30. package/dist/index21.mjs +34 -16
  31. package/dist/index22.cjs.js +25 -0
  32. package/dist/index22.mjs +24 -104
  33. package/dist/index23.cjs.js +19 -0
  34. package/dist/index23.mjs +18 -128
  35. package/dist/index24.cjs.js +342 -0
  36. package/dist/index24.mjs +340 -6
  37. package/dist/index25.cjs.js +519 -0
  38. package/dist/index25.mjs +518 -27
  39. package/dist/index26.cjs.js +11 -0
  40. package/dist/index26.mjs +10 -10
  41. package/dist/index27.cjs.js +11 -0
  42. package/dist/index27.mjs +10 -29
  43. package/dist/index28.cjs.js +90 -0
  44. package/dist/index28.mjs +88 -46
  45. package/dist/index29.cjs.js +370 -0
  46. package/dist/index29.mjs +369 -8
  47. package/dist/index3.cjs.js +19 -0
  48. package/dist/index3.mjs +18 -539
  49. package/dist/index30.cjs.js +72 -0
  50. package/dist/index30.mjs +71 -7
  51. package/dist/index31.cjs.js +191 -0
  52. package/dist/index31.mjs +190 -42
  53. package/dist/index32.cjs.js +21 -0
  54. package/dist/index32.mjs +20 -29
  55. package/dist/index33.cjs.js +336 -0
  56. package/dist/index33.mjs +335 -5
  57. package/dist/index34.cjs.js +539 -0
  58. package/dist/index34.mjs +537 -8
  59. package/dist/index4.cjs.js +150 -0
  60. package/dist/index4.mjs +149 -5
  61. package/dist/index5.cjs.js +254 -0
  62. package/dist/index5.mjs +252 -4
  63. package/dist/index6.cjs.js +125 -0
  64. package/dist/index6.mjs +124 -29
  65. package/dist/index7.cjs.js +33 -0
  66. package/dist/index7.mjs +32 -12
  67. package/dist/index8.cjs.js +12 -0
  68. package/dist/index8.mjs +10 -4
  69. package/dist/index9.cjs.js +11 -0
  70. package/dist/index9.mjs +10 -133
  71. package/package.json +1 -1
  72. package/dist/index.cjs10.js +0 -18
  73. package/dist/index.cjs11.js +0 -15
  74. package/dist/index.cjs12.js +0 -48
  75. package/dist/index.cjs13.js +0 -365
  76. package/dist/index.cjs14.js +0 -416
  77. package/dist/index.cjs15.js +0 -206
  78. package/dist/index.cjs16.js +0 -388
  79. package/dist/index.cjs17.js +0 -579
  80. package/dist/index.cjs18.js +0 -157
  81. package/dist/index.cjs19.js +0 -26
  82. package/dist/index.cjs2.js +0 -259
  83. package/dist/index.cjs20.js +0 -42
  84. package/dist/index.cjs21.js +0 -16
  85. package/dist/index.cjs22.js +0 -104
  86. package/dist/index.cjs23.js +0 -129
  87. package/dist/index.cjs24.js +0 -7
  88. package/dist/index.cjs25.js +0 -27
  89. package/dist/index.cjs26.js +0 -10
  90. package/dist/index.cjs27.js +0 -29
  91. package/dist/index.cjs28.js +0 -46
  92. package/dist/index.cjs29.js +0 -8
  93. package/dist/index.cjs3.js +0 -540
  94. package/dist/index.cjs30.js +0 -7
  95. package/dist/index.cjs31.js +0 -42
  96. package/dist/index.cjs32.js +0 -29
  97. package/dist/index.cjs33.js +0 -5
  98. package/dist/index.cjs34.js +0 -9
  99. package/dist/index.cjs4.js +0 -5
  100. package/dist/index.cjs5.js +0 -5
  101. package/dist/index.cjs6.js +0 -29
  102. package/dist/index.cjs7.js +0 -12
  103. package/dist/index.cjs8.js +0 -5
  104. package/dist/index.cjs9.js +0 -133
@@ -1,416 +0,0 @@
1
- "use strict";
2
- const deepClone = require("./index.cjs20.js");
3
- const match = require("./index.cjs24.js");
4
- const modify = require("./index.cjs7.js");
5
- const queryId = require("./index.cjs21.js");
6
- const isEqual = require("./index.cjs6.js");
7
- const getIndexInfo = require("./index.cjs23.js");
8
- const getMatchingKeys = require("./index.cjs27.js");
9
- const sortItems = require("./index.cjs26.js");
10
- const project = require("./index.cjs25.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
- executeQuery: async (selector, options) => {
124
- await ready;
125
- return this.executeQuery(collection.name, selector, options);
126
- },
127
- dispose: async () => {
128
- this.storageAdapters.delete(collection.name);
129
- this.queries.delete(collection.name);
130
- this.collectionIndices.delete(collection.name);
131
- this.storageAdapterReady.delete(collection.name);
132
- },
133
- isReady: async () => {
134
- await ready;
135
- }
136
- };
137
- }
138
- async setupStorage(collectionName, indices) {
139
- const storage = this.storageAdapters.get(collectionName);
140
- if (!storage)
141
- throw new Error(`No persistence adapter for collection ${collectionName}`);
142
- await storage.setup();
143
- await Promise.all(indices.map((index) => storage.createIndex(index)));
144
- }
145
- ensureStorageAdapter(name) {
146
- if (this.storageAdapters.has(name))
147
- return;
148
- const adapter = this.options.storage(name);
149
- if (!adapter)
150
- return;
151
- this.storageAdapters.set(name, adapter);
152
- }
153
- /**
154
- * Compute and publish the result for a specific query
155
- * @param collectionName - name of the collection
156
- * @param selector - query selector
157
- * @param options - query options
158
- */
159
- async fulfillQuery(collectionName, selector, options) {
160
- const qid = queryId(selector, options);
161
- const registry = this.queries.get(collectionName);
162
- if (!registry)
163
- throw new Error(`Collection ${collectionName} not initialized!`);
164
- const rec = registry.get(qid);
165
- if (!rec)
166
- return;
167
- this.publishState(collectionName, qid, "active", null);
168
- try {
169
- const items = await this.executeQuery(collectionName, selector, options);
170
- this.publishResult(collectionName, qid, items);
171
- this.publishState(collectionName, qid, "complete", null);
172
- } catch (error) {
173
- this.publishState(collectionName, qid, "error", error);
174
- }
175
- }
176
- /**
177
- * Notify listeners about state changes and keep the cache updated
178
- * @param collectionName - name of the collection
179
- * @param qid - query id
180
- * @param state - new state
181
- * @param error - error if state is 'error', null otherwise
182
- */
183
- publishState(collectionName, qid, state, error) {
184
- const rec = this.queries.get(collectionName)?.get(qid);
185
- if (!rec)
186
- return;
187
- rec.state = state;
188
- rec.error = error;
189
- for (const callback of rec.listeners) {
190
- try {
191
- callback(state);
192
- } catch (error_) {
193
- this.onError(error_);
194
- }
195
- }
196
- }
197
- publishResult(collectionName, qid, items) {
198
- const rec = this.queries.get(collectionName)?.get(qid);
199
- if (!rec)
200
- return;
201
- rec.items = items;
202
- }
203
- async getIndexInfo(collectionName, selector) {
204
- const storageAdapter = this.storageAdapters.get(collectionName);
205
- if (!storageAdapter)
206
- throw new Error(`No persistence adapter for collection ${collectionName}`);
207
- if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
208
- return {
209
- matched: true,
210
- ids: [selector.id].filter(Boolean),
211
- optimizedSelector: {}
212
- };
213
- }
214
- if (selector == null) {
215
- return {
216
- matched: false,
217
- ids: [],
218
- optimizedSelector: {}
219
- };
220
- }
221
- const indices = this.collectionIndices.get(collectionName) ?? [];
222
- return getIndexInfo.default(indices.map((field) => async (flatSelector) => {
223
- if (!Object.hasOwnProperty.call(flatSelector, field))
224
- return { matched: false };
225
- const index = await storageAdapter.readIndex(field);
226
- const fieldSelector = flatSelector[field];
227
- const filtersForNull = fieldSelector == null || fieldSelector.$exists === false;
228
- const keys = filtersForNull ? { include: null, exclude: [...index.keys()].filter((key) => key != null) } : getMatchingKeys(field, flatSelector);
229
- if (keys.include == null && keys.exclude == null)
230
- return { matched: false };
231
- let includedIds = [];
232
- if (keys.include == null) {
233
- for (const set of index.values())
234
- for (const pos of set)
235
- includedIds.push(pos);
236
- } else {
237
- for (const key of keys.include) {
238
- const idSet = index.get(key);
239
- if (idSet)
240
- for (const id of idSet)
241
- includedIds.push(id);
242
- }
243
- }
244
- if (keys.exclude != null) {
245
- const excludeIds = /* @__PURE__ */ new Set();
246
- for (const key of keys.exclude) {
247
- const idSet = index.get(key);
248
- if (idSet)
249
- for (const id of idSet)
250
- excludeIds.add(id);
251
- }
252
- includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
253
- }
254
- return { matched: true, ids: includedIds, fields: [field], keepSelector: filtersForNull };
255
- }), selector);
256
- }
257
- async queryItems(collectionName, selector) {
258
- const storage = this.storageAdapters.get(collectionName);
259
- if (!storage)
260
- throw new Error(`No persistence adapter for collection ${collectionName}`);
261
- const index = await this.getIndexInfo(collectionName, selector);
262
- const matchItems = (item) => {
263
- if (index.optimizedSelector == null)
264
- return true;
265
- if (Object.keys(index.optimizedSelector).length <= 0)
266
- return true;
267
- return match(item, index.optimizedSelector);
268
- };
269
- if (index.matched) {
270
- const items = await storage.readIds(index.ids);
271
- if (isEqual(index.optimizedSelector, {}))
272
- return items;
273
- return items.filter(matchItems);
274
- } else {
275
- const allItems = await storage.readAll();
276
- if (isEqual(selector, {}))
277
- return allItems;
278
- return allItems.filter(matchItems);
279
- }
280
- }
281
- async executeQuery(collectionName, selector, options) {
282
- const items = await this.queryItems(collectionName, selector || {});
283
- const { sort, skip, limit, fields } = options || {};
284
- const sorted = sort ? sortItems(items, sort) : items;
285
- const skipped = skip ? sorted.slice(skip) : sorted;
286
- const limited = limit ? skipped.slice(0, limit) : skipped;
287
- const idExcluded = fields && fields.id === 0;
288
- return limited.map((item) => {
289
- if (!fields)
290
- return item;
291
- return { ...idExcluded ? {} : { id: item.id }, ...project(item, fields) };
292
- });
293
- }
294
- /**
295
- * After mutations, recompute and push updates for affected active queries
296
- * @param collectionName - name of the collection
297
- * @param changedItems - items that were inserted/updated/replaced/removed
298
- */
299
- async checkQueryUpdates(collectionName, changedItems) {
300
- const registry = this.queries.get(collectionName);
301
- if (!registry)
302
- throw new Error(`Collection ${collectionName} not initialized!`);
303
- if (registry.size === 0)
304
- return;
305
- const affected = [...registry.values()].filter(({ selector }) => changedItems.some((item) => match(item, selector)));
306
- if (affected.length === 0)
307
- return;
308
- for (const { selector, options } of affected) {
309
- const qid = queryId(selector, options);
310
- this.publishState(collectionName, qid, "active", null);
311
- }
312
- await Promise.all(affected.map(async ({ selector, options }) => {
313
- const qid = queryId(selector, options);
314
- try {
315
- const items = await this.executeQuery(collectionName, selector, options);
316
- this.publishResult(collectionName, qid, items);
317
- this.publishState(collectionName, qid, "complete", null);
318
- } catch (error) {
319
- this.publishState(collectionName, qid, "error", error);
320
- }
321
- }));
322
- }
323
- async insert(collectionName, newItem) {
324
- const storage = this.storageAdapters.get(collectionName);
325
- if (!storage)
326
- throw new Error(`No persistence adapter for collection ${collectionName}`);
327
- const existingItems = await storage.readIds([newItem.id]);
328
- if (existingItems.length > 0)
329
- throw new Error(`Item with id ${String(newItem.id)} already exists`);
330
- await storage.insert([newItem]);
331
- await this.checkQueryUpdates(collectionName, [newItem]);
332
- return newItem;
333
- }
334
- async updateOne(collectionName, selector, modifier) {
335
- const storage = this.storageAdapters.get(collectionName);
336
- if (!storage)
337
- throw new Error(`No persistence adapter for collection ${collectionName}`);
338
- const items = await this.executeQuery(collectionName, selector, { limit: 1 });
339
- const [item] = items;
340
- const { $setOnInsert, ...rest } = modifier;
341
- if (item == null)
342
- return [];
343
- const modified = modify(deepClone.default(item), rest);
344
- if (item.id !== modified.id) {
345
- const existing = await storage.readIds([modified.id]);
346
- if (existing.length > 0)
347
- throw new Error(`Item with id ${String(modified.id)} already exists`);
348
- }
349
- await storage.replace([modified]);
350
- await this.checkQueryUpdates(collectionName, [modified]);
351
- return [modified];
352
- }
353
- async updateMany(collectionName, selector, modifier) {
354
- const storage = this.storageAdapters.get(collectionName);
355
- if (!storage)
356
- throw new Error(`No persistence adapter for collection ${collectionName}`);
357
- const items = await this.executeQuery(collectionName, selector);
358
- if (items.length === 0)
359
- return [];
360
- const { $setOnInsert, ...rest } = modifier;
361
- const changed = await Promise.all(items.map(async (item) => {
362
- const modified = modify(deepClone.default(item), rest);
363
- if (item.id !== modified.id) {
364
- const existing = await storage.readIds([modified.id]);
365
- if (existing.length > 0)
366
- throw new Error(`Item with id ${String(modified.id)} already exists`);
367
- }
368
- return modified;
369
- }));
370
- await storage.replace(changed);
371
- await this.checkQueryUpdates(collectionName, changed);
372
- return changed;
373
- }
374
- async replaceOne(collectionName, selector, replacement) {
375
- const storage = this.storageAdapters.get(collectionName);
376
- if (!storage)
377
- throw new Error(`No persistence adapter for collection ${collectionName}`);
378
- const items = await this.executeQuery(collectionName, selector, { limit: 1 });
379
- const [item] = items;
380
- if (item == null)
381
- return [];
382
- const modified = { ...replacement, id: replacement.id ?? item.id };
383
- if (item.id !== modified.id) {
384
- const existing = await storage.readIds([modified.id]);
385
- if (existing.length > 0)
386
- throw new Error(`Item with id ${String(modified.id)} already exists`);
387
- }
388
- await storage.replace([modified]);
389
- await this.checkQueryUpdates(collectionName, [modified]);
390
- return [modified];
391
- }
392
- async removeOne(collectionName, selector) {
393
- const storage = this.storageAdapters.get(collectionName);
394
- if (!storage)
395
- throw new Error(`No persistence adapter for collection ${collectionName}`);
396
- const items = await this.executeQuery(collectionName, selector, { limit: 1 });
397
- const [item] = items;
398
- if (item == null)
399
- return [];
400
- await storage.remove([item]);
401
- await this.checkQueryUpdates(collectionName, [item]);
402
- return [item];
403
- }
404
- async removeMany(collectionName, selector) {
405
- const storage = this.storageAdapters.get(collectionName);
406
- if (!storage)
407
- throw new Error(`No persistence adapter for collection ${collectionName}`);
408
- const items = await this.executeQuery(collectionName, selector);
409
- if (items.length === 0)
410
- return [];
411
- await storage.remove(items);
412
- await this.checkQueryUpdates(collectionName, items);
413
- return items;
414
- }
415
- }
416
- module.exports = AsyncDataAdapter;
@@ -1,206 +0,0 @@
1
- "use strict";
2
- const queryId = require("./index.cjs21.js");
3
- const randomId = require("./index.cjs8.js");
4
- const batchOnNextTick = require("./index.cjs28.js");
5
- class WorkerDataAdapter {
6
- worker;
7
- options;
8
- id;
9
- isDisposed = false;
10
- workerReady;
11
- log = () => {
12
- };
13
- collectionReady = /* @__PURE__ */ new Map();
14
- batchExecutionHelpers = /* @__PURE__ */ new Map();
15
- queries = {};
16
- constructor(worker, options) {
17
- this.worker = worker;
18
- this.options = options;
19
- this.id = this.options.id || "default-worker-data-adapter";
20
- if (this.options.log)
21
- this.log = this.options.log;
22
- this.workerReady = new Promise((resolve, reject) => {
23
- const timeoutId = setTimeout(() => {
24
- reject(new Error("WorkerDataAdapter initialization timed out"));
25
- }, 5e3);
26
- const handleMessage = (event) => {
27
- const { type, workerId } = event.data;
28
- if (workerId !== this.id)
29
- return;
30
- if (type === "ready") {
31
- resolve();
32
- clearTimeout(timeoutId);
33
- this.worker.removeEventListener("message", handleMessage);
34
- }
35
- };
36
- this.worker.addEventListener("message", handleMessage);
37
- });
38
- }
39
- async exec(method, collectionName, ...args) {
40
- await this.workerReady;
41
- if (method !== "isReady") {
42
- const collectionReady = this.collectionReady.get(collectionName);
43
- if (!collectionReady)
44
- throw new Error(`Collection "${collectionName}" is not registered in WorkerDataAdapter`);
45
- await collectionReady;
46
- }
47
- if (this.isDisposed) {
48
- throw new Error("WorkerDataAdapter is disposed");
49
- }
50
- return new Promise((resolve, reject) => {
51
- const messageId = randomId();
52
- const handleMessage = (event) => {
53
- const { id, workerId, type, data, error } = event.data;
54
- if (workerId !== this.id)
55
- return;
56
- if (type !== "response")
57
- return;
58
- if (id !== messageId)
59
- return;
60
- this.log(method, "result", data ?? error);
61
- if (error) {
62
- reject(error);
63
- } else {
64
- resolve(data);
65
- }
66
- this.worker.removeEventListener("message", handleMessage);
67
- };
68
- this.worker.addEventListener("message", handleMessage);
69
- this.worker.postMessage({
70
- id: messageId,
71
- workerId: this.id,
72
- method,
73
- args: [collectionName, ...args]
74
- });
75
- });
76
- }
77
- enqueueBatched(collectionName, method, args) {
78
- const helper = this.batchExecutionHelpers.get(collectionName);
79
- if (!helper)
80
- throw new Error(`Collection "${collectionName}" is not registered in WorkerDataAdapter`);
81
- return helper.enqueue(method, args);
82
- }
83
- // ---------- end batching integration ----------
84
- updateQuery(collectionName, query, update) {
85
- const id = queryId(query.selector, query.options);
86
- const collectionQueries = this.queries[collectionName];
87
- if (!collectionQueries)
88
- return;
89
- const existing = collectionQueries.get(id);
90
- const newState = {
91
- state: "active",
92
- error: null,
93
- items: [],
94
- stateChangeCallbacks: [],
95
- eventHandler: existing?.eventHandler,
96
- ...existing,
97
- ...update
98
- };
99
- collectionQueries.set(id, newState);
100
- this.queries[collectionName] = collectionQueries;
101
- }
102
- createCollectionBackend(collection, indices) {
103
- this.queries[collection.name] = /* @__PURE__ */ new Map();
104
- void this.exec("registerCollection", collection.name, indices);
105
- this.collectionReady.set(collection.name, this.exec("isReady", collection.name));
106
- this.batchExecutionHelpers.set(collection.name, batchOnNextTick(async (method, args) => this.exec(method, collection.name, args)));
107
- return {
108
- insert: async (item) => {
109
- return this.enqueueBatched(collection.name, "insert", [item]);
110
- },
111
- updateOne: async (selector, modifier) => {
112
- return this.enqueueBatched(collection.name, "updateOne", [selector, modifier]);
113
- },
114
- updateMany: async (selector, modifier) => {
115
- return this.enqueueBatched(collection.name, "updateMany", [selector, modifier]);
116
- },
117
- replaceOne: async (selector, replacement) => {
118
- return this.enqueueBatched(collection.name, "replaceOne", [selector, replacement]);
119
- },
120
- removeOne: async (selector) => {
121
- return this.enqueueBatched(collection.name, "removeOne", [selector]);
122
- },
123
- removeMany: async (selector) => {
124
- return this.enqueueBatched(collection.name, "removeMany", [selector]);
125
- },
126
- // methods for registering and unregistering queries that will be called from the collection during find/findOne
127
- registerQuery: (selector, options) => {
128
- this.updateQuery(collection.name, { selector, options }, { state: "active", error: null, items: [] });
129
- void this.exec("registerQuery", collection.name, selector, options);
130
- const handler = (event) => {
131
- const { type, data, workerId, error } = event.data;
132
- if (type !== "queryUpdate")
133
- return;
134
- if (data == null)
135
- return;
136
- const { collectionName, selector: responseSelector, options: responseOptions, state, items } = data;
137
- if (workerId !== this.id)
138
- return;
139
- if (collectionName !== collection.name)
140
- return;
141
- if (queryId(responseSelector, responseOptions) !== queryId(selector, options))
142
- return;
143
- this.log("queryUpdate", responseSelector, responseOptions, state, data ?? error);
144
- this.updateQuery(collection.name, {
145
- selector: responseSelector,
146
- options: responseOptions
147
- }, { state, error, items });
148
- const query = this.queries[collection.name]?.get(queryId(selector, options));
149
- if (!query)
150
- return;
151
- query.stateChangeCallbacks.forEach((callback) => callback(state));
152
- };
153
- this.worker.addEventListener("message", handler);
154
- this.updateQuery(collection.name, { selector, options }, { eventHandler: handler });
155
- },
156
- unregisterQuery: (selector, options) => {
157
- const qid = queryId(selector, options);
158
- const query = this.queries[collection.name]?.get(qid);
159
- if (query?.eventHandler) {
160
- this.worker.removeEventListener("message", query.eventHandler);
161
- }
162
- this.queries[collection.name]?.delete(qid);
163
- void this.exec("unregisterQuery", collection.name, selector, options);
164
- },
165
- getQueryState: (selector, options) => {
166
- const query = this.queries[collection.name]?.get(queryId(selector, options));
167
- return query?.state || "active";
168
- },
169
- getQueryError: (selector, options) => {
170
- const query = this.queries[collection.name]?.get(queryId(selector, options));
171
- return query?.error || null;
172
- },
173
- getQueryResult: (selector, options) => {
174
- const query = this.queries[collection.name]?.get(queryId(selector, options));
175
- return query?.items || [];
176
- },
177
- onQueryStateChange: (selector, options, callback) => {
178
- this.updateQuery(collection.name, { selector, options }, {
179
- stateChangeCallbacks: [
180
- ...this.queries[collection.name]?.get(queryId(selector, options))?.stateChangeCallbacks || [],
181
- callback
182
- ]
183
- });
184
- return () => {
185
- const currentCallbacks = this.queries[collection.name]?.get(queryId(selector, options))?.stateChangeCallbacks;
186
- if (!currentCallbacks)
187
- throw new Error("State change callbacks are not defined!");
188
- this.updateQuery(collection.name, { selector, options }, {
189
- stateChangeCallbacks: currentCallbacks.filter((existingCallback) => existingCallback !== callback)
190
- });
191
- };
192
- },
193
- executeQuery: (selector, options) => this.exec("executeQuery", collection.name, selector, options),
194
- // lifecycle methods
195
- dispose: async () => {
196
- await this.exec("unregisterCollection", collection.name);
197
- this.isDisposed = true;
198
- this.worker.terminate();
199
- },
200
- isReady: async () => {
201
- await this.exec("isReady", collection.name);
202
- }
203
- };
204
- }
205
- }
206
- module.exports = WorkerDataAdapter;