@signaldb/core 2.0.0-beta.1 → 2.0.0-beta.11

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 (129) hide show
  1. package/dist/.vite/manifest.json +122 -82
  2. package/dist/AsyncDataAdapter.d.ts +44 -7
  3. package/dist/AutoFetchDataAdapter.d.ts +5 -7
  4. package/dist/Collection/Cursor.d.ts +6 -5
  5. package/dist/Collection/Observer.d.ts +2 -0
  6. package/dist/Collection/index.d.ts +34 -25
  7. package/dist/Collection/types.d.ts +10 -2
  8. package/dist/DataAdapter.d.ts +12 -6
  9. package/dist/DefaultDataAdapter.d.ts +6 -6
  10. package/dist/WorkerDataAdapter.d.ts +10 -6
  11. package/dist/WorkerDataAdapterHost.d.ts +7 -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 +4 -1
  19. package/dist/index.mjs +17 -32
  20. package/dist/index10.cjs.js +23 -0
  21. package/dist/index10.mjs +21 -17
  22. package/dist/index11.cjs.js +45 -0
  23. package/dist/index11.mjs +44 -15
  24. package/dist/index12.cjs.js +22 -0
  25. package/dist/index12.mjs +21 -350
  26. package/dist/index13.cjs.js +45 -0
  27. package/dist/index13.mjs +44 -419
  28. package/dist/index14.cjs.js +86 -0
  29. package/dist/index14.mjs +85 -184
  30. package/dist/index15.cjs.js +15 -0
  31. package/dist/index15.mjs +14 -386
  32. package/dist/index16.cjs.js +136 -0
  33. package/dist/index16.mjs +133 -577
  34. package/dist/index17.cjs.js +47 -0
  35. package/dist/index17.mjs +46 -150
  36. package/dist/index18.cjs.js +15 -0
  37. package/dist/index18.mjs +14 -26
  38. package/dist/index19.cjs.js +23 -0
  39. package/dist/index19.mjs +22 -42
  40. package/dist/index2.cjs.js +33 -0
  41. package/dist/index2.mjs +32 -257
  42. package/dist/index20.cjs.js +37 -0
  43. package/dist/index20.mjs +36 -7
  44. package/dist/index21.cjs.js +35 -0
  45. package/dist/index21.mjs +33 -103
  46. package/dist/index22.cjs.js +25 -0
  47. package/dist/index22.mjs +23 -127
  48. package/dist/index23.cjs.js +19 -0
  49. package/dist/index23.mjs +18 -7
  50. package/dist/index24.cjs.js +342 -0
  51. package/dist/index24.mjs +340 -26
  52. package/dist/index25.cjs.js +542 -0
  53. package/dist/index25.mjs +541 -10
  54. package/dist/index26.cjs.js +11 -0
  55. package/dist/index26.mjs +10 -29
  56. package/dist/index27.cjs.js +11 -0
  57. package/dist/index27.mjs +10 -46
  58. package/dist/index28.cjs.js +90 -0
  59. package/dist/index28.mjs +87 -7
  60. package/dist/index29.cjs.js +424 -0
  61. package/dist/index29.mjs +423 -9
  62. package/dist/index3.cjs.js +19 -0
  63. package/dist/index3.mjs +18 -541
  64. package/dist/index30.cjs.js +72 -0
  65. package/dist/index30.mjs +71 -5
  66. package/dist/index31.cjs.js +191 -0
  67. package/dist/index31.mjs +190 -7
  68. package/dist/index32.cjs.js +21 -0
  69. package/dist/index32.mjs +20 -29
  70. package/dist/index33.cjs.js +335 -0
  71. package/dist/index33.mjs +334 -42
  72. package/dist/index34.cjs.js +539 -0
  73. package/dist/index34.mjs +539 -0
  74. package/dist/index4.cjs.js +150 -0
  75. package/dist/index4.mjs +149 -5
  76. package/dist/index5.cjs.js +254 -0
  77. package/dist/index5.mjs +252 -4
  78. package/dist/index6.cjs.js +125 -0
  79. package/dist/index6.mjs +124 -29
  80. package/dist/index7.cjs.js +33 -0
  81. package/dist/index7.mjs +32 -12
  82. package/dist/index8.cjs.js +12 -0
  83. package/dist/index8.mjs +10 -4
  84. package/dist/index9.cjs.js +11 -0
  85. package/dist/index9.mjs +10 -133
  86. package/dist/types/IndexProvider.d.ts +2 -2
  87. package/dist/types/Modifier.d.ts +1 -1
  88. package/dist/types/ReactivityAdapter.d.ts +1 -1
  89. package/dist/utils/createSignal.d.ts +2 -2
  90. package/dist/utils/deepClone.d.ts +1 -1
  91. package/dist/utils/getMatchingKeys.d.ts +2 -2
  92. package/dist/utils/isFieldExpression.d.ts +1 -1
  93. package/dist/utils/match.d.ts +1 -1
  94. package/dist/utils/modify.d.ts +1 -1
  95. package/dist/utils/queryId.d.ts +2 -2
  96. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  97. package/package.json +3 -3
  98. package/dist/index.cjs10.js +0 -18
  99. package/dist/index.cjs11.js +0 -15
  100. package/dist/index.cjs12.js +0 -350
  101. package/dist/index.cjs13.js +0 -419
  102. package/dist/index.cjs14.js +0 -184
  103. package/dist/index.cjs15.js +0 -386
  104. package/dist/index.cjs16.js +0 -579
  105. package/dist/index.cjs17.js +0 -150
  106. package/dist/index.cjs18.js +0 -26
  107. package/dist/index.cjs19.js +0 -43
  108. package/dist/index.cjs2.js +0 -258
  109. package/dist/index.cjs20.js +0 -7
  110. package/dist/index.cjs21.js +0 -104
  111. package/dist/index.cjs22.js +0 -129
  112. package/dist/index.cjs23.js +0 -7
  113. package/dist/index.cjs24.js +0 -27
  114. package/dist/index.cjs25.js +0 -10
  115. package/dist/index.cjs26.js +0 -29
  116. package/dist/index.cjs27.js +0 -46
  117. package/dist/index.cjs28.js +0 -8
  118. package/dist/index.cjs29.js +0 -9
  119. package/dist/index.cjs3.js +0 -542
  120. package/dist/index.cjs30.js +0 -5
  121. package/dist/index.cjs31.js +0 -7
  122. package/dist/index.cjs32.js +0 -29
  123. package/dist/index.cjs33.js +0 -42
  124. package/dist/index.cjs4.js +0 -5
  125. package/dist/index.cjs5.js +0 -5
  126. package/dist/index.cjs6.js +0 -29
  127. package/dist/index.cjs7.js +0 -12
  128. package/dist/index.cjs8.js +0 -5
  129. package/dist/index.cjs9.js +0 -133
