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

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.
package/dist/index32.mjs CHANGED
@@ -1,21 +1,311 @@
1
- //#region src/utils/compact.ts
2
- /**
3
- * Checks if a value is truthy.
4
- * @template T - The type of the value.
5
- * @param value - The value to check.
6
- * @returns A boolean indicating if the value is truthy.
7
- */
8
- function truthy(value) {
9
- return !!value;
10
- }
11
- /**
12
- * Filters out falsy values (`false`, `''`, `0`, `null`, `undefined`) from an array.
13
- * @template T - The type of the elements in the array.
14
- * @param array - The array to filter.
15
- * @returns A new array containing only the truthy values from the input array.
16
- */
17
- function compact(array) {
18
- return array.filter(truthy);
19
- }
1
+ import randomId from "./index8.mjs";
2
+ import deepClone from "./index17.mjs";
3
+ import match from "./index18.mjs";
4
+ import modify from "./index19.mjs";
5
+ import queryId from "./index22.mjs";
6
+ import batchOnNextTick from "./index30.mjs";
7
+ import applyQueryOptions from "./index31.mjs";
8
+ //#region src/WorkerDataAdapter.ts
9
+ var WorkerDataAdapter = class {
10
+ worker;
11
+ options;
12
+ id;
13
+ isDisposed = false;
14
+ workerReady;
15
+ log = () => {};
16
+ collectionReady = /* @__PURE__ */ new Map();
17
+ batchExecutionHelpers = /* @__PURE__ */ new Map();
18
+ queries = {};
19
+ pendingWrites = /* @__PURE__ */ new Map();
20
+ pendingWriteSeq = 0;
21
+ constructor(worker, options) {
22
+ this.worker = worker;
23
+ this.options = options;
24
+ this.id = this.options.id || "default-worker-data-adapter";
25
+ if (this.options.log) this.log = this.options.log;
26
+ this.workerReady = new Promise((resolve, reject) => {
27
+ const timeoutId = setTimeout(() => {
28
+ reject(/* @__PURE__ */ new Error("WorkerDataAdapter initialization timed out"));
29
+ }, 5e3);
30
+ const handleMessage = (event) => {
31
+ const { type, workerId } = event.data;
32
+ if (workerId !== this.id) return;
33
+ if (type === "ready") {
34
+ resolve();
35
+ clearTimeout(timeoutId);
36
+ this.worker.removeEventListener("message", handleMessage);
37
+ }
38
+ };
39
+ this.worker.addEventListener("message", handleMessage);
40
+ });
41
+ }
42
+ async exec(method, collectionName, ...args) {
43
+ await this.workerReady;
44
+ if (method !== "isReady") {
45
+ const collectionReady = this.collectionReady.get(collectionName);
46
+ if (!collectionReady) throw new Error(`Collection "${collectionName}" is not registered in WorkerDataAdapter`);
47
+ await collectionReady;
48
+ }
49
+ if (this.isDisposed) throw new Error("WorkerDataAdapter is disposed");
50
+ return new Promise((resolve, reject) => {
51
+ const messageId = randomId();
52
+ const handleMessage = (event) => {
53
+ const { id, workerId, type, data, error } = event.data;
54
+ if (workerId !== this.id) return;
55
+ if (type !== "response") return;
56
+ if (id !== messageId) return;
57
+ this.log(method, "result", data ?? error);
58
+ if (error) reject(error);
59
+ else resolve(data);
60
+ this.worker.removeEventListener("message", handleMessage);
61
+ };
62
+ this.worker.addEventListener("message", handleMessage);
63
+ this.worker.postMessage({
64
+ id: messageId,
65
+ workerId: this.id,
66
+ method,
67
+ args: [collectionName, ...args]
68
+ });
69
+ });
70
+ }
71
+ observableItems(collectionName) {
72
+ const byId = /* @__PURE__ */ new Map();
73
+ this.queries[collectionName]?.forEach((query) => {
74
+ this.mergePendingWrites(collectionName, query.items).forEach((item) => {
75
+ byId.set(item.id, item);
76
+ });
77
+ });
78
+ return [...byId.values()];
79
+ }
80
+ mergePendingWrites(collectionName, items) {
81
+ const pending = this.pendingWrites.get(collectionName);
82
+ if (!pending || pending.size === 0) return items;
83
+ const merged = new Map(items.map((item) => [item.id, item]));
84
+ [...pending.entries()].sort(([a], [b]) => a - b).forEach(([, write]) => {
85
+ write.upserts.forEach((item, id) => merged.set(id, item));
86
+ write.deletes.forEach((id) => merged.delete(id));
87
+ });
88
+ return [...merged.values()];
89
+ }
90
+ /**
91
+ * Registers a write's effect locally and notifies every active query it
92
+ * touches, then returns a function that drops it again once the write
93
+ * settles.
94
+ * @param collectionName - The collection the write targets.
95
+ * @param upserts - Items inserted or updated by the write.
96
+ * @param deletes - Ids removed by the write.
97
+ * @returns A function that drops the pending write and re-notifies.
98
+ */
99
+ applyPendingWrite(collectionName, upserts, deletes) {
100
+ if (upserts.length === 0 && deletes.length === 0) return () => {};
101
+ const seq = this.pendingWriteSeq += 1;
102
+ const pending = this.pendingWrites.get(collectionName) ?? /* @__PURE__ */ new Map();
103
+ pending.set(seq, {
104
+ upserts: new Map(upserts.map((item) => [item.id, item])),
105
+ deletes: new Set(deletes)
106
+ });
107
+ this.pendingWrites.set(collectionName, pending);
108
+ const affectedIds = new Set([...upserts.map((item) => item.id), ...deletes]);
109
+ this.notifyAffectedQueries(collectionName, upserts, affectedIds);
110
+ return () => {
111
+ const current = this.pendingWrites.get(collectionName);
112
+ if (!current) return;
113
+ current.delete(seq);
114
+ if (current.size === 0) this.pendingWrites.delete(collectionName);
115
+ this.notifyAffectedQueries(collectionName, upserts, affectedIds);
116
+ };
117
+ }
118
+ notifyAffectedQueries(collectionName, upserts, affectedIds) {
119
+ this.queries[collectionName]?.forEach((query) => {
120
+ const wasHolding = query.items.some((item) => affectedIds.has(item.id));
121
+ const nowMatches = upserts.some((item) => query.selector != null && match(item, query.selector));
122
+ if (!wasHolding && !nowMatches) return;
123
+ query.stateChangeCallbacks.forEach((callback) => callback(query.state));
124
+ });
125
+ }
126
+ matchObservableItems(collectionName, selector, onlyFirst) {
127
+ if (selector == null) return [];
128
+ const matches = this.observableItems(collectionName).filter((item) => match(item, selector));
129
+ return onlyFirst ? matches.slice(0, 1) : matches;
130
+ }
131
+ resolveUpdate(collectionName, selector, modifier, onlyFirst) {
132
+ const { $setOnInsert, ...restModifier } = modifier;
133
+ const upserts = [];
134
+ const deletes = [];
135
+ this.matchObservableItems(collectionName, selector, onlyFirst).forEach((item) => {
136
+ const modifiedItem = modify(deepClone(item), restModifier);
137
+ upserts.push(modifiedItem);
138
+ if (modifiedItem.id !== item.id) deletes.push(item.id);
139
+ });
140
+ return {
141
+ upserts,
142
+ deletes
143
+ };
144
+ }
145
+ resolveRemoval(collectionName, selector, onlyFirst) {
146
+ return this.matchObservableItems(collectionName, selector, onlyFirst).map((item) => item.id);
147
+ }
148
+ resolveReplacement(item, replacement) {
149
+ const modifiedItem = {
150
+ ...replacement,
151
+ id: replacement.id ?? item.id
152
+ };
153
+ return {
154
+ upserts: [modifiedItem],
155
+ deletes: modifiedItem.id === item.id ? [] : [item.id]
156
+ };
157
+ }
158
+ async withPendingWrite(collectionName, delta, run) {
159
+ const dropPendingWrite = this.applyPendingWrite(collectionName, delta.upserts, delta.deletes);
160
+ try {
161
+ return await run();
162
+ } finally {
163
+ dropPendingWrite();
164
+ }
165
+ }
166
+ enqueueBatched(collectionName, method, args) {
167
+ const helper = this.batchExecutionHelpers.get(collectionName);
168
+ if (!helper) throw new Error(`Collection "${collectionName}" is not registered in WorkerDataAdapter`);
169
+ return helper.enqueue(method, args);
170
+ }
171
+ updateQuery(collectionName, query, update) {
172
+ const id = queryId(query.selector, query.options);
173
+ const collectionQueries = this.queries[collectionName];
174
+ if (!collectionQueries) return;
175
+ const existing = collectionQueries.get(id);
176
+ const newState = {
177
+ selector: query.selector,
178
+ options: query.options,
179
+ state: "active",
180
+ error: null,
181
+ items: [],
182
+ stateChangeCallbacks: [],
183
+ eventHandler: existing?.eventHandler,
184
+ ...existing,
185
+ ...update
186
+ };
187
+ collectionQueries.set(id, newState);
188
+ this.queries[collectionName] = collectionQueries;
189
+ }
190
+ createCollectionBackend(collection, indices) {
191
+ this.queries[collection.name] = /* @__PURE__ */ new Map();
192
+ this.exec("registerCollection", collection.name, indices);
193
+ this.collectionReady.set(collection.name, this.exec("isReady", collection.name));
194
+ this.batchExecutionHelpers.set(collection.name, batchOnNextTick(async (method, args) => this.exec(method, collection.name, args)));
195
+ return {
196
+ insert: async (item) => {
197
+ return this.withPendingWrite(collection.name, {
198
+ upserts: [item],
199
+ deletes: []
200
+ }, () => this.enqueueBatched(collection.name, "insert", [item]));
201
+ },
202
+ updateOne: async (selector, modifier) => {
203
+ return this.withPendingWrite(collection.name, this.resolveUpdate(collection.name, selector, modifier, true), () => this.enqueueBatched(collection.name, "updateOne", [selector, modifier]));
204
+ },
205
+ updateMany: async (selector, modifier) => {
206
+ return this.withPendingWrite(collection.name, this.resolveUpdate(collection.name, selector, modifier, false), () => this.enqueueBatched(collection.name, "updateMany", [selector, modifier]));
207
+ },
208
+ replaceOne: async (selector, replacement) => {
209
+ const [item] = this.matchObservableItems(collection.name, selector, true);
210
+ return this.withPendingWrite(collection.name, item == null ? {
211
+ upserts: [],
212
+ deletes: []
213
+ } : this.resolveReplacement(item, replacement), () => this.enqueueBatched(collection.name, "replaceOne", [selector, replacement]));
214
+ },
215
+ removeOne: async (selector) => {
216
+ return this.withPendingWrite(collection.name, {
217
+ upserts: [],
218
+ deletes: this.resolveRemoval(collection.name, selector, true)
219
+ }, () => this.enqueueBatched(collection.name, "removeOne", [selector]));
220
+ },
221
+ removeMany: async (selector) => {
222
+ return this.withPendingWrite(collection.name, {
223
+ upserts: [],
224
+ deletes: this.resolveRemoval(collection.name, selector, false)
225
+ }, () => this.enqueueBatched(collection.name, "removeMany", [selector]));
226
+ },
227
+ registerQuery: (selector, options) => {
228
+ this.updateQuery(collection.name, {
229
+ selector,
230
+ options
231
+ }, {
232
+ state: "active",
233
+ error: null,
234
+ items: []
235
+ });
236
+ this.exec("registerQuery", collection.name, selector, options);
237
+ const handler = (event) => {
238
+ const { type, data, workerId, error } = event.data;
239
+ if (type !== "queryUpdate") return;
240
+ if (data == null) return;
241
+ const { collectionName, selector: responseSelector, options: responseOptions, state, items } = data;
242
+ if (workerId !== this.id) return;
243
+ if (collectionName !== collection.name) return;
244
+ if (queryId(responseSelector, responseOptions) !== queryId(selector, options)) return;
245
+ this.log("queryUpdate", responseSelector, responseOptions, state, data ?? error);
246
+ this.updateQuery(collection.name, {
247
+ selector: responseSelector,
248
+ options: responseOptions
249
+ }, {
250
+ state,
251
+ error,
252
+ items
253
+ });
254
+ const query = this.queries[collection.name]?.get(queryId(selector, options));
255
+ if (!query) return;
256
+ query.stateChangeCallbacks.forEach((callback) => callback(state));
257
+ };
258
+ this.worker.addEventListener("message", handler);
259
+ this.updateQuery(collection.name, {
260
+ selector,
261
+ options
262
+ }, { eventHandler: handler });
263
+ },
264
+ unregisterQuery: (selector, options) => {
265
+ const qid = queryId(selector, options);
266
+ const query = this.queries[collection.name]?.get(qid);
267
+ if (query?.eventHandler) this.worker.removeEventListener("message", query.eventHandler);
268
+ this.queries[collection.name]?.delete(qid);
269
+ this.exec("unregisterQuery", collection.name, selector, options);
270
+ },
271
+ getQueryState: (selector, options) => {
272
+ return (this.queries[collection.name]?.get(queryId(selector, options)))?.state || "active";
273
+ },
274
+ getQueryError: (selector, options) => {
275
+ return (this.queries[collection.name]?.get(queryId(selector, options)))?.error || null;
276
+ },
277
+ getQueryResult: (selector, options) => {
278
+ const query = this.queries[collection.name]?.get(queryId(selector, options));
279
+ if (!query) return [];
280
+ const pending = this.pendingWrites.get(collection.name);
281
+ if (!pending || pending.size === 0) return query.items;
282
+ return applyQueryOptions(this.mergePendingWrites(collection.name, query.items), selector, options);
283
+ },
284
+ onQueryStateChange: (selector, options, callback) => {
285
+ this.updateQuery(collection.name, {
286
+ selector,
287
+ options
288
+ }, { stateChangeCallbacks: [...this.queries[collection.name]?.get(queryId(selector, options))?.stateChangeCallbacks || [], callback] });
289
+ return () => {
290
+ const currentCallbacks = this.queries[collection.name]?.get(queryId(selector, options))?.stateChangeCallbacks;
291
+ if (!currentCallbacks) return;
292
+ this.updateQuery(collection.name, {
293
+ selector,
294
+ options
295
+ }, { stateChangeCallbacks: currentCallbacks.filter((existingCallback) => existingCallback !== callback) });
296
+ };
297
+ },
298
+ executeQuery: (selector, options) => this.exec("executeQuery", collection.name, selector, options),
299
+ dispose: async () => {
300
+ await this.exec("unregisterCollection", collection.name);
301
+ this.isDisposed = true;
302
+ this.worker.terminate?.();
303
+ },
304
+ isReady: async () => {
305
+ await this.exec("isReady", collection.name);
306
+ }
307
+ };
308
+ }
309
+ };
20
310
  //#endregion
