@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
@@ -1,111 +1,703 @@
1
1
  "use strict";
2
- const index = require("./index.cjs3.js");
3
- var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null;
4
- const _interopNamespaceDefaultOnly = (e) => Object.freeze(Object.defineProperty({ __proto__: null, default: e }, Symbol.toStringTag, { value: "Module" }));
5
- /* istanbul ignore file -- @preserve */
6
- const devtoolsInProductionWarning = `
7
-
8
-
9
- [@signaldb/core] !! WARNING !!
10
- You are running @signaldb/devtools in production mode.
11
- This can have a negative impact on performance and may expose sensitive information.
12
- Please move @signaldb/devtools to development dependencies to disable it in production.
13
-
14
-
15
- `;
16
- const packageName = "@signaldb/devtools";
17
- function isNodeErrorWithCode(error) {
18
- return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string";
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.cjs12.js");
7
+ const match = require("./index.cjs14.js");
8
+ const modify = require("./index.cjs10.js");
9
+ const isEqual = require("./index.cjs9.js");
10
+ const randomId = require("./index.cjs11.js");
11
+ const deepClone = require("./index.cjs15.js");
12
+ const serializeValue = require("./index.cjs16.js");
13
+ const createSignal = require("./index.cjs17.js");
14
+ const Cursor = require("./index.cjs18.js");
15
+ const getIndexInfo = require("./index.cjs19.js");
16
+ const createIndex = require("./index.cjs13.js");
17
+ function hasPendingUpdates(pendingUpdates) {
18
+ return pendingUpdates.added.length > 0 || pendingUpdates.modified.length > 0 || pendingUpdates.removed.length > 0;
19
19
  }
20
- function isFailedDevToolsImportError(error) {
21
- if (isNodeErrorWithCode(error)) {
22
- return error.code === "MODULE_NOT_FOUND";
23
- }
24
- return error.name === "TypeError" && error.message.includes("Failed to resolve module specifier") && error.message.includes(packageName);
25
- }
26
- function isCommonJS() {
27
- return typeof module !== "undefined" && !!module.exports;
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;
28
38
  }
29
- async function checkDevtoolsAvailability() {
30
- if (typeof window === "undefined") {
31
- return false;
32
- }
33
- if (isCommonJS()) {
34
- try {
35
- require.resolve(packageName);
36
- return true;
37
- } catch {
38
- return false;
39
+ const _Collection = class _Collection extends EventEmitter {
40
+ /**
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.
55
+ */
56
+ 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);
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");
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
+ });
39
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);
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;
297
+ }
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)
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();
40
341
  }
41
- try {
42
- await import(
43
- /* @vite-ignore */
44
- packageName
45
- );
46
- return true;
47
- } catch (error) {
48
- if (!isFailedDevToolsImportError(error)) {
49
- throw error;
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
+ };
357
+ }
358
+ if (selector == null || this.indicesOutdated) {
359
+ return {
360
+ matched: false,
361
+ positions: [],
362
+ optimizedSelector: {}
363
+ };
50
364
  }
365
+ return getIndexInfo.default(this.indexProviders, selector);
51
366
  }
52
- try {
53
- const modulePackage = await Promise.resolve().then(() => /* @__PURE__ */ _interopNamespaceDefaultOnly(require("./index.cjs15.js")));
54
- const createRequireFunction = modulePackage.default.createRequire;
55
- const cjsRequire = createRequireFunction(typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs2.js", document.baseURI).href);
56
- cjsRequire.resolve(packageName);
57
- return true;
58
- } catch {
59
- return false;
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 };
60
379
  }
61
- }
62
- async function checkAndImportDevtools() {
63
- const available = await checkDevtoolsAvailability();
64
- if (!available)
65
- return false;
66
- if (isCommonJS()) {
67
- try {
68
- require(packageName);
69
- return true;
70
- } catch (error) {
71
- if (isFailedDevToolsImportError(error)) {
72
- return false;
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]));
73
387
  }
74
- throw error;
75
- }
388
+ });
389
+ }
390
+ memory() {
391
+ return this.options.memory;
76
392
  }
