@signaldb/core 2.0.0-beta.2 → 2.0.0-beta.21

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 (145) hide show
  1. package/dist/.vite/manifest.json +183 -80
  2. package/dist/AsyncDataAdapter.d.ts +53 -7
  3. package/dist/AutoFetchDataAdapter.d.ts +4 -6
  4. package/dist/Collection/Cursor.d.ts +56 -4
  5. package/dist/Collection/Observer.d.ts +33 -0
  6. package/dist/Collection/index.d.ts +66 -19
  7. package/dist/Collection/types.d.ts +9 -2
  8. package/dist/DataAdapter.d.ts +24 -6
  9. package/dist/DefaultDataAdapter.d.ts +5 -5
  10. package/dist/WorkerDataAdapter.d.ts +57 -5
  11. package/dist/WorkerDataAdapterHost.d.ts +9 -7
  12. package/dist/createIndex.d.ts +2 -2
  13. package/dist/createIndexProvider.d.ts +2 -2
  14. package/dist/createReactivityAdapter.d.ts +2 -2
  15. package/dist/createStorageAdapter.d.ts +1 -1
  16. package/dist/getIndexInfo.d.ts +3 -4
  17. package/dist/index.cjs.js +33 -31
  18. package/dist/index.d.ts +6 -1
  19. package/dist/index.mjs +17 -32
  20. package/dist/index10.cjs.js +11 -0
  21. package/dist/index10.mjs +10 -18
  22. package/dist/index11.cjs.js +23 -0
  23. package/dist/index11.mjs +22 -15
  24. package/dist/index12.cjs.js +45 -0
  25. package/dist/index12.mjs +44 -353
  26. package/dist/index13.cjs.js +22 -0
  27. package/dist/index13.mjs +21 -419
  28. package/dist/index14.cjs.js +45 -0
  29. package/dist/index14.mjs +44 -206
  30. package/dist/index15.cjs.js +86 -0
  31. package/dist/index15.mjs +85 -388
  32. package/dist/index16.cjs.js +15 -0
  33. package/dist/index16.mjs +14 -579
  34. package/dist/index17.cjs.js +141 -0
  35. package/dist/index17.mjs +140 -152
  36. package/dist/index18.cjs.js +47 -0
  37. package/dist/index18.mjs +46 -26
  38. package/dist/index19.cjs.js +15 -0
  39. package/dist/index19.mjs +14 -41
  40. package/dist/index2.cjs.js +33 -0
  41. package/dist/index2.mjs +32 -258
  42. package/dist/index20.cjs.js +23 -0
  43. package/dist/index20.mjs +22 -16
  44. package/dist/index21.cjs.js +37 -0
  45. package/dist/index21.mjs +36 -104
  46. package/dist/index22.cjs.js +35 -0
  47. package/dist/index22.mjs +34 -128
  48. package/dist/index23.cjs.js +21 -0
  49. package/dist/index23.mjs +20 -7
  50. package/dist/index24.cjs.js +19 -0
  51. package/dist/index24.mjs +18 -27
  52. package/dist/index25.cjs.js +157 -0
  53. package/dist/index25.mjs +156 -11
  54. package/dist/index26.cjs.js +38 -0
  55. package/dist/index26.mjs +37 -29
  56. package/dist/index27.cjs.js +42 -0
  57. package/dist/index27.mjs +41 -46
  58. package/dist/index28.cjs.js +347 -0
  59. package/dist/index28.mjs +345 -7
  60. package/dist/index29.cjs.js +602 -0
  61. package/dist/index29.mjs +601 -7
  62. package/dist/index3.cjs.js +19 -0
  63. package/dist/index3.mjs +18 -556
  64. package/dist/index30.cjs.js +11 -0
  65. package/dist/index30.mjs +10 -42
  66. package/dist/index31.cjs.js +11 -0
  67. package/dist/index31.mjs +10 -29
  68. package/dist/index32.cjs.js +90 -0
  69. package/dist/index32.mjs +89 -10
  70. package/dist/index33.cjs.js +53 -0
  71. package/dist/index33.mjs +52 -5
  72. package/dist/index34.cjs.js +453 -0
  73. package/dist/index34.mjs +453 -0
  74. package/dist/index35.cjs.js +72 -0
  75. package/dist/index35.mjs +72 -0
  76. package/dist/index36.cjs.js +580 -0
  77. package/dist/index36.mjs +580 -0
  78. package/dist/index37.cjs.js +21 -0
  79. package/dist/index37.mjs +21 -0
  80. package/dist/index38.cjs.js +363 -0
  81. package/dist/index38.mjs +363 -0
  82. package/dist/index39.cjs.js +513 -0
  83. package/dist/index39.mjs +513 -0
  84. package/dist/index4.cjs.js +209 -0
  85. package/dist/index4.mjs +204 -5
  86. package/dist/index5.cjs.js +187 -0
  87. package/dist/index5.mjs +186 -5
  88. package/dist/index6.cjs.js +303 -0
  89. package/dist/index6.mjs +301 -28
  90. package/dist/index7.cjs.js +125 -0
  91. package/dist/index7.mjs +124 -12
  92. package/dist/index8.cjs.js +33 -0
  93. package/dist/index8.mjs +32 -5
  94. package/dist/index9.cjs.js +12 -0
  95. package/dist/index9.mjs +11 -133
  96. package/dist/types/IndexProvider.d.ts +2 -2
  97. package/dist/types/Modifier.d.ts +1 -1
  98. package/dist/types/ReactivityAdapter.d.ts +1 -1
  99. package/dist/types/StorageAdapter.d.ts +9 -1
  100. package/dist/utils/applyQueryOptions.d.ts +15 -0
  101. package/dist/utils/createSignal.d.ts +2 -2
  102. package/dist/utils/getMatchingKeys.d.ts +2 -2
  103. package/dist/utils/idIndexQuery.d.ts +20 -0
  104. package/dist/utils/incrementalQueryUpdate.d.ts +62 -0
  105. package/dist/utils/isFieldExpression.d.ts +1 -1
  106. package/dist/utils/match.d.ts +1 -1
  107. package/dist/utils/modify.d.ts +1 -1
  108. package/dist/utils/projectItems.d.ts +12 -0
  109. package/dist/utils/queryDelta.d.ts +83 -0
  110. package/dist/utils/queryId.d.ts +2 -2
  111. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  112. package/dist/utils/storageIndexQuery.d.ts +20 -0
  113. package/package.json +1 -1
  114. package/dist/index.cjs10.js +0 -18
  115. package/dist/index.cjs11.js +0 -15
  116. package/dist/index.cjs12.js +0 -353
  117. package/dist/index.cjs13.js +0 -419
  118. package/dist/index.cjs14.js +0 -206
  119. package/dist/index.cjs15.js +0 -388
  120. package/dist/index.cjs16.js +0 -579
  121. package/dist/index.cjs17.js +0 -152
  122. package/dist/index.cjs18.js +0 -26
  123. package/dist/index.cjs19.js +0 -42
  124. package/dist/index.cjs2.js +0 -259
  125. package/dist/index.cjs20.js +0 -16
  126. package/dist/index.cjs21.js +0 -104
  127. package/dist/index.cjs22.js +0 -129
  128. package/dist/index.cjs23.js +0 -7
  129. package/dist/index.cjs24.js +0 -27
  130. package/dist/index.cjs25.js +0 -10
  131. package/dist/index.cjs26.js +0 -29
  132. package/dist/index.cjs27.js +0 -46
  133. package/dist/index.cjs28.js +0 -8
  134. package/dist/index.cjs29.js +0 -7
  135. package/dist/index.cjs3.js +0 -557
  136. package/dist/index.cjs30.js +0 -42
  137. package/dist/index.cjs31.js +0 -29
  138. package/dist/index.cjs32.js +0 -9
  139. package/dist/index.cjs33.js +0 -5
  140. package/dist/index.cjs4.js +0 -5
  141. package/dist/index.cjs5.js +0 -5
  142. package/dist/index.cjs6.js +0 -29
  143. package/dist/index.cjs7.js +0 -12
  144. package/dist/index.cjs8.js +0 -5
  145. package/dist/index.cjs9.js +0 -133