21
- export { compact as default };
311
+ export { WorkerDataAdapter as default };
@@ -1,335 +1,21 @@
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
- const require_compact = require("./index32.cjs.js");
11
- //#region src/WorkerDataAdapterHost.ts
12
- var WorkerDataAdapterHost = class {
13
- workerContext;
14
- options;
15
- id;
16
- log = () => {};
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) this.onError = this.options.onError;
29
- if (this.options.log) this.log = this.options.log;
30
- this.workerContext.addEventListener("message", async (event) => {
31
- try {
32
- const { workerId, id, method, args } = event.data;
33
- await this.handleMessage(workerId, id, method, args);
34
- } catch (error) {
35
- this.onError(error);
36
- }
37
- });
38
- this.respond("ready", null, null, "ready");
39
- }
40
- respond(id, data, error = null, type = "response") {
41
- this.workerContext.postMessage({
42
- id,
43
- workerId: this.id,
44
- type,
45
- data,
46
- error
47
- });
48
- }
49
- async handleMessage(workerId, id, method, args) {
50
- if (workerId !== this.id) return;
51
- const fn = this[method];
52
- if (typeof fn !== "function") {
53
- this.respond(id, null, /* @__PURE__ */ new Error(`Method ${method} not found`));
54
- return;
55
- }
56
- this.log(method, ...args);
57
- await this.isReady(args[0]);
58
- try {
59
- const result = await fn.apply(this, args);
60
- this.respond(id, result);
61
- } catch (error) {
62
- this.respond(id, null, error);
63
- }
64
- }
65
- async getIndexInfo(collectionName, selector) {
66
- const storageAdapter = this.storageAdapters.get(collectionName);
67
- if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
68
- if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") return {
69
- matched: true,
70
- ids: require_compact.default([selector.id]),
71
- optimizedSelector: {}
72
- };
73
- if (selector == null) return {
74
- matched: false,
75
- ids: [],
76
- optimizedSelector: {}
77
- };
78
- return require_getIndexInfo.default((this.collectionIndices.get(collectionName) ?? []).map((field) => async (flatSelector) => {
79
- if (!Object.hasOwnProperty.call(flatSelector, field)) return { matched: false };
80
- const index = await storageAdapter.readIndex(field);
81
- const fieldSelector = flatSelector[field];
82
- const filteresForNull = fieldSelector == null || fieldSelector.$exists === false;
83
- const keys = filteresForNull ? {
84
- include: null,
85
- exclude: [...index.keys()].filter((key) => key != null)
86
- } : require_getMatchingKeys.default(field, flatSelector);
87
- if (keys.include == null && keys.exclude == null) return { matched: false };
88
- let includedIds = [];
89
- if (keys.include == null) for (const set of index.values()) for (const pos of set) includedIds.push(pos);
90
- else for (const key of keys.include) {
91
- const idSet = index.get(key);
92
- if (idSet) for (const id of idSet) includedIds.push(id);
93
- }
94
- if (keys.exclude != null) {
95
- const excludeIds = /* @__PURE__ */ new Set();
96
- for (const key of keys.exclude) {
97
- const idSet = index.get(key);
98
- if (idSet) for (const id of idSet) excludeIds.add(id);
99
- }
100
- includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
101
- }
102
- return {
103
- matched: true,
104
- ids: includedIds,
105
- fields: [field],
106
- keepSelector: filteresForNull
107
- };
108
- }), selector);
109
- }
110
- async queryItems(collectionName, selector) {
111
- const storageAdapter = this.storageAdapters.get(collectionName);
112
- if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
113
- const indexInfo = await this.getIndexInfo(collectionName, selector);
114
- const matchItems = (item) => {
115
- if (indexInfo.optimizedSelector == null) return true;
116
- if (Object.keys(indexInfo.optimizedSelector).length <= 0) return true;
117
- return require_match.default(item, indexInfo.optimizedSelector);
118
- };
119
- if (indexInfo.matched) {
120
- const items = await storageAdapter.readIds(indexInfo.ids);
121
- if (require_isEqual.default(indexInfo.optimizedSelector, {})) return items;
122
- return items.filter(matchItems);
123
- } else {
124
- const allItems = await storageAdapter.readAll();
125
- if (require_isEqual.default(selector, {})) return allItems;
126
- return allItems.filter(matchItems);
127
- }
128
- }
129
- async executeQuery(collectionName, selector, options) {
130
- if (selector === null) return [];
131
- const items = await this.queryItems(collectionName, selector || {});
132
- const { sort, skip, limit, fields } = options || {};
133
- const sorted = sort ? require_sortItems.default(items, sort) : items;
134
- const skipped = skip ? sorted.slice(skip) : sorted;
135
- const limited = limit ? skipped.slice(0, limit) : skipped;
136
- const idExcluded = fields && fields.id === 0;
137
- return limited.map((item) => {
138
- if (!fields) return item;
139
- return {
140
- ...idExcluded ? {} : { id: item.id },
141
- ...require_project.default(item, fields)
142
- };
143
- });
144
- }
145
- ensureQuery(collectionName, selector, options) {
146
- const id = require_queryId.default(selector, options);
147
- if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
148
- let query = this.queries.get(collectionName)?.get(id);
149
- if (!query) {
150
- query = {
151
- selector,
152
- options
153
- };
154
- this.queries.get(collectionName)?.set(id, query);
155
- }
156
- return query;
157
- }
158
- emitQueryUpdate(collectionName, selector, options, state, error, items) {
159
- const id = require_queryId.default(selector, options);
160
- if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
161
- this.respond(id, {
162
- collectionName,
163
- selector,
164
- options,
165
- state,
166
- error,
167
- items
168
- }, null, "queryUpdate");
169
- }
170
- ensureStorageAdapter(name) {
171
- if (this.storageAdapters.has(name)) return;
172
- const adapter = this.options.storage(name);
173
- if (!adapter) return;
174
- this.storageAdapters.set(name, adapter);
175
- }
176
- async checkQueryUpdates(collectionName, items) {
177
- const queries = this.queries.get(collectionName);
178
- if (!queries) throw new Error(`Collection ${collectionName} not initialized!`);
179
- const affectedQueries = [...queries.values()].filter(({ selector }) => items.some((item) => require_match.default(item, selector))) ?? [];
180
- if (affectedQueries.length === 0) return;
181
- affectedQueries.forEach(({ selector, options }) => {
182
- this.emitQueryUpdate(collectionName, selector, options, "active", null);
183
- });
184
- await Promise.all(affectedQueries.map(async ({ selector, options }) => {
185
- const queryItems = await this.executeQuery(collectionName, selector, options);
186
- this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
187
- }));
188
- }
189
- registerCollection = async (collectionName, indices) => {
190
- this.collectionIndices.set(collectionName, indices);
191
- this.queries.set(collectionName, /* @__PURE__ */ new Map());
192
- this.ensureStorageAdapter(collectionName);
193
- const storageAdapter = this.storageAdapters.get(collectionName);
194
- if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
195
- const setupPromise = (async () => {
196
- await storageAdapter.setup();
197
- await Promise.all(indices.map((index) => storageAdapter.createIndex(index)));
198
- })();
199
- this.storageAdapterReady.set(collectionName, setupPromise);
200
- await setupPromise;
201
- };
202
- unregisterCollection = async (collectionName) => {
203
- this.storageAdapters.delete(collectionName);
204
- this.queries.delete(collectionName);
205
- };
206
- registerQuery = async (collectionName, selector, options) => {
207
- this.ensureQuery(collectionName, selector, options);
208
- const queryItems = await this.executeQuery(collectionName, selector, options);
209
- this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
210
- };
211
- unregisterQuery = async (collectionName, selector, options) => {
212
- const id = require_queryId.default(selector, options);
213
- if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
214
- this.queries.get(collectionName)?.delete(id);
215
- };
216
- insert = async (collectionName, input) => {
217
- const storageAdapter = this.storageAdapters.get(collectionName);
218
- if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
219
- const existingItems = await this.executeQuery(collectionName, { id: { $in: input.map((i) => i[0].id) } });
220
- const result = input.map(([item]) => {
221
- if (item.id == null) return /* @__PURE__ */ new Error("Item must have an id");
222
- if (existingItems.some((existing) => existing.id === item.id)) return /* @__PURE__ */ new Error(`Item with id ${item.id} already exists`);
223
- return item;
224
- });
225
- const newItems = result.filter((item) => !(item instanceof Error));
226
- await storageAdapter.insert(newItems);
227
- await this.checkQueryUpdates(collectionName, newItems);
228
- return result;
229
- };
230
- updateOne = async (collectionName, parameters) => {
231
- const storageAdapter = this.storageAdapters.get(collectionName);
232
- if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
233
- const previousItems = [];
234
- const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
235
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
236
- const { $setOnInsert, ...restModifier } = modifier;
237
- if (item == null) return [];
238
- previousItems.push(item);
239
- const modifiedItem = require_modify.default(require_deepClone.default(item), restModifier);
240
- if (item.id !== modifiedItem.id) {
241
- if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) return /* @__PURE__ */ new Error(`Item with id ${modifiedItem.id} already exists`);
242
- }
243
- return [modifiedItem];
244
- }));
245
- const modifiedItems = require_compact.default(result.filter((item) => !(item instanceof Error)).flat());
246
- if (modifiedItems.length > 0) {
247
- await storageAdapter.replace(modifiedItems);
248
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
249
- }
250
- return result;
251
- };
252
- updateMany = async (collectionName, parameters) => {
253
- const storageAdapter = this.storageAdapters.get(collectionName);
254
- if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
255
- const previousItems = [];
256
- const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
257
- const items = await this.executeQuery(collectionName, selector);
258
- if (items.length === 0) return [];
259
- const { $setOnInsert, ...restModifier } = modifier;
260
- try {
261
- return await Promise.all(items.map(async (item) => {
262
- const modifiedItem = require_modify.default(require_deepClone.default(item), restModifier);
263
- if (item.id !== modifiedItem.id) {
264
- if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${modifiedItem.id} already exists`);
265
- }
266
- previousItems.push(item);
267
- return modifiedItem;
268
- }));
269
- } catch (error) {
270
- return error;
271
- }
272
- }));
273
- const modifiedItems = require_compact.default(result.filter((item) => !(item instanceof Error)).flat());
274
- if (modifiedItems.length > 0) {
275
- await storageAdapter.replace(modifiedItems);
276
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
277
- }
278
- return result;
279
- };
280
- replaceOne = async (collectionName, parameters) => {
281
- const storageAdapter = this.storageAdapters.get(collectionName);
282
- if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
283
- const previousItems = [];
284
- const result = await Promise.all(parameters.map(async ([selector, replacement]) => {
285
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
286
- if (item == null) return [];
287
- previousItems.push(item);
288
- const modifiedItem = {
289
- ...replacement,
290
- id: replacement.id ?? item.id
291
- };
292
- if (item.id !== modifiedItem.id) {
293
- if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) return /* @__PURE__ */ new Error(`Item with id ${modifiedItem.id} already exists`);
294
- }
295
- return [modifiedItem];
296
- }));
297
- const modifiedItems = require_compact.default(result.filter((item) => !(item instanceof Error)).flat());
298
- if (modifiedItems.length > 0) {
299
- await storageAdapter.replace(modifiedItems);
300
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
301
- }
302
- return result;
303
- };
304
- removeOne = async (collectionName, selectors) => {
305
- const storageAdapter = this.storageAdapters.get(collectionName);
306
- if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
307
- const result = await Promise.all(selectors.map(async ([selector]) => {
308
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
309
- if (item == null) return [];
310
- return [item];
311
- }));
312
- const items = result.flat();
313
- if (items.length > 0) {
314
- await storageAdapter.remove(items);
315
- await this.checkQueryUpdates(collectionName, items);
316
- }
317
- return result;
318
- };
319
- removeMany = async (collectionName, selectors) => {
320
- const storageAdapter = this.storageAdapters.get(collectionName);
321
- if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
322
- const result = await Promise.all(selectors.map(async ([selector]) => this.executeQuery(collectionName, selector)));
323
- const items = result.flat();
324
- if (items.length > 0) {
325
- await storageAdapter.remove(items);
326
- await this.checkQueryUpdates(collectionName, items);
327
- }
328
- return result;
329
- };
330
- isReady = async (collectionName) => {
331
- return this.storageAdapterReady.get(collectionName);
332
- };
333
- };
1
+ //#region src/utils/compact.ts
2
+ /**
3
+ * Checks if a value is truthy.
4
+ * @template T - The type of the value.
5
+ * @param value - The value to check.
6
+ * @returns A boolean indicating if the value is truthy.
7
+ */
8
+ function truthy(value) {
9
+ return !!value;
10
+ }
11
+ /**
12
+ * Filters out falsy values (`false`, `''`, `0`, `null`, `undefined`) from an array.
13
+ * @template T - The type of the elements in the array.
14
+ * @param array - The array to filter.
15
+ * @returns A new array containing only the truthy values from the input array.
16
+ */
17
+ function compact(array) {
18
+ return array.filter(truthy);
19
+ }
334
20
  //#endregion
335
- exports.default = WorkerDataAdapterHost;
21
+ exports.default = compact;