@signaldb/core 1.0.0 → 1.2.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 (76) hide show
  1. package/README.md +2 -2
  2. package/dist/.vite/manifest.json +78 -64
  3. package/dist/Collection/index.d.ts +39 -16
  4. package/dist/Collection/types.d.ts +1 -1
  5. package/dist/devtools.d.ts +4 -0
  6. package/dist/index.cjs.js +19 -11
  7. package/dist/index.cjs10.js +27 -6
  8. package/dist/index.cjs11.js +6 -3
  9. package/dist/index.cjs12.js +3 -35
  10. package/dist/index.cjs13.js +141 -16
  11. package/dist/index.cjs14.js +38 -5
  12. package/dist/index.cjs15.js +2 -42
  13. package/dist/index.cjs16.js +5 -11
  14. package/dist/index.cjs17.js +40 -17
  15. package/dist/index.cjs18.js +11 -245
  16. package/dist/index.cjs19.js +16 -67
  17. package/dist/index.cjs2.js +104 -615
  18. package/dist/index.cjs20.js +251 -67
  19. package/dist/index.cjs21.js +68 -8
  20. package/dist/index.cjs22.js +83 -22
  21. package/dist/index.cjs23.js +8 -135
  22. package/dist/index.cjs24.js +25 -16
  23. package/dist/index.cjs25.js +144 -5
  24. package/dist/index.cjs26.js +5 -17
  25. package/dist/index.cjs27.js +15 -21
  26. package/dist/index.cjs28.js +21 -39
  27. package/dist/index.cjs29.js +40 -27
  28. package/dist/index.cjs3.js +669 -136
  29. package/dist/index.cjs30.js +27 -7
  30. package/dist/index.cjs31.js +9 -0
  31. package/dist/index.cjs4.js +166 -63
  32. package/dist/index.cjs5.js +66 -3
  33. package/dist/index.cjs6.js +2 -2
  34. package/dist/index.cjs7.js +2 -2
  35. package/dist/index.cjs8.js +2 -2
  36. package/dist/index.cjs9.js +3 -28
  37. package/dist/index.d.ts +2 -0
  38. package/dist/index.mjs +20 -12
  39. package/dist/index10.mjs +27 -6
  40. package/dist/index11.mjs +6 -3
  41. package/dist/index12.mjs +3 -34
  42. package/dist/index13.mjs +141 -16
  43. package/dist/index14.mjs +37 -5
  44. package/dist/index15.mjs +2 -41
  45. package/dist/index16.mjs +5 -11
  46. package/dist/index17.mjs +39 -17
  47. package/dist/index18.mjs +11 -244
  48. package/dist/index19.mjs +16 -66
  49. package/dist/index2.mjs +80 -615
  50. package/dist/index20.mjs +251 -67
  51. package/dist/index21.mjs +67 -8
  52. package/dist/index22.mjs +82 -22
  53. package/dist/index23.mjs +8 -135
  54. package/dist/index24.mjs +25 -15
  55. package/dist/index25.mjs +144 -5
  56. package/dist/index26.mjs +5 -17
  57. package/dist/index27.mjs +15 -21
  58. package/dist/index28.mjs +21 -39
  59. package/dist/index29.mjs +40 -27
  60. package/dist/index3.mjs +669 -136
  61. package/dist/index30.mjs +27 -7
  62. package/dist/index31.mjs +10 -0
  63. package/dist/index4.mjs +166 -62
  64. package/dist/index5.mjs +65 -3
  65. package/dist/index6.mjs +2 -2
  66. package/dist/index7.mjs +2 -2
  67. package/dist/index8.mjs +2 -2
  68. package/dist/index9.mjs +3 -28
  69. package/dist/persistence/combinePersistenceAdapters.d.ts +7 -7
  70. package/dist/types/MemoryAdapter.d.ts +2 -2
  71. package/dist/utils/EventEmitter.d.ts +75 -0
  72. package/dist/utils/deepClone.d.ts +2 -2
  73. package/dist/utils/set.d.ts +2 -2
  74. package/dist/utils/uniqueBy.d.ts +2 -2
  75. package/package.json +1 -1
  76. package/dist/types/EventEmitter.d.ts +0 -25
@@ -1,165 +1,698 @@
1
1
  "use strict";
