@signaldb/core 1.2.4 → 1.3.0

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 (67) hide show
  1. package/dist/.vite/manifest.json +28 -47
  2. package/dist/index.cjs.js +12 -18
  3. package/dist/index.cjs10.js +6 -27
  4. package/dist/index.cjs11.js +3 -6
  5. package/dist/index.cjs12.js +136 -3
  6. package/dist/index.cjs13.js +40 -134
  7. package/dist/index.cjs14.js +5 -38
  8. package/dist/index.cjs15.js +42 -2
  9. package/dist/index.cjs16.js +11 -5
  10. package/dist/index.cjs17.js +17 -40
  11. package/dist/index.cjs18.js +262 -11
  12. package/dist/index.cjs19.js +66 -16
  13. package/dist/index.cjs2.js +688 -96
  14. package/dist/index.cjs20.js +71 -247
  15. package/dist/index.cjs21.js +8 -68
  16. package/dist/index.cjs22.js +22 -83
  17. package/dist/index.cjs23.js +144 -8
  18. package/dist/index.cjs24.js +5 -25
  19. package/dist/index.cjs25.js +16 -144
  20. package/dist/index.cjs26.js +27 -5
  21. package/dist/index.cjs27.js +39 -15
  22. package/dist/index.cjs28.js +25 -24
  23. package/dist/index.cjs29.js +7 -40
  24. package/dist/index.cjs3.js +139 -664
  25. package/dist/index.cjs4.js +62 -166
  26. package/dist/index.cjs5.js +3 -67
  27. package/dist/index.cjs6.js +2 -2
  28. package/dist/index.cjs7.js +2 -2
  29. package/dist/index.cjs8.js +2 -2
  30. package/dist/index.cjs9.js +27 -3
  31. package/dist/index.d.ts +0 -1
  32. package/dist/index.mjs +12 -18
  33. package/dist/index10.mjs +6 -27
  34. package/dist/index11.mjs +3 -6
  35. package/dist/index12.mjs +136 -3
  36. package/dist/index13.mjs +39 -134
  37. package/dist/index14.mjs +5 -37
  38. package/dist/index15.mjs +41 -2
  39. package/dist/index16.mjs +11 -5
  40. package/dist/index17.mjs +17 -39
  41. package/dist/index18.mjs +261 -11
  42. package/dist/index19.mjs +65 -16
  43. package/dist/index2.mjs +688 -94
  44. package/dist/index20.mjs +71 -247
  45. package/dist/index21.mjs +8 -67
  46. package/dist/index22.mjs +22 -82
  47. package/dist/index23.mjs +144 -8
  48. package/dist/index24.mjs +5 -25
  49. package/dist/index25.mjs +16 -144
  50. package/dist/index26.mjs +27 -5
  51. package/dist/index27.mjs +39 -15
  52. package/dist/index28.mjs +25 -24
  53. package/dist/index29.mjs +7 -40
  54. package/dist/index3.mjs +139 -664
  55. package/dist/index4.mjs +61 -166
  56. package/dist/index5.mjs +3 -66
  57. package/dist/index6.mjs +2 -2
  58. package/dist/index7.mjs +2 -2
  59. package/dist/index8.mjs +2 -2
  60. package/dist/index9.mjs +27 -3
  61. package/dist/utils/getMatchingKeys.d.ts +11 -6
  62. package/package.json +1 -1
  63. package/dist/devtools.d.ts +0 -4
  64. package/dist/index.cjs30.js +0 -29
  65. package/dist/index.cjs31.js +0 -9
  66. package/dist/index30.mjs +0 -30
  67. package/dist/index31.mjs +0 -10
@@ -2,697 +2,172 @@
2
2
  var __defProp = Object.defineProperty;