77
- try {
78
- await import(
79
- /* @vite-ignore */
80
- packageName
81
- );
82
- return true;
83
- } catch (error) {
84
- if (!isNodeErrorWithCode(error) || error.code !== "MODULE_NOT_FOUND") {
85
- throw error;
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
+ this.emit("getItems", selector);
413
+ const memory = this.memoryArray();
414
+ if (!indexInfo.matched) {
415
+ if (isEqual(selector, {}))
416
+ return memory;
417
+ return memory.filter(matchItems);
418
+ }
419
+ const items = indexInfo.positions.map((index) => memory[index]);
420
+ if (isEqual(indexInfo.optimizedSelector, {}))
421
+ return items;
422
+ return items.filter(matchItems);
423
+ }, (measuredTime) => this.executeInDebugMode((callstack) => this.emit("_debug.getItems", callstack, selector, measuredTime)));
424
+ }
425
+ /**
426
+ * Disposes the collection, unregisters persistence adapters, clears memory, and
427
+ * cleans up all resources used by the collection.
428
+ * @returns A promise that resolves when the collection is disposed.
429
+ */
430
+ async dispose() {
431
+ var _a;
432
+ if ((_a = this.persistenceAdapter) == null ? void 0 : _a.unregister)
433
+ await this.persistenceAdapter.unregister();
434
+ this.persistenceAdapter = null;
435
+ this.memory().map(() => this.memory().pop());
436
+ this.idIndex.clear();
437
+ this.indexProviders = [];
438
+ this.isDisposed = true;
439
+ this.removeAllListeners();
440
+ _Collection.collections = _Collection.collections.filter((collection) => collection !== this);
441
+ _Collection.onDisposeCallbacks.forEach((callback) => callback(this));
442
+ }
443
+ /**
444
+ * Finds multiple items in the collection based on a selector and optional options.
445
+ * Returns a cursor for reactive data queries.
446
+ * @template O - The options type for the find operation.
447
+ * @param [selector] - The criteria to select items.
448
+ * @param [options] - Options for the find operation, such as limit and sort.
449
+ * @returns A cursor to fetch and observe the matching items.
450
+ */
451
+ find(selector, options) {
452
+ if (this.isDisposed)
453
+ throw new Error("Collection is disposed");
454
+ if (selector !== void 0 && (!selector || typeof selector !== "object"))
455
+ throw new Error("Invalid selector");
456
+ const cursor = new Cursor.default(() => this.getItems(selector), {
457
+ reactive: this.options.reactivity,
458
+ fieldTracking: this.fieldTracking,
459
+ ...options,
460
+ transform: this.transform.bind(this),
461
+ bindEvents: (requery) => {
462
+ const handleRequery = () => {
463
+ if (this.batchOperationInProgress) {
464
+ this.postBatchCallbacks.add(requery);
465
+ return;
466
+ }
467
+ requery();
468
+ };
469
+ this.addListener("persistence.received", handleRequery);
470
+ this.addListener("added", handleRequery);
471
+ this.addListener("changed", handleRequery);
472
+ this.addListener("removed", handleRequery);
473
+ this.emit("observer.created", selector, options);
474
+ return () => {
475
+ this.removeListener("persistence.received", handleRequery);
476
+ this.removeListener("added", handleRequery);
477
+ this.removeListener("changed", handleRequery);
478
+ this.removeListener("removed", handleRequery);
479
+ this.emit("observer.disposed", selector, options);
480
+ };
481
+ }
482
+ });
483
+ this.emit("find", selector, options, cursor);
484
+ this.executeInDebugMode((callstack) => this.emit("_debug.find", callstack, selector, options, cursor));
485
+ return cursor;
486
+ }
487
+ /**
488
+ * Finds a single item in the collection based on a selector and optional options.
489
+ * ⚡️ this function is reactive!
490
+ * Returns the found item or undefined if no item matches.
491
+ * @template O - The options type for the find operation.
492
+ * @param selector - The criteria to select the item.
493
+ * @param [options] - Options for the find operation, such as projection.
494
+ * @returns The found item or `undefined`.
495
+ */
496
+ findOne(selector, options) {
497
+ if (this.isDisposed)
498
+ throw new Error("Collection is disposed");
499
+ const cursor = this.find(selector, {
500
+ limit: 1,
501
+ ...options
502
+ });
503
+ const returnValue = cursor.fetch()[0] || void 0;
504
+ this.emit("findOne", selector, options, returnValue);
505
+ this.executeInDebugMode((callstack) => this.emit("_debug.findOne", callstack, selector, options, returnValue));
506
+ return returnValue;
507
+ }
508
+ /**
509
+ * Performs a batch operation, deferring index rebuilds and allowing multiple
510
+ * modifications to be made atomically. Executes any post-batch callbacks afterwards.
511
+ * @param callback - The batch operation to execute.
512
+ */
513
+ batch(callback) {
514
+ this.batchOperationInProgress = true;
515
+ callback();
516
+ this.batchOperationInProgress = false;
517
+ this.rebuildAllIndices();
518
+ this.postBatchCallbacks.forEach((callback_) => callback_());
519
+ this.postBatchCallbacks.clear();
520
+ }
521
+ /**
522
+ * Inserts a single item into the collection. Generates a unique ID if not provided.
523
+ * @param item - The item to insert.
524
+ * @returns The ID of the inserted item.
525
+ * @throws {Error} If the collection is disposed or the item has an invalid ID.
526
+ */
527
+ insert(item) {
528
+ if (this.isDisposed)
529
+ throw new Error("Collection is disposed");
530
+ if (!item)
531
+ throw new Error("Invalid item");
532
+ const newItem = { id: randomId(), ...item };
533
+ if (this.idIndex.has(serializeValue(newItem.id)))
534
+ throw new Error("Item with same id already exists");
535
+ this.memory().push(newItem);
536
+ const itemIndex = this.memory().findIndex((document) => document === newItem);
537
+ this.idIndex.set(serializeValue(newItem.id), /* @__PURE__ */ new Set([itemIndex]));
538
+ this.rebuildIndices();
539
+ this.emit("added", newItem);
540
+ this.emit("insert", newItem);
541
+ this.executeInDebugMode((callstack) => this.emit("_debug.insert", callstack, newItem));
542
+ return newItem.id;
543
+ }
544
+ /**
545
+ * Inserts multiple items into the collection. Generates unique IDs for items if not provided.
546
+ * @param items - The items to insert.
547
+ * @returns An array of IDs of the inserted items.
548
+ * @throws {Error} If the collection is disposed or the items are invalid.
549
+ */
550
+ insertMany(items) {
551
+ if (this.isDisposed)
552
+ throw new Error("Collection is disposed");
553
+ if (!items)
554
+ throw new Error("Invalid items");
555
+ if (items.length === 0) {
556
+ return [];
86
557
  }
558
+ const ids = [];
559
+ this.batch(() => {
560
+ items.forEach((item) => {
561
+ ids.push(this.insert(item));
562
+ });
563
+ });
564
+ return ids;
565
+ }
566
+ /**
567
+ * Updates a single item in the collection that matches the given selector.
568
+ * @param selector - The criteria to select the item to update.
569
+ * @param modifier - The modifications to apply to the item.
570
+ * @returns The number of items updated (0 or 1).
571
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
572
+ */
573
+ updateOne(selector, modifier) {
574
+ if (this.isDisposed)
575
+ throw new Error("Collection is disposed");
576
+ if (!selector)
577
+ throw new Error("Invalid selector");
578
+ if (!modifier)
579
+ throw new Error("Invalid modifier");
580
+ const { item, index } = this.getItemAndIndex(selector);
581
+ if (item == null)
582
+ return 0;
583
+ const modifiedItem = modify(deepClone.default(item), modifier);
584
+ const existingItem = this.findOne({ id: modifiedItem.id }, { reactive: false });
585
+ if (!isEqual(existingItem, { ...existingItem, id: modifiedItem.id }))
586
+ throw new Error("Item with same id already exists");
587
+ this.memory().splice(index, 1, modifiedItem);
588
+ this.rebuildIndices();
589
+ this.emit("changed", modifiedItem, modifier);
590
+ this.emit("updateOne", selector, modifier);
591
+ this.executeInDebugMode((callstack) => this.emit("_debug.updateOne", callstack, selector, modifier));
592
+ return 1;
593
+ }
594
+ /**
595
+ * Updates multiple items in the collection that match the given selector.
596
+ * @param selector - The criteria to select the items to update.
597
+ * @param modifier - The modifications to apply to the items.
598
+ * @returns The number of items updated.
599
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
600
+ */
601
+ updateMany(selector, modifier) {
602
+ if (this.isDisposed)
603
+ throw new Error("Collection is disposed");
604
+ if (!selector)
605
+ throw new Error("Invalid selector");
606
+ if (!modifier)
607
+ throw new Error("Invalid modifier");
608
+ const items = this.getItems(selector);
609
+ const modifiedItems = [];
610
+ items.forEach((item) => {
611
+ const { index } = this.getItemAndIndex({ id: item.id });
612
+ if (index === -1)
613
+ throw new Error("Cannot resolve index for item");
614
+ const modifiedItem = modify(deepClone.default(item), modifier);
615
+ this.memory().splice(index, 1, modifiedItem);
616
+ modifiedItems.push(modifiedItem);
617
+ });
618
+ this.rebuildIndices();
619
+ modifiedItems.forEach((modifiedItem) => {
620
+ this.emit("changed", modifiedItem, modifier);
621
+ });
622
+ this.emit("updateMany", selector, modifier);
623
+ this.executeInDebugMode((callstack) => this.emit("_debug.updateMany", callstack, selector, modifier));
624
+ return modifiedItems.length;
87
625
  }
