@signaldb/sync 1.3.1 → 2.0.0-beta.0

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.
@@ -1,7 +1,7 @@
1
- import type { BaseItem, PersistenceAdapter, ReactivityAdapter, Changeset, LoadResponse } from '@signaldb/core';
1
+ import type { BaseItem, StorageAdapter, ReactivityAdapter, Changeset } from '@signaldb/core';
2
2
  import { Collection } from '@signaldb/core';
3
3
  import PromiseQueue from './utils/PromiseQueue';
4
- import type { Change, Snapshot, SyncOperation } from './types';
4
+ import type { Change, LoadResponse, Snapshot, SyncOperation } from './types';
5
5
  type SyncOptions<T extends Record<string, any>> = {
6
6
  name: string;
7
7
  } & T;
@@ -19,7 +19,7 @@ interface Options<CollectionOptions extends Record<string, any>, ItemType extend
19
19
  }) => Promise<void>;
20
20
  registerRemoteChange?: (collectionOptions: SyncOptions<CollectionOptions>, onChange: (data?: LoadResponse<ItemType>) => Promise<void>) => CleanupFunction | Promise<CleanupFunction>;
21
21
  id?: string;
22
- persistenceAdapter?: (id: string, registerErrorHandler: (handler: (error: Error) => void) => void) => PersistenceAdapter<any, any>;
22
+ storageAdapter?: (id: string, registerErrorHandler: (handler: (error: Error) => void) => void) => StorageAdapter<any, any>;
23
23
  reactivity?: ReactivityAdapter;
24
24
  onError?: (collectionOptions: SyncOptions<CollectionOptions>, error: Error) => void;
25
25
  autostart?: boolean;
@@ -77,15 +77,15 @@ export default class SyncManager<CollectionOptions extends Record<string, any>,
77
77
  * @param options.push Function to push data to remote source.
78
78
  * @param [options.registerRemoteChange] Function to register a callback for remote changes.
79
79
  * @param [options.id] Unique identifier for this sync manager. Only nessesary if you have multiple sync managers.
80
- * @param [options.persistenceAdapter] Persistence adapter to use for storing changes, snapshots and sync operations.
80
+ * @param [options.storageAdapter] Storage adapter to use for storing changes, snapshots and sync operations.
81
81
  * @param [options.reactivity] Reactivity adapter to use for reactivity.
82
82
  * @param [options.onError] Function to handle errors that occur async during syncing.
83
83
  * @param [options.autostart] Whether to automatically start syncing new collections.
84
84
  * @param [options.debounceTime] The time in milliseconds to debounce push operations.
85
85
  */
86
86
  constructor(options: Options<CollectionOptions, ItemType, IdType>);