2
- const ReplicatedCollection = require("./index.cjs20.js");
3
- const createSignal = require("./index.cjs17.js");
4
- class AutoFetchCollection extends ReplicatedCollection.default {
2
+ var __defProp = Object.defineProperty;
3
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
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
40
  /**
6
- * @param options {Object} - Options for the collection.
7
- * @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.
8
- * @param options.purgeDelay {Number} - The delay in milliseconds before purging an item from the cache.
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
55
  */
10
56
  constructor(options) {
11
- var _a, _b, _c, _d;
12
- let triggerRemoteChange;
13
- super(Object.assign(Object.assign({}, options), { pull: () => Promise.resolve({
14
- items: [...this.itemsCache.values()].reduce((memo, items) => {
15
- const newItems = [...memo];
16
- items.forEach((item) => {
17
- const index = newItems.findIndex((i) => i.id === item.id);
18
- if (index === -1) {
19
- newItems.push(item);
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)
20
112
  return;
21
- }
22
- newItems[index] = this.mergeItems(newItems[index], item);
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);
123
+ return;
124
+ }
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);
140
+ });
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");
23
178
  });
24
- return newItems;
25
- }, [])
26
- }), registerRemoteChange: async (onChange) => {
27
- triggerRemoteChange = onChange;
28
- return Promise.resolve();
29
- } }));
30
- this.activeObservers = /* @__PURE__ */ new Map();
31
- this.observerTimeouts = /* @__PURE__ */ new Map();
32
- this.idQueryCache = /* @__PURE__ */ new Map();
33
- this.itemsCache = /* @__PURE__ */ new Map();
34
- this.triggerReload = null;
35
- this.reactivityAdapter = null;
36
- this.loadingSignals = /* @__PURE__ */ new Map();
37
- this.mergeItems = (_a = options.mergeItems) !== null && _a !== void 0 ? _a : (itemA, itemB) => Object.assign(Object.assign({}, itemA), itemB);
38
- this.purgeDelay = (_b = options.purgeDelay) !== null && _b !== void 0 ? _b : 1e4;
39
- this.isFetchingSignal = createSignal((_c = options.reactivity) === null || _c === void 0 ? void 0 : _c.create(), false);
40
- if (!triggerRemoteChange)
41
- throw new Error("No triggerRemoteChange method found. Looks like your persistence adapter was not registered");
42
- this.triggerReload = triggerRemoteChange;
43
- this.reactivityAdapter = (_d = options.reactivity) !== null && _d !== void 0 ? _d : null;
44
- this.fetchQueryItems = options.fetchQueryItems;
45
- this.on("observer.created", (selector) => this.handleObserverCreation(selector !== null && selector !== void 0 ? selector : {}));
46
- this.on("observer.disposed", (selector) => setTimeout(() => this.handleObserverDisposal(selector !== null && selector !== void 0 ? selector : {}), 100));
47
- if (options.registerRemoteChange) {
48
- void options.registerRemoteChange(() => this.forceRefetch());
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
+ });
49
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);
230
+ });
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);
50
241
  }
51
242
  /**
52
- * Registers a query manually that items should be fetched for it
53
- * @param selector {Object} Selector of the query
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.
54
248
  */
