@signaldb/core 2.0.0-beta.5 → 2.0.0-beta.7

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 (104) hide show
  1. package/dist/.vite/manifest.json +118 -84
  2. package/dist/AsyncDataAdapter.d.ts +1 -1
  3. package/dist/index.cjs.js +33 -34
  4. package/dist/index.mjs +17 -35
  5. package/dist/index10.cjs.js +23 -0
  6. package/dist/index10.mjs +21 -17
  7. package/dist/index11.cjs.js +45 -0
  8. package/dist/index11.mjs +44 -15
  9. package/dist/index12.cjs.js +22 -0
  10. package/dist/index12.mjs +21 -47
  11. package/dist/index13.cjs.js +45 -0
  12. package/dist/index13.mjs +44 -365
  13. package/dist/index14.cjs.js +86 -0
  14. package/dist/index14.mjs +85 -416
  15. package/dist/index15.cjs.js +15 -0
  16. package/dist/index15.mjs +14 -206
  17. package/dist/index16.cjs.js +136 -0
  18. package/dist/index16.mjs +135 -388
  19. package/dist/index17.cjs.js +47 -0
  20. package/dist/index17.mjs +45 -578
  21. package/dist/index18.cjs.js +15 -0
  22. package/dist/index18.mjs +14 -157
  23. package/dist/index19.cjs.js +23 -0
  24. package/dist/index19.mjs +22 -26
  25. package/dist/index2.cjs.js +33 -0
  26. package/dist/index2.mjs +32 -258
  27. package/dist/index20.cjs.js +37 -0
  28. package/dist/index20.mjs +36 -41
  29. package/dist/index21.cjs.js +35 -0
  30. package/dist/index21.mjs +34 -16
  31. package/dist/index22.cjs.js +25 -0
  32. package/dist/index22.mjs +24 -104
  33. package/dist/index23.cjs.js +19 -0
  34. package/dist/index23.mjs +18 -128
  35. package/dist/index24.cjs.js +342 -0
  36. package/dist/index24.mjs +340 -6
  37. package/dist/index25.cjs.js +519 -0
  38. package/dist/index25.mjs +518 -27
  39. package/dist/index26.cjs.js +11 -0
  40. package/dist/index26.mjs +10 -10
  41. package/dist/index27.cjs.js +11 -0
  42. package/dist/index27.mjs +10 -29
  43. package/dist/index28.cjs.js +90 -0
  44. package/dist/index28.mjs +88 -46
  45. package/dist/index29.cjs.js +370 -0
  46. package/dist/index29.mjs +369 -8
  47. package/dist/index3.cjs.js +19 -0
  48. package/dist/index3.mjs +18 -539
  49. package/dist/index30.cjs.js +72 -0
  50. package/dist/index30.mjs +71 -7
  51. package/dist/index31.cjs.js +191 -0
  52. package/dist/index31.mjs +190 -42
  53. package/dist/index32.cjs.js +21 -0
  54. package/dist/index32.mjs +20 -29
  55. package/dist/index33.cjs.js +336 -0
  56. package/dist/index33.mjs +335 -5
  57. package/dist/index34.cjs.js +539 -0
  58. package/dist/index34.mjs +537 -8
  59. package/dist/index4.cjs.js +150 -0
  60. package/dist/index4.mjs +149 -5
  61. package/dist/index5.cjs.js +254 -0
  62. package/dist/index5.mjs +252 -4
  63. package/dist/index6.cjs.js +125 -0
  64. package/dist/index6.mjs +124 -29
  65. package/dist/index7.cjs.js +33 -0
  66. package/dist/index7.mjs +32 -12
  67. package/dist/index8.cjs.js +12 -0
  68. package/dist/index8.mjs +10 -4
  69. package/dist/index9.cjs.js +11 -0
  70. package/dist/index9.mjs +10 -133
  71. package/package.json +1 -1
  72. package/dist/index.cjs10.js +0 -18
  73. package/dist/index.cjs11.js +0 -15
  74. package/dist/index.cjs12.js +0 -48
  75. package/dist/index.cjs13.js +0 -365
  76. package/dist/index.cjs14.js +0 -416
  77. package/dist/index.cjs15.js +0 -206
  78. package/dist/index.cjs16.js +0 -388
  79. package/dist/index.cjs17.js +0 -579
  80. package/dist/index.cjs18.js +0 -157
  81. package/dist/index.cjs19.js +0 -26
  82. package/dist/index.cjs2.js +0 -259
  83. package/dist/index.cjs20.js +0 -42
  84. package/dist/index.cjs21.js +0 -16
  85. package/dist/index.cjs22.js +0 -104
  86. package/dist/index.cjs23.js +0 -129
  87. package/dist/index.cjs24.js +0 -7
  88. package/dist/index.cjs25.js +0 -27
  89. package/dist/index.cjs26.js +0 -10
  90. package/dist/index.cjs27.js +0 -29
  91. package/dist/index.cjs28.js +0 -46
  92. package/dist/index.cjs29.js +0 -8
  93. package/dist/index.cjs3.js +0 -540
  94. package/dist/index.cjs30.js +0 -7
  95. package/dist/index.cjs31.js +0 -42
  96. package/dist/index.cjs32.js +0 -29
  97. package/dist/index.cjs33.js +0 -5
  98. package/dist/index.cjs34.js +0 -9
  99. package/dist/index.cjs4.js +0 -5
  100. package/dist/index.cjs5.js +0 -5
  101. package/dist/index.cjs6.js +0 -29
  102. package/dist/index.cjs7.js +0 -12
  103. package/dist/index.cjs8.js +0 -5
  104. package/dist/index.cjs9.js +0 -133
