@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
package/dist/index15.mjs CHANGED
@@ -1,387 +1,15 @@
1
- import deepClone from "./index19.mjs";
2
- import match from "./index23.mjs";
3
- import modify from "./index7.mjs";
4
- import queryId from "./index20.mjs";
5
- import isEqual from "./index6.mjs";
6
- import getIndexInfo from "./index22.mjs";
7
- import getMatchingKeys from "./index26.mjs";
8
- import sortItems from "./index25.mjs";
9
- import project from "./index24.mjs";
10
- import compact from "./index28.mjs";
11
- class WorkerDataAdapterHost {
12
- workerContext;
13
- options;
14
- id;
15
- log = () => {
16
- };
17
- storageAdapters = /* @__PURE__ */ new Map();
18
- storageAdapterReady = /* @__PURE__ */ new Map();
19
- collectionIndices = /* @__PURE__ */ new Map();
20
- queries = /* @__PURE__ */ new Map();
21
- onError = (error) => {
22
- console.error(error);
23
- };
24
- constructor(workerContext, options) {
25
- this.workerContext = workerContext;
26
- this.options = options;
27
- this.id = this.options.id || "default-worker-data-adapter";
28
- if (this.options.onError) {
29
- this.onError = this.options.onError;
30
- }
31
- if (this.options.log)
32
- this.log = this.options.log;
33
- if (typeof addEventListener === "undefined" || typeof postMessage === "undefined") {
34
- throw new TypeError("WorkerDataAdapterHost can only be used in a Web Worker context");
35
- }
36
- this.workerContext.addEventListener("message", async (event) => {
37
- try {
38
- const { workerId, id, method, args } = event.data;
39
- await this.handleMessage(workerId, id, method, args);
40
- } catch (error) {
41
- this.onError(error);
42
- }
43
- });
44
- this.respond("ready", null, null, "ready");
45
- }
46
- respond(id, data, error = null, type = "response") {
47
- this.workerContext.postMessage({ id, workerId: this.id, type, data, error });
48
- }
49
- async handleMessage(workerId, id, method, args) {
50
- if (workerId !== this.id)
51
- return;
52
- const fn = this[method];
53
- if (typeof fn !== "function") {
54
- this.respond(id, null, new Error(`Method ${method} not found`));
55
- return;
56
- }
57
- this.log(method, ...args);
58
- await this.isReady(args[0]);
59
- try {
60
- const result = await fn.apply(this, args);
61
- this.respond(id, result);
62
- } catch (error) {
63
- this.respond(id, null, error);
64
- }
65
- }
66
- async getIndexInfo(collectionName, selector) {
67
- const storageAdapter = this.storageAdapters.get(collectionName);
68
- if (!storageAdapter)
69
- throw new Error(`No persistence adapter for collection ${collectionName}`);
70
- if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
71
- return {
72
- matched: true,
73
- ids: compact([selector.id]),
74
- optimizedSelector: {}
75
- };
76
- }
77
- if (selector == null) {
78
- return {
79
- matched: false,
80
- ids: [],
81
- optimizedSelector: {}
82
- };
83
- }
84
- const indices = this.collectionIndices.get(collectionName) ?? [];
85
- return getIndexInfo(indices.map((field) => async (flatSelector) => {
86
- if (!Object.hasOwnProperty.call(flatSelector, field)) {
87
- return { matched: false };
88
- }
89
- const index = await storageAdapter.readIndex(field);
90
- const fieldSelector = flatSelector[field];
91
- const filteresForNull = fieldSelector == null || fieldSelector.$exists === false;
92
- const keys = filteresForNull ? { include: null, exclude: [...index.keys()].filter((key) => key != null) } : getMatchingKeys(field, flatSelector);
93
- if (keys.include == null && keys.exclude == null)
94
- return { matched: false };
95
- let includedIds = [];
96
- if (keys.include == null) {
97
- for (const set of index.values()) {
98
- for (const pos of set) {
99
- includedIds.push(pos);
100
- }
101
- }
102
- } else {
103
- for (const key of keys.include) {
104
- const idSet = index.get(key);
105
- if (idSet) {
106
- for (const id of idSet) {
107
- includedIds.push(id);
108
- }
109
- }
110
- }
111
- }
112
- if (keys.exclude != null) {
113
- const excludeIds = /* @__PURE__ */ new Set();
114
- for (const key of keys.exclude) {
115
- const idSet = index.get(key);
116
- if (idSet) {
117
- for (const id of idSet) {
118
- excludeIds.add(id);
119
- }
120
- }
121
- }
122
- includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
123
- }
124
- return {
125
- matched: true,
126
- ids: includedIds,
127
- fields: [field],
128
- keepSelector: filteresForNull
129
- };
130
- }), selector);
131
- }
132
- async queryItems(collectionName, selector) {
133
- const storageAdapter = this.storageAdapters.get(collectionName);
134
- if (!storageAdapter)
135
- throw new Error(`No persistence adapter for collection ${collectionName}`);
136
- const indexInfo = await this.getIndexInfo(collectionName, selector);
137
- const matchItems = (item) => {
138
- if (indexInfo.optimizedSelector == null)
139
- return true;
140
- if (Object.keys(indexInfo.optimizedSelector).length <= 0)
141
- return true;
142
- const matches = match(item, indexInfo.optimizedSelector);
143
- return matches;
144
- };
145
- if (indexInfo.matched) {
146
- const items = await storageAdapter.readIds(indexInfo.ids);
147
- if (isEqual(indexInfo.optimizedSelector, {}))
148
- return items;
149
- return items.filter(matchItems);
150
- } else {
151
- const allItems = await storageAdapter.readAll();
152
- if (isEqual(selector, {}))
153
- return allItems;
154
- return allItems.filter(matchItems);
155
- }
156
- }
157
- async executeQuery(collectionName, selector, options) {
158
- const items = await this.queryItems(collectionName, selector || {});
159
- const { sort, skip, limit, fields } = options || {};
160
- const sorted = sort ? sortItems(items, sort) : items;
161
- const skipped = skip ? sorted.slice(skip) : sorted;
162
- const limited = limit ? skipped.slice(0, limit) : skipped;
163
- const idExcluded = fields && fields.id === 0;
164
- return limited.map((item) => {
165
- if (!fields)
166
- return item;
167
- return {
168
- ...idExcluded ? {} : { id: item.id },
169
- ...project(item, fields)
170
- };
171
- });
172
- }
173
- ensureQuery(collectionName, selector, options) {
174
- const id = queryId(selector, options);
175
- if (!this.queries.get(collectionName)) {
176
- throw new Error(`Collection ${collectionName} not initialized!`);
177
- }
178
- let query = this.queries.get(collectionName)?.get(id);
179
- if (!query) {
180
- query = { selector, options };
181
- this.queries.get(collectionName)?.set(id, query);
182
- }
183
- return query;
184
- }
185
- emitQueryUpdate(collectionName, selector, options, state, error, items) {
186
- const id = queryId(selector, options);
187
- const collectionQueries = this.queries.get(collectionName);
188
- if (!collectionQueries)
189
- throw new Error(`Collection ${collectionName} not initialized!`);
190
- this.respond(id, { collectionName, selector, options, state, error, items }, null, "queryUpdate");
191
- }
192
- ensureStorageAdapter(name) {
193
- if (this.storageAdapters.has(name))
194
- return;
195
- const adapter = this.options.storage(name);
196
- if (!adapter)
197
- return;
198
- this.storageAdapters.set(name, adapter);
199
- }
200
- async checkQueryUpdates(collectionName, items) {
201
- const queries = this.queries.get(collectionName);
202
- if (!queries)
203
- throw new Error(`Collection ${collectionName} not initialized!`);
204
- const affectedQueries = [...queries.values()].filter(({ selector }) => items.some((item) => match(item, selector))) ?? [];
205
- if (affectedQueries.length === 0)
206
- return;
207
- affectedQueries.forEach(({ selector, options }) => {
208
- this.emitQueryUpdate(collectionName, selector, options, "active", null);
209
- });
210
- await Promise.all(affectedQueries.map(async ({ selector, options }) => {
211
- const queryItems = await this.executeQuery(collectionName, selector, options);
212
- this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
213
- }));
214
- }
215
- registerCollection = async (collectionName, indices) => {
216
- this.collectionIndices.set(collectionName, indices);
217
- this.queries.set(collectionName, /* @__PURE__ */ new Map());
218
- this.ensureStorageAdapter(collectionName);
219
- const storageAdapter = this.storageAdapters.get(collectionName);
220
- if (!storageAdapter)
221
- throw new Error(`No persistence adapter for collection ${collectionName}`);
222
- const setupPromise = (async () => {
223
- await Promise.all(indices.map((index) => storageAdapter.createIndex(index)));
224
- await storageAdapter.setup();
225
- })();
226
- this.storageAdapterReady.set(collectionName, setupPromise);
227
- await setupPromise;
228
- };
229
- unregisterCollection = async (collectionName) => {
230
- this.storageAdapters.delete(collectionName);
231
- this.queries.delete(collectionName);
232
- };
233
- registerQuery = async (collectionName, selector, options) => {
234
- this.ensureQuery(collectionName, selector, options);
235
- const queryItems = await this.executeQuery(collectionName, selector, options);
236
- this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
237
- };
238
- unregisterQuery = async (collectionName, selector, options) => {
239
- const id = queryId(selector, options);
240
- if (!this.queries.get(collectionName))
241
- throw new Error(`Collection ${collectionName} not initialized!`);
242
- this.queries.get(collectionName)?.delete(id);
243
- };
244
- insert = async (collectionName, input) => {
245
- const storageAdapter = this.storageAdapters.get(collectionName);
246
- if (!storageAdapter)
247
- throw new Error(`No persistence adapter for collection ${collectionName}`);
248
- const existingItems = await this.executeQuery(collectionName, { id: { $in: input.map((i) => i[0].id) } });
249
- const result = input.map(([item]) => {
250
- if (item.id == null)
251
- throw new Error("Item must have an id");
252
- if (existingItems.some((existing) => existing.id === item.id)) {
253
- return new Error(`Item with id ${item.id} already exists`);
254
- }
255
- return item;
256
- });
257
- const newItems = result.filter((item) => !(item instanceof Error));
258
- await storageAdapter.insert(newItems);
259
- await this.checkQueryUpdates(collectionName, newItems);
260
- return result;
261
- };
262
- updateOne = async (collectionName, parameters) => {
263
- const storageAdapter = this.storageAdapters.get(collectionName);
264
- if (!storageAdapter)
265
- throw new Error(`No persistence adapter for collection ${collectionName}`);
266
- const previousItems = [];
267
- const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
268
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
269
- const { $setOnInsert, ...restModifier } = modifier;
270
- if (item == null)
271
- return [];
272
- previousItems.push(item);
273
- const modifiedItem = modify(deepClone(item), restModifier);
274
- if (item.id !== modifiedItem.id) {
275
- const existingItems = await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 });
276
- if (existingItems.length > 0) {
277
- return new Error(`Item with id ${modifiedItem.id} already exists`);
278
- }
279
- }
280
- return [modifiedItem];
281
- }));
282
- const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
283
- if (modifiedItems.length > 0) {
284
- await storageAdapter.replace(modifiedItems);
285
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
286
- }
287
- return result;
288
- };
289
- updateMany = async (collectionName, parameters) => {
290
- const storageAdapter = this.storageAdapters.get(collectionName);
291
- if (!storageAdapter)
292
- throw new Error(`No persistence adapter for collection ${collectionName}`);
293
- const previousItems = [];
294
- const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
295
- const items = await this.executeQuery(collectionName, selector);
296
- if (items.length === 0)
297
- return [];
298
- const { $setOnInsert, ...restModifier } = modifier;
299
- try {
300
- const changedItems = await Promise.all(items.map(async (item) => {
301
- const modifiedItem = modify(deepClone(item), restModifier);
302
- if (item.id !== modifiedItem.id) {
303
- const existingItems = await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 });
304
- if (existingItems.length > 0) {
305
- throw new Error(`Item with id ${modifiedItem.id} already exists`);
306
- }
307
- }
308
- previousItems.push(item);
309
- return modifiedItem;
310
- }));
311
- return changedItems;
312
- } catch (error) {
313
- return error;
314
- }
315
- }));
316
- const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
317
- if (modifiedItems.length > 0) {
318
- await storageAdapter.replace(modifiedItems);
319
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
320
- }
321
- return result;
322
- };
323
- replaceOne = async (collectionName, parameters) => {
324
- const storageAdapter = this.storageAdapters.get(collectionName);
325
- if (!storageAdapter)
326
- throw new Error(`No persistence adapter for collection ${collectionName}`);
327
- const previousItems = [];
328
- const result = await Promise.all(parameters.map(async ([selector, replacement]) => {
329
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
330
- if (item == null)
331
- return [];
332
- previousItems.push(item);
333
- const modifiedItem = {
334
- ...replacement,
335
- id: replacement.id ?? item.id
336
- };
337
- if (item.id !== modifiedItem.id) {
338
- const existingItems = await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 });
339
- if (existingItems.length > 0) {
340
- return new Error(`Item with id ${modifiedItem.id} already exists`);
341
- }
342
- }
343
- return [modifiedItem];
344
- }));
345
- const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
346
- if (modifiedItems.length > 0) {
347
- await storageAdapter.replace(modifiedItems);
348
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
349
- }
350
- return result;
351
- };
352
- removeOne = async (collectionName, selectors) => {
353
- const storageAdapter = this.storageAdapters.get(collectionName);
354
- if (!storageAdapter)
355
- throw new Error(`No persistence adapter for collection ${collectionName}`);
356
- const result = await Promise.all(selectors.map(async ([selector]) => {
357
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items2) => items2[0] ?? null);
358
- if (item == null)
359
- return [];
360
- return [item];
361
- }));
362
- const items = result.flat();
363
- if (items.length > 0) {
364
- await storageAdapter.remove(items);
365
- await this.checkQueryUpdates(collectionName, items);
366
- }
367
- return result;
368
- };
369
- removeMany = async (collectionName, selectors) => {
370
- const storageAdapter = this.storageAdapters.get(collectionName);
371
- if (!storageAdapter)
372
- throw new Error(`No persistence adapter for collection ${collectionName}`);
373
- const result = await Promise.all(selectors.map(async ([selector]) => this.executeQuery(collectionName, selector)));
374
- const items = result.flat();
375
- if (items.length > 0) {
376
- await storageAdapter.remove(items);
377
- await this.checkQueryUpdates(collectionName, items);
378
- }
379
- return result;
380
- };
381
- isReady = async (collectionName) => {
382
- return this.storageAdapterReady.get(collectionName);
383
- };
1
+ //#region src/utils/intersection.ts
2
+ /**
3
+ * Computes the intersection of multiple arrays, returning an array of unique elements
4
+ * that are present in all the input arrays.
5
+ * @template T - The type of elements in the arrays.
6
+ * @param arrays - A variable number of arrays to compute the intersection of.
7
+ * @returns An array containing the unique elements found in all the input arrays.
8
+ * - If no arrays are provided, returns an empty array.
9
+ */
10
+ function intersection(...arrays) {
11
+ if (arrays.length === 0) return [];
12
+ return [...new Set(arrays.reduce((a, b) => a.filter((c) => b.includes(c))))];
384
13
  }
