@signaldb/core 2.0.0-beta.0 → 2.0.0-beta.10

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 (128) hide show
  1. package/dist/.vite/manifest.json +128 -75
  2. package/dist/AsyncDataAdapter.d.ts +44 -7
  3. package/dist/AutoFetchDataAdapter.d.ts +5 -8
  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 +36 -25
  7. package/dist/Collection/types.d.ts +10 -2
  8. package/dist/DataAdapter.d.ts +18 -11
  9. package/dist/DefaultDataAdapter.d.ts +7 -6
  10. package/dist/WorkerDataAdapter.d.ts +7 -6
  11. package/dist/WorkerDataAdapterHost.d.ts +14 -11
  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 +3 -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 -339
  26. package/dist/index13.cjs.js +45 -0
  27. package/dist/index13.mjs +44 -407
  28. package/dist/index14.cjs.js +86 -0
  29. package/dist/index14.mjs +85 -190
  30. package/dist/index15.cjs.js +15 -0
  31. package/dist/index15.mjs +14 -341
  32. package/dist/index16.cjs.js +136 -0
  33. package/dist/index16.mjs +134 -569
  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 -254
  42. package/dist/index20.cjs.js +37 -0
  43. package/dist/index20.mjs +36 -104
  44. package/dist/index21.cjs.js +35 -0
  45. package/dist/index21.mjs +34 -128
  46. package/dist/index22.cjs.js +25 -0
  47. package/dist/index22.mjs +24 -7
  48. package/dist/index23.cjs.js +19 -0
  49. package/dist/index23.mjs +17 -26
  50. package/dist/index24.cjs.js +342 -0
  51. package/dist/index24.mjs +340 -6
  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 -5
  58. package/dist/index28.cjs.js +90 -0
  59. package/dist/index28.mjs +89 -8
  60. package/dist/index29.cjs.js +424 -0
  61. package/dist/index29.mjs +423 -29
  62. package/dist/index3.cjs.js +19 -0
  63. package/dist/index3.mjs +18 -537
  64. package/dist/index30.cjs.js +72 -0
  65. package/dist/index30.mjs +71 -42
  66. package/dist/index31.cjs.js +191 -0
  67. package/dist/index31.mjs +190 -9
  68. package/dist/index32.cjs.js +21 -0
  69. package/dist/index32.mjs +21 -0
  70. package/dist/index33.cjs.js +336 -0
  71. package/dist/index33.mjs +336 -0
  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/batchOnNextTick.d.ts +16 -0
  90. package/dist/utils/createSignal.d.ts +2 -2
  91. package/dist/utils/deepClone.d.ts +1 -1
  92. package/dist/utils/getMatchingKeys.d.ts +2 -2
  93. package/dist/utils/isFieldExpression.d.ts +1 -1
  94. package/dist/utils/match.d.ts +1 -1
  95. package/dist/utils/modify.d.ts +1 -1
  96. package/dist/utils/queryId.d.ts +2 -2
  97. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  98. package/package.json +3 -3
  99. package/dist/index.cjs10.js +0 -18
  100. package/dist/index.cjs11.js +0 -15
  101. package/dist/index.cjs12.js +0 -339
  102. package/dist/index.cjs13.js +0 -407
  103. package/dist/index.cjs14.js +0 -190
  104. package/dist/index.cjs15.js +0 -341
  105. package/dist/index.cjs16.js +0 -570
  106. package/dist/index.cjs17.js +0 -150
  107. package/dist/index.cjs18.js +0 -26
  108. package/dist/index.cjs19.js +0 -43
  109. package/dist/index.cjs2.js +0 -255
  110. package/dist/index.cjs20.js +0 -104
  111. package/dist/index.cjs21.js +0 -129
  112. package/dist/index.cjs22.js +0 -7
  113. package/dist/index.cjs23.js +0 -27
  114. package/dist/index.cjs24.js +0 -7
  115. package/dist/index.cjs25.js +0 -10
  116. package/dist/index.cjs26.js +0 -29
  117. package/dist/index.cjs27.js +0 -5
  118. package/dist/index.cjs28.js +0 -7
  119. package/dist/index.cjs29.js +0 -29
  120. package/dist/index.cjs3.js +0 -538
  121. package/dist/index.cjs30.js +0 -42
  122. package/dist/index.cjs31.js +0 -9
  123. package/dist/index.cjs4.js +0 -5
  124. package/dist/index.cjs5.js +0 -5
  125. package/dist/index.cjs6.js +0 -29
  126. package/dist/index.cjs7.js +0 -12
  127. package/dist/index.cjs8.js +0 -5
  128. package/dist/index.cjs9.js +0 -133