package/dist/index4.mjs CHANGED
@@ -1,6 +1,150 @@
1
- function createStorageAdapter(definition) {
2
- return definition;
3
- }
4
- export {
5
- createStorageAdapter as default
1
+ import isEqual from "./index2.mjs";
2
+ import uniqueBy from "./index3.mjs";
3
+ //#region src/Collection/Observer.ts
4
+ /**
5
+ * Represents an observer that tracks changes in a collection of items and triggers
6
+ * callbacks for various events such as addition, removal, and modification of items.
7
+ * @template T - The type of the items being observed, which must include an `id` field.
8
+ */
9
+ var Observer = class {
10
+ previousItems = [];
11
+ callbacks;
12
+ unbindEvents;
13
+ /**
14
+ * Creates a new instance of the `Observer` class.
15
+ * Sets up event bindings and initializes the callbacks for tracking changes in a collection.
16
+ * @param bindEvents - A function to bind external events to the observer. Must return a cleanup function to unbind those events.
17
+ */
18
+ constructor(bindEvents) {
19
+ this.callbacks = {
20
+ added: [],
21
+ addedBefore: [],
22
+ changed: [],
23
+ changedField: [],
24
+ movedBefore: [],
25
+ removed: []
26
+ };
27
+ this.unbindEvents = bindEvents();
28
+ }
29
+ call(event, ...args) {
30
+ this.callbacks[event].forEach(({ callback, options }) => {
31
+ if (!options.skipInitial || !options.isInitial) callback(...args);
32
+ });
33
+ }
34
+ hasCallbacks(events) {
35
+ return events.some((event) => this.callbacks[event].length > 0);
36
+ }
37
+ /**
38
+ * Determines if the observer has no active callbacks registered for any events.
39
+ * @returns A boolean indicating whether the observer is empty (i.e., no callbacks are registered).
40
+ */
41
+ isEmpty() {
42
+ return !this.hasCallbacks([
43
+ "added",
44
+ "addedBefore",
45
+ "changed",
46
+ "changedField",
47
+ "movedBefore",
48
+ "removed"
49
+ ]);
50
+ }
51
+ /**
52
+ * Compares the previous state of items with the new state and triggers the appropriate callbacks
53
+ * for events such as added, removed, changed, or moved items.
54
+ * @param getItems - A function that returns a promise resolving to the new items or the items themselves.
55
+ */
56
+ runChecks(getItems) {
57
+ const result = getItems();
58
+ if (result instanceof Promise) result.then((newItems) => this.checkItems(newItems)).catch((error) => {
59
+ console.error("Error while asynchronously querying items", error);
60
+ });
61
+ else this.checkItems(result);
62
+ }
63
+ checkItems(newItems) {
64
+ const oldItemsMap = new Map(this.previousItems.map((item, index) => [item.id, {
65
+ item,
66
+ index,
67
+ beforeItem: this.previousItems[index + 1] || null
68
+ }]));
69
+ const newItemsMap = new Map(newItems.map((item, index) => [item.id, {
70
+ item,
71
+ index,
72
+ beforeItem: newItems[index + 1] || null
73
+ }]));
74
+ if (this.hasCallbacks([
75
+ "changed",
76
+ "changedField",
77
+ "movedBefore",
78
+ "removed"
79
+ ])) oldItemsMap.forEach(({ item: oldItem, index, beforeItem: oldBeforeItem }) => {
80
+ const newItem = newItemsMap.get(oldItem.id);
81
+ if (newItem) {
82
+ if (this.hasCallbacks(["changed", "changedField"]) && !isEqual(newItem.item, oldItem)) {
83
+ this.call("changed", newItem.item);
84
+ if (this.hasCallbacks(["changedField"])) uniqueBy([...Object.keys(newItem.item), ...Object.keys(oldItem)], (value) => value).forEach((key) => {
85
+ if (isEqual(newItem.item[key], oldItem[key])) return;
86
+ this.call("changedField", newItem.item, key, oldItem[key], newItem.item[key]);
87
+ });
88
+ }
89
+ if (newItem.index !== index && newItem.beforeItem?.id !== oldBeforeItem?.id) this.call("movedBefore", newItem.item, newItem.beforeItem);
90
+ } else this.call("removed", oldItem);
91
+ });
92
+ if (this.hasCallbacks(["added", "addedBefore"])) newItems.forEach((newItem, index) => {
93
+ if (oldItemsMap.get(newItem.id)) return;
94
+ this.call("added", newItem);
95
+ this.call("addedBefore", newItem, newItems[index + 1] || null);
96
+ });
97
+ this.previousItems = newItems;
98
+ Object.keys(this.callbacks).forEach((key) => {
99
+ const event = key;
100
+ const callbacks = this.callbacks[event];
101
+ this.callbacks[event] = callbacks.map((callback) => ({
102
+ ...callback,
103
+ options: {
104
+ ...callback.options,
105
+ isInitial: false
106
+ }
107
+ }));
108
+ });
109
+ }
110
+ stopped = false;
111
+ /**
112
+ * Stops the observer by unbinding all events and cleaning up resources.
113
+ * Safe to call multiple times - will only unbind once.
114
+ */
115
+ stop() {
116
+ if (this.stopped) return;
117
+ this.stopped = true;
118
+ this.unbindEvents();
119
+ }
120
+ /**
121
+ * Registers callbacks for specific events to observe changes in the collection.
122
+ * @param callbacks - An object containing the callbacks for various events (e.g., 'added', 'removed').
123
+ * @param skipInitial - A boolean indicating whether to skip invoking the callbacks for the initial state of the collection.
124
+ */
125
+ addCallbacks(callbacks, skipInitial = false) {
126
+ Object.keys(callbacks).forEach((key) => {
127
+ const typedKey = key;
128
+ this.callbacks[typedKey].push({
129
+ callback: callbacks[typedKey],
130
+ options: {
131
+ skipInitial,
132
+ isInitial: true
133
+ }
134
+ });
135
+ });
136
+ }
137
+ /**
138
+ * Removes the specified callbacks for specific events, unregistering them from the observer.
139
+ * @param callbacks - An object containing the callbacks to be removed for various events.
140
+ */
141
+ removeCallbacks(callbacks) {
142
+ Object.keys(callbacks).forEach((key) => {
143
+ const typedKey = key;
144
+ const index = this.callbacks[typedKey].findIndex(({ callback }) => callback === callbacks[typedKey]);
145
+ this.callbacks[typedKey].splice(index, 1);
146
+ });
147
+ }
6
148
  };
149
+ //#endregion
150
+ export { Observer as default };
@@ -0,0 +1,254 @@
1
+ const require_Observer = require("./index4.cjs.js");
2
+ //#region src/Collection/Cursor.ts
3
+ /**
4
+ * Checks if the current scope is reactive, considering the provided reactivity adapter.
5
+ * @param reactivity - The reactivity adapter or a boolean indicating whether reactivity is enabled.
6
+ * @returns A boolean indicating if the current scope is reactive.
7
+ */
8
+ function isInReactiveScope(reactivity) {
9
+ if (!reactivity) return false;
10
+ if (!reactivity.isInScope) return true;
11
+ return reactivity.isInScope();
12
+ }
13
+ /**
14
+ * Represents a cursor for querying and observing a filtered, sorted, and transformed
15
+ * subset of items from a collection. Supports reactivity and field tracking.
16
+ * @template T - The type of the items in the collection.
17
+ * @template U - The transformed item type after applying transform (default is T).
18
+ */
19
+ var Cursor = class {
20
+ observer;
21
+ getItems;
22
+ options;
23
+ onCleanupCallbacks = [];
24
+ /**
25
+ * Creates a new instance of the `Cursor` class.
26
+ * Provides utilities for querying, observing, and transforming items from a collection.
27
+ * @template T - The type of the items in the collection.
28
+ * @template U - The transformed item type after applying transformations (default is T).
29
+ * @param getItems - A function that retrieves the filtered list of items.
30
+ * @param options - Optional configuration for the cursor.
31
+ * @param options.transform - A transformation function to apply to each item when retrieving them.
32
+ * @param options.bindEvents - A function to bind reactivity events for the cursor, which should return a cleanup function.
33
+ * @param options.fields - A projection object defining which fields of the item should be included or excluded.
34
+ * @param options.sort - A sort specifier to determine the order of the items.
35
+ * @param options.skip - The number of items to skip from the beginning of the result set.
36
+ * @param options.limit - The maximum number of items to return in the result set.
37
+ * @param options.reactive - A reactivity adapter to enable observing changes in the cursor's result set.
38
+ * @param options.fieldTracking - A boolean to enable fine-grained field tracking for reactivity.
39
+ * @param options.transformAll - A function that will be able to solve the n+1 problem
40
+ */
41
+ constructor(getItems, options) {
42
+ this.getItems = getItems;
43
+ this.options = options || {};
44
+ }
45
+ addGetters(item) {
46
+ if (!isInReactiveScope(this.options.reactive)) return item;
47
+ const depend = this.depend.bind(this);
48
+ return Object.entries(item).reduce((memo, [key, value]) => {
49
+ Object.defineProperty(memo, key, {
50
+ get() {
51
+ depend({ changedField: (notify) => (changedItem, changedFieldName) => {
52
+ if (changedFieldName !== key || changedItem.id !== item.id) return;
53
+ notify();
54
+ } });
55
+ return value;
56
+ },
57
+ enumerable: true,
58
+ configurable: true
59
+ });
60
+ return memo;
61
+ }, {});
62
+ }
63
+ transform(rawItem) {
64
+ const item = this.options.fieldTracking ? this.addGetters(rawItem) : rawItem;
65
+ if (!this.options.transform) return item;
66
+ return this.options.transform(item);
67
+ }
68
+ depend(changeEvents) {
69
+ if (this.options?.async) return;
70
+ if (!isInReactiveScope(this.options.reactive)) console.warn("Cursor.depend() called outside of a reactive scope without async option; consider using { async: true } or wrapping in a reactive scope");
71
+ if (!this.options.reactive) return;
72
+ const signal = this.options.reactive.create();
73
+ signal.depend();
74
+ const notify = () => signal.notify();
75
+ /**
76
+ * Builds a notifier function for the specified event.
77
+ * @template Event - The type of the event.
78
+ * @param event - The event for which to build the notifier.
79
+ * @returns A function that handles the event and triggers the appropriate notifications.
80
+ */
81
+ function buildNotifier(event) {
82
+ const eventHandler = changeEvents[event];
83
+ return (...args) => {
84
+ if (eventHandler === true) {
85
+ notify();
86
+ return;
87
+ }
88
+ if (typeof eventHandler !== "function") return;
89
+ eventHandler(notify)(...args);
90
+ };
91
+ }
92
+ const stop = this.observeRawChanges({
93
+ added: buildNotifier("added"),
94
+ addedBefore: buildNotifier("addedBefore"),
95
+ changed: buildNotifier("changed"),
96
+ changedField: buildNotifier("changedField"),
97
+ movedBefore: buildNotifier("movedBefore"),
98
+ removed: buildNotifier("removed")
99
+ }, true);
100
+ if (this.options.reactive.onDispose) this.options.reactive.onDispose(() => stop(), signal);
101
+ this.onCleanup(stop);
102
+ }
103
+ ensureObserver() {
104
+ if (!this.observer) {
105
+ const observer = new require_Observer.default(() => {
106
+ const requery = () => {
107
+ observer.runChecks(this.getItems);
108
+ };
109
+ const cleanup = this.options.bindEvents && this.options.bindEvents(requery);
110
+ return () => {
111
+ if (cleanup) cleanup();
112
+ };
113
+ });
114
+ this.onCleanup(() => observer.stop());
115
+ this.observer = observer;
116
+ }
117
+ return this.observer;
118
+ }
119
+ observeRawChanges(callbacks, skipInitial = false) {
120
+ const observer = this.ensureObserver();
121
+ observer.addCallbacks(callbacks, skipInitial);
122
+ observer.runChecks(this.getItems);
123
+ return () => {
124
+ observer.removeCallbacks(callbacks);
125
+ if (!observer.isEmpty()) return;
126
+ observer.stop();
127
+ this.observer = void 0;
128
+ };
129
+ }
130
+ /**
131
+ * Cleans up all resources associated with the cursor, such as reactive bindings
132
+ * and event listeners. This method should be called when the cursor is no longer needed
133
+ * to prevent memory leaks.
134
+ */
135
+ cleanup() {
136
+ this.onCleanupCallbacks.forEach((callback) => {
137
+ callback();
138
+ });
139
+ this.onCleanupCallbacks = [];
140
+ }
141
+ /**
142
+ * Registers a cleanup callback to be executed when the `cleanup` method is called.
143
+ * Useful for managing resources and ensuring proper cleanup of bindings or listeners.
144
+ * @param callback - A function to be executed during cleanup.
145
+ */
146
+ onCleanup(callback) {
147
+ this.onCleanupCallbacks.push(callback);
148
+ }
149
+ /**
150
+ * Iterates over each item in the cursor's result set, applying the provided callback
151
+ * function to each transformed item.
152
+ * ⚡️ this function is reactive!
153
+ * @param callback - A function to execute for each item in the result set.
154
+ * @param callback.item - The transformed item.
155
+ * @returns A promise that resolves when all items have been processed, or void if not in async mode.
156
+ */
157
+ forEach(callback) {
158
+ this.depend({
159
+ addedBefore: true,
160
+ removed: true,
161
+ movedBefore: true,
162
+ ...this.options.fieldTracking ? {} : { changed: true }
163
+ });
164
+ const executeForEach = (items) => {
165
+ items.forEach((item) => {
166
+ callback(this.transform(item));
167
+ });
168
+ };
169
+ const result = this.getItems();
170
+ if (result instanceof Promise) return result.then(executeForEach);
171
+ else {
172
+ executeForEach(result);
173
+ return;
174
+ }
175
+ }
176
+ /**
177
+ * Creates a new array populated with the results of applying the provided callback
178
+ * function to each transformed item in the cursor's result set.
179
+ * ⚡️ this function is reactive!
180
+ * @template V - The type of the items in the resulting array.
181
+ * @param callback - A function to execute for each item in the result set.
182
+ * @param callback.item - The transformed item.
183
+ * @returns An array of results after applying the callback to each item.
184
+ */
185
+ map(callback) {
186
+ const results = [];
187
+ const maybePromise = this.forEach((item) => {
188
+ results.push(callback(item));
189
+ });
190
+ if (maybePromise instanceof Promise) return maybePromise.then(() => results);
191
+ return results;
192
+ }
193
+ /**
194
+ * Fetches all transformed items from the cursor's result set as an array.
195
+ * Automatically applies filtering, sorting, and limiting as per the cursor's options.
196
+ * ⚡️ this function is reactive!
197
+ * @returns An array of transformed items in the result set.
198
+ */
199
+ fetch() {
200
+ return this.map((item) => item);
201
+ }
202
+ /**
203
+ * Counts the total number of items in the cursor's result set after applying
204
+ * filtering and other criteria.
205
+ * ⚡️ this function is reactive!
206
+ * @returns The total number of items in the result set.
207
+ */
208
+ count() {
209
+ this.depend({
210
+ added: true,
211
+ removed: true
212
+ });
213
+ const maybePromise = this.getItems();
214
+ return maybePromise instanceof Promise ? maybePromise.then((items) => items.length) : maybePromise.length;
215
+ }
216
+ /**
217
+ * Observes changes to the cursor's result set and triggers the specified callbacks
218
+ * when items are added, removed, or updated. Supports reactivity and transformation.
219
+ * @param callbacks - An object containing the callback functions to handle different change events.
220
+ * @param callbacks.added - Triggered when an item is added to the result set.
221
+ * @param callbacks.removed - Triggered when an item is removed from the result set.
222
+ * @param callbacks.changed - Triggered when an item in the result set is modified.
223
+ * @param callbacks.addedBefore - Triggered when an item is added before another item in the result set.
224
+ * @param callbacks.movedBefore - Triggered when an item is moved before another item in the result set.
225
+ * @param callbacks.changedField - Triggered when a specific field of an item changes.
226
+ * @param skipInitial - A boolean indicating whether to skip the initial notification of the current result set.
227
+ * @returns A function to stop observing changes.
228
+ */
229
+ observeChanges(callbacks, skipInitial = false) {
230
+ return this.observeRawChanges(Object.entries(callbacks).reduce((memo, [callbackName, callback]) => {
231
+ if (!callback) return memo;
232
+ return {
233
+ ...memo,
234
+ [callbackName]: (item, before) => {
235
+ const transformedValue = this.transform(item);
236
+ const hasBeforeParameter = before !== void 0;
237
+ const transformedBeforeValue = hasBeforeParameter && before ? this.transform(before) : null;
238
+ return callback(transformedValue, ...hasBeforeParameter ? [transformedBeforeValue] : []);
239
+ }
240
+ };
241
+ }, {}), skipInitial);
242
+ }
243
+ /**
244
+ * Forces the cursor to re-evaluate its result set by re-fetching items
245
+ * from the collection. This is useful when the underlying data or query
246
+ * criteria have changed, and you want to ensure the cursor reflects the latest state.
247
+ */
248
+ requery() {
249
+ if (!this.observer) return;
250
+ this.observer.runChecks(this.getItems);
251
+ }
252
+ };
253
+ //#endregion
254
+ exports.default = Cursor;
package/dist/index5.mjs CHANGED
@@ -1,6 +1,254 @@
1
- function createReactivityAdapter(definition) {
2
- return definition;
1
+ import Observer from "./index4.mjs";
2
+ //#region src/Collection/Cursor.ts
3
+ /**
4
+ * Checks if the current scope is reactive, considering the provided reactivity adapter.
5
+ * @param reactivity - The reactivity adapter or a boolean indicating whether reactivity is enabled.
6
+ * @returns A boolean indicating if the current scope is reactive.
7
+ */
8
+ function isInReactiveScope(reactivity) {
9
+ if (!reactivity) return false;
10
+ if (!reactivity.isInScope) return true;
11
+ return reactivity.isInScope();
3
12
  }
4
- export {
5
- createReactivityAdapter as default
13
+ /**
14
+ * Represents a cursor for querying and observing a filtered, sorted, and transformed
15
+ * subset of items from a collection. Supports reactivity and field tracking.
16
+ * @template T - The type of the items in the collection.
17
+ * @template U - The transformed item type after applying transform (default is T).
18
+ */
19
+ var Cursor = class {
20
+ observer;
21
+ getItems;
22
+ options;
23
+ onCleanupCallbacks = [];
24
+ /**
25
+ * Creates a new instance of the `Cursor` class.
26
+ * Provides utilities for querying, observing, and transforming items from a collection.
27
+ * @template T - The type of the items in the collection.
28
+ * @template U - The transformed item type after applying transformations (default is T).
29
+ * @param getItems - A function that retrieves the filtered list of items.
30
+ * @param options - Optional configuration for the cursor.
31
+ * @param options.transform - A transformation function to apply to each item when retrieving them.
32
+ * @param options.bindEvents - A function to bind reactivity events for the cursor, which should return a cleanup function.
33
+ * @param options.fields - A projection object defining which fields of the item should be included or excluded.
34
+ * @param options.sort - A sort specifier to determine the order of the items.
35
+ * @param options.skip - The number of items to skip from the beginning of the result set.
36
+ * @param options.limit - The maximum number of items to return in the result set.
37
+ * @param options.reactive - A reactivity adapter to enable observing changes in the cursor's result set.
38
+ * @param options.fieldTracking - A boolean to enable fine-grained field tracking for reactivity.
39
+ * @param options.transformAll - A function that will be able to solve the n+1 problem
40
+ */
41
+ constructor(getItems, options) {
42
+ this.getItems = getItems;
43
+ this.options = options || {};
44
+ }
45
+ addGetters(item) {
46
+ if (!isInReactiveScope(this.options.reactive)) return item;
47
+ const depend = this.depend.bind(this);
48
+ return Object.entries(item).reduce((memo, [key, value]) => {
49
+ Object.defineProperty(memo, key, {
50
+ get() {
51
+ depend({ changedField: (notify) => (changedItem, changedFieldName) => {
52
+ if (changedFieldName !== key || changedItem.id !== item.id) return;
53
+ notify();
54
+ } });
55
+ return value;
56
+ },
57
+ enumerable: true,
58
+ configurable: true
59
+ });
60
+ return memo;
61
+ }, {});
62
+ }
63
+ transform(rawItem) {
64
+ const item = this.options.fieldTracking ? this.addGetters(rawItem) : rawItem;
65
+ if (!this.options.transform) return item;
66
+ return this.options.transform(item);
67
+ }
68
+ depend(changeEvents) {
69
+ if (this.options?.async) return;
70
+ if (!isInReactiveScope(this.options.reactive)) console.warn("Cursor.depend() called outside of a reactive scope without async option; consider using { async: true } or wrapping in a reactive scope");
71
+ if (!this.options.reactive) return;
72
+ const signal = this.options.reactive.create();
73
+ signal.depend();
74
+ const notify = () => signal.notify();
75
+ /**
76
+ * Builds a notifier function for the specified event.
77
+ * @template Event - The type of the event.
78
+ * @param event - The event for which to build the notifier.
79
+ * @returns A function that handles the event and triggers the appropriate notifications.
80
+ */
81
+ function buildNotifier(event) {
82
+ const eventHandler = changeEvents[event];
83
+ return (...args) => {
84
+ if (eventHandler === true) {
85
+ notify();
86
+ return;
87
+ }
88
+ if (typeof eventHandler !== "function") return;
89
+ eventHandler(notify)(...args);
90
+ };
91
+ }
92
+ const stop = this.observeRawChanges({
93
+ added: buildNotifier("added"),
94
+ addedBefore: buildNotifier("addedBefore"),
95
+ changed: buildNotifier("changed"),
96
+ changedField: buildNotifier("changedField"),
97
+ movedBefore: buildNotifier("movedBefore"),
98
+ removed: buildNotifier("removed")
99
+ }, true);
100
+ if (this.options.reactive.onDispose) this.options.reactive.onDispose(() => stop(), signal);
101
+ this.onCleanup(stop);
102
+ }
103
+ ensureObserver() {
104
+ if (!this.observer) {
105
+ const observer = new Observer(() => {
106
+ const requery = () => {
107
+ observer.runChecks(this.getItems);
108
+ };
109
+ const cleanup = this.options.bindEvents && this.options.bindEvents(requery);
110
+ return () => {
111
+ if (cleanup) cleanup();
112
+ };
113
+ });
114
+ this.onCleanup(() => observer.stop());
115
+ this.observer = observer;
116
+ }
117
+ return this.observer;
118
+ }
119
+ observeRawChanges(callbacks, skipInitial = false) {
120
+ const observer = this.ensureObserver();
121
+ observer.addCallbacks(callbacks, skipInitial);
122
+ observer.runChecks(this.getItems);
123
+ return () => {
124
+ observer.removeCallbacks(callbacks);
125
+ if (!observer.isEmpty()) return;
126
+ observer.stop();
127
+ this.observer = void 0;
128
+ };
129
+ }
130
+ /**
131
+ * Cleans up all resources associated with the cursor, such as reactive bindings
132
+ * and event listeners. This method should be called when the cursor is no longer needed
133
+ * to prevent memory leaks.
134
+ */
135
+ cleanup() {
136
+ this.onCleanupCallbacks.forEach((callback) => {
137
+ callback();
138
+ });
139
+ this.onCleanupCallbacks = [];
140
+ }
141
+ /**
142
+ * Registers a cleanup callback to be executed when the `cleanup` method is called.
143
+ * Useful for managing resources and ensuring proper cleanup of bindings or listeners.
144
+ * @param callback - A function to be executed during cleanup.
145
+ */
146
+ onCleanup(callback) {
147
+ this.onCleanupCallbacks.push(callback);
148
+ }
149
+ /**
150
+ * Iterates over each item in the cursor's result set, applying the provided callback
151
+ * function to each transformed item.
152
+ * ⚡️ this function is reactive!
153
+ * @param callback - A function to execute for each item in the result set.
154
+ * @param callback.item - The transformed item.
155
+ * @returns A promise that resolves when all items have been processed, or void if not in async mode.
156
+ */
157
+ forEach(callback) {
158
+ this.depend({
159
+ addedBefore: true,
160
+ removed: true,
161
+ movedBefore: true,
162
+ ...this.options.fieldTracking ? {} : { changed: true }
163
+ });
164
+ const executeForEach = (items) => {
165
+ items.forEach((item) => {
166
+ callback(this.transform(item));
167
+ });
168
+ };
169
+ const result = this.getItems();
170
+ if (result instanceof Promise) return result.then(executeForEach);
171
+ else {
172
+ executeForEach(result);
173
+ return;
174
+ }
175
+ }
176
+ /**
177
+ * Creates a new array populated with the results of applying the provided callback
178
+ * function to each transformed item in the cursor's result set.
179
+ * ⚡️ this function is reactive!
180
+ * @template V - The type of the items in the resulting array.
181
+ * @param callback - A function to execute for each item in the result set.
182
+ * @param callback.item - The transformed item.
183
+ * @returns An array of results after applying the callback to each item.
184
+ */
185
+ map(callback) {
186
+ const results = [];
187
+ const maybePromise = this.forEach((item) => {
188
+ results.push(callback(item));
189
+ });
190
+ if (maybePromise instanceof Promise) return maybePromise.then(() => results);
191
+ return results;
192
+ }
193
+ /**
194
+ * Fetches all transformed items from the cursor's result set as an array.
195
+ * Automatically applies filtering, sorting, and limiting as per the cursor's options.
196
+ * ⚡️ this function is reactive!
197
+ * @returns An array of transformed items in the result set.
198
+ */
199
+ fetch() {
200
+ return this.map((item) => item);
201
+ }
202
+ /**
203
+ * Counts the total number of items in the cursor's result set after applying
204
+ * filtering and other criteria.
205
+ * ⚡️ this function is reactive!
206
+ * @returns The total number of items in the result set.
207
+ */
208
+ count() {
209
+ this.depend({
210
+ added: true,
211
+ removed: true
212
+ });
213
+ const maybePromise = this.getItems();
214
+ return maybePromise instanceof Promise ? maybePromise.then((items) => items.length) : maybePromise.length;
215
+ }
216
+ /**
217
+ * Observes changes to the cursor's result set and triggers the specified callbacks
218
+ * when items are added, removed, or updated. Supports reactivity and transformation.
219
+ * @param callbacks - An object containing the callback functions to handle different change events.
220
+ * @param callbacks.added - Triggered when an item is added to the result set.
221
+ * @param callbacks.removed - Triggered when an item is removed from the result set.
222
+ * @param callbacks.changed - Triggered when an item in the result set is modified.
223
+ * @param callbacks.addedBefore - Triggered when an item is added before another item in the result set.
224
+ * @param callbacks.movedBefore - Triggered when an item is moved before another item in the result set.
225
+ * @param callbacks.changedField - Triggered when a specific field of an item changes.
226
+ * @param skipInitial - A boolean indicating whether to skip the initial notification of the current result set.
227
+ * @returns A function to stop observing changes.
228
+ */
229
+ observeChanges(callbacks, skipInitial = false) {
230
+ return this.observeRawChanges(Object.entries(callbacks).reduce((memo, [callbackName, callback]) => {
231
+ if (!callback) return memo;
232
+ return {
233
+ ...memo,
234
+ [callbackName]: (item, before) => {
235
+ const transformedValue = this.transform(item);
236
+ const hasBeforeParameter = before !== void 0;
237
+ const transformedBeforeValue = hasBeforeParameter && before ? this.transform(before) : null;
238
+ return callback(transformedValue, ...hasBeforeParameter ? [transformedBeforeValue] : []);
239
+ }
240
+ };
241
+ }, {}), skipInitial);
242
+ }
243
+ /**
244
+ * Forces the cursor to re-evaluate its result set by re-fetching items
245
+ * from the collection. This is useful when the underlying data or query
246
+ * criteria have changed, and you want to ensure the cursor reflects the latest state.
247
+ */
248
+ requery() {
249
+ if (!this.observer) return;
250
+ this.observer.runChecks(this.getItems);
251
+ }
6
252
  };
253
+ //#endregion
254
+ export { Cursor as default };