87
- protected createPersistenceAdapter(name: string): {
88
- adapter: PersistenceAdapter<any, any>;
87
+ protected createStorageAdapter(name: string): {
88
+ adapter: StorageAdapter<any, any>;
89
89
  handler: (error: Error) => void;
90
90
  } | undefined;
91
91
  protected getSyncQueue(name: string): PromiseQueue;
@@ -1,4 +1,5 @@
1
- import type { BaseItem, LoadResponse } from '@signaldb/core';
1
+ import type { BaseItem } from '@signaldb/core';
2
+ import type { LoadResponse } from './types';
2
3
  /**
3
4
  * Gets the snapshot of items from the last snapshot and the changes.
4
5
  * @param lastSnapshot The last snapshot of items
package/dist/index.mjs CHANGED
@@ -1,23 +1,18 @@
1
- var E = Object.defineProperty;
2
- var M = (c, e, t) => e in c ? E(c, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : c[e] = t;
3
- var u = (c, e, t) => M(c, typeof e != "symbol" ? e + "" : e, t);
4
- import { isEqual as S, modify as C, randomId as D, Collection as m, createIndex as y } from "@signaldb/core";
5
- function x(c, e, t = {}) {
1
+ import { isEqual as O, modify as g, randomId as $, DefaultDataAdapter as N, Collection as y } from "@signaldb/core";
2
+ function E(h, e, t = {}) {
6
3
  let s, n;
7
4
  const { leading: o = !1, trailing: a = !0 } = t;
8
- function r(...h) {
5
+ function c(...r) {
9
6
  const i = o && !s, l = a && !s;
10
7
  return s && clearTimeout(s), s = setTimeout(() => {
11
- s = null, a && !i && (n = c.apply(this, h));
12
- }, e), i ? n = c.apply(this, h) : l || (n = null), n;
8
+ s = null, a && !i && (n = h.apply(this, r));
9
+ }, e), i ? n = h.apply(this, r) : l || (n = null), n;
13
10
  }
14
- return r;
11
+ return c;
15
12
  }
16
- class R {
17
- constructor() {
18
- u(this, "queue", []);
19
- u(this, "pendingPromise", !1);
20
- }
13
+ class D {
14
+ queue = [];
15
+ pendingPromise = !1;
21
16
  /**
22
17
  * Method to add a new promise to the queue and returns a promise that resolves when this task is done
23
18
  * @param task Function that returns a promise that will be added to the queue
@@ -51,26 +46,26 @@ class R {
51
46
  }));
52
47
  }
53
48
  }
54
- function N(c, e) {
55
- const t = [], s = Object.keys(c), n = Object.keys(e), o = /* @__PURE__ */ new Set([...s, ...n]);
49
+ function C(h, e) {
50
+ const t = [], s = Object.keys(h), n = Object.keys(e), o = /* @__PURE__ */ new Set([...s, ...n]);
56
51
  for (const a of o)
57
- if (e[a] !== c[a])
58
- if (typeof e[a] == "object" && typeof c[a] == "object" && e[a] != null && c[a] != null) {
59
- const r = N(c[a], e[a]);
60
- for (const h of r)
61
- t.push(`${a}.${h}`);
52
+ if (e[a] !== h[a])
53
+ if (typeof e[a] == "object" && typeof h[a] == "object" && e[a] != null && h[a] != null) {
54
+ const c = C(h[a], e[a]);
55
+ for (const r of c)
56
+ t.push(`${a}.${r}`);
62
57
  } else
63
58
  t.push(a);
64
59
  return t;
65
60
  }
66
- function g(c, e) {
67
- const t = [], s = [], n = /* @__PURE__ */ new Map(), o = [], a = new Map(c.map((h) => [h.id, h])), r = new Map(e.map((h) => [h.id, h]));
68
- for (const [h, i] of a) {
69
- const l = r.get(h);
70
- l ? S(l, i) || (n.set(l.id, N(i, l)), s.push(l)) : o.push(i);
61
+ function f(h, e) {
62
+ const t = [], s = [], n = /* @__PURE__ */ new Map(), o = [], a = new Map(h.map((r) => [r.id, r])), c = new Map(e.map((r) => [r.id, r]));
63
+ for (const [r, i] of a) {
64
+ const l = c.get(r);
65
+ l ? O(l, i) || (n.set(l.id, C(i, l)), s.push(l)) : o.push(i);
71
66
  }
72
- for (const [h, i] of r)
73
- a.has(h) || t.push(i);
67
+ for (const [r, i] of c)
68
+ a.has(r) || t.push(i);
74
69
  return {
75
70
  added: t,
76
71
  modified: s,
@@ -78,10 +73,10 @@ function g(c, e) {
78
73
  removed: o
79
74
  };
80
75
  }
81
- function P(c, e) {
76
+ function w(h, e) {
82
77
  if (e.items != null)
83
78
  return e.items;
84
- const t = c || [];
79
+ const t = h || [];
85
80
  return e.changes.added.forEach((s) => {
86
81
  const n = t.findIndex((o) => o.id === s.id);
87
82
  n === -1 ? t.push(s) : t[n] = s;
@@ -93,8 +88,8 @@ function P(c, e) {
93
88
  n !== -1 && t.splice(n, 1);
94
89
  }), t;
95
90
  }
96
- function v(c, e) {
97
- const t = new Map(c.map((s) => [s.id, s]));
91
+ function P(h, e) {
92
+ const t = new Map(h.map((s) => [s.id, s]));
98
93
  return e.forEach((s) => {
99
94
  if (s.type === "remove")
100
95
  t.delete(s.data);
@@ -103,98 +98,111 @@ function v(c, e) {
103
98
  t.set(s.data.id, n ? { ...n, ...s.data } : s.data);
104
99
  } else {
105
100
  const n = t.get(s.data.id);
106
- t.set(s.data.id, n ? C(n, s.data.modifier) : C({ id: s.data.id }, s.data.modifier));
101
+ t.set(s.data.id, n ? g(n, s.data.modifier) : g({ id: s.data.id }, s.data.modifier));
107
102
  }
108
103
  }), [...t.values()];
109
104
  }
110
- function O(c) {
111
- return c.added.length > 0 || c.modified.length > 0 || c.removed.length > 0;
105
+ function v(h) {
106
+ return h.added.length > 0 || h.modified.length > 0 || h.removed.length > 0;
112
107
  }
113
- function b(c, e) {
114
- return O(g(c, e));
108
+ function M(h, e) {
109
+ return v(f(h, e));
115
110
  }
116
- async function I({ changes: c, lastSnapshot: e, data: t, pull: s, push: n, insert: o, update: a, remove: r, batch: h }) {
117
- let i = t, l = e || [], f = P(e, i);
118
- if (c.length > 0) {
119
- const p = v(l, c);
120
- if (b(l, p)) {
121
- const $ = v(f, c), w = g(f, $);
122
- O(w) && (await n(w), i = await s(), f = P(f, i)), l = p;
111
+ async function F({ changes: h, lastSnapshot: e, data: t, pull: s, push: n, insert: o, update: a, remove: c, batch: r }) {
112
+ let i = t, l = e || [], p = w(e, i);
113
+ if (h.length > 0) {
114
+ const u = P(l, h);
115
+ if (M(l, u)) {
116
+ const S = P(p, h), m = f(p, S);
117
+ v(m) && (await n(m), i = await s(), p = w(p, i)), l = u;
123
118
  }
124
119
  }
125
- const d = i.changes == null ? g(l, i.items) : i.changes;
126
- return h(() => {
127
- d.added.forEach((p) => o(p)), d.modified.forEach((p) => a(p.id, { $set: p })), d.removed.forEach((p) => r(p.id));
128
- }), f;
120
+ const d = i.changes == null ? f(l, i.items) : i.changes;
121
+ return await r(async () => {
122
+ await Promise.all(d.added.map((u) => o(u))), await Promise.all(d.modified.map((u) => a(u.id, { $set: u }))), await Promise.all(d.removed.map((u) => c(u.id)));
123
+ }), p;
129
124
  }
130
- class T {
125
+ class b {
126
+ options;
127
+ collections = /* @__PURE__ */ new Map();
128
+ changes;
129
+ snapshots;
130
+ syncOperations;
131
+ scheduledPushes = /* @__PURE__ */ new Set();
132
+ remoteChanges = [];
133
+ syncQueues = /* @__PURE__ */ new Map();
134
+ persistenceReady;
135
+ isDisposed = !1;
136
+ instanceId = $();
137
+ id;
138
+ debouncedFlush;
131
139
  /**
132
140
  * @param options Collection options
133
141
  * @param options.pull Function to pull data from remote source.
134
142
  * @param options.push Function to push data to remote source.
135
143
  * @param [options.registerRemoteChange] Function to register a callback for remote changes.
136
144
  * @param [options.id] Unique identifier for this sync manager. Only nessesary if you have multiple sync managers.
137
- * @param [options.persistenceAdapter] Persistence adapter to use for storing changes, snapshots and sync operations.
145
+ * @param [options.storageAdapter] Storage adapter to use for storing changes, snapshots and sync operations.
138
146
  * @param [options.reactivity] Reactivity adapter to use for reactivity.
139
147
  * @param [options.onError] Function to handle errors that occur async during syncing.
140
148
  * @param [options.autostart] Whether to automatically start syncing new collections.
141
149
  * @param [options.debounceTime] The time in milliseconds to debounce push operations.
142
150
  */
143
151
  constructor(e) {
144
- u(this, "options");
145
- u(this, "collections", /* @__PURE__ */ new Map());
146
- u(this, "changes");
147
- u(this, "snapshots");
148
- u(this, "syncOperations");
149
- u(this, "scheduledPushes", /* @__PURE__ */ new Set());
150
- u(this, "remoteChanges", []);
151
- u(this, "syncQueues", /* @__PURE__ */ new Map());
152
- u(this, "persistenceReady");
153
- u(this, "isDisposed", !1);
154
- u(this, "instanceId", D());
155
- u(this, "id");
156
- u(this, "debouncedFlush");
157
152
  this.options = {
158
153
  autostart: !0,
159
154
  ...e
160
155
  }, this.id = this.options.id || "default-sync-manager";
161
- const { reactivity: t } = this.options, s = this.createPersistenceAdapter("changes"), n = this.createPersistenceAdapter("snapshots"), o = this.createPersistenceAdapter("sync-operations");
162
- this.changes = new m({
163
- name: `${this.options.id}-changes`,
164
- persistence: s == null ? void 0 : s.adapter,
165
- indices: [y("collectionName")],
156
+ const { reactivity: t } = this.options, s = this.createStorageAdapter("changes"), n = this.createStorageAdapter("snapshots"), o = this.createStorageAdapter("sync-operations"), a = new N({
157
+ storage: (c) => {
158
+ if (c === `${this.options.id}-changes`)
159
+ return s?.adapter;
160
+ if (c === `${this.options.id}-snapshots`)
161
+ return n?.adapter;
162
+ if (c === `${this.options.id}-sync-operations`)
163
+ return o?.adapter;
164
+ throw new Error(`Unknown storage name: ${c}`);
165
+ },
166
+ onError: (c, r) => {
167
+ if (c === "changes")
168
+ return s?.handler(r);
169
+ if (c === "snapshots")
170
+ return n?.handler(r);
171
+ if (c === "sync-operations")
172
+ return o?.handler(r);
173
+ throw new Error(`Error in unknown storage name: ${c}`, { cause: r });
174
+ }
175
+ });
176
+ this.changes = new y(`${this.options.id}-changes`, a, {
177
+ indices: ["collectionName"],
166
178
  reactivity: t
167
- }), this.snapshots = new m({
168
- name: `${this.options.id}-snapshots`,
169
- persistence: n == null ? void 0 : n.adapter,
170
- indices: [y("collectionName")],
179
+ }), this.snapshots = new y(`${this.options.id}-snapshots`, a, {
180
+ indices: ["collectionName"],
171
181
  reactivity: t
172
- }), this.syncOperations = new m({
173
- name: `${this.options.id}-sync-operations`,
174
- persistence: o == null ? void 0 : o.adapter,
175
- indices: [y("collectionName"), y("status")],
182
+ }), this.syncOperations = new y(`${this.options.id}-sync-operations`, a, {
183
+ indices: ["collectionName", "status"],
176
184
  reactivity: t
177
- }), this.changes.on("persistence.error", (a) => s == null ? void 0 : s.handler(a)), this.snapshots.on("persistence.error", (a) => n == null ? void 0 : n.handler(a)), this.syncOperations.on("persistence.error", (a) => o == null ? void 0 : o.handler(a)), this.persistenceReady = Promise.all([
185
+ }), this.persistenceReady = Promise.all([
178
186
  this.syncOperations.isReady(),
179
187
  this.changes.isReady(),
180
188
  this.snapshots.isReady()
181
189
  ]).then(() => {
182
- }), this.changes.setMaxListeners(1e3), this.snapshots.setMaxListeners(1e3), this.syncOperations.setMaxListeners(1e3), this.debouncedFlush = x(this.flushScheduledPushes, this.options.debounceTime ?? 100);
190
+ }), this.changes.setMaxListeners(1e3), this.snapshots.setMaxListeners(1e3), this.syncOperations.setMaxListeners(1e3), this.debouncedFlush = E(this.flushScheduledPushes, this.options.debounceTime ?? 100);
183
191
  }
184
- createPersistenceAdapter(e) {
185
- if (this.options.persistenceAdapter == null)
192
+ createStorageAdapter(e) {
193
+ if (this.options.storageAdapter == null)
186
194
  return;
187
195
  let t = () => {
188
196
  };
189
197
  return {
190
- adapter: this.options.persistenceAdapter(`${this.id}-${e}`, (n) => {
198
+ adapter: this.options.storageAdapter(`${this.id}-${e}`, (n) => {
191
199
  t = n;
192
200
  }),
193
201
  handler: (n) => t(n)
194
202
  };
195
203
  }
196
204
  getSyncQueue(e) {
197
- return this.syncQueues.get(e) == null && this.syncQueues.set(e, new R()), this.syncQueues.get(e);
205
+ return this.syncQueues.get(e) == null && this.syncQueues.set(e, new D()), this.syncQueues.get(e);
198
206
  }
199
207
  /**
200
208
  * Clears all internal data structures
@@ -241,7 +249,7 @@ class T {
241
249
  this.collections.set(t.name, {
242
250
  collection: e,
243
251
  options: t,
244
- readyPromise: e.isReady(),
252
+ readyPromise: e.ready(),
245
253
  syncPaused: !0
246
254
  // always start paused as the autostart will start it
247
255
  });
@@ -251,12 +259,12 @@ class T {
251
259
  return !0;
252
260
  return !1;
253
261
  }, n = (o, a) => {
254
- const r = [...this.remoteChanges];
255
- for (let h = 0; h < r.length; h += 1) {
256
- const i = r[h];
257
- i != null && i.collectionName === o && (i.type === "remove" && i.data !== a || i.data.id === a && (r[h] = null));
262
+ const c = [...this.remoteChanges];
263
+ for (let r = 0; r < c.length; r += 1) {
264
+ const i = c[r];
265
+ i != null && i.collectionName === o && (i.type === "remove" && i.data !== a || i.data.id === a && (c[r] = null));
258
266
  }
259
- this.remoteChanges = r.filter((h) => h != null);
267
+ this.remoteChanges = c.filter((r) => r != null);
260
268
  };
261
269
  e.on("added", (o) => {
262
270
  if (s({ collectionName: t.name, type: "insert", data: o })) {
@@ -268,10 +276,14 @@ class T {
268
276
  time: Date.now(),
269
277
  type: "insert",
270
278
  data: o
271
- }), !this.getCollectionProperties(t.name).syncPaused && this.schedulePush(t.name);
279
+ }).then(() => {
280
+ this.getCollectionProperties(t.name).syncPaused || this.schedulePush(t.name);
281
+ }).catch((a) => {
282
+ this.options.onError && this.options.onError(this.getCollectionProperties(t.name).options, a);
283
+ });
272
284
  }), e.on("changed", ({ id: o }, a) => {
273
- const r = { id: o, modifier: a };
274
- if (s({ collectionName: t.name, type: "update", data: r })) {
285
+ const c = { id: o, modifier: a };
286
+ if (s({ collectionName: t.name, type: "update", data: c })) {
275
287
  n(t.name, o);
276
288
  return;
277
289
  }
@@ -279,8 +291,12 @@ class T {
279
291
  collectionName: t.name,
280
292
  time: Date.now(),
281
293
  type: "update",
282
- data: r
283
- }), !this.getCollectionProperties(t.name).syncPaused && this.schedulePush(t.name);
294
+ data: c
295
+ }).then(() => {
296
+ this.getCollectionProperties(t.name).syncPaused || this.schedulePush(t.name);
297
+ }).catch((r) => {
298
+ this.options.onError && this.options.onError(this.getCollectionProperties(t.name).options, r);
299
+ });
284
300
  }), e.on("removed", ({ id: o }) => {
285
301
  if (s({ collectionName: t.name, type: "remove", data: o })) {
286
302
  n(t.name, o);
@@ -291,7 +307,11 @@ class T {
291
307
  time: Date.now(),
292
308
  type: "remove",
293
309
  data: o
294
- }), !this.getCollectionProperties(t.name).syncPaused && this.schedulePush(t.name);
310
+ }).then(() => {
311
+ this.getCollectionProperties(t.name).syncPaused || this.schedulePush(t.name);
312
+ }).catch((a) => {
313
+ this.options.onError && this.options.onError(this.getCollectionProperties(t.name).options, a);
314
+ });
295
315
  }), this.options.autostart && this.startSync(t.name).catch((o) => {
296
316
  this.options.onError && this.options.onError(this.getCollectionProperties(t.name).options, o);
297
317
  });
@@ -326,27 +346,27 @@ class T {
326
346
  if (n == null)
327
347
  await this.sync(e);
328
348
  else {
329
- const o = Date.now(), a = this.syncOperations.insert({
349
+ const o = Date.now(), a = await this.syncOperations.insert({
330
350
  start: o,
331
351
  collectionName: e,
332
352
  instanceId: this.instanceId,
333
353
  status: "active"
334
354
  });
335
- await this.syncWithData(e, n).then(() => {
336
- this.syncOperations.removeMany({
355
+ await this.syncWithData(e, n).then(async () => {
356
+ await this.syncOperations.removeMany({
337
357
  id: { $ne: a },
338
358
  collectionName: e,
339
359
  $or: [
340
360
  { end: { $lte: o } },
341
361
  { status: "active" }
342
362
  ]
343
- }), this.syncOperations.updateOne({ id: a }, {
363
+ }), await this.syncOperations.updateOne({ id: a }, {
344
364
  $set: { status: "done", end: Date.now() }
345
365
  });
346
- }).catch((r) => {
347
- throw this.options.onError && this.options.onError(this.getCollectionProperties(e).options, r), this.syncOperations.updateOne({ id: a }, {
348
- $set: { status: "error", end: Date.now(), error: r.stack || r.message }
349
- }), r;
366
+ }).catch(async (c) => {
367
+ throw this.options.onError && this.options.onError(this.getCollectionProperties(e).options, c), await this.syncOperations.updateOne({ id: a }, {
368
+ $set: { status: "error", end: Date.now(), error: c.stack || c.message }
369
+ }), c;
350
370
  });
351
371
  }
352
372
  }) : void 0;
@@ -431,11 +451,11 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
431
451
  }, {
432
452
  reactive: !1
433
453
  }).count() > 0, a = Date.now();
434
- let r = null;
454
+ let c = null;
435
455
  await new Promise((i) => {
436
456
  setTimeout(i, 0);
437
457
  });
438
- const h = async () => {
458
+ const r = async () => {
439
459
  const i = this.syncOperations.findOne({
440
460
  collectionName: e,
441
461
  status: "done"
@@ -443,7 +463,7 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
443
463
  sort: { end: -1 },
444
464
  reactive: !1
445
465
  });
446
- if (t != null && t.onlyWithChanges && this.changes.find({
466
+ if (t?.onlyWithChanges && this.changes.find({
447
467
  collectionName: e,
448
468
  time: { $lte: a }
449
469
  }, {
@@ -451,30 +471,30 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
451
471
  reactive: !1
452
472
  }).count() === 0)
453
473
  return;
454
- o || (r = this.syncOperations.insert({
474
+ o || (c = await this.syncOperations.insert({
455
475
  start: a,
456
476
  collectionName: e,
457
477
  instanceId: this.instanceId,
458
478
  status: "active"
459
479
  }));
460
480
  const l = await this.options.pull(s, {
461
- lastFinishedSyncStart: i == null ? void 0 : i.start,
462
- lastFinishedSyncEnd: i == null ? void 0 : i.end
481
+ lastFinishedSyncStart: i?.start,
482
+ lastFinishedSyncEnd: i?.end
463
483
  });
464
484
  await this.syncWithData(e, l);
465
485
  };
466
- await (t != null && t.force ? h() : this.getSyncQueue(e).add(h)).catch((i) => {
467
- throw r != null && (this.options.onError && this.options.onError(s, i), this.syncOperations.updateOne({ id: r }, {
486
+ await (t?.force ? r() : this.getSyncQueue(e).add(r)).catch(async (i) => {
487
+ throw c != null && (this.options.onError && this.options.onError(s, i), await this.syncOperations.updateOne({ id: c }, {
468
488
  $set: { status: "error", end: Date.now(), error: i.stack || i.message }
469
489
  })), i;
470
- }), r != null && (this.syncOperations.removeMany({
471
- id: { $ne: r },
490
+ }), c != null && (await this.syncOperations.removeMany({
491
+ id: { $ne: c },
472
492
  collectionName: e,
473
493
  $or: [
474
494
  { end: { $lte: a } },
475
495
  { status: "active" }
476
496
  ]
477
- }), this.syncOperations.updateOne({ id: r }, {
497
+ }), await this.syncOperations.updateOne({ id: c }, {
478
498
  $set: { status: "done", end: Date.now() }
479
499
  }));
480
500
  }
@@ -494,31 +514,31 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
494
514
  }, {
495
515
  sort: { end: -1 },
496
516
  reactive: !1
497
- }), r = this.snapshots.findOne({
517
+ }), c = this.snapshots.findOne({
498
518
  collectionName: e
499
519
  }, {
500
520
  sort: { time: -1 },
501
521
  reactive: !1
502
- }), h = this.changes.find({
522
+ }), r = this.changes.find({
503
523
  collectionName: e,
504
524
  time: { $lte: o }
505
525
  }, {
506
526
  sort: { time: 1 },
507
527
  reactive: !1
508
528
  }).fetch();
509
- await I({
510
- changes: h,
511
- lastSnapshot: r == null ? void 0 : r.items,
529
+ await F({
530
+ changes: r,
531
+ lastSnapshot: c?.items,
512
532
  data: t,
513
533
  pull: () => this.options.pull(n, {
514
- lastFinishedSyncStart: a == null ? void 0 : a.start,
515
- lastFinishedSyncEnd: a == null ? void 0 : a.end
534
+ lastFinishedSyncStart: a?.start,
535
+ lastFinishedSyncEnd: a?.end
516
536
  }),
517
537
  push: (i) => this.options.push(n, {
518
538
  changes: i,
519
- rawChanges: h
539
+ rawChanges: r
520
540
  }),
521
- insert: (i) => {
541
+ insert: async (i) => {
522
542
  this.remoteChanges.push({
523
543
  collectionName: e,
524
544
  type: "insert",
@@ -527,9 +547,9 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
527
547
  collectionName: e,
528
548
  type: "update",
529
549
  data: { id: i.id, modifier: { $set: i } }
530
- }), s.replaceOne({ id: i.id }, i, { upsert: !0 });
550
+ }), await s.replaceOne({ id: i.id }, i, { upsert: !0 });
531
551
  },
532
- update: (i, l) => {
552
+ update: async (i, l) => {
533
553
  this.remoteChanges.push({
534
554
  collectionName: e,
535
555
  type: "insert",
@@ -538,33 +558,31 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
538
558
  collectionName: e,
539
559
  type: "update",
540
560
  data: { id: i, modifier: l }
541
- }), s.updateOne({ id: i }, {
561
+ }), await s.updateOne({ id: i }, {
542
562
  ...l,
543
563
  $setOnInsert: { id: i }
544
564
  }, { upsert: !0 });
545
565
  },
546
- remove: (i) => {
566
+ remove: async (i) => {
547
567
  s.findOne({
548
568
  id: i
549
569
  }, { reactive: !1 }) && (this.remoteChanges.push({
550
570
  collectionName: e,
551
571
  type: "remove",
552
572
  data: i
553
- }), s.removeOne({ id: i }));
573
+ }), await s.removeOne({ id: i }));
554
574
  },
555
- batch: (i) => {
556
- s.batch(() => {
557
- i();
558
- });
559
- }
575
+ batch: async (i) => s.batch(async () => {
576
+ await i();
577
+ })
560
578
  }).then(async (i) => {
561
- if (this.snapshots.removeMany({
579
+ if (await this.snapshots.removeMany({
562
580
  collectionName: e,
563
581
  time: { $lte: o }
564
- }), this.changes.removeMany({
582
+ }), await this.changes.removeMany({
565
583
  collectionName: e,
566
- id: { $in: h.map((d) => d.id) }
567
- }), this.snapshots.insert({
584
+ id: { $in: r.map((d) => d.id) }
585
+ }), await this.snapshots.insert({
568
586
  time: o,
569
587
  collectionName: e,
570
588
  items: i
@@ -579,13 +597,13 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
579
597
  });
580
598
  return;
581
599
  }
582
- const f = s.find({
600
+ const p = s.find({
583
601
  id: { $nin: i.map((d) => d.id) }
584
602
  }, {
585
603
  reactive: !1
586
604
  }).map((d) => d.id);
587
- s.batch(() => {
588
- i.forEach((d) => {
605
+ await s.batch(async () => {
606
+ await Promise.all(i.map(async (d) => {
589
607
  this.remoteChanges.push({
590
608
  collectionName: e,
591
609
  type: "insert",
@@ -594,15 +612,15 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
594
612
  collectionName: e,
595
613
  type: "update",
596
614
  data: { id: d.id, modifier: { $set: d } }
597
- }), s.replaceOne({ id: d.id }, d, { upsert: !0 });
598
- }), f.forEach((d) => {
599
- s.removeOne({ id: d });
600
- });
615
+ }), await s.replaceOne({ id: d.id }, d, { upsert: !0 });
616
+ })), await Promise.all(p.map(async (d) => {
617
+ await s.removeOne({ id: d });
618
+ }));
601
619
  });
602
620
  });
603
621
  }
604
622
  }
605
623
  export {
606
- T as SyncManager
624
+ b as SyncManager
607
625
  };
608
626
  //# sourceMappingURL=index.mjs.map