@signaldb/svelte 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 (105) hide show
  1. package/dist/base/core/src/AsyncDataAdapter.d.ts +112 -0
  2. package/dist/base/core/src/AsyncDataAdapter.js +549 -0
  3. package/dist/base/core/src/AutoFetchDataAdapter.d.ts +112 -0
  4. package/dist/base/core/src/AutoFetchDataAdapter.js +612 -0
  5. package/dist/base/core/src/Collection/Cursor.d.ts +165 -0
  6. package/dist/base/core/src/Collection/Cursor.js +352 -0
  7. package/dist/base/core/src/Collection/Observer.d.ts +95 -0
  8. package/dist/base/core/src/Collection/Observer.js +227 -0
  9. package/dist/base/core/src/Collection/index.d.ts +341 -0
  10. package/dist/base/core/src/Collection/index.js +761 -0
  11. package/dist/base/core/src/Collection/types.d.ts +28 -0
  12. package/dist/base/core/src/Collection/types.js +2 -0
  13. package/dist/base/core/src/DataAdapter.d.ts +54 -0
  14. package/dist/base/core/src/DataAdapter.js +2 -0
  15. package/dist/base/core/src/DefaultDataAdapter.d.ts +35 -0
  16. package/dist/base/core/src/DefaultDataAdapter.js +408 -0
  17. package/dist/base/core/src/WorkerDataAdapter.d.ts +79 -0
  18. package/dist/base/core/src/WorkerDataAdapter.js +749 -0
  19. package/dist/base/core/src/WorkerDataAdapterHost.d.ts +64 -0
  20. package/dist/base/core/src/WorkerDataAdapterHost.js +430 -0
  21. package/dist/base/core/src/createIndex.d.ts +7 -0
  22. package/dist/base/core/src/createIndex.js +120 -0
  23. package/dist/base/core/src/createIndexProvider.d.ts +8 -0
  24. package/dist/base/core/src/createIndexProvider.js +11 -0
  25. package/dist/base/core/src/createReactivityAdapter.d.ts +8 -0
  26. package/dist/base/core/src/createReactivityAdapter.js +11 -0
  27. package/dist/base/core/src/createStorageAdapter.d.ts +9 -0
  28. package/dist/base/core/src/createStorageAdapter.js +11 -0
  29. package/dist/base/core/src/getIndexInfo.d.ts +39 -0
  30. package/dist/base/core/src/getIndexInfo.js +188 -0
  31. package/dist/base/core/src/index.d.ts +26 -0
  32. package/dist/base/core/src/index.js +39 -0
  33. package/dist/base/core/src/types/Dependency.d.ts +4 -0
  34. package/dist/base/core/src/types/Dependency.js +2 -0
  35. package/dist/base/core/src/types/IndexProvider.d.ts +26 -0
  36. package/dist/base/core/src/types/IndexProvider.js +2 -0
  37. package/dist/base/core/src/types/Modifier.d.ts +46 -0
  38. package/dist/base/core/src/types/Modifier.js +3 -0
  39. package/dist/base/core/src/types/ReactivityAdapter.d.ts +6 -0
  40. package/dist/base/core/src/types/ReactivityAdapter.js +2 -0
  41. package/dist/base/core/src/types/Selector.d.ts +46 -0
  42. package/dist/base/core/src/types/Selector.js +3 -0
  43. package/dist/base/core/src/types/Signal.d.ts +4 -0
  44. package/dist/base/core/src/types/Signal.js +2 -0
  45. package/dist/base/core/src/types/StorageAdapter.d.ts +28 -0
  46. package/dist/base/core/src/types/StorageAdapter.js +2 -0
  47. package/dist/base/core/src/utils/EventEmitter.d.ts +71 -0
  48. package/dist/base/core/src/utils/EventEmitter.js +144 -0
  49. package/dist/base/core/src/utils/applyQueryOptions.d.ts +15 -0
  50. package/dist/base/core/src/utils/applyQueryOptions.js +36 -0
  51. package/dist/base/core/src/utils/batchOnNextTick.d.ts +16 -0
  52. package/dist/base/core/src/utils/batchOnNextTick.js +72 -0
  53. package/dist/base/core/src/utils/compact.d.ts +9 -0
  54. package/dist/base/core/src/utils/compact.js +21 -0
  55. package/dist/base/core/src/utils/createSignal.d.ts +14 -0
  56. package/dist/base/core/src/utils/createSignal.js +38 -0
  57. package/dist/base/core/src/utils/deepClone.d.ts +17 -0
  58. package/dist/base/core/src/utils/deepClone.js +68 -0
  59. package/dist/base/core/src/utils/get.d.ts +9 -0
  60. package/dist/base/core/src/utils/get.js +27 -0
  61. package/dist/base/core/src/utils/getMatchingKeys.d.ts +19 -0
  62. package/dist/base/core/src/utils/getMatchingKeys.js +49 -0
  63. package/dist/base/core/src/utils/idIndexQuery.d.ts +20 -0
  64. package/dist/base/core/src/utils/idIndexQuery.js +49 -0
  65. package/dist/base/core/src/utils/incrementalQueryUpdate.d.ts +62 -0
  66. package/dist/base/core/src/utils/incrementalQueryUpdate.js +197 -0
  67. package/dist/base/core/src/utils/intersection.d.ts +9 -0
  68. package/dist/base/core/src/utils/intersection.js +16 -0
  69. package/dist/base/core/src/utils/isEqual.d.ts +14 -0
  70. package/dist/base/core/src/utils/isEqual.js +43 -0
  71. package/dist/base/core/src/utils/isFieldExpression.d.ts +11 -0
  72. package/dist/base/core/src/utils/isFieldExpression.js +52 -0
  73. package/dist/base/core/src/utils/match.d.ts +12 -0
  74. package/dist/base/core/src/utils/match.js +16 -0
  75. package/dist/base/core/src/utils/modify.d.ts +14 -0
  76. package/dist/base/core/src/utils/modify.js +29 -0
  77. package/dist/base/core/src/utils/project.d.ts +15 -0
  78. package/dist/base/core/src/utils/project.js +43 -0
  79. package/dist/base/core/src/utils/projectItems.d.ts +12 -0
  80. package/dist/base/core/src/utils/projectItems.js +25 -0
  81. package/dist/base/core/src/utils/queryDelta.d.ts +83 -0
  82. package/dist/base/core/src/utils/queryDelta.js +231 -0
  83. package/dist/base/core/src/utils/queryId.d.ts +9 -0
  84. package/dist/base/core/src/utils/queryId.js +61 -0
  85. package/dist/base/core/src/utils/randomId.d.ts +7 -0
  86. package/dist/base/core/src/utils/randomId.js +12 -0
  87. package/dist/base/core/src/utils/reactiveOrAsync.d.ts +59 -0
  88. package/dist/base/core/src/utils/reactiveOrAsync.js +93 -0
  89. package/dist/base/core/src/utils/serializeValue.d.ts +12 -0
  90. package/dist/base/core/src/utils/serializeValue.js +27 -0
  91. package/dist/base/core/src/utils/set.d.ts +13 -0
  92. package/dist/base/core/src/utils/set.js +43 -0
  93. package/dist/base/core/src/utils/sortItems.d.ts +12 -0
  94. package/dist/base/core/src/utils/sortItems.js +23 -0
  95. package/dist/base/core/src/utils/storageIndexQuery.d.ts +20 -0
  96. package/dist/base/core/src/utils/storageIndexQuery.js +75 -0
  97. package/dist/base/core/src/utils/uniqueBy.d.ts +10 -0
  98. package/dist/base/core/src/utils/uniqueBy.js +19 -0
  99. package/dist/index.cjs +38 -0
  100. package/dist/index.cjs.map +1 -0
  101. package/dist/index.mjs +38 -0
  102. package/dist/index.mjs.map +1 -0
  103. package/dist/reactivity-adapters/svelte/index.svelte.d.ts +10 -0
  104. package/dist/reactivity-adapters/svelte/index.svelte.js +36 -0
  105. package/package.json +3 -3
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const isEqual_1 = __importDefault(require("../utils/isEqual"));
7
+ const uniqueBy_1 = __importDefault(require("../utils/uniqueBy"));
8
+ const queryDelta_1 = require("../utils/queryDelta");
9
+ /**
10
+ * Represents an observer that tracks changes in a collection of items and triggers
11
+ * callbacks for various events such as addition, removal, and modification of items.
12
+ * @template T - The type of the items being observed, which must include an `id` field.
13
+ */
14
+ class Observer {
15
+ previousItems = [];
16
+ callbacks;
17
+ unbindEvents;
18
+ /**
19
+ * Creates a new instance of the `Observer` class.
20
+ * Sets up event bindings and initializes the callbacks for tracking changes in a collection.
21
+ * @param bindEvents - A function to bind external events to the observer. Must return a cleanup function to unbind those events.
22
+ */
23
+ constructor(bindEvents) {
24
+ this.callbacks = {
25
+ added: [],
26
+ addedBefore: [],
27
+ changed: [],
28
+ changedField: [],
29
+ movedBefore: [],
30
+ removed: [],
31
+ };
32
+ this.unbindEvents = bindEvents();
33
+ }
34
+ call(event, ...args) {
35
+ this.callbacks[event].forEach(({ callback, options }) => {
36
+ // execute only if it's not initial call or if initial call should not be skipped
37
+ if (!options.skipInitial || !options.isInitial) {
38
+ callback(...args);
39
+ }
40
+ });
41
+ }
42
+ hasCallbacks(events) {
43
+ return events.some(event => this.callbacks[event].length > 0);
44
+ }
45
+ /**
46
+ * Determines if the observer has no active callbacks registered for any events.
47
+ * @returns A boolean indicating whether the observer is empty (i.e., no callbacks are registered).
48
+ */
49
+ isEmpty() {
50
+ return !this.hasCallbacks([
51
+ 'added',
52
+ 'addedBefore',
53
+ 'changed',
54
+ 'changedField',
55
+ 'movedBefore',
56
+ 'removed',
57
+ ]);
58
+ }
59
+ /**
60
+ * Compares the previous state of items with the new state and triggers the appropriate callbacks
61
+ * for events such as added, removed, changed, or moved items.
62
+ * @param getItems - A function that returns a promise resolving to the new items or the items themselves.
63
+ */
64
+ runChecks(getItems) {
65
+ const result = getItems();
66
+ if (result instanceof Promise) {
67
+ result
68
+ .then(newItems => this.checkItems(newItems))
69
+ .catch((error) => {
70
+ // eslint-disable-next-line no-console
71
+ console.error('Error while asynchronously querying items', error);
72
+ });
73
+ }
74
+ else {
75
+ this.checkItems(result);
76
+ }
77
+ }
78
+ /**
79
+ * Brings the observer up to date from a description of what changed, instead of from the new
80
+ * result.
81
+ *
82
+ * `runChecks` has to rediscover the change by comparing the whole new result against the whole
83
+ * old one — a cost proportional to the result, paid on every write, to find out that one row
84
+ * moved. When the change is already known it can simply be reported, and the cost becomes
85
+ * proportional to the change.
86
+ *
87
+ * The delta must have been computed against exactly the result this observer holds. If it was
88
+ * not, this reports nothing, falls back to `runChecks`, and returns `false`.
89
+ *
90
+ * Note that the reported moves are minimal, where a comparison reports every item whose
91
+ * neighbour changed. Applying them yields the same order either way — there are simply fewer of
92
+ * them.
93
+ * @param delta - The change to report.
94
+ * @param getItems - Used to fall back to a comparison when the delta cannot be applied.
95
+ * @returns Whether the delta was applied.
96
+ */
97
+ applyDelta(delta, getItems) {
98
+ if (!(0, queryDelta_1.canApplyQueryDelta)(this.previousItems, delta)) {
99
+ this.runChecks(getItems);
100
+ return false;
101
+ }
102
+ if ((0, queryDelta_1.isEmptyQueryDelta)(delta))
103
+ return true;
104
+ this.emitDelta(delta, (0, queryDelta_1.applyQueryDelta)(this.previousItems, delta));
105
+ return true;
106
+ }
107
+ /**
108
+ * Reports a delta and adopts the result it produces.
109
+ *
110
+ * The single place the callbacks are fired from, whether the change arrived as a delta or was
111
+ * found by comparing two results — so the two can never disagree about what a consumer is told.
112
+ * @param delta - The change to report.
113
+ * @param nextItems - The result the delta produces.
114
+ */
115
+ emitDelta(delta, nextItems) {
116
+ if (this.isEmpty()) {
117
+ this.finishCheck(nextItems);
118
+ return;
119
+ }
120
+ const beforeOf = (index) => nextItems[index + 1] || null;
121
+ // Indexing the previous result costs its whole length, and most deltas do not need it: an item
122
+ // that changed is reported by its new value, and only a listener asking which *field* changed,
123
+ // or one asking about a removal, needs to see what was there before.
124
+ const needsPreviousItems = (delta.removed.length > 0 && this.hasCallbacks(['removed']))
125
+ || (delta.changed.length > 0 && this.hasCallbacks(['changedField']));
126
+ const previousById = needsPreviousItems
127
+ ? new Map(this.previousItems.map(item => [item.id, item]))
128
+ : null;
129
+ if (this.hasCallbacks(['changed', 'changedField'])) {
130
+ delta.changed.forEach((item) => {
131
+ this.call('changed', item);
132
+ if (!this.hasCallbacks(['changedField']))
133
+ return;
134
+ const oldItem = previousById?.get(item.id);
135
+ if (!oldItem)
136
+ return;
137
+ const keys = (0, uniqueBy_1.default)([
138
+ ...Object.keys(item),
139
+ ...Object.keys(oldItem),
140
+ ], value => value);
141
+ keys.forEach((key) => {
142
+ if ((0, isEqual_1.default)(item[key], oldItem[key]))
143
+ return;
144
+ this.call('changedField', item, key, oldItem[key], item[key]);
145
+ });
146
+ });
147
+ }
148
+ if (this.hasCallbacks(['removed'])) {
149
+ delta.removed.forEach((id) => {
150
+ const oldItem = previousById?.get(id);
151
+ if (oldItem)
152
+ this.call('removed', oldItem);
153
+ });
154
+ }
155
+ if (this.hasCallbacks(['added', 'addedBefore'])) {
156
+ delta.added.forEach(({ index, item }) => {
157
+ this.call('added', item);
158
+ this.call('addedBefore', item, beforeOf(index));
159
+ });
160
+ }
161
+ if (this.hasCallbacks(['movedBefore'])) {
162
+ delta.moved.forEach(({ index }) => {
163
+ this.call('movedBefore', nextItems[index], beforeOf(index));
164
+ });
165
+ }
166
+ this.finishCheck(nextItems);
167
+ }
168
+ finishCheck(newItems) {
169
+ // Store new items as previous items for next check
170
+ this.previousItems = newItems;
171
+ Object.keys(this.callbacks).forEach((key) => {
172
+ const event = key;
173
+ const callbacks = this.callbacks[event];
174
+ this.callbacks[event] = callbacks.map(callback => ({
175
+ ...callback,
176
+ options: {
177
+ ...callback.options,
178
+ isInitial: false,
179
+ },
180
+ }));
181
+ });
182
+ }
183
+ checkItems(newItems) {
184
+ // Derives the change and reports it through the same path a change that arrived ready-made
185
+ // takes. Comparing and then reporting item by item, as this used to, meant the two paths could
186
+ // describe the same change differently — most visibly in how many moves they reported.
187
+ this.emitDelta((0, queryDelta_1.diffQueryResults)(this.previousItems, newItems), newItems);
188
+ }
189
+ stopped = false;
190
+ /**
191
+ * Stops the observer by unbinding all events and cleaning up resources.
192
+ * Safe to call multiple times - will only unbind once.
193
+ */
194
+ stop() {
195
+ if (this.stopped)
196
+ return;
197
+ this.stopped = true;
198
+ this.unbindEvents();
199
+ }
200
+ /**
201
+ * Registers callbacks for specific events to observe changes in the collection.
202
+ * @param callbacks - An object containing the callbacks for various events (e.g., 'added', 'removed').
203
+ * @param skipInitial - A boolean indicating whether to skip invoking the callbacks for the initial state of the collection.
204
+ */
205
+ addCallbacks(callbacks, skipInitial = false) {
206
+ Object.keys(callbacks).forEach((key) => {
207
+ const typedKey = key;
208
+ this.callbacks[typedKey].push({
209
+ callback: callbacks[typedKey],
210
+ options: { skipInitial, isInitial: true },
211
+ });
212
+ });
213
+ }
214
+ /**
215
+ * Removes the specified callbacks for specific events, unregistering them from the observer.
216
+ * @param callbacks - An object containing the callbacks to be removed for various events.
217
+ */
218
+ removeCallbacks(callbacks) {
219
+ Object.keys(callbacks).forEach((key) => {
220
+ const typedKey = key;
221
+ const index = this.callbacks[typedKey]
222
+ .findIndex(({ callback }) => callback === callbacks[typedKey]);
223
+ this.callbacks[typedKey].splice(index, 1);
224
+ });
225
+ }
226
+ }
227
+ exports.default = Observer;
@@ -0,0 +1,341 @@
1
+ import type ReactivityAdapter from '../types/ReactivityAdapter';
2
+ import EventEmitter from '../utils/EventEmitter';
3
+ import type Selector from '../types/Selector';
4
+ import type Modifier from '../types/Modifier';
5
+ import type DataAdapter from '../DataAdapter';
6
+ import type { QueryOptions } from '../DataAdapter';
7
+ import type StorageAdapter from '../types/StorageAdapter';
8
+ import Cursor from './Cursor';
9
+ import type { AsyncFindOptions, BaseItem, FindOptions, SyncFindOptions, Transform, TransformAll } from './types';
10
+ export type { AnyFindOptions, AsyncFindOptions, BaseItem, Transform, TransformAll, SortSpecifier, FieldSpecifier, FindOptions, SyncFindOptions, } from './types';
11
+ export type { CursorOptions, QueryStateAccessor } from './Cursor';
12
+ export type { ObserveCallbacks } from './Observer';
13
+ export { default as createIndex } from '../createIndex';
14
+ export interface CollectionOptions<T extends BaseItem<I>, I, E extends BaseItem = T, U = E> {
15
+ /**
16
+ * @deprecated Use new constructor parameters instead.
17
+ */
18
+ name?: string;
19
+ /**
20
+ * @deprecated Use `DataAdapter` options instead.
21
+ */
22
+ persistence?: StorageAdapter<T, I>;
23
+ primaryKeyGenerator?: (item: Omit<T, 'id'>) => I;
24
+ reactivity?: ReactivityAdapter;
25
+ transform?: Transform<E, U>;
26
+ transformAll?: TransformAll<T, E>;
27
+ indices?: string[];
28
+ enableDebugMode?: boolean;
29
+ fieldTracking?: boolean;
30
+ }
31
+ interface CollectionEvents<T extends BaseItem, E extends BaseItem = T, U = E> {
32
+ 'added': (item: T) => void;
33
+ 'changed': (item: T, modifier: Modifier<T>) => void;
34
+ 'removed': (item: T) => void;
35
+ 'observer.created': <O extends QueryOptions<T>>(selector?: Selector<T>, options?: O) => void;
36
+ 'observer.disposed': <O extends QueryOptions<T>>(selector?: Selector<T>, options?: O) => void;
37
+ /**
38
+ * A query backing at least one live cursor failed and will not deliver
39
+ * results. The cursor keeps returning its neutral empty value, so without
40
+ * listening here a consumer cannot distinguish failure from "no data".
41
+ */
42
+ 'query.error': <O extends QueryOptions<T>>(error: Error, selector?: Selector<T>, options?: O) => void;
43
+ 'getItems': (selector: Selector<T> | undefined) => void;
44
+ 'find': <Async extends boolean, O extends FindOptions<T, Async>>(selector: Selector<T> | undefined, options: O | undefined, cursor: Cursor<E, U, Async>) => void;
45
+ 'findOne': <O extends QueryOptions<T>>(selector: Selector<T>, options: O | undefined, item: U | undefined) => void;
46
+ 'insert': (item: Omit<T, 'id'> & Partial<Pick<T, 'id'>>) => void;
47
+ 'updateOne': (selector: Selector<T>, modifier: Modifier<T>) => void;
48
+ 'updateMany': (selector: Selector<T>, modifier: Modifier<T>) => void;
49
+ 'replaceOne': (selector: Selector<T>, item: Omit<T, 'id'> & Partial<Pick<T, 'id'>>) => void;
50
+ 'removeOne': (selector: Selector<T>) => void;
51
+ 'removeMany': (selector: Selector<T>) => void;
52
+ 'validate': (item: T) => void;
53
+ '_debug.getItems': (callstack: string, selector: Selector<T> | undefined, measuredTime: number) => void;
54
+ '_debug.find': <Async extends boolean, O extends FindOptions<T, Async>>(callstack: string, selector: Selector<T> | undefined, options: O | undefined, cursor: Cursor<E, U, Async>) => void;
55
+ '_debug.findOne': <Async extends boolean, O extends FindOptions<T, Async>>(callstack: string, selector: Selector<T>, options: O | undefined, item: U | undefined) => void;
56
+ '_debug.insert': (callstack: string, item: Omit<T, 'id'> & Partial<Pick<T, 'id'>>) => void;
57
+ '_debug.updateOne': (callstack: string, selector: Selector<T>, modifier: Modifier<T>) => void;
58
+ '_debug.updateMany': (callstack: string, selector: Selector<T>, modifier: Modifier<T>) => void;
59
+ '_debug.replaceOne': (callstack: string, selector: Selector<T>, item: Omit<T, 'id'> & Partial<Pick<T, 'id'>>) => void;
60
+ '_debug.removeOne': (callstack: string, selector: Selector<T>) => void;
61
+ '_debug.removeMany': (callstack: string, selector: Selector<T>) => void;
62
+ }
63
+ /**
64
+ * Represents a collection of data items with support for in-memory operations,
65
+ * persistence, reactivity, and event-based notifications. The collection provides
66
+ * CRUD operations, observer patterns, and batch operations.
67
+ * @template T - The type of the items stored in the collection.
68
+ * @template I - The type of the unique identifier for the items.
69
+ * @template U - The transformed item type after applying transformations (default is T).
70
+ */
71
+ export default class Collection<T extends BaseItem<I> = BaseItem, I = any, E extends BaseItem = T, U = E> extends EventEmitter<CollectionEvents<T, E, U>> {
72
+ private static collections;
73
+ private static debugMode;
74
+ private static batchOperationInProgress;
75
+ private static fieldTracking;
76
+ private static onCreationCallbacks;
77
+ private static onDisposeCallbacks;
78
+ private static largeQueryWarningThreshold;
79
+ private static reportedLargeQueries;
80
+ static getCollections(): Collection<any, any, any, any>[];
81
+ /**
82
+ * Reports live queries whose result is larger than `rows`, once each, with
83
+ * the stack that registered them.
84
+ *
85
+ * A reactive query is re-evaluated whenever the data under it changes, and
86
+ * one registered from a long-lived place — a navigation bar, a provider
87
+ * near the root — keeps that cost for the lifetime of the application. There
88
+ * is otherwise nothing to see: the query works, and its price is only
89
+ * visible as an application that has grown slow. Finding one such query in a
90
+ * real app took a purpose-built profiler and the better part of a day.
91
+ * @param rows - Result size to report above, or `null` to switch the check off.
92
+ */
93
+ static reportLargeQueries(rows: number | null): void;
94
+ static onCreation(callback: (collection: Collection<any>) => void): void;
95
+ static onDispose(callback: (collection: Collection<any>) => void): void;
96
+ /**
97
+ * Enables debug mode for all collections.
98
+ */
99
+ static enableDebugMode: () => void;
100
+ /**
101
+ * Enables field tracking for all collections.
102
+ * @param enable - A boolean indicating whether to enable field tracking.
103
+ */
104
+ static setFieldTracking: (enable: boolean) => void;
105
+ /**
106
+ * Executes a batch operation, allowing multiple modifications to the collection
107
+ * while deferring index rebuilding until all operations in the batch are completed.
108
+ * This improves performance by avoiding repetitive index recalculations and
109
+ * provides atomicity for the batch of operations.
110
+ * Supports both synchronous and asynchronous callbacks.
111
+ *
112
+ * **Without a `collections` argument this affects every collection in the
113
+ * process, not only the ones being written to.** Each of them defers every
114
+ * live query's requery until the batch ends. That is what makes a batch
115
+ * cheap for a handful of writes belonging to one event, and what makes it
116
+ * dangerous around a loop whose length is data-dependent: while it is open
117
+ * nothing anywhere updates, and everything deferred is flushed at once when
118
+ * it closes. One application wrapped a sync of roughly 1,100 records this
119
+ * way and its screens stopped resolving their data for the whole drain.
120
+ *
121
+ * Pass the collections being written to whenever that scope is known — it is
122
+ * both cheaper and safer. `Collection.batch([logs, versions], () => …)`
123
+ * defers those two and leaves everything else live.
124
+ * @param collections - The collections to batch. Omit to batch all of them.
125
+ * @param callback - The batch operation to execute.
126
+ * @returns A promise if the callback returns a promise, otherwise `void`.
127
+ */
128
+ static batch<ReturnType>(callback: () => Promise<ReturnType>): Promise<void>;
129
+ static batch<ReturnType>(callback: () => ReturnType): void;
130
+ static batch<ReturnType>(collections: Collection<any, any, any, any>[], callback: () => Promise<ReturnType>): Promise<void>;
131
+ static batch<ReturnType>(collections: Collection<any, any, any, any>[], callback: () => ReturnType): void;
132
+ readonly name: string;
133
+ private backend;
134
+ private options;
135
+ private isPullingSignal;
136
+ private isPushingSignal;
137
+ private readySignal;
138
+ private debugMode;
139
+ private batchOperationInProgress;
140
+ private isDisposed;
141
+ private postBatchCallbacks;
142
+ private fieldTracking;
143
+ private queryListenersMap;
144
+ private settledQueriesSet;
145
+ /**
146
+ * Initializes a new instance of the `Collection` class with optional configuration.
147
+ * Sets up memory, persistence, reactivity, and indices as specified in the options.
148
+ * @template T - The type of the items stored in the collection.
149
+ * @template I - The type of the unique identifier for the items.
150
+ * @template U - The transformed item type after applying transformations (default is T).
151
+ * @param name - The name of the collection.
152
+ * @param dataAdapter - The data adapter for creating the collection backend.
153
+ * @param options - Optional configuration for the collection.
154
+ * @param options.name - An optional name for the collection.
155
+ * @param options.memory - The in-memory adapter for storing items.
156
+ * @param options.reactivity - The reactivity adapter for observing changes in the collection.
157
+ * @param options.transform - A transformation function to apply to items when retrieving them.
158
+ * @param options.persistence - The persistence adapter for saving and loading items.
159
+ * @param options.indices - An array of index providers for optimized querying.
160
+ * @param options.enableDebugMode - A boolean to enable or disable debug mode.
161
+ * @param options.fieldTracking - A boolean to enable or disable field tracking by default.
162
+ * @param options.transformAll - A function that will be able to solve the n+1 problem
163
+ */
164
+ constructor(options?: CollectionOptions<T, I, E, U>);
165
+ constructor(name: string, dataAdapter: DataAdapter, options?: CollectionOptions<T, I, E, U>);
166
+ /**
167
+ * Reports a live query the first time its result is found to be larger than
168
+ * the configured threshold. Once per query, because it re-runs on every
169
+ * write and a warning per write would be its own performance problem.
170
+ * @param selector - The query's selector.
171
+ * @param options - The query's options.
172
+ * @param registrationStack - Where the query was registered, if captured.
173
+ */
174
+ private reportIfLargeQuery;
175
+ isBatchOperationInProgress(): boolean;
176
+ /**
177
+ * Checks whether the collection is currently performing a pull operation
178
+ * ⚡️ this function is reactive!
179
+ * (loading data from the persistence adapter).
180
+ * @returns A boolean indicating if the collection is in the process of pulling data.
181
+ */
182
+ isPulling(): boolean;
183
+ /**
184
+ * Checks whether the collection is currently performing a push operation
185
+ * ⚡️ this function is reactive!
186
+ * (saving data to the persistence adapter).
187
+ * @returns A boolean indicating if the collection is in the process of pushing data.
188
+ */
189
+ isPushing(): boolean;
190
+ /**
191
+ * Checks whether the collection is currently performing either a pull or push operation,
192
+ * ⚡️ this function is reactive!
193
+ * indicating that it is loading or saving data.
194
+ * @returns A boolean indicating if the collection is in the process of loading or saving data.
195
+ */
196
+ isLoading(): boolean;
197
+ /**
198
+ * Retrieves the current debug mode status of the collection.
199
+ * @returns A boolean indicating whether debug mode is enabled for the collection.
200
+ */
201
+ getDebugMode(): boolean;
202
+ /**
203
+ * Enables or disables debug mode for the collection.
204
+ * When debug mode is enabled, additional debugging information and events are emitted.
205
+ * @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) debug mode.
206
+ */
207
+ setDebugMode(enable: boolean): void;
208
+ /**
209
+ * Enables or disables field tracking for the collection.
210
+ * @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) field tracking.
211
+ */
212
+ setFieldTracking(enable: boolean): void;
213
+ /**
214
+ * Resolves when the persistence adapter finished initializing
215
+ * and the collection is ready to be used.
216
+ * @returns A promise that resolves when the collection is ready.
217
+ * @example
218
+ * ```ts
219
+ * const collection = new Collection({
220
+ * persistence: // ...
221
+ * })
222
+ * await collection.isReady()
223
+ *
224
+ * collection.insert({ name: 'Item 1' })
225
+ */
226
+ ready(): Promise<void>;
227
+ /**
228
+ * Checks if the collection is ready.
229
+ * ⚡️ this function is reactive!
230
+ * @returns A boolean indicating whether the collection is ready.
231
+ */
232
+ isReady(): boolean;
233
+ private profile;
234
+ private executeInDebugMode;
235
+ private transform;
236
+ private transformAll;
237
+ private getItem;
238
+ private getItems;
239
+ private withPushState;
240
+ private queryListeners;
241
+ /**
242
+ * Disposes the collection, unregisters persistence adapters, clears memory, and
243
+ * cleans up all resources used by the collection.
244
+ * @returns A promise that resolves when the collection is disposed.
245
+ */
246
+ dispose(): Promise<void>;
247
+ /**
248
+ * Finds multiple items in the collection based on a selector and optional options.
249
+ * Returns a cursor for reactive data queries.
250
+ * @param [selector] - The criteria to select items.
251
+ * @param [options] - Options for the find operation, such as limit and sort.
252
+ * @returns A cursor to fetch and observe the matching items.
253
+ */
254
+ find(selector?: Selector<T>, options?: SyncFindOptions<T>): Cursor<E, U, false>;
255
+ find(selector: Selector<T> | undefined, options: AsyncFindOptions<T>): Cursor<E, U, true>;
256
+ find(selector?: Selector<T>, options?: FindOptions<T, boolean>): Cursor<E, U, boolean>;
257
+ /**
258
+ * Finds a single item in the collection based on a selector and optional options.
259
+ * ⚡️ this function is reactive!
260
+ * Returns the found item or undefined if no item matches.
261
+ * @param selector - The criteria to select the item.
262
+ * @param [options] - Options for the find operation, such as projection.
263
+ * @returns The found item or `undefined`.
264
+ */
265
+ findOne(selector: Selector<T>, options?: Omit<SyncFindOptions<T>, 'limit'>): U | undefined;
266
+ findOne(selector: Selector<T>, options: Omit<AsyncFindOptions<T>, 'limit'>): Promise<U | undefined>;
267
+ findOne(selector: Selector<T>, options?: Omit<FindOptions<T, boolean>, 'limit'>): Promise<U | undefined> | U | undefined;
268
+ /**
269
+ * Performs a batch operation, deferring index rebuilds and allowing multiple
270
+ * modifications to be made atomically. Executes any post-batch callbacks afterwards.
271
+ * @param callback - The batch operation to execute.
272
+ * @returns A promise if the callback returns a promise, otherwise void.
273
+ */
274
+ batch<ReturnType>(callback: () => Promise<ReturnType>): Promise<void>;
275
+ batch<ReturnType>(callback: () => ReturnType): void;
276
+ onPostBatch(callback: () => void): void;
277
+ /**
278
+ * Inserts a single item into the collection. Generates a unique ID if not provided.
279
+ * @param item - The item to insert.
280
+ * @returns The ID of the inserted item.
281
+ * @throws {Error} If the collection is disposed or the item has an invalid ID.
282
+ */
283
+ insert(item: Omit<T, 'id'> & Partial<Pick<T, 'id'>>): Promise<I>;
284
+ /**
285
+ * Inserts multiple items into the collection. Generates unique IDs for items if not provided.
286
+ * @param items - The items to insert.
287
+ * @returns An array of IDs of the inserted items.
288
+ * @throws {Error} If the collection is disposed or the items are invalid.
289
+ */
290
+ insertMany(items: Array<Omit<T, 'id'> & Partial<Pick<T, 'id'>>>): Promise<I[]>;
291
+ /**
292
+ * Updates a single item in the collection that matches the given selector.
293
+ * @param selector - The criteria to select the item to update.
294
+ * @param modifier - The modifications to apply to the item.
295
+ * @param [options] - Optional settings for the update operation.
296
+ * @param [options.upsert] - If `true`, creates a new item if no item matches the selector.
297
+ * @returns The number of items updated (0 or 1).
298
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
299
+ */
300
+ updateOne(selector: Selector<T>, modifier: Modifier<T>, options?: {
301
+ upsert?: boolean;
302
+ }): Promise<number>;
303
+ /**
304
+ * Updates multiple items in the collection that match the given selector.
305
+ * @param selector - The criteria to select the items to update.
306
+ * @param modifier - The modifications to apply to the items.
307
+ * @param [options] - Optional settings for the update operation.
308
+ * @param [options.upsert] - If `true`, creates new items if no items match the selector.
309
+ * @returns The number of items updated.
310
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
311
+ */
312
+ updateMany(selector: Selector<T>, modifier: Modifier<T>, options?: {
313
+ upsert?: boolean;
314
+ }): Promise<number>;
315
+ /**
316
+ * Replaces a single item in the collection that matches the given selector.
317
+ * @param selector - The criteria to select the item to replace.
318
+ * @param replacement - The item to replace the selected item with.
319
+ * @param [options] - Optional settings for the replace operation.
320
+ * @param [options.upsert] - If `true`, creates a new item if no item matches the selector.
321
+ * @returns The number of items replaced (0 or 1).
322
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
323
+ */
324
+ replaceOne(selector: Selector<T>, replacement: Omit<T, 'id'> & Partial<Pick<T, 'id'>>, options?: {
325
+ upsert?: boolean;
326
+ }): Promise<number>;
327
+ /**
328
+ * Removes a single item from the collection that matches the given selector.
329
+ * @param selector - The criteria to select the item to remove.
330
+ * @returns The number of items removed (0 or 1).
331
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
332
+ */
333
+ removeOne(selector: Selector<T>): Promise<number>;
334
+ /**
335
+ * Removes multiple items from the collection that match the given selector.
336
+ * @param selector - The criteria to select the items to remove.
337
+ * @returns The number of items removed.
338
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
339
+ */
340
+ removeMany(selector: Selector<T>): Promise<number>;
341
+ }