@@ -1,407 +0,0 @@
1
- "use strict";
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);
151
- }
152
- /**
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
157
- */
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);
173
- }
174
- }
175
- /**
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
181
- */
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
- }
195
- }
196
- publishResult(collectionName, qid, items) {
197
- const rec = this.queries.get(collectionName)?.get(qid);
198
- if (!rec)
199
- return;
200
- rec.items = items;
201
- }
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: {} };
211
- }
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);
247
- }
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
- }
271
- }
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) };
283
- });
284
- }
285
- /**
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
289
- */
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
- }));
313
- }
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;
324
- }
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`);
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`);
378
- }
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;
405
- }
406
- }
407
- module.exports = AsyncDataAdapter;
@@ -1,190 +0,0 @@
1
- "use strict";
2
- const queryId = require("./index.cjs24.js");
3
- const randomId = require("./index.cjs8.js");
4
- class WorkerDataAdapter {
5
- worker;
6
- options;
7
- id;
8
- isDisposed = false;
9
- workerReady;
10
- collectionReady = /* @__PURE__ */ new Map();
11
- queries = {};
12
- constructor(worker, options) {
13
- this.worker = worker;
14
- this.options = options;
15
- this.id = this.options.id || "default-worker-data-adapter";
16
- this.workerReady = new Promise((resolve, reject) => {
17
- const timeoutId = setTimeout(() => {
18
- reject(new Error("WorkerDataAdapter initialization timed out"));
19
- }, 5e3);
20
- const handleMessage = (event) => {
21
- const { type, workerId } = event.data;
22
- if (workerId !== this.id)
23
- return;
24
- if (type === "ready") {
25
- resolve();
26
- clearTimeout(timeoutId);
27
- this.worker.removeEventListener("message", handleMessage);
28
- }
29
- };
30
- this.worker.addEventListener("message", handleMessage);
31
- });
32
- }
33
- async exec(method, collectionName, ...args) {
34
- await this.workerReady;
35
- if (method !== "isReady") {
36
- const collectionReady = this.collectionReady.get(collectionName);
37
- if (!collectionReady)
38
- throw new Error(`Collection "${collectionName}" is not registered in WorkerDataAdapter`);
39
- await collectionReady;
40
- }
41
- if (this.isDisposed) {
42
- throw new Error("WorkerDataAdapter is disposed");
43
- }
44
- return new Promise((resolve, reject) => {
45
- const messageId = randomId();
46
- const handleMessage = (event) => {
47
- const { id, workerId, type, data, error } = event.data;
48
- if (workerId !== this.id)
49
- return;
50
- if (type !== "response")
51
- return;
52
- if (id !== messageId)
53
- return;
54
- if (error) {
55
- reject(error);
56
- } else {
57
- resolve(data);
58
- }
59
- this.worker.removeEventListener("message", handleMessage);
60
- };
61
- this.worker.addEventListener("message", handleMessage);
62
- this.worker.postMessage({
63
- id: messageId,
64
- workerId: this.id,
65
- method,
66
- args: [collectionName, ...args]
67
- });
68
- });
69
- }
70
- queryListeners(collectionName, query, listeners) {
71
- if (listeners != null) {
72
- return this.updateQuery(collectionName, query, { listeners });
73
- }
74
- const id = queryId(query.selector, query.options);
75
- const collectionQueries = this.queries[collectionName];
76
- if (!collectionQueries)
77
- return 0;
78
- const existing = collectionQueries.get(id);
79
- return existing?.listeners || 0;
80
- }
81
- updateQuery(collectionName, query, update) {
82
- const id = queryId(query.selector, query.options);
83
- const collectionQueries = this.queries[collectionName];
84
- if (!collectionQueries)
85
- return;
86
- const existing = collectionQueries.get(id);
87
- collectionQueries.set(id, {
88
- listeners: 0,
89
- state: "active",
90
- error: null,
91
- items: [],
92
- ...existing,
93
- ...update
94
- });
95
- this.queries[collectionName] = collectionQueries;
96
- }
97
- createCollectionBackend(collection, indices = []) {
98
- this.queries[collection.name] = /* @__PURE__ */ new Map();
99
- void this.exec("registerCollection", collection.name, indices);
100
- this.collectionReady.set(collection.name, this.exec("isReady", collection.name));
101
- return {
102
- insert: async (item) => {
103
- return this.exec("insert", collection.name, item);
104
- },
105
- updateOne: async (selector, modifier) => {
106
- return this.exec("updateOne", collection.name, selector, modifier);
107
- },
108
- updateMany: async (selector, modifier) => {
109
- return this.exec("updateMany", collection.name, selector, modifier);
110
- },
111
- replaceOne: async (selector, replacement) => {
112
- return this.exec("replaceOne", collection.name, selector, replacement);
113
- },
114
- removeOne: async (selector) => {
115
- return this.exec("removeOne", collection.name, selector);
116
- },
117
- removeMany: async (selector) => {
118
- return this.exec("removeMany", collection.name, selector);
119
- },
120
- // methods for registering and unregistering queries that will be called from the collection during find/findOne
121
- registerQuery: (selector, options) => {
122
- const listeners = this.queryListeners(collection.name, { selector, options });
123
- if (listeners === 0) {
124
- this.updateQuery(collection.name, { selector, options }, { state: "active", error: null, items: [] });
125
- void this.exec("registerQuery", collection.name, selector, options);
126
- }
127
- this.queryListeners(collection.name, { selector, options }, listeners + 1);
128
- },
129
- unregisterQuery: (selector, options) => {
130
- setTimeout(() => {
131
- const listeners = this.queryListeners(collection.name, { selector, options });
132
- const newListeners = Math.max(0, listeners - 1);
133
- if (newListeners === 0) {
134
- this.queries[collection.name]?.delete(queryId(selector, options));
135
- void this.exec("unregisterQuery", collection.name, selector, options);
136
- }
137
- }, 0);
138
- },
139
- getQueryState: (selector, options) => {
140
- const query = this.queries[collection.name]?.get(queryId(selector, options));
141
- return query?.state || "active";
142
- },
143
- getQueryError: (selector, options) => {
144
- const query = this.queries[collection.name]?.get(queryId(selector, options));
145
- return query?.error || null;
146
- },
147
- getQueryResult: (selector, options) => {
148
- const query = this.queries[collection.name]?.get(queryId(selector, options));
149
- return query?.items || [];
150
- },
151
- onQueryStateChange: (selector, options, callback) => {
152
- const handler = (event) => {
153
- const { type, data, workerId, error } = event.data;
154
- if (type !== "queryUpdate")
155
- return;
156
- if (data == null)
157
- return;
158
- const { collectionName, selector: responseSelector, options: responseOptions, state, items } = data;
159
- if (workerId !== this.id)
160
- return;
161
- if (collectionName !== collection.name)
162
- return;
163
- if (JSON.stringify(responseSelector) !== JSON.stringify(selector))
164
- return;
165
- if (JSON.stringify(responseOptions) !== JSON.stringify(options))
166
- return;
167
- this.updateQuery(collection.name, {
168
- selector: responseSelector,
169
- options: responseOptions
170
- }, { state, error, items });
171
- callback(state);
172
- };
173
- this.worker.addEventListener("message", handler);
174
- return () => {
175
- this.worker.removeEventListener("message", handler);
176
- };
177
- },
178
- // lifecycle methods
179
- dispose: async () => {
180
- await this.exec("unregisterCollection", collection.name);
181
- this.isDisposed = true;
182
- this.worker.terminate();
183
- },
184
- isReady: async () => {
185
- await this.exec("isReady", collection.name);
186
- }
187
- };
188
- }
189
- }
190
- module.exports = WorkerDataAdapter;