@signaldb/core 2.0.0-beta.4 → 2.0.0-beta.6

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 (60) hide show
  1. package/dist/.vite/manifest.json +27 -21
  2. package/dist/Collection/Observer.d.ts +2 -0
  3. package/dist/Collection/index.d.ts +11 -10
  4. package/dist/Collection/types.d.ts +7 -0
  5. package/dist/DefaultDataAdapter.d.ts +2 -0
  6. package/dist/index.cjs.js +8 -5
  7. package/dist/index.cjs12.js +41 -346
  8. package/dist/index.cjs13.js +308 -359
  9. package/dist/index.cjs14.js +387 -177
  10. package/dist/index.cjs15.js +182 -364
  11. package/dist/index.cjs16.js +287 -478
  12. package/dist/index.cjs17.js +563 -136
  13. package/dist/index.cjs18.js +154 -23
  14. package/dist/index.cjs19.js +23 -39
  15. package/dist/index.cjs2.js +1 -1
  16. package/dist/index.cjs20.js +39 -13
  17. package/dist/index.cjs21.js +14 -102
  18. package/dist/index.cjs22.js +93 -118
  19. package/dist/index.cjs23.js +127 -5
  20. package/dist/index.cjs24.js +5 -25
  21. package/dist/index.cjs25.js +24 -7
  22. package/dist/index.cjs26.js +8 -27
  23. package/dist/index.cjs27.js +25 -42
  24. package/dist/index.cjs28.js +44 -6
  25. package/dist/index.cjs29.js +6 -7
  26. package/dist/index.cjs3.js +9 -26
  27. package/dist/index.cjs30.js +7 -3
  28. package/dist/index.cjs32.js +40 -27
  29. package/dist/index.cjs33.js +27 -40
  30. package/dist/index.cjs34.js +5 -0
  31. package/dist/index.cjs7.js +1 -1
  32. package/dist/index.d.ts +2 -1
  33. package/dist/index.mjs +10 -7
  34. package/dist/index12.mjs +40 -346
  35. package/dist/index13.mjs +308 -359
  36. package/dist/index14.mjs +387 -177
  37. package/dist/index15.mjs +182 -364
  38. package/dist/index16.mjs +287 -478
  39. package/dist/index17.mjs +563 -136
  40. package/dist/index18.mjs +154 -23
  41. package/dist/index19.mjs +23 -38
  42. package/dist/index2.mjs +1 -1
  43. package/dist/index20.mjs +38 -13
  44. package/dist/index21.mjs +14 -102
  45. package/dist/index22.mjs +93 -117
  46. package/dist/index23.mjs +126 -5
  47. package/dist/index24.mjs +5 -25
  48. package/dist/index25.mjs +24 -7
  49. package/dist/index26.mjs +8 -27
  50. package/dist/index27.mjs +25 -42
  51. package/dist/index28.mjs +44 -6
  52. package/dist/index29.mjs +6 -7
  53. package/dist/index3.mjs +9 -26
  54. package/dist/index30.mjs +7 -3
  55. package/dist/index32.mjs +40 -27
  56. package/dist/index33.mjs +27 -40
  57. package/dist/index34.mjs +6 -0
  58. package/dist/index7.mjs +1 -1
  59. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  60. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -8,25 +8,28 @@ import { default as default8 } from "./index8.mjs";
8
8
  import { default as default9 } from "./index9.mjs";
9
9
  import { default as default10 } from "./index10.mjs";
10
10
  import { default as default11 } from "./index11.mjs";
11
- import { default as default12 } from "./index12.mjs";
11
+ import { default as default12, unwrap } from "./index12.mjs";
12
12
  import { default as default13 } from "./index13.mjs";
13
13
  import { default as default14 } from "./index14.mjs";
14
14
  import { default as default15 } from "./index15.mjs";
15
15
  import { default as default16 } from "./index16.mjs";
16
+ import { default as default17 } from "./index17.mjs";
16
17
  export {
17
- default13 as AsyncDataAdapter,
18
- default16 as AutoFetchDataAdapter,
18
+ default14 as AsyncDataAdapter,
19
+ default17 as AutoFetchDataAdapter,
19
20
  default3 as Collection,
20
21
  default2 as Cursor,
21
- default12 as DefaultDataAdapter,
22
+ default13 as DefaultDataAdapter,
22
23
  default9 as EventEmitter,
23
- default14 as WorkerDataAdapter,
24
- default15 as WorkerDataAdapterHost,
24
+ default15 as WorkerDataAdapter,
25
+ default16 as WorkerDataAdapterHost,
25
26
  default5 as createReactivityAdapter,
26
27
  default4 as createStorageAdapter,
27
28
  default10 as get,
28
29
  default6 as isEqual,
29
30
  default7 as modify,
30
31
  default8 as randomId,
31
- default11 as serializeValue
32
+ default12 as reactiveOrAsync,
33
+ default11 as serializeValue,
34
+ unwrap
32
35
  };
