@signaldb/core 2.0.0-beta.0 → 2.0.0-beta.10

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 (128) hide show
  1. package/dist/.vite/manifest.json +128 -75
  2. package/dist/AsyncDataAdapter.d.ts +44 -7
  3. package/dist/AutoFetchDataAdapter.d.ts +5 -8
  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 +36 -25
  7. package/dist/Collection/types.d.ts +10 -2
  8. package/dist/DataAdapter.d.ts +18 -11
  9. package/dist/DefaultDataAdapter.d.ts +7 -6
  10. package/dist/WorkerDataAdapter.d.ts +7 -6
  11. package/dist/WorkerDataAdapterHost.d.ts +14 -11
  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 +3 -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 -339
  26. package/dist/index13.cjs.js +45 -0
  27. package/dist/index13.mjs +44 -407
  28. package/dist/index14.cjs.js +86 -0
  29. package/dist/index14.mjs +85 -190
  30. package/dist/index15.cjs.js +15 -0
  31. package/dist/index15.mjs +14 -341
  32. package/dist/index16.cjs.js +136 -0
  33. package/dist/index16.mjs +134 -569
  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 -254
  42. package/dist/index20.cjs.js +37 -0
  43. package/dist/index20.mjs +36 -104
  44. package/dist/index21.cjs.js +35 -0
  45. package/dist/index21.mjs +34 -128
  46. package/dist/index22.cjs.js +25 -0
  47. package/dist/index22.mjs +24 -7
  48. package/dist/index23.cjs.js +19 -0
  49. package/dist/index23.mjs +17 -26
  50. package/dist/index24.cjs.js +342 -0
  51. package/dist/index24.mjs +340 -6
  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 -5
  58. package/dist/index28.cjs.js +90 -0
  59. package/dist/index28.mjs +89 -8
  60. package/dist/index29.cjs.js +424 -0
  61. package/dist/index29.mjs +423 -29
  62. package/dist/index3.cjs.js +19 -0
  63. package/dist/index3.mjs +18 -537
  64. package/dist/index30.cjs.js +72 -0
  65. package/dist/index30.mjs +71 -42
  66. package/dist/index31.cjs.js +191 -0
  67. package/dist/index31.mjs +190 -9
  68. package/dist/index32.cjs.js +21 -0
  69. package/dist/index32.mjs +21 -0
  70. package/dist/index33.cjs.js +336 -0
  71. package/dist/index33.mjs +336 -0
  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/batchOnNextTick.d.ts +16 -0
  90. package/dist/utils/createSignal.d.ts +2 -2
  91. package/dist/utils/deepClone.d.ts +1 -1
  92. package/dist/utils/getMatchingKeys.d.ts +2 -2
  93. package/dist/utils/isFieldExpression.d.ts +1 -1
  94. package/dist/utils/match.d.ts +1 -1
  95. package/dist/utils/modify.d.ts +1 -1
  96. package/dist/utils/queryId.d.ts +2 -2
  97. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  98. package/package.json +3 -3
  99. package/dist/index.cjs10.js +0 -18
  100. package/dist/index.cjs11.js +0 -15
  101. package/dist/index.cjs12.js +0 -339
  102. package/dist/index.cjs13.js +0 -407
  103. package/dist/index.cjs14.js +0 -190
  104. package/dist/index.cjs15.js +0 -341
  105. package/dist/index.cjs16.js +0 -570
  106. package/dist/index.cjs17.js +0 -150
  107. package/dist/index.cjs18.js +0 -26
  108. package/dist/index.cjs19.js +0 -43
  109. package/dist/index.cjs2.js +0 -255
  110. package/dist/index.cjs20.js +0 -104
  111. package/dist/index.cjs21.js +0 -129
  112. package/dist/index.cjs22.js +0 -7
  113. package/dist/index.cjs23.js +0 -27
  114. package/dist/index.cjs24.js +0 -7
  115. package/dist/index.cjs25.js +0 -10
  116. package/dist/index.cjs26.js +0 -29
  117. package/dist/index.cjs27.js +0 -5
  118. package/dist/index.cjs28.js +0 -7
  119. package/dist/index.cjs29.js +0 -29
  120. package/dist/index.cjs3.js +0 -538
  121. package/dist/index.cjs30.js +0 -42
  122. package/dist/index.cjs31.js +0 -9
  123. package/dist/index.cjs4.js +0 -5
  124. package/dist/index.cjs5.js +0 -5
  125. package/dist/index.cjs6.js +0 -29
  126. package/dist/index.cjs7.js +0 -12
  127. package/dist/index.cjs8.js +0 -5
  128. package/dist/index.cjs9.js +0 -133