@@ -0,0 +1,602 @@
1
+ const require_Cursor = require("./index6.cjs.js");
2
+ const require_EventEmitter = require("./index7.cjs.js");
3
+ const require_createSignal = require("./index8.cjs.js");
4
+ const require_randomId = require("./index9.cjs.js");
5
+ require("./index15.cjs.js");
6
+ const require_deepClone = require("./index18.cjs.js");
7
+ const require_modify = require("./index20.cjs.js");
8
+ const require_queryId = require("./index26.cjs.js");
9
+ const require_DefaultDataAdapter = require("./index28.cjs.js");
10
+ //#region src/Collection/index.ts
11
+ /**
12
+ * Represents a collection of data items with support for in-memory operations,
13
+ * persistence, reactivity, and event-based notifications. The collection provides
14
+ * CRUD operations, observer patterns, and batch operations.
15
+ * @template T - The type of the items stored in the collection.
16
+ * @template I - The type of the unique identifier for the items.
17
+ * @template U - The transformed item type after applying transformations (default is T).
18
+ */
19
+ var Collection = class Collection extends require_EventEmitter.default {
20
+ static collections = [];
21
+ static debugMode = false;
22
+ static batchOperationInProgress = false;
23
+ static fieldTracking = false;
24
+ static onCreationCallbacks = [];
25
+ static onDisposeCallbacks = [];
26
+ static largeQueryWarningThreshold = null;
27
+ static reportedLargeQueries = /* @__PURE__ */ new Set();
28
+ static getCollections() {
29
+ return Collection.collections;
30
+ }
31
+ /**
32
+ * Reports live queries whose result is larger than `rows`, once each, with
33
+ * the stack that registered them.
34
+ *
35
+ * A reactive query is re-evaluated whenever the data under it changes, and
36
+ * one registered from a long-lived place — a navigation bar, a provider
37
+ * near the root — keeps that cost for the lifetime of the application. There
38
+ * is otherwise nothing to see: the query works, and its price is only
39
+ * visible as an application that has grown slow. Finding one such query in a
40
+ * real app took a purpose-built profiler and the better part of a day.
41
+ * @param rows - Result size to report above, or `null` to switch the check off.
42
+ */
43
+ static reportLargeQueries(rows) {
44
+ Collection.largeQueryWarningThreshold = rows;
45
+ if (rows == null) Collection.reportedLargeQueries.clear();
46
+ }
47
+ static onCreation(callback) {
48
+ Collection.onCreationCallbacks.push(callback);
49
+ }
50
+ static onDispose(callback) {
51
+ Collection.onDisposeCallbacks.push(callback);
52
+ }
53
+ /**
54
+ * Enables debug mode for all collections.
55
+ */
56
+ static enableDebugMode = () => {
57
+ Collection.debugMode = true;
58
+ if (Collection.largeQueryWarningThreshold == null) Collection.reportLargeQueries(500);
59
+ Collection.collections.forEach((collection) => {
60
+ collection.setDebugMode(true);
61
+ });
62
+ };
63
+ /**
64
+ * Enables field tracking for all collections.
65
+ * @param enable - A boolean indicating whether to enable field tracking.
66
+ */
67
+ static setFieldTracking = (enable) => {
68
+ Collection.fieldTracking = enable;
69
+ Collection.collections.forEach((collection) => {
70
+ collection.setFieldTracking(enable);
71
+ });
72
+ };
73
+ static batch(collectionsOrCallback, maybeCallback) {
74
+ const scoped = Array.isArray(collectionsOrCallback);
75
+ const callback = scoped ? maybeCallback : collectionsOrCallback;
76
+ if (typeof callback !== "function") throw new TypeError("Collection.batch requires a callback");
77
+ const collections = scoped ? collectionsOrCallback : Collection.collections;
78
+ if (!scoped) Collection.batchOperationInProgress = true;
79
+ const execute = () => collections.reduce((memo, collection) => () => {
80
+ return collection.batch(memo);
81
+ }, callback)();
82
+ const afterBatch = () => {
83
+ if (!scoped) Collection.batchOperationInProgress = false;
84
+ };
85
+ let maybePromise;
86
+ try {
87
+ maybePromise = execute();
88
+ } catch (error) {
89
+ afterBatch();
90
+ throw error;
91
+ }
92
+ if (maybePromise && typeof maybePromise.then === "function") return maybePromise.then(() => afterBatch(), (error) => {
93
+ afterBatch();
94
+ throw error;
95
+ });
96
+ else afterBatch();
97
+ }
98
+ name;
99
+ backend;
100
+ options;
101
+ isPullingSignal;
102
+ isPushingSignal;
103
+ readySignal;
104
+ debugMode;
105
+ batchOperationInProgress = false;
106
+ isDisposed = false;
107
+ postBatchCallbacks = /* @__PURE__ */ new Set();
108
+ fieldTracking = false;
109
+ queryListenersMap = /* @__PURE__ */ new Map();
110
+ settledQueriesSet = /* @__PURE__ */ new Set();
111
+ constructor(nameOrOptions, maybeDataAdapter, maybeOptions) {
112
+ super();
113
+ const name = typeof nameOrOptions === "string" ? nameOrOptions : nameOrOptions?.name || `${this.constructor.name}-${require_randomId.default()}`;
114
+ const options = typeof nameOrOptions === "string" ? maybeOptions || {} : nameOrOptions || {};
115
+ const persistence = options.persistence;
116
+ const dataAdapter = maybeDataAdapter || new require_DefaultDataAdapter.default({ ...persistence ? { storage: () => persistence } : {} });
117
+ Collection.collections.push(this);
118
+ this.name = name;
119
+ this.options = { ...options };
120
+ this.fieldTracking = this.options.fieldTracking ?? Collection.fieldTracking;
121
+ this.debugMode = this.options.enableDebugMode ?? Collection.debugMode;
122
+ this.isPullingSignal = require_createSignal.default(this.options.reactivity, false);
123
+ this.isPushingSignal = require_createSignal.default(this.options.reactivity, false);
124
+ this.readySignal = require_createSignal.default(this.options.reactivity, false);
125
+ this.backend = dataAdapter.createCollectionBackend(this, this.options.indices ?? []);
126
+ this.backend.isReady().then(() => {
127
+ this.readySignal.set(true);
128
+ }).catch(() => {});
129
+ Collection.onCreationCallbacks.forEach((callback) => callback(this));
130
+ }
131
+ /**
132
+ * Reports a live query the first time its result is found to be larger than
133
+ * the configured threshold. Once per query, because it re-runs on every
134
+ * write and a warning per write would be its own performance problem.
135
+ * @param selector - The query's selector.
136
+ * @param options - The query's options.
137
+ * @param registrationStack - Where the query was registered, if captured.
138
+ */
139
+ reportIfLargeQuery(selector, options, registrationStack) {
140
+ const threshold = Collection.largeQueryWarningThreshold;
141
+ if (threshold == null) return;
142
+ const id = `${this.name}:${require_queryId.default(selector, options)}`;
143
+ if (Collection.reportedLargeQueries.has(id)) return;
144
+ const rows = this.backend.getQueryResult(selector, options || {}).length;
145
+ if (rows <= threshold) return;
146
+ Collection.reportedLargeQueries.add(id);
147
+ const keys = selector && typeof selector === "object" ? Object.keys(selector) : [];
148
+ console.warn(`[SignalDB] Live query on "${this.name}" holds ${rows} rows with selector {${keys.join(", ")}}. It is re-evaluated on every write to this collection, for as long as it stays registered. ${registrationStack ?? ""}`);
149
+ }
150
+ isBatchOperationInProgress() {
151
+ return Collection.batchOperationInProgress || this.batchOperationInProgress;
152
+ }
153
+ /**
154
+ * Checks whether the collection is currently performing a pull operation
155
+ * ⚡️ this function is reactive!
156
+ * (loading data from the persistence adapter).
157
+ * @returns A boolean indicating if the collection is in the process of pulling data.
158
+ */
159
+ isPulling() {
160
+ return this.isPullingSignal.get() ?? false;
161
+ }
162
+ /**
163
+ * Checks whether the collection is currently performing a push operation
164
+ * ⚡️ this function is reactive!
165
+ * (saving data to the persistence adapter).
166
+ * @returns A boolean indicating if the collection is in the process of pushing data.
167
+ */
168
+ isPushing() {
169
+ return this.isPushingSignal.get() ?? false;
170
+ }
171
+ /**
172
+ * Checks whether the collection is currently performing either a pull or push operation,
173
+ * ⚡️ this function is reactive!
174
+ * indicating that it is loading or saving data.
175
+ * @returns A boolean indicating if the collection is in the process of loading or saving data.
176
+ */
177
+ isLoading() {
178
+ const isPulling = this.isPulling();
179
+ const isPushing = this.isPushing();
180
+ return isPulling || isPushing;
181
+ }
182
+ /**
183
+ * Retrieves the current debug mode status of the collection.
184
+ * @returns A boolean indicating whether debug mode is enabled for the collection.
185
+ */
186
+ getDebugMode() {
187
+ return this.debugMode;
188
+ }
189
+ /**
190
+ * Enables or disables debug mode for the collection.
191
+ * When debug mode is enabled, additional debugging information and events are emitted.
192
+ * @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) debug mode.
193
+ */
194
+ setDebugMode(enable) {
195
+ this.debugMode = enable;
196
+ }
197
+ /**
198
+ * Enables or disables field tracking for the collection.
199
+ * @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) field tracking.
200
+ */
201
+ setFieldTracking(enable) {
202
+ this.fieldTracking = enable;
203
+ }
204
+ /**
205
+ * Resolves when the persistence adapter finished initializing
206
+ * and the collection is ready to be used.
207
+ * @returns A promise that resolves when the collection is ready.
208
+ * @example
209
+ * ```ts
210
+ * const collection = new Collection({
211
+ * persistence: // ...
212
+ * })
213
+ * await collection.isReady()
214
+ *
215
+ * collection.insert({ name: 'Item 1' })
216
+ */
217
+ async ready() {
218
+ return this.backend.isReady();
219
+ }
220
+ /**
221
+ * Checks if the collection is ready.
222
+ * ⚡️ this function is reactive!
223
+ * @returns A boolean indicating whether the collection is ready.
224
+ */
225
+ isReady() {
226
+ return this.readySignal.get() ?? false;
227
+ }
228
+ profile(fn, measureFunction) {
229
+ if (!this.debugMode) return fn();
230
+ const startTime = performance.now();
231
+ const handleProfileEnd = (result) => {
232
+ measureFunction(performance.now() - startTime);
233
+ return result;
234
+ };
235
+ const maybePromise = fn();
236
+ return maybePromise instanceof Promise ? maybePromise.then(handleProfileEnd) : handleProfileEnd(maybePromise);
237
+ }
238
+ executeInDebugMode(fn) {
239
+ if (!this.debugMode) return;
240
+ fn((/* @__PURE__ */ new Error()).stack || "");
241
+ }
242
+ transform(item) {
243
+ if (!this.options.transform) return item;
244
+ return this.options.transform(item);
245
+ }
246
+ transformAll(items, fields) {
247
+ if (!this.options.transformAll) return items;
248
+ return this.options.transformAll(require_deepClone.default(items), fields);
249
+ }
250
+ getItem(selector, options) {
251
+ const itemsOrPromise = this.getItems(selector, {
252
+ ...options,
253
+ limit: 1
254
+ });
255
+ if (itemsOrPromise instanceof Promise) return itemsOrPromise.then((items) => {
256
+ return items[0] || void 0;
257
+ });
258
+ return itemsOrPromise[0];
259
+ }
260
+ getItems(selector, options) {
261
+ this.emit("getItems", selector);
262
+ return this.profile(() => {
263
+ if (!options?.async) return this.backend.getQueryResult(selector, options);
264
+ this.isPullingSignal.set(true);
265
+ return this.backend.executeQuery(selector, options).finally(() => {
266
+ this.isPullingSignal.set(false);
267
+ });
268
+ }, (measuredTime) => this.executeInDebugMode((callstack) => this.emit("_debug.getItems", callstack, selector, measuredTime)));
269
+ }
270
+ async withPushState(asyncFunction) {
271
+ this.isPushingSignal.set(true);
272
+ try {
273
+ return await asyncFunction();
274
+ } finally {
275
+ this.isPushingSignal.set(false);
276
+ }
277
+ }
278
+ queryListeners(query, listeners) {
279
+ const id = require_queryId.default(query.selector, query.options);
280
+ if (listeners != null) return this.queryListenersMap.set(id, listeners);
281
+ return this.queryListenersMap.get(id) ?? 0;
282
+ }
283
+ /**
284
+ * Disposes the collection, unregisters persistence adapters, clears memory, and
285
+ * cleans up all resources used by the collection.
286
+ * @returns A promise that resolves when the collection is disposed.
287
+ */
288
+ async dispose() {
289
+ await this.backend.dispose();
290
+ this.isDisposed = true;
291
+ this.removeAllListeners();
292
+ Collection.collections = Collection.collections.filter((collection) => collection !== this);
293
+ Collection.onDisposeCallbacks.forEach((callback) => callback(this));
294
+ }
295
+ find(selector = {}, options) {
296
+ if (this.isDisposed) throw new Error("Collection is disposed");
297
+ if (selector !== void 0 && (!selector || typeof selector !== "object")) throw new Error("Invalid selector");
298
+ const getTransformedItems = () => {
299
+ const itemsOrPromise = this.getItems(selector, options || {});
300
+ if (itemsOrPromise instanceof Promise) return itemsOrPromise.then((items) => {
301
+ return this.transformAll(items, options?.fields);
302
+ });
303
+ const items = itemsOrPromise;
304
+ return this.transformAll(items, options?.fields);
305
+ };
306
+ const cursor = new require_Cursor.default(getTransformedItems, {
307
+ reactive: this.options.reactivity,
308
+ fieldTracking: this.fieldTracking,
309
+ ...options,
310
+ transform: this.transform.bind(this),
311
+ queryState: {
312
+ hasSettled: () => {
313
+ if (this.settledQueriesSet.has(require_queryId.default(selector, options))) return true;
314
+ const state = this.backend.getQueryState(selector, options || {});
315
+ return state === "complete" || state === "error";
316
+ },
317
+ onSettled: (callback) => this.backend.onQueryStateChange(selector, options || {}, (state) => {
318
+ if (state !== "complete" && state !== "error") return;
319
+ this.settledQueriesSet.add(require_queryId.default(selector, options));
320
+ callback();
321
+ })
322
+ },
323
+ bindEvents: (requery, applyDelta) => {
324
+ const handleRequery = () => {
325
+ if (this.batchOperationInProgress) {
326
+ this.postBatchCallbacks.add(requery);
327
+ return;
328
+ }
329
+ requery();
330
+ };
331
+ const canApplyDeltas = !this.options.transformAll && !options?.async;
332
+ const listeners = this.queryListeners({
333
+ selector,
334
+ options
335
+ });
336
+ const didRegister = listeners === 0;
337
+ if (didRegister) this.backend.registerQuery(selector, options || {});
338
+ this.queryListeners({
339
+ selector,
340
+ options
341
+ }, listeners + 1);
342
+ const registrationStack = didRegister && Collection.largeQueryWarningThreshold != null ? (/* @__PURE__ */ new Error("query registered here")).stack : void 0;
343
+ if (didRegister) this.reportIfLargeQuery(selector, options, registrationStack);
344
+ const queryStateChangeCleanup = this.backend.onQueryStateChange(selector, options || {}, (state, delta) => {
345
+ if (state === "error") {
346
+ const queryError = this.backend.getQueryError(selector, options || {}) || /* @__PURE__ */ new Error(`Query on "${this.name}" failed`);
347
+ this.emit("query.error", queryError, selector, options);
348
+ return;
349
+ }
350
+ if (state !== "complete") return;
351
+ this.reportIfLargeQuery(selector, options, registrationStack);
352
+ if (delta != null && canApplyDeltas && !this.batchOperationInProgress) {
353
+ applyDelta(delta);
354
+ return;
355
+ }
356
+ handleRequery();
357
+ });
358
+ this.emit("observer.created", selector, options);
359
+ return () => {
360
+ queueMicrotask(() => {
361
+ const newListeners = Math.max(0, this.queryListeners({
362
+ selector,
363
+ options
364
+ }) - 1);
365
+ if (newListeners === 0) {
366
+ this.backend.unregisterQuery(selector, options || {});
367
+ this.settledQueriesSet.delete(require_queryId.default(selector, options));
368
+ }
369
+ this.queryListeners({
370
+ selector,
371
+ options
372
+ }, newListeners);
373
+ queryStateChangeCleanup();
374
+ this.emit("observer.disposed", selector, options);
375
+ });
376
+ };
377
+ }
378
+ });
379
+ this.emit("find", selector, options, cursor);
380
+ this.executeInDebugMode((callstack) => this.emit("_debug.find", callstack, selector, options, cursor));
381
+ return cursor;
382
+ }
383
+ findOne(selector, options) {
384
+ if (this.isDisposed) throw new Error("Collection is disposed");
385
+ const cursor = this.find(selector, {
386
+ limit: 1,
387
+ ...options
388
+ });
389
+ const handleItems = (items) => {
390
+ const returnValue = items[0] || void 0;
391
+ this.emit("findOne", selector, options, returnValue);
392
+ this.executeInDebugMode((callstack) => this.emit("_debug.findOne", callstack, selector, options, returnValue));
393
+ return returnValue;
394
+ };
395
+ const maybePromise = cursor.fetch();
396
+ return maybePromise instanceof Promise ? maybePromise.then(handleItems) : handleItems(maybePromise);
397
+ }
398
+ batch(callback) {
399
+ if (this.batchOperationInProgress) return callback();
400
+ this.batchOperationInProgress = true;
401
+ const afterBatch = () => {
402
+ this.batchOperationInProgress = false;
403
+ this.postBatchCallbacks.forEach((callback_) => callback_());
404
+ this.postBatchCallbacks.clear();
405
+ };
406
+ let maybePromise;
407
+ try {
408
+ maybePromise = callback();
409
+ } catch (error) {
410
+ afterBatch();
411
+ throw error;
412
+ }
413
+ if (maybePromise && typeof maybePromise.then === "function") return maybePromise.then(() => afterBatch(), (error) => {
414
+ afterBatch();
415
+ throw error;
416
+ });
417
+ else afterBatch();
418
+ }
419
+ onPostBatch(callback) {
420
+ if (this.isDisposed) throw new Error("Collection is disposed");
421
+ if (this.batchOperationInProgress) {
422
+ this.postBatchCallbacks.add(callback);
423
+ return;
424
+ }
425
+ return callback();
426
+ }
427
+ /**
428
+ * Inserts a single item into the collection. Generates a unique ID if not provided.
429
+ * @param item - The item to insert.
430
+ * @returns The ID of the inserted item.
431
+ * @throws {Error} If the collection is disposed or the item has an invalid ID.
432
+ */
433
+ async insert(item) {
434
+ if (this.isDisposed) throw new Error("Collection is disposed");
435
+ if (!item) throw new Error("Invalid item");
436
+ const itemWithId = {
437
+ id: (this.options.primaryKeyGenerator ?? require_randomId.default)(item),
438
+ ...item
439
+ };
440
+ this.emit("validate", itemWithId);
441
+ const newItem = await this.withPushState(() => this.backend.insert(itemWithId));
442
+ this.emit("added", newItem);
443
+ this.emit("insert", newItem);
444
+ this.executeInDebugMode((callstack) => this.emit("_debug.insert", callstack, newItem));
445
+ return newItem.id;
446
+ }
447
+ /**
448
+ * Inserts multiple items into the collection. Generates unique IDs for items if not provided.
449
+ * @param items - The items to insert.
450
+ * @returns An array of IDs of the inserted items.
451
+ * @throws {Error} If the collection is disposed or the items are invalid.
452
+ */
453
+ async insertMany(items) {
454
+ if (this.isDisposed) throw new Error("Collection is disposed");
455
+ if (!items) throw new Error("Invalid items");
456
+ if (items.length === 0) return [];
457
+ const ids = [];
458
+ await this.batch(async () => {
459
+ await Promise.all(items.map(async (item) => {
460
+ ids.push(await this.insert(item));
461
+ }));
462
+ });
463
+ return ids;
464
+ }
465
+ /**
466
+ * Updates a single item in the collection that matches the given selector.
467
+ * @param selector - The criteria to select the item to update.
468
+ * @param modifier - The modifications to apply to the item.
469
+ * @param [options] - Optional settings for the update operation.
470
+ * @param [options.upsert] - If `true`, creates a new item if no item matches the selector.
471
+ * @returns The number of items updated (0 or 1).
472
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
473
+ */
474
+ async updateOne(selector, modifier, options) {
475
+ if (this.isDisposed) throw new Error("Collection is disposed");
476
+ if (!selector) throw new Error("Invalid selector");
477
+ if (!modifier) throw new Error("Invalid modifier");
478
+ const { $setOnInsert, ...restModifier } = modifier;
479
+ if (this.listenerCount("validate") > 0) {
480
+ const item = await this.getItem(selector, { async: true });
481
+ if (item != null) this.emit("validate", require_modify.default(require_deepClone.default(item), restModifier));
482
+ }
483
+ const changes = await this.withPushState(() => this.backend.updateOne(selector, modifier));
484
+ if (changes.length === 0) {
485
+ if (!options?.upsert) return 0;
486
+ const newItem = require_modify.default({}, {
487
+ ...restModifier,
488
+ $set: {
489
+ ...$setOnInsert,
490
+ ...restModifier.$set
491
+ }
492
+ });
493
+ await this.insert(newItem);
494
+ return 1;
495
+ }
496
+ changes.forEach((item) => this.emit("changed", item, restModifier));
497
+ this.emit("updateOne", selector, modifier);
498
+ this.executeInDebugMode((callstack) => this.emit("_debug.updateOne", callstack, selector, modifier));
499
+ return changes.length;
500
+ }
501
+ /**
502
+ * Updates multiple items in the collection that match the given selector.
503
+ * @param selector - The criteria to select the items to update.
504
+ * @param modifier - The modifications to apply to the items.
505
+ * @param [options] - Optional settings for the update operation.
506
+ * @param [options.upsert] - If `true`, creates new items if no items match the selector.
507
+ * @returns The number of items updated.
508
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
509
+ */
510
+ async updateMany(selector, modifier, options) {
511
+ if (this.isDisposed) throw new Error("Collection is disposed");
512
+ if (!selector) throw new Error("Invalid selector");
513
+ if (!modifier) throw new Error("Invalid modifier");
514
+ const { $setOnInsert, ...restModifier } = modifier;
515
+ if (this.listenerCount("validate") > 0) (await this.getItems(selector, { async: true })).forEach((item) => {
516
+ this.emit("validate", require_modify.default(require_deepClone.default(item), restModifier));
517
+ });
518
+ const changes = await this.withPushState(() => this.backend.updateMany(selector, modifier));
519
+ if (changes.length === 0) {
520
+ if (!options?.upsert) return 0;
521
+ const newItem = require_modify.default({}, {
522
+ ...restModifier,
523
+ $set: {
524
+ ...$setOnInsert,
525
+ ...restModifier.$set
526
+ }
527
+ });
528
+ await this.insert(newItem);
529
+ return 1;
530
+ }
531
+ changes.forEach((item) => {
532
+ this.emit("changed", item, restModifier);
533
+ });
534
+ this.emit("updateMany", selector, modifier);
535
+ this.executeInDebugMode((callstack) => this.emit("_debug.updateMany", callstack, selector, modifier));
536
+ return changes.length;
537
+ }
538
+ /**
539
+ * Replaces a single item in the collection that matches the given selector.
540
+ * @param selector - The criteria to select the item to replace.
541
+ * @param replacement - The item to replace the selected item with.
542
+ * @param [options] - Optional settings for the replace operation.
543
+ * @param [options.upsert] - If `true`, creates a new item if no item matches the selector.
544
+ * @returns The number of items replaced (0 or 1).
545
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
546
+ */
547
+ async replaceOne(selector, replacement, options) {
548
+ if (this.isDisposed) throw new Error("Collection is disposed");
549
+ if (!selector) throw new Error("Invalid selector");
550
+ if (this.listenerCount("validate") > 0) {
551
+ const item = await this.getItem(selector, { async: true });
552
+ if (item != null) this.emit("validate", {
553
+ id: item.id,
554
+ ...replacement
555
+ });
556
+ }
557
+ const changes = await this.withPushState(() => this.backend.replaceOne(selector, replacement));
558
+ if (changes.length === 0) {
559
+ if (!options?.upsert) return 0;
560
+ await this.insert(replacement);
561
+ return 1;
562
+ }
563
+ changes.forEach((item) => this.emit("changed", item, replacement));
564
+ this.emit("replaceOne", selector, replacement);
565
+ this.executeInDebugMode((callstack) => this.emit("_debug.replaceOne", callstack, selector, replacement));
566
+ return changes.length;
567
+ }
568
+ /**
569
+ * Removes a single item from the collection that matches the given selector.
570
+ * @param selector - The criteria to select the item to remove.
571
+ * @returns The number of items removed (0 or 1).
572
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
573
+ */
574
+ async removeOne(selector) {
575
+ if (this.isDisposed) throw new Error("Collection is disposed");
576
+ if (!selector) throw new Error("Invalid selector");
577
+ const removedItems = await this.withPushState(() => this.backend.removeOne(selector));
578
+ this.emit("removed", removedItems[0]);
579
+ this.emit("removeOne", selector);
580
+ this.executeInDebugMode((callstack) => this.emit("_debug.removeOne", callstack, selector));
581
+ return removedItems.length;
582
+ }
583
+ /**
584
+ * Removes multiple items from the collection that match the given selector.
585
+ * @param selector - The criteria to select the items to remove.
586
+ * @returns The number of items removed.
587
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
588
+ */
589
+ async removeMany(selector) {
590
+ if (this.isDisposed) throw new Error("Collection is disposed");
591
+ if (!selector) throw new Error("Invalid selector");
592
+ const removedItems = await this.withPushState(() => this.backend.removeMany(selector));
593
+ removedItems.forEach((item) => {
594
+ this.emit("removed", item);
595
+ });
596
+ this.emit("removeMany", selector);
597
+ this.executeInDebugMode((callstack) => this.emit("_debug.removeMany", callstack, selector));
598
+ return removedItems.length;
599
+ }
600
+ };
601
+ //#endregion
602
+ exports.default = Collection;