3
3
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
4
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
- Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
6
- const EventEmitter = require("./index.cjs13.js");
7
- const match = require("./index.cjs16.js");
8
- const modify = require("./index.cjs11.js");
9
- const isEqual = require("./index.cjs10.js");
10
- const randomId = require("./index.cjs12.js");
11
- const deepClone = require("./index.cjs17.js");
12
- const serializeValue = require("./index.cjs18.js");
13
- const createSignal = require("./index.cjs19.js");
14
- const Cursor = require("./index.cjs20.js");
15
- const getIndexInfo = require("./index.cjs21.js");
16
- const createIndex = require("./index.cjs14.js");
17
- function hasPendingUpdates(pendingUpdates) {
18
- return pendingUpdates.added.length > 0 || pendingUpdates.modified.length > 0 || pendingUpdates.removed.length > 0;
19
- }
20
- function applyUpdates(currentItems, { added, modified, removed }) {
21
- const items = [...currentItems];
22
- added.forEach((item) => {
23
- items.push(item);
24
- });
25
- modified.forEach((item) => {
26
- const index = items.findIndex(({ id }) => id === item.id);
27
- if (index === -1)
28
- return;
29
- items[index] = item;
30
- });
31
- removed.forEach((item) => {
32
- const index = items.findIndex(({ id }) => id === item.id);
33
- if (index === -1)
34
- return;
35
- items.splice(index, 1);
36
- });
37
- return items;
38
- }
39
- const _Collection = class _Collection extends EventEmitter {
5
+ const ReplicatedCollection = require("./index.cjs20.js");
6
+ const createSignal = require("./index.cjs17.js");
7
+ class AutoFetchCollection extends ReplicatedCollection.default {
40
8
  /**
41
- * Initializes a new instance of the `Collection` class with optional configuration.
42
- * Sets up memory, persistence, reactivity, and indices as specified in the options.
43
- * @template T - The type of the items stored in the collection.
44
- * @template I - The type of the unique identifier for the items.
45
- * @template U - The transformed item type after applying transformations (default is T).
46
- * @param options - Optional configuration for the collection.
47
- * @param options.name - An optional name for the collection.
48
- * @param options.memory - The in-memory adapter for storing items.
49
- * @param options.reactivity - The reactivity adapter for observing changes in the collection.
50
- * @param options.transform - A transformation function to apply to items when retrieving them.
51
- * @param options.persistence - The persistence adapter for saving and loading items.
52
- * @param options.indices - An array of index providers for optimized querying.
53
- * @param options.enableDebugMode - A boolean to enable or disable debug mode.
54
- * @param options.fieldTracking - A boolean to enable or disable field tracking by default.
9
+ * @param options {Object} - Options for the collection.
10
+ * @param options.fetchQueryItems {Function} - A function that fetches items from the server. It takes the selector as an argument and returns a promise that resolves to an object with an `items` property.
11
+ * @param options.purgeDelay {Number} - The delay in milliseconds before purging an item from the cache.
55
12
  */
56
13
  constructor(options) {
57
- var _a, _b;
58
- super();
59
- __publicField(this, "name");
60
- __publicField(this, "options");
61
- __publicField(this, "persistenceAdapter", null);
62
- __publicField(this, "isPullingSignal");
63
- __publicField(this, "isPushingSignal");
64
- __publicField(this, "indexProviders", []);
65
- __publicField(this, "indicesOutdated", false);
66
- __publicField(this, "idIndex", /* @__PURE__ */ new Map());
67
- __publicField(this, "debugMode");
68
- __publicField(this, "batchOperationInProgress", false);
69
- __publicField(this, "isDisposed", false);
70
- __publicField(this, "postBatchCallbacks", /* @__PURE__ */ new Set());
71
- __publicField(this, "fieldTracking", false);
72
- __publicField(this, "persistenceReadyPromise");
73
- _Collection.collections.push(this);
74
- this.name = (options == null ? void 0 : options.name) ?? `${this.constructor.name}-${randomId()}`;
75
- this.options = {
76
- memory: [],
77
- ...options
78
- };
79
- this.fieldTracking = this.options.fieldTracking ?? _Collection.fieldTracking;
80
- this.debugMode = this.options.enableDebugMode ?? _Collection.debugMode;
81
- this.indexProviders = [
82
- createIndex.createExternalIndex("id", this.idIndex),
83
- ...this.options.indices || []
84
- ];
85
- this.rebuildIndices();
86
- this.isPullingSignal = createSignal((_a = this.options.reactivity) == null ? void 0 : _a.create(), !!(options == null ? void 0 : options.persistence));
87
- this.isPushingSignal = createSignal((_b = this.options.reactivity) == null ? void 0 : _b.create(), false);
88
- this.on("persistence.pullStarted", () => {
89
- this.isPullingSignal.set(true);
90
- });
91
- this.on("persistence.pullCompleted", () => {
92
- this.isPullingSignal.set(false);
93
- });
94
- this.on("persistence.pushStarted", () => {
95
- this.isPushingSignal.set(true);
96
- });
97
- this.on("persistence.pushCompleted", () => {
98
- this.isPushingSignal.set(false);
99
- });
100
- this.persistenceAdapter = this.options.persistence ?? null;
101
- if (this.persistenceAdapter) {
102
- let ongoingSaves = 0;
103
- let isInitialized = false;
104
- const pendingUpdates = { added: [], modified: [], removed: [] };
105
- const loadPersistentData = async (data) => {
106
- if (!this.persistenceAdapter)
107
- throw new Error("Persistence adapter not found");
108
- this.emit("persistence.pullStarted");
109
- const { items, changes } = data ?? await this.persistenceAdapter.load();
110
- if (items) {
111
- if (ongoingSaves > 0)
112
- return;
113
- this.memory().splice(0, this.memoryArray().length, ...items);
114
- this.idIndex.clear();
115
- this.memory().map((item, index) => {
116
- this.idIndex.set(serializeValue(item.id), /* @__PURE__ */ new Set([index]));
117
- });
118
- } else if (changes) {
119
- changes.added.forEach((item) => {
120
- const index = this.memory().findIndex((document) => document.id === item.id);
121
- if (index !== -1) {
122
- this.memory().splice(index, 1, item);
14
+ var _a;
15
+ let triggerRemoteChange;
16
+ super({
17
+ ...options,
18
+ pull: () => Promise.resolve({
19
+ items: [...this.itemsCache.values()].reduce((memo, items) => {
20
+ const newItems = [...memo];
21
+ items.forEach((item) => {
22
+ const index = newItems.findIndex((i) => i.id === item.id);
23
+ if (index === -1) {
24
+ newItems.push(item);
123
25
  return;
124
26
  }
125
- this.memory().push(item);
126
- const itemIndex = this.memory().findIndex((document) => document === item);
127
- this.idIndex.set(serializeValue(item.id), /* @__PURE__ */ new Set([itemIndex]));
128
- });
129
- changes.modified.forEach((item) => {
130
- const index = this.memory().findIndex((document) => document.id === item.id);
131
- if (index === -1)
132
- throw new Error("Cannot resolve index for item");
133
- this.memory().splice(index, 1, item);
134
- });
135
- changes.removed.forEach((item) => {
136
- const index = this.memory().findIndex((document) => document.id === item.id);
137
- if (index === -1)
138
- throw new Error("Cannot resolve index for item");
139
- this.memory().splice(index, 1);
27
+ newItems[index] = this.mergeItems(newItems[index], item);
140
28
  });
141
- }
142
- this.rebuildIndices();
143
- this.emit("persistence.received");
144
- setTimeout(() => this.emit("persistence.pullCompleted"), 0);
145
- };
146
- const saveQueue = {
147
- added: [],
148
- modified: [],
149
- removed: []
150
- };
151
- let isFlushing = false;
152
- const flushQueue = () => {
153
- if (!this.persistenceAdapter)
154
- throw new Error("Persistence adapter not found");
155
- if (ongoingSaves <= 0)
156
- this.emit("persistence.pushStarted");
157
- if (isFlushing)
158
- return;
159
- if (!hasPendingUpdates(saveQueue))
160
- return;
161
- isFlushing = true;
162
- ongoingSaves += 1;
163
- const currentItems = this.memoryArray();
164
- const changes = { ...saveQueue };
165
- saveQueue.added = [];
166
- saveQueue.modified = [];
167
- saveQueue.removed = [];
168
- this.persistenceAdapter.save(currentItems, changes).then(() => {
169
- this.emit("persistence.transmitted");
170
- }).catch((error) => {
171
- this.emit("persistence.error", error instanceof Error ? error : new Error(error));
172
- }).finally(() => {
173
- ongoingSaves -= 1;
174
- isFlushing = false;
175
- flushQueue();
176
- if (ongoingSaves <= 0)
177
- this.emit("persistence.pushCompleted");
178
- });
179
- };
180
- this.on("added", (item) => {
181
- if (!isInitialized) {
182
- pendingUpdates.added.push(item);
183
- return;
184
- }
185
- saveQueue.added.push(item);
186
- flushQueue();
187
- });
188
- this.on("changed", (item) => {
189
- if (!isInitialized) {
190
- pendingUpdates.modified.push(item);
191
- return;
192
- }
193
- saveQueue.modified.push(item);
194
- flushQueue();
195
- });
196
- this.on("removed", (item) => {
197
- if (!isInitialized) {
198
- pendingUpdates.removed.push(item);
199
- return;
200
- }
201
- saveQueue.removed.push(item);
202
- flushQueue();
203
- });
204
- this.persistenceAdapter.register((data) => loadPersistentData(data)).then(async () => {
205
- if (!this.persistenceAdapter)
206
- throw new Error("Persistence adapter not found");
207
- let currentItems = this.memoryArray();
208
- await loadPersistentData();
209
- while (hasPendingUpdates(pendingUpdates)) {
210
- const added = pendingUpdates.added.splice(0);
211
- const modified = pendingUpdates.modified.splice(0);
212
- const removed = pendingUpdates.removed.splice(0);
213
- currentItems = applyUpdates(this.memoryArray(), { added, modified, removed });
214
- await this.persistenceAdapter.save(currentItems, { added, modified, removed }).then(() => {
215
- this.emit("persistence.transmitted");
216
- });
217
- }
218
- await loadPersistentData();
219
- isInitialized = true;
220
- setTimeout(() => this.emit("persistence.init"), 0);
221
- }).catch((error) => {
222
- this.emit("persistence.error", error instanceof Error ? error : new Error(error));
223
- });
224
- }
225
- this.persistenceReadyPromise = new Promise((resolve, reject) => {
226
- if (!this.persistenceAdapter)
227
- return resolve();
228
- this.once("persistence.init", resolve);
229
- this.once("persistence.error", reject);
29
+ return newItems;
30
+ }, [])
31
+ }),
32
+ registerRemoteChange: async (onChange) => {
33
+ triggerRemoteChange = onChange;
34
+ }
230
35
  });
231
- _Collection.onCreationCallbacks.forEach((callback) => callback(this));
232
- }
233
- static getCollections() {
234
- return _Collection.collections;
235
- }
236
- static onCreation(callback) {
237
- _Collection.onCreationCallbacks.push(callback);
238
- }
239
- static onDispose(callback) {
240
- _Collection.onDisposeCallbacks.push(callback);
241
- }
242
- /**
243
- * Executes a batch operation, allowing multiple modifications to the collection
244
- * while deferring index rebuilding until all operations in the batch are completed.
245
- * This improves performance by avoiding repetitive index recalculations and
246
- * provides atomicity for the batch of operations.
247
- * @param callback - The batch operation to execute.
248
- */
249
- static batch(callback) {
250
- _Collection.batchOperationInProgress = true;
251
- _Collection.collections.reduce((memo, collection) => () => collection.batch(() => memo()), callback)();
252
- _Collection.batchOperationInProgress = false;
253
- }
254
- /**
255
- * Checks whether the collection is currently performing a pull operation
256
- * ⚡️ this function is reactive!
257
- * (loading data from the persistence adapter).
258
- * @returns A boolean indicating if the collection is in the process of pulling data.
259
- */
260
- isPulling() {
261
- return this.isPullingSignal.get() ?? false;
262
- }
263
- /**
264
- * Checks whether the collection is currently performing a push operation
265
- * ⚡️ this function is reactive!
266
- * (saving data to the persistence adapter).
267
- * @returns A boolean indicating if the collection is in the process of pushing data.
268
- */
269
- isPushing() {
270
- return this.isPushingSignal.get() ?? false;
271
- }
272
- /**
273
- * Checks whether the collection is currently performing either a pull or push operation,
274
- * ⚡️ this function is reactive!
275
- * indicating that it is loading or saving data.
276
- * @returns A boolean indicating if the collection is in the process of loading or saving data.
277
- */
278
- isLoading() {
279
- const isPulling = this.isPulling();
280
- const isPushing = this.isPushing();
281
- return isPulling || isPushing;
282
- }
283
- /**
284
- * Retrieves the current debug mode status of the collection.
285
- * @returns A boolean indicating whether debug mode is enabled for the collection.
286
- */
287
- getDebugMode() {
288
- return this.debugMode;
289
- }
290
- /**
291
- * Enables or disables debug mode for the collection.
292
- * When debug mode is enabled, additional debugging information and events are emitted.
293
- * @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) debug mode.
294
- */
295
- setDebugMode(enable) {
296
- this.debugMode = enable;
36
+ __publicField(this, "activeObservers", /* @__PURE__ */ new Map());
37
+ __publicField(this, "observerTimeouts", /* @__PURE__ */ new Map());
38
+ __publicField(this, "purgeDelay");
39
+ __publicField(this, "idQueryCache", /* @__PURE__ */ new Map());
40
+ __publicField(this, "itemsCache", /* @__PURE__ */ new Map());
41
+ __publicField(this, "fetchQueryItems");
42
+ __publicField(this, "triggerReload", null);
43
+ __publicField(this, "reactivityAdapter", null);
44
+ __publicField(this, "loadingSignals", /* @__PURE__ */ new Map());
45
+ __publicField(this, "isFetchingSignal");
46
+ __publicField(this, "mergeItems");
47
+ this.mergeItems = options.mergeItems ?? ((itemA, itemB) => ({ ...itemA, ...itemB }));
48
+ this.purgeDelay = options.purgeDelay ?? 1e4;
49
+ this.isFetchingSignal = createSignal((_a = options.reactivity) == null ? void 0 : _a.create(), false);
50
+ if (!triggerRemoteChange)
51
+ throw new Error("No triggerRemoteChange method found. Looks like your persistence adapter was not registered");
52
+ this.triggerReload = triggerRemoteChange;
53
+ this.reactivityAdapter = options.reactivity ?? null;
54
+ this.fetchQueryItems = options.fetchQueryItems;
55
+ this.on("observer.created", (selector) => this.handleObserverCreation(selector ?? {}));
56
+ this.on("observer.disposed", (selector) => setTimeout(() => this.handleObserverDisposal(selector ?? {}), 100));
57
+ if (options.registerRemoteChange) {
58
+ void options.registerRemoteChange(() => this.forceRefetch());
59
+ }
297
60
  }
298
61
  /**
299
- * Enables or disables field tracking for the collection.
300
- * @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) field tracking.
62
+ * Registers a query manually that items should be fetched for it
63
+ * @param selector {Object} Selector of the query
301
64
  */
302
- setFieldTracking(enable) {
303
- this.fieldTracking = enable;
65
+ registerQuery(selector) {
66
+ this.handleObserverCreation(selector);
304
67
  }
305
68
  /**
306
- * Resolves when the persistence adapter finished initializing
307
- * and the collection is ready to be used.
308
- * @returns A promise that resolves when the collection is ready.
309
- * @example
310
- * ```ts
311
- * const collection = new Collection({
312
- * persistence: // ...
313
- * })
314
- * await collection.isReady()
315
- *
316
- * collection.insert({ name: 'Item 1' })
69
+ * Unregisters a query manually that items are not fetched anymore for it
70
+ * @param selector {Object} Selector of the query
317
71
  */
318
- async isReady() {
319
- return this.persistenceReadyPromise;
72
+ unregisterQuery(selector) {
73
+ this.handleObserverDisposal(selector);
320
74
  }
321
- profile(fn, measureFunction) {
322
- if (!this.debugMode)
323
- return fn();
324
- const startTime = performance.now();
325
- const result = fn();
326
- const endTime = performance.now();
327
- measureFunction(endTime - startTime);
328
- return result;
75
+ getKeyForSelector(selector) {
76
+ return JSON.stringify(selector);
329
77
  }
330
- executeInDebugMode(fn) {
331
- if (!this.debugMode)
332
- return;
333
- const callstack = new Error().stack || "";
334
- fn(callstack);
335
- }
336
- rebuildIndices() {
337
- this.indicesOutdated = true;
338
- if (this.batchOperationInProgress)
339
- return;
340
- this.rebuildAllIndices();
341
- }
342
- rebuildAllIndices() {
343
- this.idIndex.clear();
344
- this.memory().map((item, index) => {
345
- this.idIndex.set(serializeValue(item.id), /* @__PURE__ */ new Set([index]));
78
+ async forceRefetch() {
79
+ return Promise.all([...this.activeObservers.values()].map(({ selector }) => this.fetchSelector(selector))).then(() => {
346
80
  });
347
- this.indexProviders.forEach((index) => index.rebuild(this.memoryArray()));
348
- this.indicesOutdated = false;
349
- }
350
- getIndexInfo(selector) {
351
- if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
352
- return {
353
- matched: true,
354
- positions: [...this.idIndex.get(serializeValue(selector.id)) || []],
355
- optimizedSelector: {}
356
- };
357
- }
358
- if (selector == null || this.indicesOutdated) {
359
- return {
360
- matched: false,
361
- positions: [],
362
- optimizedSelector: {}
363
- };
364
- }
365
- return getIndexInfo.default(this.indexProviders, selector);
366
- }
367
- getItemAndIndex(selector) {
368
- const memory = this.memoryArray();
369
- const indexInfo = this.getIndexInfo(selector);
370
- const items = indexInfo.matched ? indexInfo.positions.map((index2) => memory[index2]) : memory;
371
- const item = items.find((document) => match(document, selector));
372
- const foundInIndex = indexInfo.matched && indexInfo.positions.find((itemIndex) => memory[itemIndex] === item);
373
- const index = foundInIndex || memory.findIndex((document) => document === item);
374
- if (item == null)
375
- return { item: null, index: -1 };
376
- if (index === -1)
377
- throw new Error("Cannot resolve index for item");
378
- return { item, index };
379
81
  }
380
- deleteFromIdIndex(id, index) {
381
- this.idIndex.delete(serializeValue(id));
382
- if (!this.batchOperationInProgress)
383
- return;
384
- this.idIndex.forEach(([currenIndex], key) => {
385
- if (currenIndex > index) {
386
- this.idIndex.set(key, /* @__PURE__ */ new Set([currenIndex - 1]));
387
- }
82
+ fetchSelector(selector) {
83
+ this.isFetchingSignal.set(true);
84
+ return this.fetchQueryItems(selector).then((response) => {
85
+ if (!response.items)
86
+ throw new Error("AutoFetchCollection currently only works with a full item response");
87
+ this.itemsCache.set(this.getKeyForSelector(selector), response.items);
88
+ response.items.forEach((item) => {
89
+ const queries = this.idQueryCache.get(item.id) ?? [];
90
+ queries.push(selector);
91
+ this.idQueryCache.set(item.id, queries);
92
+ });
93
+ this.setLoading(selector, true);
94
+ this.once("persistence.received", () => {
95
+ this.setLoading(selector, false);
96
+ });
97
+ if (!this.triggerReload)
98
+ throw new Error("No triggerReload method found. Looks like your persistence adapter was not registered");
99
+ void this.triggerReload();
100
+ }).catch((error) => {
101
+ this.emit("persistence.error", error);
102
+ }).finally(() => {
103
+ this.isFetchingSignal.set(false);
388
104
  });
389
105
  }
390
- memory() {
391
- return this.options.memory;
392
- }
393
- memoryArray() {
394
- return this.memory().map((item) => item);
395
- }
396
- transform(item) {
397
- if (!this.options.transform)
398
- return item;
399
- return this.options.transform(item);
400
- }
401
- getItems(selector) {
402
- return this.profile(() => {
403
- const indexInfo = this.getIndexInfo(selector);
404
- const matchItems = (item) => {
405
- if (indexInfo.optimizedSelector == null)
406
- return true;
407
- if (Object.keys(indexInfo.optimizedSelector).length <= 0)
408
- return true;
409
- const matches = match(item, indexInfo.optimizedSelector);
410
- return matches;
411
- };
412
- if (!indexInfo.matched)
413
- return this.memory().filter(matchItems);
414
- const memory = this.memoryArray();
415
- const items = indexInfo.positions.map((index) => memory[index]);
416
- this.emit("getItems", selector);
417
- return items.filter(matchItems);
418
- }, (measuredTime) => this.executeInDebugMode((callstack) => this.emit("_debug.getItems", callstack, selector, measuredTime)));
419
- }
420
- /**
421
- * Disposes the collection, unregisters persistence adapters, clears memory, and
422
- * cleans up all resources used by the collection.
423
- * @returns A promise that resolves when the collection is disposed.
424
- */
425
- async dispose() {
106
+ handleObserverCreation(selector) {
426
107
  var _a;
427
- if ((_a = this.persistenceAdapter) == null ? void 0 : _a.unregister)
428
- await this.persistenceAdapter.unregister();
429
- this.persistenceAdapter = null;
430
- this.memory().map(() => this.memory().pop());
431
- this.idIndex.clear();
432
- this.indexProviders = [];
433
- this.isDisposed = true;
434
- this.removeAllListeners();
435
- _Collection.collections = _Collection.collections.filter((collection) => collection !== this);
436
- _Collection.onDisposeCallbacks.forEach((callback) => callback(this));
437
- }
438
- /**
439
- * Finds multiple items in the collection based on a selector and optional options.
440
- * Returns a cursor for reactive data queries.
441
- * @template O - The options type for the find operation.
442
- * @param [selector] - The criteria to select items.
443
- * @param [options] - Options for the find operation, such as limit and sort.
444
- * @returns A cursor to fetch and observe the matching items.
445
- */
446
- find(selector, options) {
447
- if (this.isDisposed)
448
- throw new Error("Collection is disposed");
449
- if (selector !== void 0 && (!selector || typeof selector !== "object"))
450
- throw new Error("Invalid selector");
451
- const cursor = new Cursor.default(() => this.getItems(selector), {
452
- reactive: this.options.reactivity,
453
- fieldTracking: this.fieldTracking,
454
- ...options,
455
- transform: this.transform.bind(this),
456
- bindEvents: (requery) => {
457
- const handleRequery = () => {
458
- if (this.batchOperationInProgress) {
459
- this.postBatchCallbacks.add(requery);
460
- return;
461
- }
462
- requery();
463
- };
464
- this.addListener("persistence.received", handleRequery);
465
- this.addListener("added", handleRequery);
466
- this.addListener("changed", handleRequery);
467
- this.addListener("removed", handleRequery);
468
- this.emit("observer.created", selector, options);
469
- return () => {
470
- this.removeListener("persistence.received", handleRequery);
471
- this.removeListener("added", handleRequery);
472
- this.removeListener("changed", handleRequery);
473
- this.removeListener("removed", handleRequery);
474
- this.emit("observer.disposed", selector, options);
475
- };
476
- }
108
+ const activeObservers = ((_a = this.activeObservers.get(this.getKeyForSelector(selector))) == null ? void 0 : _a.count) ?? 0;
109
+ this.activeObservers.set(this.getKeyForSelector(selector), {
110
+ selector,
111
+ count: activeObservers + 1
477
112
  });
478
- this.emit("find", selector, options, cursor);
479
- this.executeInDebugMode((callstack) => this.emit("_debug.find", callstack, selector, options, cursor));
480
- return cursor;
113
+ const timeout = this.observerTimeouts.get(this.getKeyForSelector(selector));
114
+ if (timeout)
115
+ clearTimeout(timeout);
116
+ if (activeObservers === 0)
117
+ void this.fetchSelector(selector);
481
118
  }
482
- /**
483
- * Finds a single item in the collection based on a selector and optional options.
484
- * ⚡️ this function is reactive!
485
- * Returns the found item or undefined if no item matches.
486
- * @template O - The options type for the find operation.
487
- * @param selector - The criteria to select the item.
488
- * @param [options] - Options for the find operation, such as projection.
489
- * @returns The found item or `undefined`.
490
- */
491
- findOne(selector, options) {
492
- if (this.isDisposed)
493
- throw new Error("Collection is disposed");
494
- const cursor = this.find(selector, {
495
- limit: 1,
496
- ...options
497
- });
498
- const returnValue = cursor.fetch()[0] || void 0;
499
- this.emit("findOne", selector, options, returnValue);
500
- this.executeInDebugMode((callstack) => this.emit("_debug.findOne", callstack, selector, options, returnValue));
501
- return returnValue;
502
- }
503
- /**
504
- * Performs a batch operation, deferring index rebuilds and allowing multiple
505
- * modifications to be made atomically. Executes any post-batch callbacks afterwards.
506
- * @param callback - The batch operation to execute.
507
- */
508
- batch(callback) {
509
- this.batchOperationInProgress = true;
510
- callback();
511
- this.batchOperationInProgress = false;
512
- this.rebuildAllIndices();
513
- this.postBatchCallbacks.forEach((callback_) => callback_());
514
- this.postBatchCallbacks.clear();
515
- }
516
- /**
517
- * Inserts a single item into the collection. Generates a unique ID if not provided.
518
- * @param item - The item to insert.
519
- * @returns The ID of the inserted item.
520
- * @throws {Error} If the collection is disposed or the item has an invalid ID.
521
- */
522
- insert(item) {
523
- if (this.isDisposed)
524
- throw new Error("Collection is disposed");
525
- if (!item)
526
- throw new Error("Invalid item");
527
- const newItem = { id: randomId(), ...item };
528
- if (this.idIndex.has(serializeValue(newItem.id)))
529
- throw new Error("Item with same id already exists");
530
- this.memory().push(newItem);
531
- const itemIndex = this.memory().findIndex((document) => document === newItem);
532
- this.idIndex.set(serializeValue(newItem.id), /* @__PURE__ */ new Set([itemIndex]));
533
- this.rebuildIndices();
534
- this.emit("added", newItem);
535
- this.emit("insert", newItem);
536
- this.executeInDebugMode((callstack) => this.emit("_debug.insert", callstack, newItem));
537
- return newItem.id;
538
- }
539
- /**
540
- * Inserts multiple items into the collection. Generates unique IDs for items if not provided.
541
- * @param items - The items to insert.
542
- * @returns An array of IDs of the inserted items.
543
- * @throws {Error} If the collection is disposed or the items are invalid.
544
- */
545
- insertMany(items) {
546
- if (this.isDisposed)
547
- throw new Error("Collection is disposed");
548
- if (!items)
549
- throw new Error("Invalid items");
550
- if (items.length === 0) {
551
- return [];
552
- }
553
- const ids = [];
554
- this.batch(() => {
555
- items.forEach((item) => {
556
- ids.push(this.insert(item));
119
+ handleObserverDisposal(selector) {
120
+ var _a;
121
+ const currentObservers = ((_a = this.activeObservers.get(this.getKeyForSelector(selector))) == null ? void 0 : _a.count) ?? 0;
122
+ const activeObservers = currentObservers - 1;
123
+ if (activeObservers > 0) {
124
+ this.activeObservers.set(this.getKeyForSelector(selector), {
125
+ selector,
126
+ count: activeObservers
557
127
  });
558
- });
559
- return ids;
128
+ return;
129
+ }
130
+ const timeout = this.observerTimeouts.get(this.getKeyForSelector(selector));
131
+ if (timeout)
132
+ clearTimeout(timeout);
133
+ const removeObserver = () => {
134
+ this.activeObservers.delete(this.getKeyForSelector(selector));
135
+ this.itemsCache.delete(this.getKeyForSelector(selector));
136
+ if (!this.triggerReload)
137
+ throw new Error("No triggerReload method found. Looks like your persistence adapter was not registered");
138
+ void this.triggerReload();
139
+ };
140
+ if (this.purgeDelay === 0) {
141
+ removeObserver();
142
+ return;
143
+ }
144
+ this.observerTimeouts.set(this.getKeyForSelector(selector), setTimeout(removeObserver, this.purgeDelay));
560
145
  }
561
- /**
562
- * Updates a single item in the collection that matches the given selector.
563
- * @param selector - The criteria to select the item to update.
564
- * @param modifier - The modifications to apply to the item.
565
- * @returns The number of items updated (0 or 1).
566
- * @throws {Error} If the collection is disposed or invalid arguments are provided.
567
- */
568
- updateOne(selector, modifier) {
569
- if (this.isDisposed)
570
- throw new Error("Collection is disposed");
571
- if (!selector)
572
- throw new Error("Invalid selector");
573
- if (!modifier)
574
- throw new Error("Invalid modifier");
575
- const { item, index } = this.getItemAndIndex(selector);
576
- if (item == null)
577
- return 0;
578
- const modifiedItem = modify(deepClone.default(item), modifier);
579
- const existingItem = this.findOne({ id: modifiedItem.id }, { reactive: false });
580
- if (!isEqual(existingItem, { ...existingItem, id: modifiedItem.id }))
581
- throw new Error("Item with same id already exists");
582
- this.memory().splice(index, 1, modifiedItem);
583
- this.rebuildIndices();
584
- this.emit("changed", modifiedItem, modifier);
585
- this.emit("updateOne", selector, modifier);
586
- this.executeInDebugMode((callstack) => this.emit("_debug.updateOne", callstack, selector, modifier));
587
- return 1;
146
+ ensureSignal(selector) {
147
+ if (!this.reactivityAdapter)
148
+ throw new Error("No reactivity adapter found");
149
+ if (!this.loadingSignals.has(this.getKeyForSelector(selector))) {
150
+ this.loadingSignals.set(this.getKeyForSelector(selector), createSignal(this.reactivityAdapter.create(), false));
151
+ }
152
+ return this.loadingSignals.get(this.getKeyForSelector(selector));
588
153
  }
589
- /**
590
- * Updates multiple items in the collection that match the given selector.
591
- * @param selector - The criteria to select the items to update.
592
- * @param modifier - The modifications to apply to the items.
593
- * @returns The number of items updated.
594
- * @throws {Error} If the collection is disposed or invalid arguments are provided.
595
- */
596
- updateMany(selector, modifier) {
597
- if (this.isDisposed)
598
- throw new Error("Collection is disposed");
599
- if (!selector)
600
- throw new Error("Invalid selector");
601
- if (!modifier)
602
- throw new Error("Invalid modifier");
603
- const items = this.getItems(selector);
604
- const modifiedItems = [];
605
- items.forEach((item) => {
606
- const { index } = this.getItemAndIndex({ id: item.id });
607
- if (index === -1)
608
- throw new Error("Cannot resolve index for item");
609
- const modifiedItem = modify(deepClone.default(item), modifier);
610
- this.memory().splice(index, 1, modifiedItem);
611
- modifiedItems.push(modifiedItem);
612
- });
613
- this.rebuildIndices();
614
- modifiedItems.forEach((modifiedItem) => {
615
- this.emit("changed", modifiedItem, modifier);
616
- });
617
- this.emit("updateMany", selector, modifier);
618
- this.executeInDebugMode((callstack) => this.emit("_debug.updateMany", callstack, selector, modifier));
619
- return modifiedItems.length;
154
+ setLoading(selector, value) {
155
+ const signal = this.ensureSignal(selector);
156
+ signal.set(value);
620
157
  }
621
158
  /**
622
- * Removes a single item from the collection that matches the given selector.
623
- * @param selector - The criteria to select the item to remove.
624
- * @returns The number of items removed (0 or 1).
625
- * @throws {Error} If the collection is disposed or invalid arguments are provided.
159
+ * Indicates wether a query is currently been loaded
160
+ * ⚡️ this function is reactive!
161
+ * @param selector {Object} Selector of the query
162
+ * @returns The loading state
626
163
  */
627
- removeOne(selector) {
628
- if (this.isDisposed)
629
- throw new Error("Collection is disposed");
630
- if (!selector)
631
- throw new Error("Invalid selector");
632
- const { item, index } = this.getItemAndIndex(selector);
633
- if (item != null) {
634
- this.memory().splice(index, 1);
635
- this.deleteFromIdIndex(item.id, index);
636
- this.rebuildIndices();
637
- this.emit("removed", item);
164
+ isLoading(selector) {
165
+ const isPushing = this.isPushing();
166
+ if (!selector) {
167
+ return this.isFetchingSignal.get() || isPushing;
638
168
  }
639
- this.emit("removeOne", selector);
640
- this.executeInDebugMode((callstack) => this.emit("_debug.removeOne", callstack, selector));
641
- return item == null ? 0 : 1;
169
+ const signal = this.ensureSignal(selector);
170
+ return signal.get() || isPushing;
642
171
  }
643
- /**
644
- * Removes multiple items from the collection that match the given selector.
645
- * @param selector - The criteria to select the items to remove.
646
- * @returns The number of items removed.
647
- * @throws {Error} If the collection is disposed or invalid arguments are provided.
648
- */
649
- removeMany(selector) {
650
- if (this.isDisposed)
651
- throw new Error("Collection is disposed");
652
- if (!selector)
653
- throw new Error("Invalid selector");
654
- const items = this.getItems(selector);
655
- items.forEach((item) => {
656
- const index = this.memory().findIndex((document) => document === item);
657
- if (index === -1)
658
- throw new Error("Cannot resolve index for item");
659
- this.memory().splice(index, 1);
660
- this.deleteFromIdIndex(item.id, index);
661
- this.rebuildIndices();
662
- });
663
- items.forEach((item) => {
664
- this.emit("removed", item);
665
- });
666
- this.emit("removeMany", selector);
667
- this.executeInDebugMode((callstack) => this.emit("_debug.removeMany", callstack, selector));
668
- return items.length;
669
- }
670
- };
671
- __publicField(_Collection, "collections", []);
672
- __publicField(_Collection, "debugMode", false);
673
- __publicField(_Collection, "batchOperationInProgress", false);
674
- __publicField(_Collection, "fieldTracking", false);
675
- __publicField(_Collection, "onCreationCallbacks", []);
676
- __publicField(_Collection, "onDisposeCallbacks", []);
677
- /**
678
- * Enables debug mode for all collections.
679
- */
680
- __publicField(_Collection, "enableDebugMode", () => {
681
- _Collection.debugMode = true;
682
- _Collection.collections.forEach((collection) => {
683
- collection.setDebugMode(true);
684
- });
685
- });
686
- /**
687
- * Enables field tracking for all collections.
688
- * @param enable - A boolean indicating whether to enable field tracking.
689
- */
690
- __publicField(_Collection, "setFieldTracking", (enable) => {
691
- _Collection.fieldTracking = enable;
692
- _Collection.collections.forEach((collection) => {
693
- collection.setFieldTracking(enable);
694
- });
695
- });
696
- let Collection = _Collection;
697
- exports.createIndex = createIndex.default;
698
- exports.default = Collection;
172
+ }
173
+ module.exports = AutoFetchCollection;