@@ -0,0 +1,59 @@
1
+ export type MaybePromise<T> = T | Promise<T>;
2
+ /**
3
+ * Options that control execution mode (and potential future mode-specific behavior).
4
+ * Keep this minimal; you can extend it later (e.g. signal, timeoutMs, debugLabel).
5
+ */
6
+ export type ModeOptions = {
7
+ async?: boolean;
8
+ };
9
+ /**
10
+ * A generator helper that makes TypeScript infer the “synchronous value type” for maybe-async expressions.
11
+ *
12
+ * Usage:
13
+ * const doc = yield* unwrap(Collection.findOne(...))
14
+ * const list = yield* unwrap(Collection.find(...).fetch())
15
+ *
16
+ * Runtime note:
17
+ * This does not “unwrap” Promises by itself. It yields the value/Promise to the runner and returns the
18
+ * value that the runner feeds back via `.next(...)`.
19
+ * @param value The value (or Promise of a value) to yield to the runner.
20
+ * @returns A generator that yields `value` and resolves to the runner-supplied unwrapped `T`.
21
+ */
22
+ export declare function unwrap<T>(value: MaybePromise<T>): Generator<MaybePromise<T>, T, T>;
23
+ /**
24
+ * Generator shape used by the factory.
25
+ *
26
+ * `TThis` is the type of `this` inside the generator.
27
+ * `Args` are the method parameters (excluding the mode flag).
28
+ * `TReturn` is the final return value of the workflow.
29
+ * `TNext` is the type that is yielded/awaited and fed back via `.next(...)`.
30
+ *
31
+ * Note:
32
+ * - For best inference at yield sites, prefer `yield* unwrap(expr)` for maybe-async expressions.
33
+ */
34
+ export type ReactiveOrAsyncGen<TThis, Arguments extends any[], TReturn, TNext> = (this: TThis, a: boolean, ...args: Arguments) => Generator<MaybePromise<TNext>, TReturn, TNext>;
35
+ /**
36
+ * The method type produced from the generator signature.
37
+ * Adds overloads so that `{ async: true }` yields a `Promise<...>` return type.
38
+ */
39
+ export type ReactiveOrAsyncMethod<TThis, P extends any[], R, N> = {
40
+ (this: TThis, ...args: P): R;
41
+ (this: TThis, ...args: [...P, ModeOptions?]): MaybePromise<R>;
42
+ (this: TThis, ...args: [...P, {
43
+ async: true;
44
+ }]): Promise<R>;
45
+ } & {
46
+ /** Exposes the underlying generator for composition via `yield* method.generator.call(this, a, ...)` */
47
+ generator: (this: TThis, a: boolean, ...args: P) => Generator<MaybePromise<N>, R, N>;
48
+ };
49
+ /**
50
+ * Factory that turns a generator workflow into a callable method that can run in sync (reactive) or async mode.
51
+ *
52
+ * Call style:
53
+ * fn(a, b) -> sync/reactive return
54
+ * await fn(a, b, { async: true }) -> async return
55
+ * @param gen Generator workflow. Receives `(a)` which indicates async mode and should `yield`/`yield* unwrap(...)`
56
+ * any values that may be Promises.
57
+ * @returns A callable method with overloads plus a `.generator` property for composition.
58
+ */
59
+ export default function reactiveOrAsync<TThis, P extends any[], R, N>(gen: (this: TThis, a: boolean, ...args: P) => Generator<MaybePromise<N>, R, N>): ReactiveOrAsyncMethod<TThis, P, R, N>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@signaldb/core",
3
- "version": "2.0.0-beta.1",
3
+ "version": "2.0.0-beta.11",
4
4
  "description": "SignalDB is a client-side database that provides a simple MongoDB-like interface to the data with first-class typescript support to achieve an optimistic UI. Data persistence can be achieved by using storage providers that store the data through a JSON interface to places such as localStorage.",