88
- try {
89
- const modulePackage = await Promise.resolve().then(() => /* @__PURE__ */ _interopNamespaceDefaultOnly(require("./index.cjs15.js")));
90
- const createRequireFunction = modulePackage.default.createRequire;
91
- const cjsRequire = createRequireFunction(typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs2.js", document.baseURI).href);
92
- cjsRequire(packageName);
93
- return true;
94
- } catch (error) {
95
- if (isNodeErrorWithCode(error) && error.code === "MODULE_NOT_FOUND") {
96
- return false;
626
+ /**
627
+ * Removes a single item from the collection that matches the given selector.
628
+ * @param selector - The criteria to select the item to remove.
629
+ * @returns The number of items removed (0 or 1).
630
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
631
+ */
632
+ removeOne(selector) {
633
+ if (this.isDisposed)
634
+ throw new Error("Collection is disposed");
635
+ if (!selector)
636
+ throw new Error("Invalid selector");
637
+ const { item, index } = this.getItemAndIndex(selector);
638
+ if (item != null) {
639
+ this.memory().splice(index, 1);
640
+ this.deleteFromIdIndex(item.id, index);
641
+ this.rebuildIndices();
642
+ this.emit("removed", item);
97
643
  }
98
- throw error;
644
+ this.emit("removeOne", selector);
645
+ this.executeInDebugMode((callstack) => this.emit("_debug.removeOne", callstack, selector));
646
+ return item == null ? 0 : 1;
99
647
  }
100
- }
101
- function loadDeveloperTools() {
102
- const isProduction = process.env.NODE_ENV === "production";
103
- void checkAndImportDevtools().then((devtoolsLoaded) => {
104
- if (!devtoolsLoaded)
105
- return;
106
- index.default.enableDebugMode();
107
- if (isProduction)
108
- console.warn(devtoolsInProductionWarning);
648
+ /**
649
+ * Removes multiple items from the collection that match the given selector.
650
+ * @param selector - The criteria to select the items to remove.
651
+ * @returns The number of items removed.
652
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
653
+ */
654
+ removeMany(selector) {
655
+ if (this.isDisposed)
656
+ throw new Error("Collection is disposed");
657
+ if (!selector)
658
+ throw new Error("Invalid selector");
659
+ const items = this.getItems(selector);
660
+ items.forEach((item) => {
661
+ const index = this.memory().findIndex((document) => document === item);
662
+ if (index === -1)
663
+ throw new Error("Cannot resolve index for item");
664
+ this.memory().splice(index, 1);
665
+ this.deleteFromIdIndex(item.id, index);
666
+ this.rebuildIndices();
667
+ });
668
+ items.forEach((item) => {
669
+ this.emit("removed", item);
670
+ });
671
+ this.emit("removeMany", selector);
672
+ this.executeInDebugMode((callstack) => this.emit("_debug.removeMany", callstack, selector));
673
+ return items.length;
674
+ }
675
+ };
676
+ __publicField(_Collection, "collections", []);
677
+ __publicField(_Collection, "debugMode", false);
678
+ __publicField(_Collection, "batchOperationInProgress", false);
679
+ __publicField(_Collection, "fieldTracking", false);
680
+ __publicField(_Collection, "onCreationCallbacks", []);
681
+ __publicField(_Collection, "onDisposeCallbacks", []);
682
+ /**
683
+ * Enables debug mode for all collections.
684
+ */
685
+ __publicField(_Collection, "enableDebugMode", () => {
686
+ _Collection.debugMode = true;
687
+ _Collection.collections.forEach((collection) => {
688
+ collection.setDebugMode(true);
109
689
  });
110
- }
111
- module.exports = loadDeveloperTools;
690
+ });
691
+ /**
692
+ * Enables field tracking for all collections.
693
+ * @param enable - A boolean indicating whether to enable field tracking.
694
+ */
695
+ __publicField(_Collection, "setFieldTracking", (enable) => {
696
+ _Collection.fieldTracking = enable;
697
+ _Collection.collections.forEach((collection) => {
698
+ collection.setFieldTracking(enable);
699
+ });
700
+ });
701
+ let Collection = _Collection;
702
+ exports.createIndex = createIndex.default;
703
+ exports.default = Collection;