package/dist/index12.mjs CHANGED
@@ -1,354 +1,48 @@
1
- import createIndex from "./index21.mjs";
2
- import getIndexInfo from "./index22.mjs";
3
- import deepClone from "./index19.mjs";
4
- import EventEmitter from "./index9.mjs";
5
- import isEqual from "./index6.mjs";
6
- import match from "./index23.mjs";
7
- import modify from "./index7.mjs";
8
- import project from "./index24.mjs";
9
- import queryId from "./index20.mjs";
10
- import serializeValue from "./index11.mjs";
11
- import sortItems from "./index25.mjs";
12
- function hasPendingUpdates(pendingUpdates) {
13
- return pendingUpdates.added.length > 0 || pendingUpdates.modified.length > 0 || pendingUpdates.removed.length > 0;
1
+ function unwrap(value) {
2
+ return (function* () {
3
+ return yield value;
4
+ })();
14
5
  }
15
- class DefaultDataAdapter {
16
- items = /* @__PURE__ */ new Map();
17
- options;
18
- storageAdapters = /* @__PURE__ */ new Map();
19
- indices = /* @__PURE__ */ new Map();
20
- activeQueries = /* @__PURE__ */ new Map();
21
- queryEmitters = /* @__PURE__ */ new Map();
22
- queuedQueryUpdates = /* @__PURE__ */ new Map();
23
- cachedQueryResults = /* @__PURE__ */ new Map();
24
- constructor(options) {
25
- this.options = options || {};
26
- }
27
- ensureStorageAdapter(name) {
28
- if (this.storageAdapters.get(name))
29
- return;
30
- if (!this.options.storage)
31
- return;
32
- const adapter = this.options.storage(name);
33
- if (!adapter)
34
- return;
35
- this.storageAdapters.set(name, adapter);
36
- }
37
- rebuildIndices(collection) {
38
- const items = this.items.get(collection.name);
39
- if (!items)
40
- throw new Error(`Items not found for collection ${collection.name}`);
41
- const indices = this.indices.get(collection.name);
42
- if (!indices)
43
- throw new Error(`Indices not found for collection ${collection.name}`);
44
- indices.forEach((index) => index.rebuild([...items.values()]));
45
- }
46
- async setupStorageAdapter(collection) {
47
- const storageAdapter = this.storageAdapters.get(collection.name);
48
- if (!storageAdapter)
49
- return;
50
- return storageAdapter.setup().then(async () => {
51
- const items = await storageAdapter.readAll();
52
- this.items.set(collection.name, items.reduce((map, item) => {
53
- map.set(serializeValue(item.id), item);
54
- return map;
55
- }, /* @__PURE__ */ new Map()));
56
- this.rebuildIndices(collection);
57
- }).catch((error) => {
58
- if (!this.options.onError) {
59
- console.error(`Error during data persistence operation in collection ${collection.name}`, error);
60
- return;
61
- }
62
- this.options.onError(collection.name, error instanceof Error ? error : new Error(error));
63
- });
64
- }
65
- getIndexInfo(collection, selector) {
66
- if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
67
- return {
68
- matched: true,
69
- ids: [serializeValue(selector.id)],
70
- optimizedSelector: {}
71
- };
72
- }
73
- if (selector == null) {
74
- return {
75
- matched: false,
76
- ids: [],
77
- optimizedSelector: {}
78
- };
6
+ function isThenable(value) {
7
+ return typeof value === "object" && value !== null && typeof value.then === "function";
8
+ }
9
+ function runReactiveOrAsync(thisArgument, mode, gen) {
10
+ const a = !!mode?.async;
11
+ const it = gen.call(thisArgument, a);
12
+ if (!a) {
13
+ let step = it.next();
14
+ while (!step.done) {
15
+ const y = step.value;
16
+ if (isThenable(y))
17
+ throw new Error("Promise yielded in sync flow");
18
+ step = it.next(y);
79
19
  }
80
- return getIndexInfo((this.indices.get(collection.name) ?? []).map((i) => i.query.bind(i)), selector);
81
- }
82
- applyIndexDeltas(collection, changes) {
83
- const indices = this.indices.get(collection.name) ?? [];
84
- for (const index of indices) {
85
- if (changes.modified)
86
- index.update(changes.modified);
87
- if (changes.added && changes.added.length > 0)
88
- index.insert(changes.added);
89
- if (changes.removed && changes.removed.length > 0)
90
- index.remove(changes.removed);
20
+ return step.value;
21
+ }
22
+ return (async function() {
23
+ let step = it.next();
24
+ while (!step.done) {
25
+ const y = step.value;
26
+ const v = isThenable(y) ? await y : y;
27
+ step = it.next(v);
91
28
  }
92
- }
93
- getItem(collection, selector) {
94
- const memory = this.items.get(collection.name) ?? /* @__PURE__ */ new Map();
95
- const indexInfo = this.getIndexInfo(collection, selector);
96
- const items = indexInfo.matched ? indexInfo.ids.map((id) => memory.get(serializeValue(id))).filter((i) => i != null) : [...memory.values()];
97
- const item = items.find((document) => match(document, selector));
98
- return item;
99
- }
100
- queryItems(collection, selector) {
101
- const indexInfo = this.getIndexInfo(collection, selector);
102
- const matchItems = (item) => {
103
- if (indexInfo.optimizedSelector == null)
104
- return true;
105
- if (Object.keys(indexInfo.optimizedSelector).length <= 0)
106
- return true;
107
- const matches = match(item, indexInfo.optimizedSelector);
108
- return matches;
109
- };
110
- const items = this.items.get(collection.name);
111
- if (!indexInfo.matched) {
112
- if (isEqual(selector, {}))
113
- return [...items.values()];
114
- return [...items.values()].filter(matchItems);
115
- }
116
- const foundItems = indexInfo.ids.map((ids) => items.get(serializeValue(ids))).filter((i) => i != null);
117
- if (isEqual(indexInfo.optimizedSelector, {}))
118
- return foundItems;
119
- return foundItems.filter(matchItems);
120
- }
121
- executeQuery(collection, selector, options) {
122
- const items = this.queryItems(collection, selector || {});
123
- const { sort, skip, limit, fields } = options || {};
124
- const sorted = sort ? sortItems(items, sort) : items;
125
- const skipped = skip ? sorted.slice(skip) : sorted;
126
- const limited = limit ? skipped.slice(0, limit) : skipped;
127
- const idExcluded = fields && fields.id === 0;
128
- return limited.map((item) => {
129
- if (!fields)
130
- return item;
131
- return {
132
- ...idExcluded ? {} : { id: item.id },
133
- ...project(item, fields)
134
- };
135
- });
136
- }
137
- flushQueuedQueryUpdates(collection) {
138
- if (!this.queuedQueryUpdates.get(collection.name))
139
- return;
140
- const changes = this.queuedQueryUpdates.get(collection.name);
141
- if (!changes || !hasPendingUpdates(changes))
142
- return;
143
- this.queuedQueryUpdates.set(collection.name, { added: [], modified: [], removed: [] });
144
- const flatItems = [...changes.added, ...changes.modified, ...changes.removed];
145
- const itemIds = new Set(flatItems.map((i) => i.id));
146
- const queries = [
147
- ...this.activeQueries.get(collection.name)?.values() ?? []
148
- ].filter(({ selector, options }) => {
149
- const idsInQuery = this.cachedQueryResults.get(collection.name)?.get(queryId(selector, options))?.map((i) => i.id) ?? [];
150
- if (idsInQuery.some((id) => itemIds.has(id)))
151
- return true;
152
- return flatItems.some((item) => match(item, selector));
153
- });
154
- queries.forEach(({ selector, options }) => {
155
- this.executeAndCacheQuery(collection, selector, options);
29
+ return step.value;
30
+ })();
31
+ }
32
+ function reactiveOrAsync(gen) {
33
+ function method(...allArguments) {
34
+ const last = allArguments.length > 0 ? allArguments.at(-1) : void 0;
35
+ const hasMode = typeof last === "object" && last !== null && "async" in last;
36
+ const mode = hasMode ? last : void 0;
37
+ const parameters = hasMode ? allArguments.slice(0, -1) : allArguments;
38
+ return runReactiveOrAsync(this, mode, function* (a) {
39
+ return yield* gen.call(this, a, ...parameters);
156
40
  });
157
41
  }
158
- executeAndCacheQuery(collection, selector, options) {
159
- const result = this.executeQuery(collection, selector, options);
160
- this.cachedQueryResults.set(collection.name, this.cachedQueryResults.get(collection.name) || /* @__PURE__ */ new Map());
161
- this.cachedQueryResults.get(collection.name)?.set(queryId(selector, options), result);
162
- const emitter = this.queryEmitters.get(collection.name);
163
- if (!emitter)
164
- return;
165
- emitter.emit("change", selector, options, "complete");
166
- }
167
- updateQueries(collection, changes) {
168
- this.queuedQueryUpdates.set(collection.name, this.queuedQueryUpdates.get(collection.name) || { added: [], modified: [], removed: [] });
169
- this.queuedQueryUpdates.get(collection.name)?.added.push(...changes.added);
170
- this.queuedQueryUpdates.get(collection.name)?.modified.push(...changes.modified);
171
- this.queuedQueryUpdates.get(collection.name)?.removed.push(...changes.removed);
172
- this.flushQueuedQueryUpdates(collection);
173
- }
174
- createCollectionBackend(collection, indices) {
175
- this.ensureStorageAdapter(collection.name);
176
- this.items.set(collection.name, this.items.get(collection.name) ?? /* @__PURE__ */ new Map());
177
- this.queryEmitters.set(collection.name, this.queryEmitters.get(collection.name) ?? new EventEmitter());
178
- this.queryEmitters.get(collection.name)?.setMaxListeners(Infinity);
179
- this.activeQueries.set(collection.name, this.activeQueries.get(collection.name) || /* @__PURE__ */ new Map());
180
- this.indices.set(collection.name, indices.map((field) => createIndex(field)));
181
- this.rebuildIndices(collection);
182
- const persistenceReadyPromise = this.setupStorageAdapter(collection);
183
- const backend = {
184
- // CRUD operations
185
- insert: async (newItem) => {
186
- const items = this.items.get(collection.name);
187
- if (!items)
188
- throw new Error(`Items not found for collection ${collection.name}`);
189
- if (items.has(serializeValue(newItem.id))) {
190
- throw new Error(`Item with id '${newItem.id}' already exists`);
191
- }
192
- this.items.get(collection.name)?.set(serializeValue(newItem.id), newItem);
193
- await this.storageAdapters.get(collection.name)?.insert([newItem]);
194
- this.applyIndexDeltas(collection, { added: [newItem] });
195
- this.updateQueries(collection, {
196
- added: [],
197
- modified: [newItem],
198
- removed: []
199
- });
200
- return newItem;
201
- },
202
- updateOne: async (selector, modifier) => {
203
- const { $setOnInsert, ...restModifier } = modifier;
204
- const item = this.getItem(collection, selector);
205
- if (item == null)
206
- return [];
207
- const modifiedItem = modify(deepClone(item), restModifier);
208
- const hasItemWithSameId = item.id !== modifiedItem.id && this.getItem(collection, { id: modifiedItem.id }) != null;
209
- if (hasItemWithSameId) {
210
- throw new Error(`Item with id '${modifiedItem.id}' already exists`);
211
- }
212
- this.items.get(collection.name)?.set(serializeValue(modifiedItem.id), modifiedItem);
213
- await this.storageAdapters.get(collection.name)?.replace([modifiedItem]);
214
- this.applyIndexDeltas(collection, { modified: [{ oldItem: item, newItem: modifiedItem }] });
215
- this.updateQueries(collection, {
216
- added: [],
217
- modified: [modifiedItem],
218
- removed: []
219
- });
220
- return [modifiedItem];
221
- },
222
- updateMany: async (selector, modifier) => {
223
- const { $setOnInsert, ...restModifier } = modifier;
224
- const items = this.executeQuery(collection, selector, {});
225
- const changedItems = items.map((item) => {
226
- const modifiedItem = modify(deepClone(item), restModifier);
227
- const hasItemWithSameId = item.id !== modifiedItem.id && this.getItem(collection, { id: modifiedItem.id }) != null;
228
- if (hasItemWithSameId) {
229
- throw new Error(`Item with id '${modifiedItem.id}' already exists`);
230
- }
231
- return modifiedItem;
232
- });
233
- changedItems.forEach((item) => {
234
- this.items.get(collection.name)?.set(serializeValue(item.id), item);
235
- });
236
- await this.storageAdapters.get(collection.name)?.replace(changedItems);
237
- const pairs = items.map((oldItem, index) => ({ oldItem, newItem: changedItems[index] }));
238
- this.applyIndexDeltas(collection, { modified: pairs });
239
- this.updateQueries(collection, {
240
- added: [],
241
- modified: changedItems,
242
- removed: []
243
- });
244
- return changedItems;
245
- },
246
- replaceOne: async (selector, replacement) => {
247
- const item = this.getItem(collection, selector);
248
- if (item == null)
249
- return [];
250
- const hasItemWithSameId = item.id !== replacement.id && replacement.id != null && this.getItem(collection, { id: replacement.id }) != null;
251
- if (hasItemWithSameId) {
252
- throw new Error(`Item with id '${replacement.id}' already exists`);
253
- }
254
- const modifiedItem = { id: item.id, ...replacement };
255
- this.items.get(collection.name)?.set(serializeValue(modifiedItem.id), modifiedItem);
256
- await this.storageAdapters.get(collection.name)?.replace([modifiedItem]);
257
- this.applyIndexDeltas(collection, { modified: [{ oldItem: item, newItem: modifiedItem }] });
258
- this.updateQueries(collection, {
259
- added: [],
260
- modified: [modifiedItem],
261
- removed: []
262
- });
263
- return [modifiedItem];
264
- },
265
- removeOne: async (selector) => {
266
- const item = this.getItem(collection, selector);
267
- if (item == null)
268
- return [];
269
- this.items.get(collection.name)?.delete(serializeValue(item.id));
270
- await this.storageAdapters.get(collection.name)?.remove([item]);
271
- this.applyIndexDeltas(collection, { removed: [item] });
272
- this.updateQueries(collection, {
273
- added: [],
274
- modified: [],
275
- removed: [item]
276
- });
277
- return [item];
278
- },
279
- removeMany: async (selector) => {
280
- const items = backend.getQueryResult(selector, {});
281
- items.forEach((item) => {
282
- this.items.get(collection.name)?.delete(serializeValue(item.id));
283
- });
284
- await this.storageAdapters.get(collection.name)?.remove(items);
285
- this.applyIndexDeltas(collection, { removed: items });
286
- this.updateQueries(collection, {
287
- added: [],
288
- modified: [],
289
- removed: items
290
- });
291
- return items;
292
- },
293
- // methods for registering and unregistering queries that will be called from the collection during find/findOne
294
- registerQuery: (selector, options) => {
295
- this.activeQueries.set(collection.name, this.activeQueries.get(collection.name) || /* @__PURE__ */ new Map());
296
- this.activeQueries.get(collection.name)?.set(queryId(selector, options), {
297
- selector,
298
- options
299
- });
300
- this.executeAndCacheQuery(collection, selector, options);
301
- },
302
- unregisterQuery: (selector, options) => {
303
- if (!this.activeQueries.get(collection.name))
304
- return;
305
- this.activeQueries.get(collection.name)?.delete(queryId(selector, options));
306
- },
307
- getQueryState: () => "complete",
308
- onQueryStateChange: (selector, options, callback) => {
309
- const emitter = this.queryEmitters.get(collection.name);
310
- if (!emitter)
311
- throw new Error(`Query emitter not found for collection ${collection.name}`);
312
- const handler = (querySelector, queryOptions, state) => {
313
- if (queryId(querySelector, queryOptions) !== queryId(selector, options))
314
- return;
315
- callback(state);
316
- };
317
- emitter.on("change", handler);
318
- return () => {
319
- emitter.off("change", handler);
320
- };
321
- },
322
- getQueryError: () => null,
323
- getQueryResult: (selector, options) => {
324
- const isQueryActive = this.activeQueries.get(collection.name)?.has(queryId(selector, options));
325
- if (isQueryActive) {
326
- const results = this.cachedQueryResults.get(collection.name)?.get(queryId(selector, options));
327
- if (!results)
328
- throw new Error("Cached query results are not defined!");
329
- return results;
330
- }
331
- return this.executeQuery(collection, selector, options);
332
- },
333
- executeQuery: (selector, options) => Promise.resolve(this.executeQuery(collection, selector, options)),
334
- // lifecycle methods
335
- dispose: async () => {
336
- const adapter = this.storageAdapters.get(collection.name);
337
- if (adapter?.teardown)
338
- await adapter.teardown();
339
- this.storageAdapters.delete(collection.name);
340
- this.items.delete(collection.name);
341
- this.indices.delete(collection.name);
342
- this.activeQueries.delete(collection.name);
343
- this.queryEmitters.delete(collection.name);
344
- this.queuedQueryUpdates.delete(collection.name);
345
- this.cachedQueryResults.delete(collection.name);
346
- },
347
- isReady: () => persistenceReadyPromise
348
- };
349
- return backend;
350
- }
42
+ method.generator = gen;
43
+ return method;
351
44
  }
352
45
  export {
353
- DefaultDataAdapter as default
46
+ reactiveOrAsync as default,
47
+ unwrap
354
48
  };