5
5
  "scripts": {
6
6
  "build": "rimraf dist && vite build",
@@ -55,9 +55,9 @@
55
55
  ],
56
56
  "dependencies": {
57
57
  "fast-sort": "^3.4.1",
58
- "mingo": "^6.5.1"
58
+ "mingo": "^7.1.1"
59
59
  },
60
60
  "devDependencies": {
61
- "zod": "^4.0.14"
61
+ "zod": "^4.3.5"
62
62
  }
63
63
  }
@@ -1,18 +0,0 @@
1
- "use strict";
2
- function get(value, path) {
3
- const normalized = path.replaceAll(/\[(\w+)\]/g, ".$1");
4
- if (normalized.includes("..") || normalized.startsWith(".") || normalized.endsWith(".")) {
5
- return;
6
- }
7
- const segments = normalized.split(".");
8
- let current = value;
9
- for (const key of segments) {
10
- if (current == null)
11
- return;
12
- current = current[key];
13
- }
14
- if (current === void 0)
15
- return;
16
- return current;
17
- }
18
- module.exports = get;
@@ -1,15 +0,0 @@
1
- "use strict";
2
- function serializeValue(value) {
3
- if (value == null)
4
- return null;
5
- if (typeof value === "string")
6
- return value;
7
- if (typeof value === "number")
8
- return value.toString();
9
- if (typeof value === "boolean")
10
- return value.toString();
11
- if (value instanceof Date)
12
- return value.toISOString();
13
- return JSON.stringify(value);
14
- }
15
- module.exports = serializeValue;
@@ -1,350 +0,0 @@
1
- "use strict";
2
- const createIndex = require("./index.cjs21.js");
3
- const getIndexInfo = require("./index.cjs22.js");
4
- const deepClone = require("./index.cjs19.js");
5
- const EventEmitter = require("./index.cjs9.js");
6
- const isEqual = require("./index.cjs6.js");
7
- const match = require("./index.cjs23.js");
8
- const modify = require("./index.cjs7.js");
9
- const project = require("./index.cjs24.js");
10
- const queryId = require("./index.cjs20.js");
11
- const serializeValue = require("./index.cjs11.js");
12
- const sortItems = require("./index.cjs25.js");
13
- function hasPendingUpdates(pendingUpdates) {
14
- return pendingUpdates.added.length > 0 || pendingUpdates.modified.length > 0 || pendingUpdates.removed.length > 0;
15
- }
16
- class DefaultDataAdapter {
17
- items = /* @__PURE__ */ new Map();
18
- options;
19
- storageAdapters = /* @__PURE__ */ new Map();
20
- indices = /* @__PURE__ */ new Map();
21
- activeQueries = /* @__PURE__ */ new Map();
22
- queryEmitters = /* @__PURE__ */ new Map();
23
- queuedQueryUpdates = /* @__PURE__ */ new Map();
24
- cachedQueryResults = /* @__PURE__ */ new Map();
25
- constructor(options) {
26
- this.options = options || {};
27
- }
28
- ensureStorageAdapter(name) {
29
- if (this.storageAdapters.get(name))
30
- return;
31
- if (!this.options.storage)
32
- return;
33
- const adapter = this.options.storage(name);
34
- if (!adapter)
35
- return;
36
- this.storageAdapters.set(name, adapter);
37
- }
38
- rebuildIndices(collection) {
39
- const items = this.items.get(collection.name);
40
- if (!items)
41
- throw new Error(`Items not found for collection ${collection.name}`);
42
- const indices = this.indices.get(collection.name);
43
- if (!indices)
44
- throw new Error(`Indices not found for collection ${collection.name}`);
45
- indices.forEach((index) => index.rebuild([...items.values()]));
46
- }
47
- async setupStorageAdapter(collection) {
48
- const storageAdapter = this.storageAdapters.get(collection.name);
49
- if (!storageAdapter)
50
- return;
51
- return storageAdapter.setup().then(async () => {
52
- const items = await storageAdapter.readAll();
53
- this.items.set(collection.name, items.reduce((map, item) => {
54
- map.set(serializeValue(item.id), item);
55
- return map;
56
- }, /* @__PURE__ */ new Map()));
57
- this.rebuildIndices(collection);
58
- }).catch((error) => {
59
- if (!this.options.onError) {
60
- console.error(`Error during data persistence operation in collection ${collection.name}`, error);
61
- return;
62
- }
63
- this.options.onError(collection.name, error instanceof Error ? error : new Error(error));
64
- });
65
- }
66
- getIndexInfo(collection, selector) {
67
- if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
68
- return {
69
- matched: true,
70
- ids: [serializeValue(selector.id)],
71
- optimizedSelector: {}
72
- };
73
- }
74
- if (selector == null) {
75
- return {
76
- matched: false,
77
- ids: [],
78
- optimizedSelector: {}
79
- };
80
- }
81
- return getIndexInfo.default((this.indices.get(collection.name) ?? []).map((i) => i.query.bind(i)), selector);
82
- }
83
- applyIndexDeltas(collection, changes) {
84
- const indices = this.indices.get(collection.name) ?? [];
85
- for (const index of indices) {
86
- if (changes.modified)
87
- index.update(changes.modified);
88
- if (changes.added && changes.added.length > 0)
89
- index.insert(changes.added);
90
- if (changes.removed && changes.removed.length > 0)
91
- index.remove(changes.removed);
92
- }
93
- }
94
- getItem(collection, selector) {
95
- const memory = this.items.get(collection.name) ?? /* @__PURE__ */ new Map();
96
- const indexInfo = this.getIndexInfo(collection, selector);
97
- const items = indexInfo.matched ? indexInfo.ids.map((id) => memory.get(serializeValue(id))).filter((i) => i != null) : [...memory.values()];
98
- const item = items.find((document) => match(document, selector));
99
- return item;
100
- }
101
- queryItems(collection, selector) {
102
- const indexInfo = this.getIndexInfo(collection, selector);
103
- const matchItems = (item) => {
104
- if (indexInfo.optimizedSelector == null)
105
- return true;
106
- if (Object.keys(indexInfo.optimizedSelector).length <= 0)
107
- return true;
108
- const matches = match(item, indexInfo.optimizedSelector);
109
- return matches;
110
- };
111
- const items = this.items.get(collection.name);
112
- if (!indexInfo.matched) {
113
- if (isEqual(selector, {}))
114
- return [...items.values()];
115
- return [...items.values()].filter(matchItems);
116
- }
117
- const foundItems = indexInfo.ids.map((ids) => items.get(serializeValue(ids))).filter((i) => i != null);
118
- if (isEqual(indexInfo.optimizedSelector, {}))
119
- return foundItems;
120
- return foundItems.filter(matchItems);
121
- }
122
- executeQuery(collection, selector, options) {
123
- const items = this.queryItems(collection, selector || {});
124
- const { sort, skip, limit, fields } = options || {};
125
- const sorted = sort ? sortItems(items, sort) : items;
126
- const skipped = skip ? sorted.slice(skip) : sorted;
127
- const limited = limit ? skipped.slice(0, limit) : skipped;
128
- const idExcluded = fields && fields.id === 0;
129
- return limited.map((item) => {
130
- if (!fields)
131
- return item;
132
- return {
133
- ...idExcluded ? {} : { id: item.id },
134
- ...project(item, fields)
135
- };
136
- });
137
- }
138
- flushQueuedQueryUpdates(collection) {
139
- if (!this.queuedQueryUpdates.get(collection.name))
140
- return;
141
- const changes = this.queuedQueryUpdates.get(collection.name);
142
- if (!changes || !hasPendingUpdates(changes))
143
- return;
144
- this.queuedQueryUpdates.set(collection.name, { added: [], modified: [], removed: [] });
145
- const flatItems = [...changes.added, ...changes.modified, ...changes.removed];
146
- const itemIds = new Set(flatItems.map((i) => i.id));
147
- const queries = [
148
- ...this.activeQueries.get(collection.name)?.values() ?? []
149
- ].filter(({ selector, options }) => {
150
- const idsInQuery = this.cachedQueryResults.get(collection.name)?.get(queryId(selector, options))?.map((i) => i.id) ?? [];
151
- if (idsInQuery.some((id) => itemIds.has(id)))
152
- return true;
153
- return flatItems.some((item) => match(item, selector));
154
- });
155
- queries.forEach(({ selector, options }) => {
156
- this.executeAndCacheQuery(collection, selector, options);
157
- });
158
- }
159
- executeAndCacheQuery(collection, selector, options) {
160
- const result = this.executeQuery(collection, selector, options);
161
- this.cachedQueryResults.set(collection.name, this.cachedQueryResults.get(collection.name) || /* @__PURE__ */ new Map());
162
- this.cachedQueryResults.get(collection.name)?.set(queryId(selector, options), result);
163
- const emitter = this.queryEmitters.get(collection.name);
164
- if (!emitter)
165
- return;
166
- emitter.emit("change", selector, options, "complete");
167
- }
168
- updateQueries(collection, changes) {
169
- this.queuedQueryUpdates.set(collection.name, this.queuedQueryUpdates.get(collection.name) || { added: [], modified: [], removed: [] });
170
- this.queuedQueryUpdates.get(collection.name)?.added.push(...changes.added);
171
- this.queuedQueryUpdates.get(collection.name)?.modified.push(...changes.modified);
172
- this.queuedQueryUpdates.get(collection.name)?.removed.push(...changes.removed);
173
- this.flushQueuedQueryUpdates(collection);
174
- }
175
- createCollectionBackend(collection, indices) {
176
- this.ensureStorageAdapter(collection.name);
177
- this.items.set(collection.name, this.items.get(collection.name) ?? /* @__PURE__ */ new Map());
178
- this.queryEmitters.set(collection.name, this.queryEmitters.get(collection.name) ?? new EventEmitter());
179
- this.queryEmitters.get(collection.name)?.setMaxListeners(Infinity);
180
- this.activeQueries.set(collection.name, this.activeQueries.get(collection.name) || /* @__PURE__ */ new Map());
181
- this.indices.set(collection.name, indices.map((field) => createIndex(field)));
182
- this.rebuildIndices(collection);
183
- const persistenceReadyPromise = this.setupStorageAdapter(collection);
184
- const backend = {
185
- // CRUD operations
186
- insert: async (newItem) => {
187
- const items = this.items.get(collection.name);
188
- if (!items)
189
- throw new Error(`Items not found for collection ${collection.name}`);
190
- if (items.has(serializeValue(newItem.id))) {
191
- throw new Error(`Item with id '${newItem.id}' already exists`);
192
- }
193
- this.items.get(collection.name)?.set(serializeValue(newItem.id), newItem);
194
- await this.storageAdapters.get(collection.name)?.insert([newItem]);
195
- this.applyIndexDeltas(collection, { added: [newItem] });
196
- this.updateQueries(collection, {
197
- added: [],
198
- modified: [newItem],
199
- removed: []
200
- });
201
- return newItem;
202
- },
203
- updateOne: async (selector, modifier) => {
204
- const { $setOnInsert, ...restModifier } = modifier;
205
- const item = this.getItem(collection, selector);
206
- if (item == null)
207
- return [];
208
- const modifiedItem = modify(deepClone.default(item), restModifier);
209
- const hasItemWithSameId = item.id !== modifiedItem.id && this.getItem(collection, { id: modifiedItem.id }) != null;
210
- if (hasItemWithSameId) {
211
- throw new Error(`Item with id '${modifiedItem.id}' already exists`);
212
- }
213
- this.items.get(collection.name)?.set(serializeValue(modifiedItem.id), modifiedItem);
214
- await this.storageAdapters.get(collection.name)?.replace([modifiedItem]);
215
- this.applyIndexDeltas(collection, { modified: [{ oldItem: item, newItem: modifiedItem }] });
216
- this.updateQueries(collection, {
217
- added: [],
218
- modified: [modifiedItem],
219
- removed: []
220
- });
221
- return [modifiedItem];
222
- },
223
- updateMany: async (selector, modifier) => {
224
- const { $setOnInsert, ...restModifier } = modifier;
225
- const items = this.executeQuery(collection, selector, {});
226
- const changedItems = items.map((item) => {
227
- const modifiedItem = modify(deepClone.default(item), restModifier);
228
- const hasItemWithSameId = item.id !== modifiedItem.id && this.getItem(collection, { id: modifiedItem.id }) != null;
229
- if (hasItemWithSameId) {
230
- throw new Error(`Item with id '${modifiedItem.id}' already exists`);
231
- }
232
- return modifiedItem;
233
- });
234
- changedItems.forEach((item) => {
235
- this.items.get(collection.name)?.set(serializeValue(item.id), item);
236
- });
237
- await this.storageAdapters.get(collection.name)?.replace(changedItems);
238
- const pairs = items.map((oldItem, index) => ({ oldItem, newItem: changedItems[index] }));
239
- this.applyIndexDeltas(collection, { modified: pairs });
240
- this.updateQueries(collection, {
241
- added: [],
242
- modified: changedItems,
243
- removed: []
244
- });
245
- return changedItems;
246
- },
247
- replaceOne: async (selector, replacement) => {
248
- const item = this.getItem(collection, selector);
249
- if (item == null)
250
- return [];
251
- const hasItemWithSameId = item.id !== replacement.id && replacement.id != null && this.getItem(collection, { id: replacement.id }) != null;
252
- if (hasItemWithSameId) {
253
- throw new Error(`Item with id '${replacement.id}' already exists`);
254
- }
255
- const modifiedItem = { id: item.id, ...replacement };
256
- this.items.get(collection.name)?.set(serializeValue(modifiedItem.id), modifiedItem);
257
- await this.storageAdapters.get(collection.name)?.replace([modifiedItem]);
258
- this.applyIndexDeltas(collection, { modified: [{ oldItem: item, newItem: modifiedItem }] });
259
- this.updateQueries(collection, {
260
- added: [],
261
- modified: [modifiedItem],
262
- removed: []
263
- });
264
- return [modifiedItem];
265
- },
266
- removeOne: async (selector) => {
267
- const item = this.getItem(collection, selector);
268
- if (item == null)
269
- return [];
270
- this.items.get(collection.name)?.delete(serializeValue(item.id));
271
- await this.storageAdapters.get(collection.name)?.remove([item]);
272
- this.applyIndexDeltas(collection, { removed: [item] });
273
- this.updateQueries(collection, {
274
- added: [],
275
- modified: [],
276
- removed: [item]
277
- });
278
- return [item];
279
- },
280
- removeMany: async (selector) => {
281
- const items = backend.getQueryResult(selector, {});
282
- items.forEach((item) => {
283
- this.items.get(collection.name)?.delete(serializeValue(item.id));
284
- });
285
- await this.storageAdapters.get(collection.name)?.remove(items);
286
- this.applyIndexDeltas(collection, { removed: items });
287
- this.updateQueries(collection, {
288
- added: [],
289
- modified: [],
290
- removed: items
291
- });
292
- return items;
293
- },
294
- // methods for registering and unregistering queries that will be called from the collection during find/findOne
295
- registerQuery: (selector, options) => {
296
- this.activeQueries.set(collection.name, this.activeQueries.get(collection.name) || /* @__PURE__ */ new Map());
297
- this.activeQueries.get(collection.name)?.set(queryId(selector, options), {
298
- selector,
299
- options
300
- });
301
- this.executeAndCacheQuery(collection, selector, options);
302
- },
303
- unregisterQuery: (selector, options) => {
304
- if (!this.activeQueries.get(collection.name))
305
- return;
306
- this.activeQueries.get(collection.name)?.delete(queryId(selector, options));
307
- },
308
- getQueryState: () => "complete",
309
- onQueryStateChange: (selector, options, callback) => {
310
- const emitter = this.queryEmitters.get(collection.name);
311
- if (!emitter)
312
- throw new Error(`Query emitter not found for collection ${collection.name}`);
313
- const handler = (querySelector, queryOptions, state) => {
314
- if (queryId(querySelector, queryOptions) !== queryId(selector, options))
315
- return;
316
- callback(state);
317
- };
318
- emitter.on("change", handler);
319
- return () => {
320
- emitter.off("change", handler);
321
- };
322
- },
323
- getQueryError: () => null,
324
- getQueryResult: (selector, options) => {
325
- const isQueryActive = this.activeQueries.get(collection.name)?.has(queryId(selector, options));
326
- if (isQueryActive) {
327
- return this.cachedQueryResults.get(collection.name)?.get(queryId(selector, options)) ?? [];
328
- }
329
- return this.executeQuery(collection, selector, options);
330
- },
331
- executeQuery: (selector, options) => Promise.resolve(this.executeQuery(collection, selector, options)),
332
- // lifecycle methods
333
- dispose: async () => {
334
- const adapter = this.storageAdapters.get(collection.name);
335
- if (adapter?.teardown)
336
- await adapter.teardown();
337
- this.storageAdapters.delete(collection.name);
338
- this.items.delete(collection.name);
339
- this.indices.delete(collection.name);
340
- this.activeQueries.delete(collection.name);
341
- this.queryEmitters.delete(collection.name);
342
- this.queuedQueryUpdates.delete(collection.name);
343
- this.cachedQueryResults.delete(collection.name);
344
- },
345
- isReady: () => persistenceReadyPromise
346
- };
347
- return backend;
348
- }
349
- }
350
- module.exports = DefaultDataAdapter;