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