55
- registerQuery(selector) {
56
- this.handleObserverCreation(selector);
249
+ static batch(callback) {
250
+ _Collection.batchOperationInProgress = true;
251
+ _Collection.collections.reduce((memo, collection) => () => collection.batch(() => memo()), callback)();
252
+ _Collection.batchOperationInProgress = false;
57
253
  }
58
254
  /**
59
- * Unregisters a query manually that items are not fetched anymore for it
60
- * @param selector {Object} Selector of the query
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.
61
259
  */
62
- unregisterQuery(selector) {
63
- this.handleObserverDisposal(selector);
260
+ isPulling() {
261
+ return this.isPullingSignal.get() ?? false;
64
262
  }
65
- // eslint-disable-next-line class-methods-use-this
66
- getKeyForSelector(selector) {
67
- return JSON.stringify(selector);
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;
68
271
  }
69
- async forceRefetch() {
70
- return Promise.all([...this.activeObservers.values()].map(({ selector }) => this.fetchSelector(selector))).then(() => {
71
- });
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;
72
282
  }
73
- fetchSelector(selector) {
74
- this.isFetchingSignal.set(true);
75
- return this.fetchQueryItems(selector).then((response) => {
76
- if (!response.items)
77
- throw new Error("AutoFetchCollection currently only works with a full item response");
78
- this.itemsCache.set(this.getKeyForSelector(selector), response.items);
79
- response.items.forEach((item) => {
80
- var _a;
81
- const queries = (_a = this.idQueryCache.get(item.id)) !== null && _a !== void 0 ? _a : [];
82
- queries.push(selector);
83
- this.idQueryCache.set(item.id, queries);
84
- });
85
- this.setLoading(selector, true);
86
- this.once("persistence.received", () => {
87
- this.setLoading(selector, false);
88
- });
89
- if (!this.triggerReload)
90
- throw new Error("No triggerReload method found. Looks like your persistence adapter was not registered");
91
- void this.triggerReload();
92
- }).catch((error) => {
93
- this.emit("persistence.error", error);
94
- }).finally(() => {
95
- this.isFetchingSignal.set(false);
96
- });
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;
97
289
  }
98
- handleObserverCreation(selector) {
99
- var _a, _b;
100
- const activeObservers = (_b = (_a = this.activeObservers.get(this.getKeyForSelector(selector))) === null || _a === void 0 ? void 0 : _a.count) !== null && _b !== void 0 ? _b : 0;
101
- this.activeObservers.set(this.getKeyForSelector(selector), {
102
- selector,
103
- count: activeObservers + 1
104
- });
105
- const timeout = this.observerTimeouts.get(this.getKeyForSelector(selector));
106
- if (timeout)
107
- clearTimeout(timeout);
108
- if (activeObservers === 0)
109
- void this.fetchSelector(selector);
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;
110
297
  }
111
- handleObserverDisposal(selector) {
112
- var _a, _b;
113
- const currentObservers = (_b = (_a = this.activeObservers.get(this.getKeyForSelector(selector))) === null || _a === void 0 ? void 0 : _a.count) !== null && _b !== void 0 ? _b : 0;
114
- const activeObservers = currentObservers - 1;
115
- if (activeObservers > 0) {
116
- this.activeObservers.set(this.getKeyForSelector(selector), {
117
- selector,
118
- count: activeObservers
119
- });
298
+ /**
299
+ * Enables or disables field tracking for the collection.
300
+ * @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) field tracking.
301
+ */
302
+ setFieldTracking(enable) {
303
+ this.fieldTracking = enable;
304
+ }
305
+ /**
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' })
317
+ */
318
+ async isReady() {
319
+ return this.persistenceReadyPromise;
320
+ }
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;
329
+ }
330
+ executeInDebugMode(fn) {
331
+ if (!this.debugMode)
120
332
  return;
121
- }
122
- const timeout = this.observerTimeouts.get(this.getKeyForSelector(selector));
123
- if (timeout)
124
- clearTimeout(timeout);
125
- const removeObserver = () => {
126
- this.activeObservers.delete(this.getKeyForSelector(selector));
127
- this.itemsCache.delete(this.getKeyForSelector(selector));
128
- if (!this.triggerReload)
129
- throw new Error("No triggerReload method found. Looks like your persistence adapter was not registered");
130
- void this.triggerReload();
131
- };
132
- if (this.purgeDelay === 0) {
133
- removeObserver();
333
+ const callstack = new Error().stack || "";
334
+ fn(callstack);
335
+ }
336
+ rebuildIndices() {
337
+ this.indicesOutdated = true;
338
+ if (this.batchOperationInProgress)
134
339
  return;
135
- }
136
- this.observerTimeouts.set(this.getKeyForSelector(selector), setTimeout(removeObserver, this.purgeDelay));
340
+ this.rebuildAllIndices();
137
341
  }
138
- ensureSignal(selector) {
139
- if (!this.reactivityAdapter)
140
- throw new Error("No reactivity adapter found");
141
- if (!this.loadingSignals.has(this.getKeyForSelector(selector))) {
142
- this.loadingSignals.set(this.getKeyForSelector(selector), createSignal(this.reactivityAdapter.create(), false));
342
+ rebuildAllIndices() {
343
+ this.idIndex.clear();
344
+ this.memory().map((item, index) => {
345
+ this.idIndex.set(serializeValue(item.id), /* @__PURE__ */ new Set([index]));
346
+ });
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
+ };
143
357
  }
144
- return this.loadingSignals.get(this.getKeyForSelector(selector));
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
+ }
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
+ }
388
+ });
145
389
  }
146
- setLoading(selector, value) {
147
- const signal = this.ensureSignal(selector);
148
- signal.set(value);
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() {
426
+ 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));
149
437
  }
150
438
  /**
151
- * Indicates wether a query is currently been loaded
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
+ }
477
+ });
478
+ this.emit("find", selector, options, cursor);
479
+ this.executeInDebugMode((callstack) => this.emit("_debug.find", callstack, selector, options, cursor));
480
+ return cursor;
481
+ }
482
+ /**
483
+ * Finds a single item in the collection based on a selector and optional options.
152
484
  * ⚡️ this function is reactive!
153
- * @param selector {Object} Selector of the query
154
- * @returns The loading state
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`.
155
490
  */
156
- isLoading(selector) {
157
- const isPushing = this.isPushing();
158
- if (!selector) {
159
- return this.isFetchingSignal.get() || isPushing;
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 [];
160
552
  }
161
- const signal = this.ensureSignal(selector);
162
- return signal.get() || isPushing;
553
+ const ids = [];
554
+ this.batch(() => {
555
+ items.forEach((item) => {
556
+ ids.push(this.insert(item));
557
+ });
558
+ });
559
+ return ids;
163
560
  }
164
- }
165
- module.exports = AutoFetchCollection;
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;
588
+ }
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;
620
+ }
621
+ /**
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.
626
+ */
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);
638
+ }
639
+ this.emit("removeOne", selector);
640
+ this.executeInDebugMode((callstack) => this.emit("_debug.removeOne", callstack, selector));
641
+ return item == null ? 0 : 1;
642
+ }
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;