@@ -0,0 +1,90 @@
1
+ //#region src/utils/reactiveOrAsync.ts
2
+ /**
3
+ * A generator helper that makes TypeScript infer the “synchronous value type” for maybe-async expressions.
4
+ *
5
+ * Usage:
6
+ * const doc = yield* unwrap(Collection.findOne(...))
7
+ * const list = yield* unwrap(Collection.find(...).fetch())
8
+ *
9
+ * Runtime note:
10
+ * This does not “unwrap” Promises by itself. It yields the value/Promise to the runner and returns the
11
+ * value that the runner feeds back via `.next(...)`.
12
+ * @param value The value (or Promise of a value) to yield to the runner.
13
+ * @returns A generator that yields `value` and resolves to the runner-supplied unwrapped `T`.
14
+ */
15
+ function unwrap(value) {
16
+ return (function* () {
17
+ return yield value;
18
+ })();
19
+ }
20
+ /**
21
+ * Internal: checks for thenables (Promise-like).
22
+ * @param value The value to test.
23
+ * @returns `true` if `value` looks like a Promise/thenable.
24
+ */
25
+ function isThenable(value) {
26
+ return typeof value === "object" && value !== null && typeof value.then === "function";
27
+ }
28
+ /**
29
+ * Internal runner: executes a generator either synchronously (reactive) or asynchronously (imperative).
30
+ *
31
+ * - In sync mode, yielding a Promise is a programming error and throws.
32
+ * - In async mode, yielded Promises are awaited.
33
+ * @param thisArgument The `this` value to bind when invoking `gen`.
34
+ * @param mode Execution mode options.
35
+ * @param gen The generator workflow to run.
36
+ * @returns The workflow result (a plain value in sync mode, or a Promise in async mode).
37
+ */
38
+ function runReactiveOrAsync(thisArgument, mode, gen) {
39
+ const a = !!mode?.async;
40
+ const it = gen.call(thisArgument, a);
41
+ if (!a) {
42
+ let step = it.next();
43
+ while (!step.done) {
44
+ const y = step.value;
45
+ if (isThenable(y)) throw new Error("Promise yielded in sync flow");
46
+ step = it.next(y);
47
+ }
48
+ return step.value;
49
+ }
50
+ return (async function() {
51
+ let step = it.next();
52
+ while (!step.done) {
53
+ const y = step.value;
54
+ const v = isThenable(y) ? await y : y;
55
+ step = it.next(v);
56
+ }
57
+ return step.value;
58
+ })();
59
+ }
60
+ /**
61
+ * Factory that turns a generator workflow into a callable method that can run in sync (reactive) or async mode.
62
+ *
63
+ * Call style:
64
+ * fn(a, b) -> sync/reactive return
65
+ * await fn(a, b, { async: true }) -> async return
66
+ * @param gen Generator workflow. Receives `(a)` which indicates async mode and should `yield`/`yield* unwrap(...)`
67
+ * any values that may be Promises.
68
+ * @returns A callable method with overloads plus a `.generator` property for composition.
69
+ */
70
+ function reactiveOrAsync(gen) {
71
+ /**
72
+ * The generated method wrapper.
73
+ * @param allArguments Method arguments, optionally ending with a `ModeOptions` object.
74
+ * @returns The workflow result (sync) or a Promise of the result (async).
75
+ */
76
+ function method(...allArguments) {
77
+ const last = allArguments.length > 0 ? allArguments.at(-1) : void 0;
78
+ const hasMode = typeof last === "object" && last !== null && "async" in last;
79
+ const mode = hasMode ? last : void 0;
80
+ const parameters = hasMode ? allArguments.slice(0, -1) : allArguments;
81
+ return runReactiveOrAsync(this, mode, function* (a) {
82
+ return yield* gen.call(this, a, ...parameters);
83
+ });
84
+ }
85
+ method.generator = gen;
86
+ return method;
87
+ }
88
+ //#endregion
89
+ exports.default = reactiveOrAsync;
90
+ exports.unwrap = unwrap;
package/dist/index28.mjs CHANGED
@@ -1,8 +1,89 @@
1
- function intersection(...arrays) {
2
- if (arrays.length === 0)
3
- return [];
4
- return [...new Set(arrays.reduce((a, b) => a.filter((c) => b.includes(c))))];
5
- }
6
- export {
7
- intersection as default
8
- };
1
+ //#region src/utils/reactiveOrAsync.ts
2
+ /**
3
+ * A generator helper that makes TypeScript infer the “synchronous value type” for maybe-async expressions.
4
+ *
5
+ * Usage:
6
+ * const doc = yield* unwrap(Collection.findOne(...))
7
+ * const list = yield* unwrap(Collection.find(...).fetch())
8
+ *
9
+ * Runtime note:
10
+ * This does not “unwrap” Promises by itself. It yields the value/Promise to the runner and returns the
11
+ * value that the runner feeds back via `.next(...)`.
12
+ * @param value The value (or Promise of a value) to yield to the runner.
13
+ * @returns A generator that yields `value` and resolves to the runner-supplied unwrapped `T`.
14
+ */
15
+ function unwrap(value) {
16
+ return (function* () {
17
+ return yield value;
18
+ })();
19
+ }
20
+ /**
21
+ * Internal: checks for thenables (Promise-like).
22
+ * @param value The value to test.
23
+ * @returns `true` if `value` looks like a Promise/thenable.
24
+ */
25
+ function isThenable(value) {
26
+ return typeof value === "object" && value !== null && typeof value.then === "function";
27
+ }
28
+ /**
29
+ * Internal runner: executes a generator either synchronously (reactive) or asynchronously (imperative).
30
+ *
31
+ * - In sync mode, yielding a Promise is a programming error and throws.
32
+ * - In async mode, yielded Promises are awaited.
33
+ * @param thisArgument The `this` value to bind when invoking `gen`.
34
+ * @param mode Execution mode options.
35
+ * @param gen The generator workflow to run.
36
+ * @returns The workflow result (a plain value in sync mode, or a Promise in async mode).
37
+ */
38
+ function runReactiveOrAsync(thisArgument, mode, gen) {
39
+ const a = !!mode?.async;
40
+ const it = gen.call(thisArgument, a);
41
+ if (!a) {
42
+ let step = it.next();
43
+ while (!step.done) {
44
+ const y = step.value;
45
+ if (isThenable(y)) throw new Error("Promise yielded in sync flow");
46
+ step = it.next(y);
47
+ }
48
+ return step.value;
49
+ }
50
+ return (async function() {
51
+ let step = it.next();
52
+ while (!step.done) {
53
+ const y = step.value;
54
+ const v = isThenable(y) ? await y : y;
55
+ step = it.next(v);
56
+ }
57
+ return step.value;
58
+ })();
59
+ }
60
+ /**
61
+ * Factory that turns a generator workflow into a callable method that can run in sync (reactive) or async mode.
62
+ *
63
+ * Call style:
64
+ * fn(a, b) -> sync/reactive return
65
+ * await fn(a, b, { async: true }) -> async return
66
+ * @param gen Generator workflow. Receives `(a)` which indicates async mode and should `yield`/`yield* unwrap(...)`
67
+ * any values that may be Promises.
68
+ * @returns A callable method with overloads plus a `.generator` property for composition.
69
+ */
70
+ function reactiveOrAsync(gen) {
71
+ /**
72
+ * The generated method wrapper.
73
+ * @param allArguments Method arguments, optionally ending with a `ModeOptions` object.
74
+ * @returns The workflow result (sync) or a Promise of the result (async).
75
+ */
76
+ function method(...allArguments) {
77
+ const last = allArguments.length > 0 ? allArguments.at(-1) : void 0;
78
+ const hasMode = typeof last === "object" && last !== null && "async" in last;
79
+ const mode = hasMode ? last : void 0;
80
+ const parameters = hasMode ? allArguments.slice(0, -1) : allArguments;
81
+ return runReactiveOrAsync(this, mode, function* (a) {
82
+ return yield* gen.call(this, a, ...parameters);
83
+ });
84
+ }
85
+ method.generator = gen;
86
+ return method;
87
+ }
88
+ //#endregion
89
+ export { reactiveOrAsync as default, unwrap };
@@ -0,0 +1,424 @@
1
+ const require_isEqual = require("./index2.cjs.js");
2
+ const require_getMatchingKeys = require("./index13.cjs.js");
3
+ const require_getIndexInfo = require("./index16.cjs.js");
4
+ const require_deepClone = require("./index17.cjs.js");
5
+ const require_match = require("./index18.cjs.js");
6
+ const require_modify = require("./index19.cjs.js");
7
+ const require_project = require("./index21.cjs.js");
8
+ const require_queryId = require("./index22.cjs.js");
9
+ const require_sortItems = require("./index23.cjs.js");
10
+ //#region src/AsyncDataAdapter.ts
11
+ /**
12
+ * Carries the context needed to act on a failed query. The bare storage error
13
+ * on its own does not say which collection or selector produced it, which made
14
+ * the default `console.error` hook close to useless.
15
+ */
16
+ var QueryError = class extends Error {
17
+ collectionName;
18
+ selector;
19
+ options;
20
+ attempts;
21
+ constructor(collectionName, selector, options, attempts, cause) {
22
+ const reason = cause instanceof Error ? cause.message : String(cause);
23
+ super(`Query on "${collectionName}" failed after ${attempts} attempt(s): ${reason}`);
24
+ this.name = "QueryError";
25
+ this.collectionName = collectionName;
26
+ this.selector = selector;
27
+ this.options = options;
28
+ this.attempts = attempts;
29
+ this.cause = cause;
30
+ }
31
+ };
32
+ var DEFAULT_RETRY_ATTEMPTS = 3;
33
+ var defaultRetryDelay = (attempt) => 100 * 4 ** (attempt - 1);
34
+ var wait = (ms) => new Promise((resolve) => {
35
+ setTimeout(resolve, ms);
36
+ });
37
+ /**
38
+ * AsyncDataAdapter
39
+ * Combines WorkerDataAdapter + WorkerDataAdapterHost into a single, transport-free adapter.
40
+ * - Keeps the DataAdapter/CollectionBackend surface identical to the Worker version.
41
+ * - Executes queries and mutations directly against the provided StorageAdapter.
42
+ * - Preserves index-aware query optimization and push-style query updates to listeners.
43
+ */
44
+ var AsyncDataAdapter = class {
45
+ options;
46
+ id;
47
+ onError;
48
+ retryAttempts;
49
+ retryDelay;
50
+ storageAdapters = /* @__PURE__ */ new Map();
51
+ storageAdapterReady = /* @__PURE__ */ new Map();
52
+ collectionIndices = /* @__PURE__ */ new Map();
53
+ queries = /* @__PURE__ */ new Map();
54
+ constructor(options) {
55
+ this.options = options;
56
+ this.id = options.id || "async-data-adapter";
57
+ this.onError = options.onError ?? ((error) => {
58
+ console.error(error);
59
+ });
60
+ this.retryAttempts = Math.max(1, options.retry?.attempts ?? DEFAULT_RETRY_ATTEMPTS);
61
+ this.retryDelay = options.retry?.delay ?? defaultRetryDelay;
62
+ }
63
+ createCollectionBackend(collection, indices) {
64
+ this.collectionIndices.set(collection.name, indices);
65
+ this.queries.set(collection.name, /* @__PURE__ */ new Map());
66
+ this.ensureStorageAdapter(collection.name);
67
+ const ready = (async () => {
68
+ try {
69
+ await this.setupStorage(collection.name, indices);
70
+ } catch (error) {
71
+ this.onError(error);
72
+ throw error;
73
+ }
74
+ })();
75
+ this.storageAdapterReady.set(collection.name, ready);
76
+ const registerQuery = (selector, options) => {
77
+ const qid = require_queryId.default(selector, options);
78
+ const registry = this.queries.get(collection.name);
79
+ if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
80
+ registry.set(qid, {
81
+ selector,
82
+ options,
83
+ items: [],
84
+ listeners: /* @__PURE__ */ new Set(),
85
+ ...registry.get(qid),
86
+ state: "active",
87
+ error: null
88
+ });
89
+ this.fulfillQuery(collection.name, selector, options).catch(this.onError);
90
+ };
91
+ const unregisterQuery = (selector, options) => {
92
+ const qid = require_queryId.default(selector, options);
93
+ this.queries.get(collection.name)?.delete(qid);
94
+ };
95
+ const getQueryState = (selector, options) => {
96
+ return (this.queries.get(collection.name)?.get(require_queryId.default(selector, options)))?.state ?? "active";
97
+ };
98
+ const getQueryError = (selector, options) => {
99
+ return (this.queries.get(collection.name)?.get(require_queryId.default(selector, options)))?.error ?? null;
100
+ };
101
+ const getQueryResult = (selector, options) => {
102
+ return (this.queries.get(collection.name)?.get(require_queryId.default(selector, options)))?.items ?? [];
103
+ };
104
+ const retryQuery = (selector, options) => {
105
+ const qid = require_queryId.default(selector, options);
106
+ if (!this.queries.get(collection.name)?.get(qid)) return;
107
+ this.publishState(collection.name, qid, "active", null);
108
+ this.runQuery(collection.name, selector, options);
109
+ };
110
+ const onQueryStateChange = (selector, options, callback) => {
111
+ const qid = require_queryId.default(selector, options);
112
+ const registry = this.queries.get(collection.name);
113
+ if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
114
+ if (!registry.has(qid)) registry.set(qid, {
115
+ selector,
116
+ options,
117
+ state: "active",
118
+ error: null,
119
+ items: [],
120
+ listeners: /* @__PURE__ */ new Set()
121
+ });
122
+ registry.get(qid)?.listeners.add(callback);
123
+ if (registry.get(qid)?.state === "error") retryQuery(selector, options);
124
+ return () => registry.get(qid)?.listeners.delete(callback);
125
+ };
126
+ return {
127
+ insert: async (item) => {
128
+ await ready;
129
+ return await this.insert(collection.name, item);
130
+ },
131
+ updateOne: async (selector, modifier) => {
132
+ await ready;
133
+ return this.updateOne(collection.name, selector, modifier);
134
+ },
135
+ updateMany: async (selector, modifier) => {
136
+ await ready;
137
+ return this.updateMany(collection.name, selector, modifier);
138
+ },
139
+ replaceOne: async (selector, replacement) => {
140
+ await ready;
141
+ return this.replaceOne(collection.name, selector, replacement);
142
+ },
143
+ removeOne: async (selector) => {
144
+ await ready;
145
+ return this.removeOne(collection.name, selector);
146
+ },
147
+ removeMany: async (selector) => {
148
+ await ready;
149
+ return this.removeMany(collection.name, selector);
150
+ },
151
+ registerQuery,
152
+ unregisterQuery,
153
+ retryQuery,
154
+ getQueryState,
155
+ getQueryError,
156
+ getQueryResult,
157
+ onQueryStateChange,
158
+ executeQuery: async (selector, options) => {
159
+ await ready;
160
+ return this.executeQuery(collection.name, selector, options);
161
+ },
162
+ dispose: async () => {
163
+ this.storageAdapters.delete(collection.name);
164
+ this.queries.delete(collection.name);
165
+ this.collectionIndices.delete(collection.name);
166
+ this.storageAdapterReady.delete(collection.name);
167
+ },
168
+ isReady: async () => {
169
+ await ready;
170
+ }
171
+ };
172
+ }
173
+ async setupStorage(collectionName, indices) {
174
+ const storage = this.storageAdapters.get(collectionName);
175
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
176
+ await storage.setup();
177
+ await Promise.all(indices.map((index) => storage.createIndex(index)));
178
+ }
179
+ ensureStorageAdapter(name) {
180
+ if (this.storageAdapters.has(name)) return;
181
+ const adapter = this.options.storage(name);
182
+ if (!adapter) return;
183
+ this.storageAdapters.set(name, adapter);
184
+ }
185
+ /**
186
+ * Compute and publish the result for a specific query
187
+ * @param collectionName - name of the collection
188
+ * @param selector - query selector
189
+ * @param options - query options
190
+ */
191
+ async fulfillQuery(collectionName, selector, options) {
192
+ const qid = require_queryId.default(selector, options);
193
+ const registry = this.queries.get(collectionName);
194
+ if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
195
+ if (!registry.get(qid)) return;
196
+ this.publishState(collectionName, qid, "active", null);
197
+ await this.runQuery(collectionName, selector, options);
198
+ }
199
+ /**
200
+ * Executes a query, retrying transient failures before giving up. The state
201
+ * stays `'active'` across retries — consumers should see "still loading",
202
+ * not "failed", until we actually stop trying. Only the final failure is
203
+ * published as `'error'` and reported through `onError`; previously that
204
+ * error was swallowed entirely (`fulfillQuery` caught it internally, so the
205
+ * `.catch(this.onError)` on its call site was unreachable) and the query
206
+ * stayed dead for the rest of the session.
207
+ * @param collectionName - name of the collection
208
+ * @param selector - query selector
209
+ * @param options - query options
210
+ */
211
+ async runQuery(collectionName, selector, options) {
212
+ const qid = require_queryId.default(selector, options);
213
+ let lastError;
214
+ for (let attempt = 1; attempt <= this.retryAttempts; attempt += 1) {
215
+ if (!this.queries.get(collectionName)?.has(qid)) return;
216
+ try {
217
+ const items = await this.executeQuery(collectionName, selector, options);
218
+ this.publishResult(collectionName, qid, items);
219
+ this.publishState(collectionName, qid, "complete", null);
220
+ return;
221
+ } catch (error) {
222
+ lastError = error;
223
+ if (attempt < this.retryAttempts) await wait(this.retryDelay(attempt));
224
+ }
225
+ }
226
+ const queryError = new QueryError(collectionName, selector, options, this.retryAttempts, lastError);
227
+ this.publishState(collectionName, qid, "error", queryError);
228
+ this.onError(queryError);
229
+ }
230
+ /**
231
+ * Notify listeners about state changes and keep the cache updated
232
+ * @param collectionName - name of the collection
233
+ * @param qid - query id
234
+ * @param state - new state
235
+ * @param error - error if state is 'error', null otherwise
236
+ */
237
+ publishState(collectionName, qid, state, error) {
238
+ const rec = this.queries.get(collectionName)?.get(qid);
239
+ if (!rec) return;
240
+ rec.state = state;
241
+ rec.error = error;
242
+ for (const callback of rec.listeners) try {
243
+ callback(state);
244
+ } catch (error_) {
245
+ this.onError(error_);
246
+ }
247
+ }
248
+ publishResult(collectionName, qid, items) {
249
+ const rec = this.queries.get(collectionName)?.get(qid);
250
+ if (!rec) return;
251
+ rec.items = items;
252
+ }
253
+ async getIndexInfo(collectionName, selector) {
254
+ const storageAdapter = this.storageAdapters.get(collectionName);
255
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
256
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") return {
257
+ matched: true,
258
+ ids: [selector.id].filter(Boolean),
259
+ optimizedSelector: {}
260
+ };
261
+ if (selector == null) return {
262
+ matched: false,
263
+ ids: [],
264
+ optimizedSelector: {}
265
+ };
266
+ return require_getIndexInfo.default((this.collectionIndices.get(collectionName) ?? []).map((field) => async (flatSelector) => {
267
+ if (!Object.hasOwnProperty.call(flatSelector, field)) return { matched: false };
268
+ const index = await storageAdapter.readIndex(field);
269
+ const fieldSelector = flatSelector[field];
270
+ const filtersForNull = fieldSelector == null || fieldSelector.$exists === false;
271
+ const keys = filtersForNull ? {
272
+ include: null,
273
+ exclude: [...index.keys()].filter((key) => key != null)
274
+ } : require_getMatchingKeys.default(field, flatSelector);
275
+ if (keys.include == null && keys.exclude == null) return { matched: false };
276
+ let includedIds = [];
277
+ if (keys.include == null) for (const set of index.values()) for (const pos of set) includedIds.push(pos);
278
+ else for (const key of keys.include) {
279
+ const idSet = index.get(key);
280
+ if (idSet) for (const id of idSet) includedIds.push(id);
281
+ }
282
+ if (keys.exclude != null) {
283
+ const excludeIds = /* @__PURE__ */ new Set();
284
+ for (const key of keys.exclude) {
285
+ const idSet = index.get(key);
286
+ if (idSet) for (const id of idSet) excludeIds.add(id);
287
+ }
288
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
289
+ }
290
+ return {
291
+ matched: true,
292
+ ids: includedIds,
293
+ fields: [field],
294
+ keepSelector: filtersForNull
295
+ };
296
+ }), selector);
297
+ }
298
+ async queryItems(collectionName, selector) {
299
+ const storage = this.storageAdapters.get(collectionName);
300
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
301
+ const index = await this.getIndexInfo(collectionName, selector);
302
+ const matchItems = (item) => {
303
+ if (index.optimizedSelector == null) return true;
304
+ if (Object.keys(index.optimizedSelector).length <= 0) return true;
305
+ return require_match.default(item, index.optimizedSelector);
306
+ };
307
+ if (index.matched) {
308
+ const items = await storage.readIds(index.ids);
309
+ if (require_isEqual.default(index.optimizedSelector, {})) return items;
310
+ return items.filter(matchItems);
311
+ } else {
312
+ const allItems = await storage.readAll();
313
+ if (require_isEqual.default(selector, {})) return allItems;
314
+ return allItems.filter(matchItems);
315
+ }
316
+ }
317
+ async executeQuery(collectionName, selector, options) {
318
+ const items = await this.queryItems(collectionName, selector || {});
319
+ const { sort, skip, limit, fields } = options || {};
320
+ const sorted = sort ? require_sortItems.default(items, sort) : items;
321
+ const skipped = skip ? sorted.slice(skip) : sorted;
322
+ const limited = limit ? skipped.slice(0, limit) : skipped;
323
+ const idExcluded = fields && fields.id === 0;
324
+ return limited.map((item) => {
325
+ if (!fields) return item;
326
+ return {
327
+ ...idExcluded ? {} : { id: item.id },
328
+ ...require_project.default(item, fields)
329
+ };
330
+ });
331
+ }
332
+ /**
333
+ * After mutations, recompute and push updates for affected active queries
334
+ * @param collectionName - name of the collection
335
+ * @param affectedItems - item states before and/or after the mutation
336
+ */
337
+ async checkQueryUpdates(collectionName, affectedItems) {
338
+ const registry = this.queries.get(collectionName);
339
+ if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
340
+ if (registry.size === 0) return;
341
+ const affected = [...registry.values()].filter(({ selector }) => affectedItems.some((item) => require_match.default(item, selector)));
342
+ if (affected.length === 0) return;
343
+ for (const { selector, options } of affected) {
344
+ const qid = require_queryId.default(selector, options);
345
+ this.publishState(collectionName, qid, "active", null);
346
+ }
347
+ await Promise.all(affected.map(({ selector, options }) => this.runQuery(collectionName, selector, options)));
348
+ }
349
+ async insert(collectionName, newItem) {
350
+ const storage = this.storageAdapters.get(collectionName);
351
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
352
+ if ((await storage.readIds([newItem.id])).length > 0) throw new Error(`Item with id ${String(newItem.id)} already exists`);
353
+ await storage.insert([newItem]);
354
+ await this.checkQueryUpdates(collectionName, [newItem]);
355
+ return newItem;
356
+ }
357
+ async updateOne(collectionName, selector, modifier) {
358
+ const storage = this.storageAdapters.get(collectionName);
359
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
360
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
361
+ const { $setOnInsert, ...rest } = modifier;
362
+ if (item == null) return [];
363
+ const modified = require_modify.default(require_deepClone.default(item), rest);
364
+ if (item.id !== modified.id) {
365
+ if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
366
+ }
367
+ await storage.replace([modified]);
368
+ await this.checkQueryUpdates(collectionName, [item, modified]);
369
+ return [modified];
370
+ }
371
+ async updateMany(collectionName, selector, modifier) {
372
+ const storage = this.storageAdapters.get(collectionName);
373
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
374
+ const items = await this.executeQuery(collectionName, selector);
375
+ if (items.length === 0) return [];
376
+ const { $setOnInsert, ...rest } = modifier;
377
+ const changed = await Promise.all(items.map(async (item) => {
378
+ const modified = require_modify.default(require_deepClone.default(item), rest);
379
+ if (item.id !== modified.id) {
380
+ if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
381
+ }
382
+ return modified;
383
+ }));
384
+ await storage.replace(changed);
385
+ await this.checkQueryUpdates(collectionName, [...items, ...changed]);
386
+ return changed;
387
+ }
388
+ async replaceOne(collectionName, selector, replacement) {
389
+ const storage = this.storageAdapters.get(collectionName);
390
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
391
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
392
+ if (item == null) return [];
393
+ const modified = {
394
+ ...replacement,
395
+ id: replacement.id ?? item.id
396
+ };
397
+ if (item.id !== modified.id) {
398
+ if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
399
+ }
400
+ await storage.replace([modified]);
401
+ await this.checkQueryUpdates(collectionName, [item, modified]);
402
+ return [modified];
403
+ }
404
+ async removeOne(collectionName, selector) {
405
+ const storage = this.storageAdapters.get(collectionName);
406
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
407
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
408
+ if (item == null) return [];
409
+ await storage.remove([item]);
410
+ await this.checkQueryUpdates(collectionName, [item]);
411
+ return [item];
412
+ }
413
+ async removeMany(collectionName, selector) {
414
+ const storage = this.storageAdapters.get(collectionName);
415
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
416
+ const items = await this.executeQuery(collectionName, selector);
417
+ if (items.length === 0) return [];
418
+ await storage.remove(items);
419
+ await this.checkQueryUpdates(collectionName, items);
420
+ return items;
421
+ }
422
+ };
423
+ //#endregion
424
+ exports.default = AsyncDataAdapter;