385
- export {
386
- WorkerDataAdapterHost as default
387
- };
14
+ //#endregion
15
+ export { intersection as default };
@@ -0,0 +1,136 @@
1
+ const require_intersection = require("./index15.cjs.js");
2
+ //#region src/getIndexInfo.ts
3
+ /**
4
+ * Retrieves merged index information for a given flat selector by querying multiple
5
+ * index providers. Combines results from all index providers to determine matched ids
6
+ * and an optimized selector.
7
+ * @template T - The type of the items in the collection.
8
+ * @template I - The type of the unique identifier for the items.
9
+ * @param queryFunctions - An array of index providers to query.
10
+ * @param selector - The flat selector used to filter items.
11
+ * @returns An object containing:
12
+ * - `matched`: A boolean indicating if the selector matched any items.
13
+ * - `ids`: An array of matched item ids.
14
+ * - `optimizedSelector`: A flat selector optimized based on the index results.
15
+ */
16
+ function getMergedIndexInfo(queryFunctions, selector) {
17
+ return queryFunctions.reduce((memoOrPromise, queryFunction) => {
18
+ const resultOrPromise = queryFunction(selector);
19
+ const processResult = (memo, result) => {
20
+ if (!result.matched) return memo;
21
+ const optimizedSelector = result.keepSelector ? memo.optimizedSelector : Object.fromEntries(Object.entries(memo.optimizedSelector).filter(([key]) => !result.fields.includes(key)));
22
+ return {
23
+ matched: true,
24
+ ids: [...new Set(memo.matched ? require_intersection.default(memo.ids, result.ids) : result.ids)],
25
+ optimizedSelector
26
+ };
27
+ };
28
+ if (resultOrPromise instanceof Promise) return resultOrPromise.then(async (result) => {
29
+ return processResult(memoOrPromise instanceof Promise ? await memoOrPromise : memoOrPromise, result);
30
+ });
31
+ const memo = memoOrPromise;
32
+ if (memo instanceof Promise) throw new Error("Mixing async and sync index providers is not supported");
33
+ return processResult(memo, resultOrPromise);
34
+ }, {
35
+ matched: false,
36
+ ids: [],
37
+ optimizedSelector: { ...selector }
38
+ });
39
+ }
40
+ /**
41
+ * Optimizes a logic gate ($and/$or) of selectors by querying multiple index providers.
42
+ * @param queryFunctions - An array of index providers to query.
43
+ * @param logicGate - An array of selectors representing the logic gate.
44
+ * @param idsCallback - A callback function called with matched ids.
45
+ * @returns An array of optimized selectors or a promise that resolves to such an array.
46
+ */
47
+ function optimizeLogicGate(queryFunctions, logicGate, idsCallback) {
48
+ return logicGate.reduce((memoOrPromise, sel) => {
49
+ const getSelector = (indexInfo) => {
50
+ const { matched: selMatched, ids: selIds, optimizedSelector } = indexInfo;
51
+ if (selMatched) {
52
+ idsCallback(true, selIds);
53
+ if (Object.keys(optimizedSelector).length > 0) return optimizedSelector;
54
+ } else {
55
+ idsCallback(false, []);
56
+ return sel;
57
+ }
58
+ };
59
+ const indexInfoOrPromise = getIndexInfo(queryFunctions, sel);
60
+ if (indexInfoOrPromise instanceof Promise) return indexInfoOrPromise.then(async (indexInfo) => {
61
+ const memo = memoOrPromise instanceof Promise ? await memoOrPromise : memoOrPromise;
62
+ const optimizedSelector = getSelector(indexInfo);
63
+ if (optimizedSelector) memo.push(optimizedSelector);
64
+ return memo;
65
+ });
66
+ const memo = memoOrPromise;
67
+ if (memo instanceof Promise) throw new Error("Mixing async and sync index providers is not supported");
68
+ const optimizedSelector = getSelector(indexInfoOrPromise);
69
+ if (optimizedSelector) memo.push(optimizedSelector);
70
+ return memo;
71
+ }, []);
72
+ }
73
+ /**
74
+ * Retrieves index information for a given complex selector by querying multiple
75
+ * index providers. Handles nested `$and` and `$or` conditions in the selector and
76
+ * optimizes the selector to minimize processing overhead.
77
+ * @template T - The type of the items in the collection.
78
+ * @template I - The type of the unique identifier for the items.
79
+ * @param queryFunctions - An array of index providers to query.
80
+ * @param selector - The complex selector used to filter items.
81
+ * @returns An object containing:
82
+ * - `matched`: A boolean indicating if the selector matched any items.
83
+ * - `ids`: An array of matched item ids.
84
+ * - `optimizedSelector`: A selector optimized based on the index results, with unused
85
+ * conditions removed.
86
+ */
87
+ function getIndexInfo(queryFunctions, selector) {
88
+ if (selector == null || Object.keys(selector).length <= 0) return {
89
+ matched: false,
90
+ ids: [],
91
+ optimizedSelector: selector
92
+ };
93
+ const { $and, $or, ...rest } = selector;
94
+ const flatInfoOrPromise = getMergedIndexInfo(queryFunctions, rest);
95
+ const processFlatInfo = (flatInfo) => {
96
+ let { matched, ids } = flatInfo;
97
+ const newSelector = flatInfo.optimizedSelector;
98
+ const $andNewOrPromise = Array.isArray($and) ? optimizeLogicGate(queryFunctions, $and, (match, selIds) => {
99
+ if (!match) return;
100
+ ids = matched ? require_intersection.default(ids, selIds) : selIds;
101
+ matched = true;
102
+ }) : void 0;
103
+ const process$and = ($andNew) => {
104
+ if ($andNew && $andNew.length > 0) newSelector.$and = $andNew;
105
+ let hasNonIndexField = false;
106
+ const matchedBefore = matched;
107
+ const idsBefore = ids;
108
+ const process$or = ($orNew) => {
109
+ if (hasNonIndexField || $orNew && $orNew.length > 0) {
110
+ newSelector.$or = $or;
111
+ matched = matchedBefore;
112
+ ids = idsBefore;
113
+ }
114
+ return {
115
+ matched,
116
+ ids: ids || [],
117
+ optimizedSelector: newSelector
118
+ };
119
+ };
120
+ const $orNewOrPromise = Array.isArray($or) ? optimizeLogicGate(queryFunctions, $or, (match, selIds) => {
121
+ if (match) {
122
+ ids = [...new Set([...ids, ...selIds])];
123
+ matched = true;
124
+ } else hasNonIndexField = true;
125
+ }) : void 0;
126
+ if ($orNewOrPromise instanceof Promise) return $orNewOrPromise.then(($orNew) => process$or($orNew));
127
+ return process$or($orNewOrPromise);
128
+ };
129
+ if ($andNewOrPromise instanceof Promise) return $andNewOrPromise.then(($andNew) => process$and($andNew));
130
+ return process$and($andNewOrPromise);
131
+ };
132
+ if (flatInfoOrPromise instanceof Promise) return flatInfoOrPromise.then(processFlatInfo);
133
+ return processFlatInfo(flatInfoOrPromise);
134
+ }
135
+ //#endregion
136
+ exports.default = getIndexInfo;