@signaldb/sync 1.1.1 → 1.1.2

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/index.mjs CHANGED
@@ -1,19 +1,19 @@
1
- var E = Object.defineProperty;
2
- var $ = (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) => $(c, typeof e != "symbol" ? e + "" : e, t);
4
- import { isEqual as m, Collection as y, modify as N, randomId as D } from "@signaldb/core";
5
- function x(c, e, t = {}) {
6
- let s, n;
1
+ var N = Object.defineProperty;
2
+ var $ = (r, e, t) => e in r ? N(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
3
+ var u = (r, e, t) => $(r, typeof e != "symbol" ? e + "" : e, t);
4
+ import { isEqual as g, Collection as m, modify as x, randomId as D, createIndex as y } from "@signaldb/core";
5
+ function S(r, e, t = {}) {
6
+ let s, i;
7
7
  const { leading: a = !1, trailing: o = !0 } = t;
8
- function r(...l) {
9
- const i = a && !s, d = o && !s;
8
+ function c(...l) {
9
+ const n = a && !s, d = o && !s;
10
10
  return s && clearTimeout(s), s = setTimeout(() => {
11
- s = null, o && !i && (n = c.apply(this, l));
12
- }, e), i ? n = c.apply(this, l) : d || (n = null), n;
11
+ s = null, o && !n && (i = r.apply(this, l));
12
+ }, e), n ? i = r.apply(this, l) : d || (i = null), i;
13
13
  }
14
- return r;
14
+ return c;
15
15
  }
16
- class S {
16
+ class M {
17
17
  constructor() {
18
18
  u(this, "queue", []);
19
19
  u(this, "pendingPromise", !1);
@@ -25,8 +25,8 @@ class S {
25
25
  */
26
26
  add(e) {
27
27
  return new Promise((t, s) => {
28
- this.queue.push(() => e().then(t).catch((n) => {
29
- throw s(n), n;
28
+ this.queue.push(() => e().then(t).catch((i) => {
29
+ throw s(i), i;
30
30
  })), this.dequeue();
31
31
  });
32
32
  }
@@ -51,71 +51,71 @@ class S {
51
51
  }));
52
52
  }
53
53
  }
54
- function g(c, e) {
55
- const t = [], s = [], n = [], a = new Map(c.map((r) => [r.id, r])), o = new Map(e.map((r) => [r.id, r]));
56
- for (const [r, l] of a) {
57
- const i = o.get(r);
58
- i ? m(i, l) || s.push(i) : n.push(l);
54
+ function w(r, e) {
55
+ const t = [], s = [], i = [], a = new Map(r.map((c) => [c.id, c])), o = new Map(e.map((c) => [c.id, c]));
56
+ for (const [c, l] of a) {
57
+ const n = o.get(c);
58
+ n ? g(n, l) || s.push(n) : i.push(l);
59
59
  }
60
- for (const [r, l] of o)
61
- a.has(r) || t.push(l);
62
- return { added: t, modified: s, removed: n };
60
+ for (const [c, l] of o)
61
+ a.has(c) || t.push(l);
62
+ return { added: t, modified: s, removed: i };
63
63
  }
64
- function C(c, e) {
64
+ function P(r, e) {
65
65
  if (e.items != null)
66
66
  return e.items;
67
- const t = c || [];
67
+ const t = r || [];
68
68
  return e.changes.added.forEach((s) => {
69
- const n = t.findIndex((a) => a.id === s.id);
70
- n === -1 ? t.push(s) : t[n] = s;
69
+ const i = t.findIndex((a) => a.id === s.id);
70
+ i === -1 ? t.push(s) : t[i] = s;
71
71
  }), e.changes.modified.forEach((s) => {
72
- const n = t.findIndex((a) => a.id === s.id);
73
- n === -1 ? t.push(s) : t[n] = s;
72
+ const i = t.findIndex((a) => a.id === s.id);
73
+ i === -1 ? t.push(s) : t[i] = s;
74
74
  }), e.changes.removed.forEach((s) => {
75
- const n = t.findIndex((a) => a.id === s.id);
76
- n !== -1 && t.splice(n, 1);
75
+ const i = t.findIndex((a) => a.id === s.id);
76
+ i !== -1 && t.splice(i, 1);
77
77
  }), t;
78
78
  }
79
- async function P(c, e) {
80
- const t = new y();
79
+ async function v(r, e) {
80
+ const t = new m();
81
81
  t.batch(() => {
82
- c.forEach((n) => t.insert(n)), e.forEach((n) => {
83
- if (n.type === "remove") {
84
- t.removeOne({ id: n.data });
82
+ r.forEach((i) => t.insert(i)), e.forEach((i) => {
83
+ if (i.type === "remove") {
84
+ t.removeOne({ id: i.data });
85
85
  return;
86
86
  }
87
- const a = { id: n.data.id }, o = t.findOne(a);
88
- if (n.type === "insert") {
89
- o ? t.updateOne(a, { $set: n.data }) : t.insert(n.data);
87
+ const a = { id: i.data.id }, o = t.findOne(a);
88
+ if (i.type === "insert") {
89
+ o ? t.updateOne(a, { $set: i.data }) : t.insert(i.data);
90
90
  return;
91
91
  }
92
- o ? t.updateOne(a, n.data.modifier) : t.insert(N(a, n.data.modifier));
92
+ o ? t.updateOne(a, i.data.modifier) : t.insert(x(a, i.data.modifier));
93
93
  });
94
94
  });
95
95
  const s = t.find().fetch();
96
96
  return await t.dispose(), s;
97
97
  }
98
- function v(c) {
99
- return c.added.length > 0 || c.modified.length > 0 || c.removed.length > 0;
98
+ function O(r) {
99
+ return r.added.length > 0 || r.modified.length > 0 || r.removed.length > 0;
100
100
  }
101
- function M(c, e) {
102
- return v(g(c, e));
101
+ function I(r, e) {
102
+ return O(w(r, e));
103
103
  }
104
- async function I({ changes: c, lastSnapshot: e, data: t, pull: s, push: n, insert: a, update: o, remove: r, batch: l }) {
105
- let i = t, d = e || [], f = C(e, i);
106
- if (c.length > 0) {
107
- const p = await P(d, c);
108
- if (M(d, p)) {
109
- const O = await P(f, c), w = g(f, O);
110
- v(w) && (await n(w), i = await s(), f = C(f, i)), d = p;
104
+ async function R({ changes: r, lastSnapshot: e, data: t, pull: s, push: i, insert: a, update: o, remove: c, batch: l }) {
105
+ let n = t, d = e || [], f = P(e, n);
106
+ if (r.length > 0) {
107
+ const p = await v(d, r);
108
+ if (I(d, p)) {
109
+ const E = await v(f, r), C = w(f, E);
110
+ O(C) && (await i(C), n = await s(), f = P(f, n)), d = p;
111
111
  }
112
112
  }
113
- const h = i.changes == null ? g(d, i.items) : i.changes;
113
+ const h = n.changes == null ? w(d, n.items) : n.changes;
114
114
  return l(() => {
115
- h.added.forEach((p) => a(p)), h.modified.forEach((p) => o(p.id, { $set: p })), h.removed.forEach((p) => r(p.id));
115
+ h.added.forEach((p) => a(p)), h.modified.forEach((p) => o(p.id, { $set: p })), h.removed.forEach((p) => c(p.id));
116
116
  }), f;
117
117
  }
118
- class q {
118
+ class T {
119
119
  /**
120
120
  * @param options Collection options
121
121
  * @param options.pull Function to pull data from remote source.
@@ -138,7 +138,7 @@ class q {
138
138
  u(this, "isDisposed", !1);
139
139
  u(this, "instanceId", D());
140
140
  u(this, "id");
141
- u(this, "deboucedPush", x((e) => {
141
+ u(this, "deboucedPush", S((e) => {
142
142
  this.pushChanges(e).catch(() => {
143
143
  });
144
144
  }, 100));
@@ -146,20 +146,23 @@ class q {
146
146
  autostart: !0,
147
147
  ...e
148
148
  }, this.id = this.options.id || "default-sync-manager";
149
- const { reactivity: t } = this.options, s = this.createPersistenceAdapter("changes"), n = this.createPersistenceAdapter("snapshots"), a = this.createPersistenceAdapter("sync-operations");
150
- this.changes = new y({
149
+ const { reactivity: t } = this.options, s = this.createPersistenceAdapter("changes"), i = this.createPersistenceAdapter("snapshots"), a = this.createPersistenceAdapter("sync-operations");
150
+ this.changes = new m({
151
151
  name: `${this.options.id}-changes`,
152
152
  persistence: s == null ? void 0 : s.adapter,
153
+ indices: [y("collectionName")],
153
154
  reactivity: t
154
- }), this.snapshots = new y({
155
+ }), this.snapshots = new m({
155
156
  name: `${this.options.id}-snapshots`,
156
- persistence: n == null ? void 0 : n.adapter,
157
+ persistence: i == null ? void 0 : i.adapter,
158
+ indices: [y("collectionName")],
157
159
  reactivity: t
158
- }), this.syncOperations = new y({
160
+ }), this.syncOperations = new m({
159
161
  name: `${this.options.id}-sync-operations`,
160
162
  persistence: a == null ? void 0 : a.adapter,
163
+ indices: [y("collectionName"), y("status")],
161
164
  reactivity: t
162
- }), this.changes.on("persistence.error", (o) => s == null ? void 0 : s.handler(o)), this.snapshots.on("persistence.error", (o) => n == null ? void 0 : n.handler(o)), this.syncOperations.on("persistence.error", (o) => a == null ? void 0 : a.handler(o)), this.persistenceReady = Promise.all([
165
+ }), this.changes.on("persistence.error", (o) => s == null ? void 0 : s.handler(o)), this.snapshots.on("persistence.error", (o) => i == null ? void 0 : i.handler(o)), this.syncOperations.on("persistence.error", (o) => a == null ? void 0 : a.handler(o)), this.persistenceReady = Promise.all([
163
166
  this.syncOperations.isReady(),
164
167
  this.changes.isReady(),
165
168
  this.snapshots.isReady()
@@ -172,14 +175,14 @@ class q {
172
175
  let t = () => {
173
176
  };
174
177
  return {
175
- adapter: this.options.persistenceAdapter(`${this.id}-${e}`, (n) => {
176
- t = n;
178
+ adapter: this.options.persistenceAdapter(`${this.id}-${e}`, (i) => {
179
+ t = i;
177
180
  }),
178
- handler: (n) => t(n)
181
+ handler: (i) => t(i)
179
182
  };
180
183
  }
181
184
  getSyncQueue(e) {
182
- return this.syncQueues.get(e) == null && this.syncQueues.set(e, new S()), this.syncQueues.get(e);
185
+ return this.syncQueues.get(e) == null && this.syncQueues.set(e, new M()), this.syncQueues.get(e);
183
186
  }
184
187
  /**
185
188
  * Clears all internal data structures
@@ -232,19 +235,19 @@ class q {
232
235
  });
233
236
  const s = (a) => {
234
237
  for (const o of this.remoteChanges)
235
- if (m(o, a))
238
+ if (g(o, a))
236
239
  return !0;
237
240
  return !1;
238
- }, n = (a) => {
241
+ }, i = (a) => {
239
242
  for (let o = 0; o < this.remoteChanges.length; o += 1)
240
- if (m(this.remoteChanges[o], a)) {
243
+ if (g(this.remoteChanges[o], a)) {
241
244
  this.remoteChanges.splice(o, 1);
242
245
  return;
243
246
  }
244
247
  };
245
248
  e.on("added", (a) => {
246
249
  if (s({ collectionName: t.name, type: "insert", data: a })) {
247
- n({ collectionName: t.name, type: "insert", data: a });
250
+ i({ collectionName: t.name, type: "insert", data: a });
248
251
  return;
249
252
  }
250
253
  this.changes.insert({
@@ -254,20 +257,20 @@ class q {
254
257
  data: a
255
258
  }), !this.getCollectionProperties(t.name).syncPaused && this.schedulePush(t.name);
256
259
  }), e.on("changed", ({ id: a }, o) => {
257
- const r = { id: a, modifier: o };
258
- if (s({ collectionName: t.name, type: "update", data: r })) {
259
- n({ collectionName: t.name, type: "update", data: r });
260
+ const c = { id: a, modifier: o };
261
+ if (s({ collectionName: t.name, type: "update", data: c })) {
262
+ i({ collectionName: t.name, type: "update", data: c });
260
263
  return;
261
264
  }
262
265
  this.changes.insert({
263
266
  collectionName: t.name,
264
267
  time: Date.now(),
265
268
  type: "update",
266
- data: r
269
+ data: c
267
270
  }), !this.getCollectionProperties(t.name).syncPaused && this.schedulePush(t.name);
268
271
  }), e.on("removed", ({ id: a }) => {
269
272
  if (s({ collectionName: t.name, type: "remove", data: a })) {
270
- n({ collectionName: t.name, type: "remove", data: a });
273
+ i({ collectionName: t.name, type: "remove", data: a });
271
274
  return;
272
275
  }
273
276
  this.changes.insert({
@@ -300,8 +303,8 @@ class q {
300
303
  if (!t.syncPaused)
301
304
  return;
302
305
  this.schedulePush(e);
303
- const s = this.options.registerRemoteChange ? await this.options.registerRemoteChange(t.options, async (n) => {
304
- if (n == null)
306
+ const s = this.options.registerRemoteChange ? await this.options.registerRemoteChange(t.options, async (i) => {
307
+ if (i == null)
305
308
  await this.sync(e);
306
309
  else {
307
310
  const a = Date.now(), o = this.syncOperations.insert({
@@ -310,7 +313,7 @@ class q {
310
313
  instanceId: this.instanceId,
311
314
  status: "active"
312
315
  });
313
- await this.syncWithData(e, n).then(() => {
316
+ await this.syncWithData(e, i).then(() => {
314
317
  this.syncOperations.removeMany({
315
318
  id: { $ne: o },
316
319
  collectionName: e,
@@ -321,10 +324,10 @@ class q {
321
324
  }), this.syncOperations.updateOne({ id: o }, {
322
325
  $set: { status: "done", end: Date.now() }
323
326
  });
324
- }).catch((r) => {
325
- throw this.options.onError && this.options.onError(this.getCollectionProperties(e).options, r), this.syncOperations.updateOne({ id: o }, {
326
- $set: { status: "error", end: Date.now(), error: r.stack || r.message }
327
- }), r;
327
+ }).catch((c) => {
328
+ throw this.options.onError && this.options.onError(this.getCollectionProperties(e).options, c), this.syncOperations.updateOne({ id: o }, {
329
+ $set: { status: "error", end: Date.now(), error: c.stack || c.message }
330
+ }), c;
328
331
  });
329
332
  }
330
333
  }) : void 0;
@@ -400,8 +403,8 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
400
403
  if (this.isDisposed)
401
404
  throw new Error("SyncManager is disposed");
402
405
  await this.isReady();
403
- const { options: s, readyPromise: n } = this.getCollectionProperties(e);
404
- await n;
406
+ const { options: s, readyPromise: i } = this.getCollectionProperties(e);
407
+ await i;
405
408
  const a = this.syncOperations.find({
406
409
  collectionName: e,
407
410
  instanceId: this.instanceId,
@@ -409,12 +412,12 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
409
412
  }, {
410
413
  reactive: !1
411
414
  }).count() > 0, o = Date.now();
412
- let r = null;
413
- await new Promise((i) => {
414
- setTimeout(i, 0);
415
+ let c = null;
416
+ await new Promise((n) => {
417
+ setTimeout(n, 0);
415
418
  });
416
419
  const l = async () => {
417
- const i = this.syncOperations.findOne({
420
+ const n = this.syncOperations.findOne({
418
421
  collectionName: e,
419
422
  status: "done"
420
423
  }, {
@@ -423,38 +426,36 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
423
426
  });
424
427
  if (t != null && t.onlyWithChanges && this.changes.find({
425
428
  collectionName: e,
426
- $and: [
427
- { time: { $lte: o } }
428
- ]
429
+ time: { $lte: o }
429
430
  }, {
430
431
  sort: { time: 1 },
431
432
  reactive: !1
432
433
  }).count() === 0)
433
434
  return;
434
- a || (r = this.syncOperations.insert({
435
+ a || (c = this.syncOperations.insert({
435
436
  start: o,
436
437
  collectionName: e,
437
438
  instanceId: this.instanceId,
438
439
  status: "active"
439
440
  }));
440
441
  const d = await this.options.pull(s, {
441
- lastFinishedSyncStart: i == null ? void 0 : i.start,
442
- lastFinishedSyncEnd: i == null ? void 0 : i.end
442
+ lastFinishedSyncStart: n == null ? void 0 : n.start,
443
+ lastFinishedSyncEnd: n == null ? void 0 : n.end
443
444
  });
444
445
  await this.syncWithData(e, d);
445
446
  };
446
- await (t != null && t.force ? l() : this.getSyncQueue(e).add(l)).catch((i) => {
447
- throw r != null && (this.options.onError && this.options.onError(s, i), this.syncOperations.updateOne({ id: r }, {
448
- $set: { status: "error", end: Date.now(), error: i.stack || i.message }
449
- })), i;
450
- }), r != null && (this.syncOperations.removeMany({
451
- id: { $ne: r },
447
+ await (t != null && t.force ? l() : this.getSyncQueue(e).add(l)).catch((n) => {
448
+ throw c != null && (this.options.onError && this.options.onError(s, n), this.syncOperations.updateOne({ id: c }, {
449
+ $set: { status: "error", end: Date.now(), error: n.stack || n.message }
450
+ })), n;
451
+ }), c != null && (this.syncOperations.removeMany({
452
+ id: { $ne: c },
452
453
  collectionName: e,
453
454
  $or: [
454
455
  { end: { $lte: o } },
455
456
  { status: "active" }
456
457
  ]
457
- }), this.syncOperations.updateOne({ id: r }, {
458
+ }), this.syncOperations.updateOne({ id: c }, {
458
459
  $set: { status: "done", end: Date.now() }
459
460
  }));
460
461
  }
@@ -468,57 +469,55 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
468
469
  });
469
470
  }
470
471
  async syncWithData(e, t) {
471
- const { collection: s, options: n } = this.getCollectionProperties(e), a = Date.now(), o = this.syncOperations.findOne({
472
+ const { collection: s, options: i } = this.getCollectionProperties(e), a = Date.now(), o = this.syncOperations.findOne({
472
473
  collectionName: e,
473
474
  status: "done"
474
475
  }, {
475
476
  sort: { end: -1 },
476
477
  reactive: !1
477
- }), r = this.snapshots.findOne({
478
+ }), c = this.snapshots.findOne({
478
479
  collectionName: e
479
480
  }, {
480
481
  sort: { time: -1 },
481
482
  reactive: !1
482
483
  }), l = this.changes.find({
483
484
  collectionName: e,
484
- $and: [
485
- { time: { $lte: a } }
486
- ]
485
+ time: { $lte: a }
487
486
  }, {
488
487
  sort: { time: 1 },
489
488
  reactive: !1
490
489
  }).fetch();
491
- await I({
490
+ await R({
492
491
  changes: l,
493
- lastSnapshot: r == null ? void 0 : r.items,
492
+ lastSnapshot: c == null ? void 0 : c.items,
494
493
  data: t,
495
- pull: () => this.options.pull(n, {
494
+ pull: () => this.options.pull(i, {
496
495
  lastFinishedSyncStart: o == null ? void 0 : o.start,
497
496
  lastFinishedSyncEnd: o == null ? void 0 : o.end
498
497
  }),
499
- push: (i) => this.options.push(n, { changes: i }),
500
- insert: (i) => {
501
- if (i.id && !!s.findOne({
502
- id: i.id
498
+ push: (n) => this.options.push(i, { changes: n }),
499
+ insert: (n) => {
500
+ if (n.id && !!s.findOne({
501
+ id: n.id
503
502
  }, { reactive: !1 })) {
504
503
  this.remoteChanges.push({
505
504
  collectionName: e,
506
505
  type: "update",
507
- data: { id: i.id, modifier: { $set: i } }
508
- }), s.updateOne({ id: i.id }, { $set: i });
506
+ data: { id: n.id, modifier: { $set: n } }
507
+ }), s.updateOne({ id: n.id }, { $set: n });
509
508
  return;
510
509
  }
511
510
  this.remoteChanges.push({
512
511
  collectionName: e,
513
512
  type: "insert",
514
- data: i
515
- }), s.insert(i);
513
+ data: n
514
+ }), s.insert(n);
516
515
  },
517
- update: (i, d) => {
518
- if (i && !s.findOne({
519
- id: i
516
+ update: (n, d) => {
517
+ if (n && !s.findOne({
518
+ id: n
520
519
  }, { reactive: !1 })) {
521
- const h = { ...d.$set, id: i };
520
+ const h = { ...d.$set, id: n };
522
521
  this.remoteChanges.push({
523
522
  collectionName: e,
524
523
  type: "insert",
@@ -529,24 +528,24 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
529
528
  this.remoteChanges.push({
530
529
  collectionName: e,
531
530
  type: "update",
532
- data: { id: i, modifier: d }
533
- }), s.updateOne({ id: i }, d);
531
+ data: { id: n, modifier: d }
532
+ }), s.updateOne({ id: n }, d);
534
533
  },
535
- remove: (i) => {
534
+ remove: (n) => {
536
535
  s.findOne({
537
- id: i
536
+ id: n
538
537
  }, { reactive: !1 }) && (this.remoteChanges.push({
539
538
  collectionName: e,
540
539
  type: "remove",
541
- data: i
542
- }), s.removeOne({ id: i }));
540
+ data: n
541
+ }), s.removeOne({ id: n }));
543
542
  },
544
- batch: (i) => {
543
+ batch: (n) => {
545
544
  s.batch(() => {
546
- i();
545
+ n();
547
546
  });
548
547
  }
549
- }).then(async (i) => {
548
+ }).then(async (n) => {
550
549
  if (this.snapshots.removeMany({
551
550
  collectionName: e,
552
551
  time: { $lte: a }
@@ -556,7 +555,7 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
556
555
  }), this.snapshots.insert({
557
556
  time: a,
558
557
  collectionName: e,
559
- items: i
558
+ items: n
560
559
  }), await new Promise((h) => {
561
560
  setTimeout(h, 0);
562
561
  }), this.changes.find({
@@ -569,12 +568,12 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
569
568
  return;
570
569
  }
571
570
  const f = s.find({
572
- id: { $nin: i.map((h) => h.id) }
571
+ id: { $nin: n.map((h) => h.id) }
573
572
  }, {
574
573
  reactive: !1
575
574
  }).map((h) => h.id);
576
575
  s.batch(() => {
577
- i.forEach((h) => {
576
+ n.forEach((h) => {
578
577
  const p = !!s.findOne({
579
578
  id: h.id
580
579
  }, {
@@ -598,6 +597,6 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
598
597
  }
599
598
  }
600
599
  export {
601
- q as SyncManager
600
+ T as SyncManager
602
601
  };
603
602
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/utils/debounce.ts","../src/utils/PromiseQueue.ts","../src/computeChanges.ts","../src/getSnapshot.ts","../src/applyChanges.ts","../src/sync.ts","../src/SyncManager.ts"],"sourcesContent":["/**\n * Debounces a function.\n * @param fn Function to debounce\n * @param wait Time to wait before calling the function.\n * @param [options] Debounce options\n * @param [options.leading] Whether to call the function on the leading edge of the wait interval.\n * @param [options.trailing] Whether to call the function on the trailing edge of the wait interval.\n * @returns The debounced function.\n */\nexport default function debounce(fn, wait, options = {}) {\n let timeout;\n let result;\n const { leading = false, trailing = true } = options;\n /**\n * The debounced function that will be returned.\n * @param this The context to bind the function to.\n * @param args The arguments to pass to the function.\n * @returns The result of the debounced function.\n */\n function debounced(...args) {\n const shouldCallImmediately = leading && !timeout;\n const shouldCallTrailing = trailing && !timeout;\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n timeout = null;\n if (trailing && !shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n }, wait);\n if (shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n else if (!shouldCallTrailing) {\n result = null;\n }\n return result;\n }\n return debounced;\n}\n","/**\n * Class for queuing promises to be executed one after the other.\n * This is useful for tasks that should not be executed in parallel.\n * @example\n * const queue = new PromiseQueue();\n * queue.add(() => fetch('https://example.com/api/endpoint1'));\n * queue.add(() => fetch('https://example.com/api/endpoint2'));\n * // The second fetch will only be executed after the first one is done.\n */\nexport default class PromiseQueue {\n queue = [];\n pendingPromise = false;\n /**\n * Method to add a new promise to the queue and returns a promise that resolves when this task is done\n * @param task Function that returns a promise that will be added to the queue\n * @returns Promise that resolves when the task is done\n */\n add(task) {\n return new Promise((resolve, reject) => {\n // Wrap the task with the resolve and reject to control its completion from the outside\n this.queue.push(() => task()\n .then(resolve)\n .catch((error) => {\n reject(error);\n throw error;\n }));\n this.dequeue();\n });\n }\n /**\n * Method to check if there is a pending promise in the queue\n * @returns True if there is a pending promise, false otherwise\n */\n hasPendingPromise() {\n return this.pendingPromise;\n }\n /**\n * Method to process the queue\n */\n dequeue() {\n if (this.pendingPromise || this.queue.length === 0) {\n return;\n }\n const task = this.queue.shift();\n if (!task)\n return;\n this.pendingPromise = true;\n task()\n .then(() => {\n this.pendingPromise = false;\n this.dequeue();\n })\n .catch(() => {\n this.pendingPromise = false;\n this.dequeue();\n });\n }\n}\n","import { isEqual } from '@signaldb/core';\n/**\n * Compute changes between two arrays of items.\n * @param oldItems Array of the old items\n * @param newItems Array of the new items\n * @returns The changeset\n */\nexport default function computeChanges(oldItems, newItems) {\n const added = [];\n const modified = [];\n const removed = [];\n const oldItemsMap = new Map(oldItems.map(item => [item.id, item]));\n const newItemsMap = new Map(newItems.map(item => [item.id, item]));\n for (const [id, oldItem] of oldItemsMap) {\n const newItem = newItemsMap.get(id);\n if (!newItem) {\n removed.push(oldItem);\n }\n else if (!isEqual(newItem, oldItem)) {\n modified.push(newItem);\n }\n }\n for (const [id, newItem] of newItemsMap) {\n if (!oldItemsMap.has(id)) {\n added.push(newItem);\n }\n }\n return { added, modified, removed };\n}\n","/**\n * Gets the snapshot of items from the last snapshot and the changes.\n * @param lastSnapshot The last snapshot of items\n * @param data The changes to apply to the last snapshot\n * @returns The new snapshot of items\n */\nexport default function getSnapshot(lastSnapshot, data) {\n if (data.items != null)\n return data.items;\n const items = lastSnapshot || [];\n data.changes.added.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.modified.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.removed.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index !== -1)\n items.splice(index, 1);\n });\n return items;\n}\n","import { Collection, modify } from '@signaldb/core';\n/**\n * applies changes to a collection of items\n * @param items The items to apply the changes to\n * @param changes The changes to apply to the items\n * @returns The new items after applying the changes\n */\nexport default async function applyChanges(items, changes) {\n const collection = new Collection();\n collection.batch(() => {\n items.forEach(item => collection.insert(item));\n changes.forEach((change) => {\n if (change.type === 'remove') {\n collection.removeOne({ id: change.data });\n return;\n }\n const selector = { id: change.data.id };\n const itemExists = collection.findOne(selector);\n if (change.type === 'insert') {\n if (itemExists) { // update item if it alread exists\n collection.updateOne(selector, { $set: change.data });\n }\n else { // insert item if it does not exist\n collection.insert(change.data);\n }\n return;\n }\n // change.type === 'update'\n if (itemExists) { // update item if it exists\n collection.updateOne(selector, change.data.modifier);\n }\n else { // insert item if it does not exist\n collection.insert(modify(selector, change.data.modifier));\n }\n });\n });\n const result = collection.find().fetch();\n await collection.dispose();\n return result;\n}\n","import computeChanges from './computeChanges';\nimport getSnapshot from './getSnapshot';\nimport applyChanges from './applyChanges';\n/**\n * Checks if there are any changes in the given changeset.\n * @param changes The changeset to check.\n * @returns True if there are changes, false otherwise.\n */\nfunction hasChanges(changes) {\n return changes.added.length > 0\n || changes.modified.length > 0\n || changes.removed.length > 0;\n}\n/**\n * Checks if there is a difference between the old items and the new items.\n * @param oldItems The old items.\n * @param newItems The new items.\n * @returns True if there is a difference, false otherwise.\n */\nfunction hasDifference(oldItems, newItems) {\n return hasChanges(computeChanges(oldItems, newItems));\n}\n/**\n * Does a sync operation based on the provided options. If changes are supplied, these will be rebased on the new data.\n * Afterwards the push method will be called with the remaining changes. A new snapshot will be created and returned.\n * @param options Sync options\n * @param options.changes Changes to call the push method with\n * @param [options.lastSnapshot] The last snapshot\n * @param options.data The new data\n * @param options.pull Method to pull new data\n * @param options.push Method to push changes\n * @param options.insert Method to insert an item\n * @param options.update Method to update an item\n * @param options.remove Method to remove an item\n * @param options.batch Method to batch multiple operations\n * @returns The new snapshot\n */\nexport default async function sync({ changes, lastSnapshot, data, pull, push, insert, update, remove, batch, }) {\n let newData = data;\n let previousSnapshot = lastSnapshot || [];\n let newSnapshot = getSnapshot(lastSnapshot, newData);\n if (changes.length > 0) {\n // apply changes on last snapshot and check if there is a difference\n const lastSnapshotWithChanges = await applyChanges(previousSnapshot, changes);\n if (hasDifference(previousSnapshot, lastSnapshotWithChanges)) {\n // if yes, apply the changes on the newSnapshot and check if there is a difference\n const newSnapshotWithChanges = await applyChanges(newSnapshot, changes);\n const changesToPush = computeChanges(newSnapshot, newSnapshotWithChanges);\n if (hasChanges(changesToPush)) {\n // if yes, push the changes to the server\n await push(changesToPush);\n // pull new data afterwards to ensure that all server changes are applied\n newData = await pull();\n newSnapshot = getSnapshot(newSnapshot, newData);\n }\n previousSnapshot = lastSnapshotWithChanges;\n }\n }\n // apply the new changes on the collection\n const newChanges = newData.changes == null\n ? computeChanges(previousSnapshot, newData.items)\n : newData.changes;\n batch(() => {\n newChanges.added.forEach(item => insert(item));\n newChanges.modified.forEach(item => update(item.id, { $set: item }));\n newChanges.removed.forEach(item => remove(item.id));\n });\n return newSnapshot;\n}\n","import { Collection, randomId, isEqual } from '@signaldb/core';\nimport debounce from './utils/debounce';\nimport PromiseQueue from './utils/PromiseQueue';\nimport sync from './sync';\n/**\n * Class to manage syncing of collections.\n * @template CollectionOptions\n * @template ItemType\n * @template IdType\n * @example\n * const syncManager = new SyncManager({\n * pull: async (collectionOptions) => {\n * const response = await fetch(`/api/collections/${collectionOptions.name}`)\n * return await response.json()\n * },\n * push: async (collectionOptions, { changes }) => {\n * await fetch(`/api/collections/${collectionOptions.name}`, {\n * method: 'POST',\n * body: JSON.stringify(changes),\n * })\n * },\n * })\n *\n * const collection = new Collection()\n * syncManager.addCollection(collection, {\n * name: 'todos',\n * })\n *\n * syncManager.sync('todos')\n */\nexport default class SyncManager {\n options;\n collections = new Map();\n changes;\n snapshots;\n syncOperations;\n remoteChanges = [];\n syncQueues = new Map();\n persistenceReady;\n isDisposed = false;\n instanceId = randomId();\n id;\n /**\n * @param options Collection options\n * @param options.pull Function to pull data from remote source.\n * @param options.push Function to push data to remote source.\n * @param [options.registerRemoteChange] Function to register a callback for remote changes.\n * @param [options.id] Unique identifier for this sync manager. Only nessesary if you have multiple sync managers.\n * @param [options.persistenceAdapter] Persistence adapter to use for storing changes, snapshots and sync operations.\n * @param [options.reactivity] Reactivity adapter to use for reactivity.\n * @param [options.onError] Function to handle errors that occur async during syncing.\n */\n constructor(options) {\n this.options = {\n autostart: true,\n ...options,\n };\n this.id = this.options.id || 'default-sync-manager';\n const { reactivity } = this.options;\n const changesPersistence = this.createPersistenceAdapter('changes');\n const snapshotsPersistence = this.createPersistenceAdapter('snapshots');\n const syncOperationsPersistence = this.createPersistenceAdapter('sync-operations');\n this.changes = new Collection({\n name: `${this.options.id}-changes`,\n persistence: changesPersistence?.adapter,\n reactivity,\n });\n this.snapshots = new Collection({\n name: `${this.options.id}-snapshots`,\n persistence: snapshotsPersistence?.adapter,\n reactivity,\n });\n this.syncOperations = new Collection({\n name: `${this.options.id}-sync-operations`,\n persistence: syncOperationsPersistence?.adapter,\n reactivity,\n });\n this.changes.on('persistence.error', error => changesPersistence?.handler(error));\n this.snapshots.on('persistence.error', error => snapshotsPersistence?.handler(error));\n this.syncOperations.on('persistence.error', error => syncOperationsPersistence?.handler(error));\n this.persistenceReady = Promise.all([\n this.syncOperations.isReady(),\n this.changes.isReady(),\n this.snapshots.isReady(),\n ]).then(() => { });\n this.changes.setMaxListeners(1000);\n this.snapshots.setMaxListeners(1000);\n this.syncOperations.setMaxListeners(1000);\n }\n createPersistenceAdapter(name) {\n if (this.options.persistenceAdapter == null)\n return;\n let errorHandler = () => { };\n const adapter = this.options.persistenceAdapter(`${this.id}-${name}`, (handler) => {\n errorHandler = handler;\n });\n return {\n adapter,\n handler: (error) => errorHandler(error),\n };\n }\n getSyncQueue(name) {\n if (this.syncQueues.get(name) == null) {\n this.syncQueues.set(name, new PromiseQueue());\n }\n return this.syncQueues.get(name);\n }\n /**\n * Clears all internal data structures\n */\n async dispose() {\n this.collections.clear();\n this.syncQueues.clear();\n this.remoteChanges.splice(0, this.remoteChanges.length);\n await Promise.all([\n this.changes.dispose(),\n this.snapshots.dispose(),\n this.syncOperations.dispose(),\n ]);\n this.isDisposed = true;\n }\n /**\n * Gets a collection with it's options by name\n * @deprecated Use getCollectionProperties instead.\n * @param name Name of the collection\n * @throws Will throw an error if the name wasn't found\n * @returns Tuple of collection and options\n */\n getCollection(name) {\n const { collection, options } = this.getCollectionProperties(name);\n return [collection, options];\n }\n /**\n * Gets collection options by name\n * @param name Name of the collection\n * @throws Will throw an error if the name wasn't found\n * @returns An object of all properties of the collection\n */\n getCollectionProperties(name) {\n const collectionParameters = this.collections.get(name);\n if (collectionParameters == null)\n throw new Error(`Collection with id '${name}' not found`);\n return collectionParameters;\n }\n /**\n * Adds a collection to the sync manager.\n * @param collection Collection to add\n * @param options Options for the collection. The object needs at least a `name` property.\n * @param options.name Unique name of the collection\n */\n addCollection(collection, options) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n this.collections.set(options.name, {\n collection,\n options,\n readyPromise: collection.isReady(),\n syncPaused: true, // always start paused as the autostart will start it\n });\n const hasRemoteChange = (change) => {\n for (const remoteChange of this.remoteChanges) {\n if (isEqual(remoteChange, change)) {\n return true;\n }\n }\n return false;\n };\n const removeRemoteChange = (change) => {\n for (let i = 0; i < this.remoteChanges.length; i += 1) {\n if (isEqual(this.remoteChanges[i], change)) {\n this.remoteChanges.splice(i, 1);\n return;\n }\n }\n };\n collection.on('added', (item) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'insert', data: item })) {\n removeRemoteChange({ collectionName: options.name, type: 'insert', data: item });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'insert',\n data: item,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n collection.on('changed', ({ id }, modifier) => {\n const data = { id, modifier };\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'update', data })) {\n removeRemoteChange({ collectionName: options.name, type: 'update', data });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'update',\n data,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n collection.on('removed', ({ id }) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'remove', data: id })) {\n removeRemoteChange({ collectionName: options.name, type: 'remove', data: id });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'remove',\n data: id,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n if (this.options.autostart) {\n this.startSync(options.name)\n .catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n }\n }\n deboucedPush = debounce((name) => {\n this.pushChanges(name).catch(() => { });\n }, 100);\n schedulePush(name) {\n this.deboucedPush(name);\n }\n /**\n * Setup all collections to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n */\n async startAll() {\n await Promise.all([...this.collections.keys()].map(id => this.startSync(id)));\n }\n /**\n * Setup a collection to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n * @param name Name of the collection\n */\n async startSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (!collectionParameters.syncPaused)\n return; // already started\n this.schedulePush(name); // push changes that were made while paused\n const cleanupFunction = this.options.registerRemoteChange\n ? await this.options.registerRemoteChange(collectionParameters.options, async (data) => {\n if (data == null) {\n await this.sync(name);\n }\n else {\n const syncTime = Date.now();\n const syncId = this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n await this.syncWithData(name, data)\n .then(() => {\n // clean up old sync operations\n this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n })\n .catch((error) => {\n if (this.options.onError) {\n this.options.onError(this.getCollectionProperties(name).options, error);\n }\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n throw error;\n });\n }\n })\n : undefined;\n this.collections.set(name, {\n ...collectionParameters,\n syncPaused: false,\n cleanupFunction,\n });\n }\n /**\n * Pauses the sync process for all collections.\n * This means that the collections will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n */\n async pauseAll() {\n await Promise.all([...this.collections.keys()].map(id => this.pauseSync(id)));\n }\n /**\n * Pauses the sync process for a collection.\n * This means that the collection will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n * @param name Name of the collection\n */\n async pauseSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (collectionParameters.syncPaused)\n return; // already paused\n if (collectionParameters.cleanupFunction)\n await collectionParameters.cleanupFunction();\n this.collections.set(name, {\n ...collectionParameters,\n cleanupFunction: undefined,\n syncPaused: true,\n });\n }\n /**\n * Starts the sync process for all collections\n */\n async syncAll() {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n const errors = [];\n await Promise.all([...this.collections.keys()].map(id => this.sync(id).catch((error) => {\n errors.push({ id, error });\n })));\n if (errors.length > 0)\n throw new Error(`Error while syncing collections:\\n${errors.map(error => `${error.id}: ${error.error.message}`).join('\\n\\n')}`);\n }\n /**\n * Checks if a collection is currently beeing synced\n * @param [name] Name of the collection. If not provided, it will check if any collection is currently beeing synced.\n * @returns True if the collection is currently beeing synced, false otherwise.\n */\n isSyncing(name) {\n return this.syncOperations.findOne({\n ...name ? { collectionName: name } : {},\n status: 'active',\n }, { fields: { status: 1 } }) != null;\n }\n /**\n * Checks if the sync manager is ready to sync.\n * @returns A promise that resolves when the sync manager is ready to sync.\n */\n async isReady() {\n await this.persistenceReady;\n }\n /**\n * Starts the sync process for a collection\n * @param name Name of the collection\n * @param options Options for the sync process.\n * @param options.force If true, the sync process will be started even if there are no changes and onlyWithChanges is true.\n * @param options.onlyWithChanges If true, the sync process will only be started if there are changes.\n */\n async sync(name, options = {}) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n await this.isReady();\n const { options: collectionOptions, readyPromise } = this.getCollectionProperties(name);\n await readyPromise;\n const hasActiveSyncs = this.syncOperations.find({\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n }, {\n reactive: false,\n }).count() > 0;\n const syncTime = Date.now();\n let syncId = null;\n // schedule for next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const doSync = async () => {\n const lastFinishedSync = this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n });\n if (options?.onlyWithChanges) {\n const currentChanges = this.changes.find({\n collectionName: name,\n $and: [\n { time: { $lte: syncTime } },\n ],\n }, {\n sort: { time: 1 },\n reactive: false,\n }).count();\n if (currentChanges === 0)\n return;\n }\n if (!hasActiveSyncs) {\n syncId = this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n }\n const data = await this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n });\n await this.syncWithData(name, data);\n };\n await (options?.force ? doSync() : this.getSyncQueue(name).add(doSync))\n .catch((error) => {\n if (syncId != null) {\n if (this.options.onError)\n this.options.onError(collectionOptions, error);\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n }\n throw error;\n });\n if (syncId != null) {\n // clean up old sync operations\n this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n }\n }\n /**\n * Starts the push process for a collection (sync process but only if there are changes)\n * @param name Name of the collection\n */\n async pushChanges(name) {\n await this.sync(name, {\n onlyWithChanges: true,\n });\n }\n async syncWithData(name, data) {\n const { collection, options: collectionOptions } = this.getCollectionProperties(name);\n const syncTime = Date.now();\n const lastFinishedSync = this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n });\n const lastSnapshot = this.snapshots.findOne({\n collectionName: name,\n }, {\n sort: { time: -1 },\n reactive: false,\n });\n const currentChanges = this.changes.find({\n collectionName: name,\n $and: [\n { time: { $lte: syncTime } },\n ],\n }, {\n sort: { time: 1 },\n reactive: false,\n }).fetch();\n await sync({\n changes: currentChanges,\n lastSnapshot: lastSnapshot?.items,\n data,\n pull: () => this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n }),\n push: changes => this.options.push(collectionOptions, { changes }),\n insert: (item) => {\n const itemExists = item.id && !!collection.findOne({\n id: item.id,\n }, { reactive: false });\n if (itemExists) {\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // update the item if it already exists\n collection.updateOne({ id: item.id }, { $set: item });\n return;\n }\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n collection.insert(item);\n },\n update: (itemId, modifier) => {\n const itemExists = itemId && !collection.findOne({\n id: itemId,\n }, { reactive: false });\n if (itemExists) {\n const item = { ...modifier.$set, id: itemId };\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n // insert the item if it does not exist\n collection.insert(item);\n return;\n }\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: itemId, modifier },\n });\n collection.updateOne({ id: itemId }, modifier);\n },\n remove: (itemId) => {\n const itemExists = !!collection.findOne({\n id: itemId,\n }, { reactive: false });\n if (!itemExists)\n return;\n this.remoteChanges.push({\n collectionName: name,\n type: 'remove',\n data: itemId,\n });\n collection.removeOne({ id: itemId });\n },\n batch: (fn) => {\n collection.batch(() => {\n fn();\n });\n },\n })\n .then(async (snapshot) => {\n // clean up old snapshots\n this.snapshots.removeMany({\n collectionName: name,\n time: { $lte: syncTime },\n });\n // clean up processed changes\n this.changes.removeMany({\n collectionName: name,\n id: { $in: currentChanges.map(c => c.id) },\n });\n // insert new snapshot\n this.snapshots.insert({\n time: syncTime,\n collectionName: name,\n items: snapshot,\n });\n // delay sync operation update to next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const hasChanges = this.changes.find({\n collectionName: name,\n }, { reactive: false }).count() > 0;\n if (hasChanges) {\n // check if there are unsynced changes to push\n // and sync again if there are any\n await this.sync(name, {\n force: true,\n onlyWithChanges: true,\n });\n return;\n }\n // if there are no unsynced changes apply the last snapshot\n // to make sure that collection and snapshot are in sync\n // find all items that are not in the snapshot\n const nonExistingItemIds = collection.find({\n id: { $nin: snapshot.map(item => item.id) },\n }, {\n reactive: false,\n }).map(item => item.id);\n collection.batch(() => {\n // update all items that are in the snapshot\n snapshot.forEach((item) => {\n const itemExists = !!collection.findOne({\n id: item.id,\n }, {\n reactive: false,\n });\n /* istanbul ignore else -- @preserve */\n if (itemExists) {\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n collection.updateOne({ id: item.id }, { $set: item });\n }\n else { // this case should never happen\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n collection.insert(item);\n }\n });\n // remove all items that are not in the snapshot\n nonExistingItemIds.forEach((id) => {\n collection.removeOne({ id });\n });\n });\n });\n }\n}\n"],"names":["debounce","fn","wait","options","timeout","result","leading","trailing","debounced","args","shouldCallImmediately","shouldCallTrailing","PromiseQueue","__publicField","task","resolve","reject","error","computeChanges","oldItems","newItems","added","modified","removed","oldItemsMap","item","newItemsMap","id","oldItem","newItem","isEqual","getSnapshot","lastSnapshot","data","items","index","i","applyChanges","changes","collection","Collection","change","selector","itemExists","modify","hasChanges","hasDifference","sync","pull","push","insert","update","remove","batch","newData","previousSnapshot","newSnapshot","lastSnapshotWithChanges","newSnapshotWithChanges","changesToPush","newChanges","SyncManager","randomId","name","reactivity","changesPersistence","snapshotsPersistence","syncOperationsPersistence","errorHandler","handler","collectionParameters","hasRemoteChange","remoteChange","removeRemoteChange","modifier","cleanupFunction","syncTime","syncId","errors","collectionOptions","readyPromise","hasActiveSyncs","doSync","lastFinishedSync","currentChanges","itemId","snapshot","c","nonExistingItemIds"],"mappings":";;;;AASA,SAAwBA,EAASC,GAAIC,GAAMC,IAAU,CAAA,GAAI;AACjD,MAAAC,GACAC;AACJ,QAAM,EAAE,SAAAC,IAAU,IAAO,UAAAC,IAAW,GAAS,IAAAJ;AAO7C,WAASK,KAAaC,GAAM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IkB,KACA,KAAK,cAAc,KAAK;AAAA,YACpB,gBAAgBoB;AAAA,YAChB,MAAM;AAAA,YACN,MAAM,EAAE,IAAItC,EAAK,IAAI,UAAU,EAAE,MAAMA,EAAO,EAAA;AAAA,UAAA,CACjD,GACUc,EAAA,UAAU,EAAE,IAAId,EAAK,MAAM,EAAE,MAAMA,GAAM,MAGpD,KAAK,cAAc,KAAK;AAAA,YACpB,gBAAgBsC;AAAA,YAChB,MAAM;AAAA,YACN,MAAMtC;AAAA,UAAA,CACT,GACDc,EAAW,OAAOd,CAAI;AAAA,QAC1B,CACH,GAEkB+D,EAAA,QAAQ,CAAC7D,MAAO;AACpB,UAAAY,EAAA,UAAU,EAAE,IAAAZ,GAAI;AAAA,QAAA,CAC9B;AAAA,MAAA,CACJ;AAAA,IAAA,CACJ;AAAA,EAAA;AAET;"}
1
+ {"version":3,"file":"index.mjs","sources":["../src/utils/debounce.ts","../src/utils/PromiseQueue.ts","../src/computeChanges.ts","../src/getSnapshot.ts","../src/applyChanges.ts","../src/sync.ts","../src/SyncManager.ts"],"sourcesContent":["/**\n * Debounces a function.\n * @param fn Function to debounce\n * @param wait Time to wait before calling the function.\n * @param [options] Debounce options\n * @param [options.leading] Whether to call the function on the leading edge of the wait interval.\n * @param [options.trailing] Whether to call the function on the trailing edge of the wait interval.\n * @returns The debounced function.\n */\nexport default function debounce(fn, wait, options = {}) {\n let timeout;\n let result;\n const { leading = false, trailing = true } = options;\n /**\n * The debounced function that will be returned.\n * @param this The context to bind the function to.\n * @param args The arguments to pass to the function.\n * @returns The result of the debounced function.\n */\n function debounced(...args) {\n const shouldCallImmediately = leading && !timeout;\n const shouldCallTrailing = trailing && !timeout;\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n timeout = null;\n if (trailing && !shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n }, wait);\n if (shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n else if (!shouldCallTrailing) {\n result = null;\n }\n return result;\n }\n return debounced;\n}\n","/**\n * Class for queuing promises to be executed one after the other.\n * This is useful for tasks that should not be executed in parallel.\n * @example\n * const queue = new PromiseQueue();\n * queue.add(() => fetch('https://example.com/api/endpoint1'));\n * queue.add(() => fetch('https://example.com/api/endpoint2'));\n * // The second fetch will only be executed after the first one is done.\n */\nexport default class PromiseQueue {\n queue = [];\n pendingPromise = false;\n /**\n * Method to add a new promise to the queue and returns a promise that resolves when this task is done\n * @param task Function that returns a promise that will be added to the queue\n * @returns Promise that resolves when the task is done\n */\n add(task) {\n return new Promise((resolve, reject) => {\n // Wrap the task with the resolve and reject to control its completion from the outside\n this.queue.push(() => task()\n .then(resolve)\n .catch((error) => {\n reject(error);\n throw error;\n }));\n this.dequeue();\n });\n }\n /**\n * Method to check if there is a pending promise in the queue\n * @returns True if there is a pending promise, false otherwise\n */\n hasPendingPromise() {\n return this.pendingPromise;\n }\n /**\n * Method to process the queue\n */\n dequeue() {\n if (this.pendingPromise || this.queue.length === 0) {\n return;\n }\n const task = this.queue.shift();\n if (!task)\n return;\n this.pendingPromise = true;\n task()\n .then(() => {\n this.pendingPromise = false;\n this.dequeue();\n })\n .catch(() => {\n this.pendingPromise = false;\n this.dequeue();\n });\n }\n}\n","import { isEqual } from '@signaldb/core';\n/**\n * Compute changes between two arrays of items.\n * @param oldItems Array of the old items\n * @param newItems Array of the new items\n * @returns The changeset\n */\nexport default function computeChanges(oldItems, newItems) {\n const added = [];\n const modified = [];\n const removed = [];\n const oldItemsMap = new Map(oldItems.map(item => [item.id, item]));\n const newItemsMap = new Map(newItems.map(item => [item.id, item]));\n for (const [id, oldItem] of oldItemsMap) {\n const newItem = newItemsMap.get(id);\n if (!newItem) {\n removed.push(oldItem);\n }\n else if (!isEqual(newItem, oldItem)) {\n modified.push(newItem);\n }\n }\n for (const [id, newItem] of newItemsMap) {\n if (!oldItemsMap.has(id)) {\n added.push(newItem);\n }\n }\n return { added, modified, removed };\n}\n","/**\n * Gets the snapshot of items from the last snapshot and the changes.\n * @param lastSnapshot The last snapshot of items\n * @param data The changes to apply to the last snapshot\n * @returns The new snapshot of items\n */\nexport default function getSnapshot(lastSnapshot, data) {\n if (data.items != null)\n return data.items;\n const items = lastSnapshot || [];\n data.changes.added.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.modified.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.removed.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index !== -1)\n items.splice(index, 1);\n });\n return items;\n}\n","import { Collection, modify } from '@signaldb/core';\n/**\n * applies changes to a collection of items\n * @param items The items to apply the changes to\n * @param changes The changes to apply to the items\n * @returns The new items after applying the changes\n */\nexport default async function applyChanges(items, changes) {\n const collection = new Collection();\n collection.batch(() => {\n items.forEach(item => collection.insert(item));\n changes.forEach((change) => {\n if (change.type === 'remove') {\n collection.removeOne({ id: change.data });\n return;\n }\n const selector = { id: change.data.id };\n const itemExists = collection.findOne(selector);\n if (change.type === 'insert') {\n if (itemExists) { // update item if it alread exists\n collection.updateOne(selector, { $set: change.data });\n }\n else { // insert item if it does not exist\n collection.insert(change.data);\n }\n return;\n }\n // change.type === 'update'\n if (itemExists) { // update item if it exists\n collection.updateOne(selector, change.data.modifier);\n }\n else { // insert item if it does not exist\n collection.insert(modify(selector, change.data.modifier));\n }\n });\n });\n const result = collection.find().fetch();\n await collection.dispose();\n return result;\n}\n","import computeChanges from './computeChanges';\nimport getSnapshot from './getSnapshot';\nimport applyChanges from './applyChanges';\n/**\n * Checks if there are any changes in the given changeset.\n * @param changes The changeset to check.\n * @returns True if there are changes, false otherwise.\n */\nfunction hasChanges(changes) {\n return changes.added.length > 0\n || changes.modified.length > 0\n || changes.removed.length > 0;\n}\n/**\n * Checks if there is a difference between the old items and the new items.\n * @param oldItems The old items.\n * @param newItems The new items.\n * @returns True if there is a difference, false otherwise.\n */\nfunction hasDifference(oldItems, newItems) {\n return hasChanges(computeChanges(oldItems, newItems));\n}\n/**\n * Does a sync operation based on the provided options. If changes are supplied, these will be rebased on the new data.\n * Afterwards the push method will be called with the remaining changes. A new snapshot will be created and returned.\n * @param options Sync options\n * @param options.changes Changes to call the push method with\n * @param [options.lastSnapshot] The last snapshot\n * @param options.data The new data\n * @param options.pull Method to pull new data\n * @param options.push Method to push changes\n * @param options.insert Method to insert an item\n * @param options.update Method to update an item\n * @param options.remove Method to remove an item\n * @param options.batch Method to batch multiple operations\n * @returns The new snapshot\n */\nexport default async function sync({ changes, lastSnapshot, data, pull, push, insert, update, remove, batch, }) {\n let newData = data;\n let previousSnapshot = lastSnapshot || [];\n let newSnapshot = getSnapshot(lastSnapshot, newData);\n if (changes.length > 0) {\n // apply changes on last snapshot and check if there is a difference\n const lastSnapshotWithChanges = await applyChanges(previousSnapshot, changes);\n if (hasDifference(previousSnapshot, lastSnapshotWithChanges)) {\n // if yes, apply the changes on the newSnapshot and check if there is a difference\n const newSnapshotWithChanges = await applyChanges(newSnapshot, changes);\n const changesToPush = computeChanges(newSnapshot, newSnapshotWithChanges);\n if (hasChanges(changesToPush)) {\n // if yes, push the changes to the server\n await push(changesToPush);\n // pull new data afterwards to ensure that all server changes are applied\n newData = await pull();\n newSnapshot = getSnapshot(newSnapshot, newData);\n }\n previousSnapshot = lastSnapshotWithChanges;\n }\n }\n // apply the new changes on the collection\n const newChanges = newData.changes == null\n ? computeChanges(previousSnapshot, newData.items)\n : newData.changes;\n batch(() => {\n newChanges.added.forEach(item => insert(item));\n newChanges.modified.forEach(item => update(item.id, { $set: item }));\n newChanges.removed.forEach(item => remove(item.id));\n });\n return newSnapshot;\n}\n","import { Collection, randomId, isEqual, createIndex } from '@signaldb/core';\nimport debounce from './utils/debounce';\nimport PromiseQueue from './utils/PromiseQueue';\nimport sync from './sync';\n/**\n * Class to manage syncing of collections.\n * @template CollectionOptions\n * @template ItemType\n * @template IdType\n * @example\n * const syncManager = new SyncManager({\n * pull: async (collectionOptions) => {\n * const response = await fetch(`/api/collections/${collectionOptions.name}`)\n * return await response.json()\n * },\n * push: async (collectionOptions, { changes }) => {\n * await fetch(`/api/collections/${collectionOptions.name}`, {\n * method: 'POST',\n * body: JSON.stringify(changes),\n * })\n * },\n * })\n *\n * const collection = new Collection()\n * syncManager.addCollection(collection, {\n * name: 'todos',\n * })\n *\n * syncManager.sync('todos')\n */\nexport default class SyncManager {\n options;\n collections = new Map();\n changes;\n snapshots;\n syncOperations;\n remoteChanges = [];\n syncQueues = new Map();\n persistenceReady;\n isDisposed = false;\n instanceId = randomId();\n id;\n /**\n * @param options Collection options\n * @param options.pull Function to pull data from remote source.\n * @param options.push Function to push data to remote source.\n * @param [options.registerRemoteChange] Function to register a callback for remote changes.\n * @param [options.id] Unique identifier for this sync manager. Only nessesary if you have multiple sync managers.\n * @param [options.persistenceAdapter] Persistence adapter to use for storing changes, snapshots and sync operations.\n * @param [options.reactivity] Reactivity adapter to use for reactivity.\n * @param [options.onError] Function to handle errors that occur async during syncing.\n */\n constructor(options) {\n this.options = {\n autostart: true,\n ...options,\n };\n this.id = this.options.id || 'default-sync-manager';\n const { reactivity } = this.options;\n const changesPersistence = this.createPersistenceAdapter('changes');\n const snapshotsPersistence = this.createPersistenceAdapter('snapshots');\n const syncOperationsPersistence = this.createPersistenceAdapter('sync-operations');\n this.changes = new Collection({\n name: `${this.options.id}-changes`,\n persistence: changesPersistence?.adapter,\n indices: [createIndex('collectionName')],\n reactivity,\n });\n this.snapshots = new Collection({\n name: `${this.options.id}-snapshots`,\n persistence: snapshotsPersistence?.adapter,\n indices: [createIndex('collectionName')],\n reactivity,\n });\n this.syncOperations = new Collection({\n name: `${this.options.id}-sync-operations`,\n persistence: syncOperationsPersistence?.adapter,\n indices: [createIndex('collectionName'), createIndex('status')],\n reactivity,\n });\n this.changes.on('persistence.error', error => changesPersistence?.handler(error));\n this.snapshots.on('persistence.error', error => snapshotsPersistence?.handler(error));\n this.syncOperations.on('persistence.error', error => syncOperationsPersistence?.handler(error));\n this.persistenceReady = Promise.all([\n this.syncOperations.isReady(),\n this.changes.isReady(),\n this.snapshots.isReady(),\n ]).then(() => { });\n this.changes.setMaxListeners(1000);\n this.snapshots.setMaxListeners(1000);\n this.syncOperations.setMaxListeners(1000);\n }\n createPersistenceAdapter(name) {\n if (this.options.persistenceAdapter == null)\n return;\n let errorHandler = () => { };\n const adapter = this.options.persistenceAdapter(`${this.id}-${name}`, (handler) => {\n errorHandler = handler;\n });\n return {\n adapter,\n handler: (error) => errorHandler(error),\n };\n }\n getSyncQueue(name) {\n if (this.syncQueues.get(name) == null) {\n this.syncQueues.set(name, new PromiseQueue());\n }\n return this.syncQueues.get(name);\n }\n /**\n * Clears all internal data structures\n */\n async dispose() {\n this.collections.clear();\n this.syncQueues.clear();\n this.remoteChanges.splice(0, this.remoteChanges.length);\n await Promise.all([\n this.changes.dispose(),\n this.snapshots.dispose(),\n this.syncOperations.dispose(),\n ]);\n this.isDisposed = true;\n }\n /**\n * Gets a collection with it's options by name\n * @deprecated Use getCollectionProperties instead.\n * @param name Name of the collection\n * @throws Will throw an error if the name wasn't found\n * @returns Tuple of collection and options\n */\n getCollection(name) {\n const { collection, options } = this.getCollectionProperties(name);\n return [collection, options];\n }\n /**\n * Gets collection options by name\n * @param name Name of the collection\n * @throws Will throw an error if the name wasn't found\n * @returns An object of all properties of the collection\n */\n getCollectionProperties(name) {\n const collectionParameters = this.collections.get(name);\n if (collectionParameters == null)\n throw new Error(`Collection with id '${name}' not found`);\n return collectionParameters;\n }\n /**\n * Adds a collection to the sync manager.\n * @param collection Collection to add\n * @param options Options for the collection. The object needs at least a `name` property.\n * @param options.name Unique name of the collection\n */\n addCollection(collection, options) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n this.collections.set(options.name, {\n collection,\n options,\n readyPromise: collection.isReady(),\n syncPaused: true, // always start paused as the autostart will start it\n });\n const hasRemoteChange = (change) => {\n for (const remoteChange of this.remoteChanges) {\n if (isEqual(remoteChange, change)) {\n return true;\n }\n }\n return false;\n };\n const removeRemoteChange = (change) => {\n for (let i = 0; i < this.remoteChanges.length; i += 1) {\n if (isEqual(this.remoteChanges[i], change)) {\n this.remoteChanges.splice(i, 1);\n return;\n }\n }\n };\n collection.on('added', (item) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'insert', data: item })) {\n removeRemoteChange({ collectionName: options.name, type: 'insert', data: item });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'insert',\n data: item,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n collection.on('changed', ({ id }, modifier) => {\n const data = { id, modifier };\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'update', data })) {\n removeRemoteChange({ collectionName: options.name, type: 'update', data });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'update',\n data,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n collection.on('removed', ({ id }) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'remove', data: id })) {\n removeRemoteChange({ collectionName: options.name, type: 'remove', data: id });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'remove',\n data: id,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n if (this.options.autostart) {\n this.startSync(options.name)\n .catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n }\n }\n deboucedPush = debounce((name) => {\n this.pushChanges(name).catch(() => { });\n }, 100);\n schedulePush(name) {\n this.deboucedPush(name);\n }\n /**\n * Setup all collections to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n */\n async startAll() {\n await Promise.all([...this.collections.keys()].map(id => this.startSync(id)));\n }\n /**\n * Setup a collection to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n * @param name Name of the collection\n */\n async startSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (!collectionParameters.syncPaused)\n return; // already started\n this.schedulePush(name); // push changes that were made while paused\n const cleanupFunction = this.options.registerRemoteChange\n ? await this.options.registerRemoteChange(collectionParameters.options, async (data) => {\n if (data == null) {\n await this.sync(name);\n }\n else {\n const syncTime = Date.now();\n const syncId = this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n await this.syncWithData(name, data)\n .then(() => {\n // clean up old sync operations\n this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n })\n .catch((error) => {\n if (this.options.onError) {\n this.options.onError(this.getCollectionProperties(name).options, error);\n }\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n throw error;\n });\n }\n })\n : undefined;\n this.collections.set(name, {\n ...collectionParameters,\n syncPaused: false,\n cleanupFunction,\n });\n }\n /**\n * Pauses the sync process for all collections.\n * This means that the collections will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n */\n async pauseAll() {\n await Promise.all([...this.collections.keys()].map(id => this.pauseSync(id)));\n }\n /**\n * Pauses the sync process for a collection.\n * This means that the collection will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n * @param name Name of the collection\n */\n async pauseSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (collectionParameters.syncPaused)\n return; // already paused\n if (collectionParameters.cleanupFunction)\n await collectionParameters.cleanupFunction();\n this.collections.set(name, {\n ...collectionParameters,\n cleanupFunction: undefined,\n syncPaused: true,\n });\n }\n /**\n * Starts the sync process for all collections\n */\n async syncAll() {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n const errors = [];\n await Promise.all([...this.collections.keys()].map(id => this.sync(id).catch((error) => {\n errors.push({ id, error });\n })));\n if (errors.length > 0)\n throw new Error(`Error while syncing collections:\\n${errors.map(error => `${error.id}: ${error.error.message}`).join('\\n\\n')}`);\n }\n /**\n * Checks if a collection is currently beeing synced\n * @param [name] Name of the collection. If not provided, it will check if any collection is currently beeing synced.\n * @returns True if the collection is currently beeing synced, false otherwise.\n */\n isSyncing(name) {\n return this.syncOperations.findOne({\n ...name ? { collectionName: name } : {},\n status: 'active',\n }, { fields: { status: 1 } }) != null;\n }\n /**\n * Checks if the sync manager is ready to sync.\n * @returns A promise that resolves when the sync manager is ready to sync.\n */\n async isReady() {\n await this.persistenceReady;\n }\n /**\n * Starts the sync process for a collection\n * @param name Name of the collection\n * @param options Options for the sync process.\n * @param options.force If true, the sync process will be started even if there are no changes and onlyWithChanges is true.\n * @param options.onlyWithChanges If true, the sync process will only be started if there are changes.\n */\n async sync(name, options = {}) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n await this.isReady();\n const { options: collectionOptions, readyPromise } = this.getCollectionProperties(name);\n await readyPromise;\n const hasActiveSyncs = this.syncOperations.find({\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n }, {\n reactive: false,\n }).count() > 0;\n const syncTime = Date.now();\n let syncId = null;\n // schedule for next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const doSync = async () => {\n const lastFinishedSync = this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n });\n if (options?.onlyWithChanges) {\n const currentChanges = this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n }).count();\n if (currentChanges === 0)\n return;\n }\n if (!hasActiveSyncs) {\n syncId = this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n }\n const data = await this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n });\n await this.syncWithData(name, data);\n };\n await (options?.force ? doSync() : this.getSyncQueue(name).add(doSync))\n .catch((error) => {\n if (syncId != null) {\n if (this.options.onError)\n this.options.onError(collectionOptions, error);\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n }\n throw error;\n });\n if (syncId != null) {\n // clean up old sync operations\n this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n }\n }\n /**\n * Starts the push process for a collection (sync process but only if there are changes)\n * @param name Name of the collection\n */\n async pushChanges(name) {\n await this.sync(name, {\n onlyWithChanges: true,\n });\n }\n async syncWithData(name, data) {\n const { collection, options: collectionOptions } = this.getCollectionProperties(name);\n const syncTime = Date.now();\n const lastFinishedSync = this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n });\n const lastSnapshot = this.snapshots.findOne({\n collectionName: name,\n }, {\n sort: { time: -1 },\n reactive: false,\n });\n const currentChanges = this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n }).fetch();\n await sync({\n changes: currentChanges,\n lastSnapshot: lastSnapshot?.items,\n data,\n pull: () => this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n }),\n push: changes => this.options.push(collectionOptions, { changes }),\n insert: (item) => {\n const itemExists = item.id && !!collection.findOne({\n id: item.id,\n }, { reactive: false });\n if (itemExists) {\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // update the item if it already exists\n collection.updateOne({ id: item.id }, { $set: item });\n return;\n }\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n collection.insert(item);\n },\n update: (itemId, modifier) => {\n const itemExists = itemId && !collection.findOne({\n id: itemId,\n }, { reactive: false });\n if (itemExists) {\n const item = { ...modifier.$set, id: itemId };\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n // insert the item if it does not exist\n collection.insert(item);\n return;\n }\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: itemId, modifier },\n });\n collection.updateOne({ id: itemId }, modifier);\n },\n remove: (itemId) => {\n const itemExists = !!collection.findOne({\n id: itemId,\n }, { reactive: false });\n if (!itemExists)\n return;\n this.remoteChanges.push({\n collectionName: name,\n type: 'remove',\n data: itemId,\n });\n collection.removeOne({ id: itemId });\n },\n batch: (fn) => {\n collection.batch(() => {\n fn();\n });\n },\n })\n .then(async (snapshot) => {\n // clean up old snapshots\n this.snapshots.removeMany({\n collectionName: name,\n time: { $lte: syncTime },\n });\n // clean up processed changes\n this.changes.removeMany({\n collectionName: name,\n id: { $in: currentChanges.map(c => c.id) },\n });\n // insert new snapshot\n this.snapshots.insert({\n time: syncTime,\n collectionName: name,\n items: snapshot,\n });\n // delay sync operation update to next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const hasChanges = this.changes.find({\n collectionName: name,\n }, { reactive: false }).count() > 0;\n if (hasChanges) {\n // check if there are unsynced changes to push\n // and sync again if there are any\n await this.sync(name, {\n force: true,\n onlyWithChanges: true,\n });\n return;\n }\n // if there are no unsynced changes apply the last snapshot\n // to make sure that collection and snapshot are in sync\n // find all items that are not in the snapshot\n const nonExistingItemIds = collection.find({\n id: { $nin: snapshot.map(item => item.id) },\n }, {\n reactive: false,\n }).map(item => item.id);\n collection.batch(() => {\n // update all items that are in the snapshot\n snapshot.forEach((item) => {\n const itemExists = !!collection.findOne({\n id: item.id,\n }, {\n reactive: false,\n });\n /* istanbul ignore else -- @preserve */\n if (itemExists) {\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n collection.updateOne({ id: item.id }, { $set: item });\n }\n else { // this case should never happen\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n collection.insert(item);\n }\n });\n // remove all items that are not in the snapshot\n nonExistingItemIds.forEach((id) => {\n collection.removeOne({ id });\n });\n });\n });\n }\n}\n"],"names":["debounce","fn","wait","options","timeout","result","leading","trailing","debounced","args","shouldCallImmediately","shouldCallTrailing","PromiseQueue","__publicField","task","resolve","reject","error","computeChanges","oldItems","newItems","added","modified","removed","oldItemsMap","item","newItemsMap","id","oldItem","newItem","isEqual","getSnapshot","lastSnapshot","data","items","index","i","applyChanges","changes","collection","Collection","change","selector","itemExists","modify","hasChanges","hasDifference","sync","pull","push","insert","update","remove","batch","newData","previousSnapshot","newSnapshot","lastSnapshotWithChanges","newSnapshotWithChanges","changesToPush","newChanges","SyncManager","randomId","name","reactivity","changesPersistence","snapshotsPersistence","syncOperationsPersistence","createIndex","errorHandler","handler","collectionParameters","hasRemoteChange","remoteChange","removeRemoteChange","modifier","cleanupFunction","syncTime","syncId","errors","collectionOptions","readyPromise","hasActiveSyncs","doSync","lastFinishedSync","currentChanges","itemId","snapshot","c","nonExistingItemIds"],"mappings":";;;;AASA,SAAwBA,EAASC,GAAIC,GAAMC,IAAU,CAAA,GAAI;AACjD,MAAAC,GACAC;AACJ,QAAM,EAAE,SAAAC,IAAU,IAAO,UAAAC,IAAW,GAAS,IAAAJ;AAO7C,WAASK,KAAaC,GAAM;AAClB,UAAAC,IAAwBJ,KAAW,CAACF,GACpCO,IAAqBJ,KAAY,CAACH;AACxC,WAAIA,KACA,aAAaA,CAAO,GAExBA,IAAU,WAAW,MAAM;AACb,MAAAA,IAAA,MACNG,KAAY,CAACG,MACJL,IAAAJ,EAAG,MAAM,MAAMQ,CAAI;AAAA,OAEjCP,CAAI,GACHQ,IACSL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,UAAA,CACjD,GACUc,EAAA,UAAU,EAAE,IAAId,EAAK,MAAM,EAAE,MAAMA,GAAM,MAGpD,KAAK,cAAc,KAAK;AAAA,YACpB,gBAAgBsC;AAAA,YAChB,MAAM;AAAA,YACN,MAAMtC;AAAA,UAAA,CACT,GACDc,EAAW,OAAOd,CAAI;AAAA,QAC1B,CACH,GAEkBgE,EAAA,QAAQ,CAAC9D,MAAO;AACpB,UAAAY,EAAA,UAAU,EAAE,IAAAZ,GAAI;AAAA,QAAA,CAC9B;AAAA,MAAA,CACJ;AAAA,IAAA,CACJ;AAAA,EAAA;AAET;"}
package/dist/index.umd.js CHANGED
@@ -1,5 +1,5 @@
1
- (function(f,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("@signaldb/core")):typeof define=="function"&&define.amd?define(["exports","@signaldb/core"],h):(f=typeof globalThis<"u"?globalThis:f||self,h(f.SignalDB={},f.core))})(this,function(f,h){"use strict";var x=Object.defineProperty;var M=(f,h,g)=>h in f?x(f,h,{enumerable:!0,configurable:!0,writable:!0,value:g}):f[h]=g;var p=(f,h,g)=>M(f,typeof h!="symbol"?h+"":h,g);function g(l,e,t={}){let s,n;const{leading:a=!1,trailing:o=!0}=t;function c(...d){const i=a&&!s,u=o&&!s;return s&&clearTimeout(s),s=setTimeout(()=>{s=null,o&&!i&&(n=l.apply(this,d))},e),i?n=l.apply(this,d):u||(n=null),n}return c}class E{constructor(){p(this,"queue",[]);p(this,"pendingPromise",!1)}add(e){return new Promise((t,s)=>{this.queue.push(()=>e().then(t).catch(n=>{throw s(n),n})),this.dequeue()})}hasPendingPromise(){return this.pendingPromise}dequeue(){if(this.pendingPromise||this.queue.length===0)return;const e=this.queue.shift();e&&(this.pendingPromise=!0,e().then(()=>{this.pendingPromise=!1,this.dequeue()}).catch(()=>{this.pendingPromise=!1,this.dequeue()}))}}function w(l,e){const t=[],s=[],n=[],a=new Map(l.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id,c]));for(const[c,d]of a){const i=o.get(c);i?h.isEqual(i,d)||s.push(i):n.push(d)}for(const[c,d]of o)a.has(c)||t.push(d);return{added:t,modified:s,removed:n}}function C(l,e){if(e.items!=null)return e.items;const t=l||[];return e.changes.added.forEach(s=>{const n=t.findIndex(a=>a.id===s.id);n===-1?t.push(s):t[n]=s}),e.changes.modified.forEach(s=>{const n=t.findIndex(a=>a.id===s.id);n===-1?t.push(s):t[n]=s}),e.changes.removed.forEach(s=>{const n=t.findIndex(a=>a.id===s.id);n!==-1&&t.splice(n,1)}),t}async function P(l,e){const t=new h.Collection;t.batch(()=>{l.forEach(n=>t.insert(n)),e.forEach(n=>{if(n.type==="remove"){t.removeOne({id:n.data});return}const a={id:n.data.id},o=t.findOne(a);if(n.type==="insert"){o?t.updateOne(a,{$set:n.data}):t.insert(n.data);return}o?t.updateOne(a,n.data.modifier):t.insert(h.modify(a,n.data.modifier))})});const s=t.find().fetch();return await t.dispose(),s}function v(l){return l.added.length>0||l.modified.length>0||l.removed.length>0}function $(l,e){return v(w(l,e))}async function N({changes:l,lastSnapshot:e,data:t,pull:s,push:n,insert:a,update:o,remove:c,batch:d}){let i=t,u=e||[],m=C(e,i);if(l.length>0){const y=await P(u,l);if($(u,y)){const D=await P(m,l),O=w(m,D);v(O)&&(await n(O),i=await s(),m=C(m,i)),u=y}}const r=i.changes==null?w(u,i.items):i.changes;return d(()=>{r.added.forEach(y=>a(y)),r.modified.forEach(y=>o(y.id,{$set:y})),r.removed.forEach(y=>c(y.id))}),m}class S{constructor(e){p(this,"options");p(this,"collections",new Map);p(this,"changes");p(this,"snapshots");p(this,"syncOperations");p(this,"remoteChanges",[]);p(this,"syncQueues",new Map);p(this,"persistenceReady");p(this,"isDisposed",!1);p(this,"instanceId",h.randomId());p(this,"id");p(this,"deboucedPush",g(e=>{this.pushChanges(e).catch(()=>{})},100));this.options={autostart:!0,...e},this.id=this.options.id||"default-sync-manager";const{reactivity:t}=this.options,s=this.createPersistenceAdapter("changes"),n=this.createPersistenceAdapter("snapshots"),a=this.createPersistenceAdapter("sync-operations");this.changes=new h.Collection({name:`${this.options.id}-changes`,persistence:s==null?void 0:s.adapter,reactivity:t}),this.snapshots=new h.Collection({name:`${this.options.id}-snapshots`,persistence:n==null?void 0:n.adapter,reactivity:t}),this.syncOperations=new h.Collection({name:`${this.options.id}-sync-operations`,persistence:a==null?void 0:a.adapter,reactivity:t}),this.changes.on("persistence.error",o=>s==null?void 0:s.handler(o)),this.snapshots.on("persistence.error",o=>n==null?void 0:n.handler(o)),this.syncOperations.on("persistence.error",o=>a==null?void 0:a.handler(o)),this.persistenceReady=Promise.all([this.syncOperations.isReady(),this.changes.isReady(),this.snapshots.isReady()]).then(()=>{}),this.changes.setMaxListeners(1e3),this.snapshots.setMaxListeners(1e3),this.syncOperations.setMaxListeners(1e3)}createPersistenceAdapter(e){if(this.options.persistenceAdapter==null)return;let t=()=>{};return{adapter:this.options.persistenceAdapter(`${this.id}-${e}`,n=>{t=n}),handler:n=>t(n)}}getSyncQueue(e){return this.syncQueues.get(e)==null&&this.syncQueues.set(e,new E),this.syncQueues.get(e)}async dispose(){this.collections.clear(),this.syncQueues.clear(),this.remoteChanges.splice(0,this.remoteChanges.length),await Promise.all([this.changes.dispose(),this.snapshots.dispose(),this.syncOperations.dispose()]),this.isDisposed=!0}getCollection(e){const{collection:t,options:s}=this.getCollectionProperties(e);return[t,s]}getCollectionProperties(e){const t=this.collections.get(e);if(t==null)throw new Error(`Collection with id '${e}' not found`);return t}addCollection(e,t){if(this.isDisposed)throw new Error("SyncManager is disposed");this.collections.set(t.name,{collection:e,options:t,readyPromise:e.isReady(),syncPaused:!0});const s=a=>{for(const o of this.remoteChanges)if(h.isEqual(o,a))return!0;return!1},n=a=>{for(let o=0;o<this.remoteChanges.length;o+=1)if(h.isEqual(this.remoteChanges[o],a)){this.remoteChanges.splice(o,1);return}};e.on("added",a=>{if(s({collectionName:t.name,type:"insert",data:a})){n({collectionName:t.name,type:"insert",data:a});return}this.changes.insert({collectionName:t.name,time:Date.now(),type:"insert",data:a}),!this.getCollectionProperties(t.name).syncPaused&&this.schedulePush(t.name)}),e.on("changed",({id:a},o)=>{const c={id:a,modifier:o};if(s({collectionName:t.name,type:"update",data:c})){n({collectionName:t.name,type:"update",data:c});return}this.changes.insert({collectionName:t.name,time:Date.now(),type:"update",data:c}),!this.getCollectionProperties(t.name).syncPaused&&this.schedulePush(t.name)}),e.on("removed",({id:a})=>{if(s({collectionName:t.name,type:"remove",data:a})){n({collectionName:t.name,type:"remove",data:a});return}this.changes.insert({collectionName:t.name,time:Date.now(),type:"remove",data:a}),!this.getCollectionProperties(t.name).syncPaused&&this.schedulePush(t.name)}),this.options.autostart&&this.startSync(t.name).catch(a=>{this.options.onError&&this.options.onError(this.getCollectionProperties(t.name).options,a)})}schedulePush(e){this.deboucedPush(e)}async startAll(){await Promise.all([...this.collections.keys()].map(e=>this.startSync(e)))}async startSync(e){const t=this.getCollectionProperties(e);if(!t.syncPaused)return;this.schedulePush(e);const s=this.options.registerRemoteChange?await this.options.registerRemoteChange(t.options,async n=>{if(n==null)await this.sync(e);else{const a=Date.now(),o=this.syncOperations.insert({start:a,collectionName:e,instanceId:this.instanceId,status:"active"});await this.syncWithData(e,n).then(()=>{this.syncOperations.removeMany({id:{$ne:o},collectionName:e,$or:[{end:{$lte:a}},{status:"active"}]}),this.syncOperations.updateOne({id:o},{$set:{status:"done",end:Date.now()}})}).catch(c=>{throw this.options.onError&&this.options.onError(this.getCollectionProperties(e).options,c),this.syncOperations.updateOne({id:o},{$set:{status:"error",end:Date.now(),error:c.stack||c.message}}),c})}}):void 0;this.collections.set(e,{...t,syncPaused:!1,cleanupFunction:s})}async pauseAll(){await Promise.all([...this.collections.keys()].map(e=>this.pauseSync(e)))}async pauseSync(e){const t=this.getCollectionProperties(e);t.syncPaused||(t.cleanupFunction&&await t.cleanupFunction(),this.collections.set(e,{...t,cleanupFunction:void 0,syncPaused:!0}))}async syncAll(){if(this.isDisposed)throw new Error("SyncManager is disposed");const e=[];if(await Promise.all([...this.collections.keys()].map(t=>this.sync(t).catch(s=>{e.push({id:t,error:s})}))),e.length>0)throw new Error(`Error while syncing collections:
1
+ (function(f,r){typeof exports=="object"&&typeof module<"u"?r(exports,require("@signaldb/core")):typeof define=="function"&&define.amd?define(["exports","@signaldb/core"],r):(f=typeof globalThis<"u"?globalThis:f||self,r(f.SignalDB={},f.core))})(this,function(f,r){"use strict";var D=Object.defineProperty;var I=(f,r,g)=>r in f?D(f,r,{enumerable:!0,configurable:!0,writable:!0,value:g}):f[r]=g;var p=(f,r,g)=>I(f,typeof r!="symbol"?r+"":r,g);function g(l,e,t={}){let s,i;const{leading:a=!1,trailing:o=!0}=t;function c(...d){const n=a&&!s,u=o&&!s;return s&&clearTimeout(s),s=setTimeout(()=>{s=null,o&&!n&&(i=l.apply(this,d))},e),n?i=l.apply(this,d):u||(i=null),i}return c}class E{constructor(){p(this,"queue",[]);p(this,"pendingPromise",!1)}add(e){return new Promise((t,s)=>{this.queue.push(()=>e().then(t).catch(i=>{throw s(i),i})),this.dequeue()})}hasPendingPromise(){return this.pendingPromise}dequeue(){if(this.pendingPromise||this.queue.length===0)return;const e=this.queue.shift();e&&(this.pendingPromise=!0,e().then(()=>{this.pendingPromise=!1,this.dequeue()}).catch(()=>{this.pendingPromise=!1,this.dequeue()}))}}function w(l,e){const t=[],s=[],i=[],a=new Map(l.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id,c]));for(const[c,d]of a){const n=o.get(c);n?r.isEqual(n,d)||s.push(n):i.push(d)}for(const[c,d]of o)a.has(c)||t.push(d);return{added:t,modified:s,removed:i}}function C(l,e){if(e.items!=null)return e.items;const t=l||[];return e.changes.added.forEach(s=>{const i=t.findIndex(a=>a.id===s.id);i===-1?t.push(s):t[i]=s}),e.changes.modified.forEach(s=>{const i=t.findIndex(a=>a.id===s.id);i===-1?t.push(s):t[i]=s}),e.changes.removed.forEach(s=>{const i=t.findIndex(a=>a.id===s.id);i!==-1&&t.splice(i,1)}),t}async function P(l,e){const t=new r.Collection;t.batch(()=>{l.forEach(i=>t.insert(i)),e.forEach(i=>{if(i.type==="remove"){t.removeOne({id:i.data});return}const a={id:i.data.id},o=t.findOne(a);if(i.type==="insert"){o?t.updateOne(a,{$set:i.data}):t.insert(i.data);return}o?t.updateOne(a,i.data.modifier):t.insert(r.modify(a,i.data.modifier))})});const s=t.find().fetch();return await t.dispose(),s}function v(l){return l.added.length>0||l.modified.length>0||l.removed.length>0}function N(l,e){return v(w(l,e))}async function $({changes:l,lastSnapshot:e,data:t,pull:s,push:i,insert:a,update:o,remove:c,batch:d}){let n=t,u=e||[],m=C(e,n);if(l.length>0){const y=await P(u,l);if(N(u,y)){const S=await P(m,l),O=w(m,S);v(O)&&(await i(O),n=await s(),m=C(m,n)),u=y}}const h=n.changes==null?w(u,n.items):n.changes;return d(()=>{h.added.forEach(y=>a(y)),h.modified.forEach(y=>o(y.id,{$set:y})),h.removed.forEach(y=>c(y.id))}),m}class x{constructor(e){p(this,"options");p(this,"collections",new Map);p(this,"changes");p(this,"snapshots");p(this,"syncOperations");p(this,"remoteChanges",[]);p(this,"syncQueues",new Map);p(this,"persistenceReady");p(this,"isDisposed",!1);p(this,"instanceId",r.randomId());p(this,"id");p(this,"deboucedPush",g(e=>{this.pushChanges(e).catch(()=>{})},100));this.options={autostart:!0,...e},this.id=this.options.id||"default-sync-manager";const{reactivity:t}=this.options,s=this.createPersistenceAdapter("changes"),i=this.createPersistenceAdapter("snapshots"),a=this.createPersistenceAdapter("sync-operations");this.changes=new r.Collection({name:`${this.options.id}-changes`,persistence:s==null?void 0:s.adapter,indices:[r.createIndex("collectionName")],reactivity:t}),this.snapshots=new r.Collection({name:`${this.options.id}-snapshots`,persistence:i==null?void 0:i.adapter,indices:[r.createIndex("collectionName")],reactivity:t}),this.syncOperations=new r.Collection({name:`${this.options.id}-sync-operations`,persistence:a==null?void 0:a.adapter,indices:[r.createIndex("collectionName"),r.createIndex("status")],reactivity:t}),this.changes.on("persistence.error",o=>s==null?void 0:s.handler(o)),this.snapshots.on("persistence.error",o=>i==null?void 0:i.handler(o)),this.syncOperations.on("persistence.error",o=>a==null?void 0:a.handler(o)),this.persistenceReady=Promise.all([this.syncOperations.isReady(),this.changes.isReady(),this.snapshots.isReady()]).then(()=>{}),this.changes.setMaxListeners(1e3),this.snapshots.setMaxListeners(1e3),this.syncOperations.setMaxListeners(1e3)}createPersistenceAdapter(e){if(this.options.persistenceAdapter==null)return;let t=()=>{};return{adapter:this.options.persistenceAdapter(`${this.id}-${e}`,i=>{t=i}),handler:i=>t(i)}}getSyncQueue(e){return this.syncQueues.get(e)==null&&this.syncQueues.set(e,new E),this.syncQueues.get(e)}async dispose(){this.collections.clear(),this.syncQueues.clear(),this.remoteChanges.splice(0,this.remoteChanges.length),await Promise.all([this.changes.dispose(),this.snapshots.dispose(),this.syncOperations.dispose()]),this.isDisposed=!0}getCollection(e){const{collection:t,options:s}=this.getCollectionProperties(e);return[t,s]}getCollectionProperties(e){const t=this.collections.get(e);if(t==null)throw new Error(`Collection with id '${e}' not found`);return t}addCollection(e,t){if(this.isDisposed)throw new Error("SyncManager is disposed");this.collections.set(t.name,{collection:e,options:t,readyPromise:e.isReady(),syncPaused:!0});const s=a=>{for(const o of this.remoteChanges)if(r.isEqual(o,a))return!0;return!1},i=a=>{for(let o=0;o<this.remoteChanges.length;o+=1)if(r.isEqual(this.remoteChanges[o],a)){this.remoteChanges.splice(o,1);return}};e.on("added",a=>{if(s({collectionName:t.name,type:"insert",data:a})){i({collectionName:t.name,type:"insert",data:a});return}this.changes.insert({collectionName:t.name,time:Date.now(),type:"insert",data:a}),!this.getCollectionProperties(t.name).syncPaused&&this.schedulePush(t.name)}),e.on("changed",({id:a},o)=>{const c={id:a,modifier:o};if(s({collectionName:t.name,type:"update",data:c})){i({collectionName:t.name,type:"update",data:c});return}this.changes.insert({collectionName:t.name,time:Date.now(),type:"update",data:c}),!this.getCollectionProperties(t.name).syncPaused&&this.schedulePush(t.name)}),e.on("removed",({id:a})=>{if(s({collectionName:t.name,type:"remove",data:a})){i({collectionName:t.name,type:"remove",data:a});return}this.changes.insert({collectionName:t.name,time:Date.now(),type:"remove",data:a}),!this.getCollectionProperties(t.name).syncPaused&&this.schedulePush(t.name)}),this.options.autostart&&this.startSync(t.name).catch(a=>{this.options.onError&&this.options.onError(this.getCollectionProperties(t.name).options,a)})}schedulePush(e){this.deboucedPush(e)}async startAll(){await Promise.all([...this.collections.keys()].map(e=>this.startSync(e)))}async startSync(e){const t=this.getCollectionProperties(e);if(!t.syncPaused)return;this.schedulePush(e);const s=this.options.registerRemoteChange?await this.options.registerRemoteChange(t.options,async i=>{if(i==null)await this.sync(e);else{const a=Date.now(),o=this.syncOperations.insert({start:a,collectionName:e,instanceId:this.instanceId,status:"active"});await this.syncWithData(e,i).then(()=>{this.syncOperations.removeMany({id:{$ne:o},collectionName:e,$or:[{end:{$lte:a}},{status:"active"}]}),this.syncOperations.updateOne({id:o},{$set:{status:"done",end:Date.now()}})}).catch(c=>{throw this.options.onError&&this.options.onError(this.getCollectionProperties(e).options,c),this.syncOperations.updateOne({id:o},{$set:{status:"error",end:Date.now(),error:c.stack||c.message}}),c})}}):void 0;this.collections.set(e,{...t,syncPaused:!1,cleanupFunction:s})}async pauseAll(){await Promise.all([...this.collections.keys()].map(e=>this.pauseSync(e)))}async pauseSync(e){const t=this.getCollectionProperties(e);t.syncPaused||(t.cleanupFunction&&await t.cleanupFunction(),this.collections.set(e,{...t,cleanupFunction:void 0,syncPaused:!0}))}async syncAll(){if(this.isDisposed)throw new Error("SyncManager is disposed");const e=[];if(await Promise.all([...this.collections.keys()].map(t=>this.sync(t).catch(s=>{e.push({id:t,error:s})}))),e.length>0)throw new Error(`Error while syncing collections:
2
2
  ${e.map(t=>`${t.id}: ${t.error.message}`).join(`
3
3
 
4
- `)}`)}isSyncing(e){return this.syncOperations.findOne({...e?{collectionName:e}:{},status:"active"},{fields:{status:1}})!=null}async isReady(){await this.persistenceReady}async sync(e,t={}){if(this.isDisposed)throw new Error("SyncManager is disposed");await this.isReady();const{options:s,readyPromise:n}=this.getCollectionProperties(e);await n;const a=this.syncOperations.find({collectionName:e,instanceId:this.instanceId,status:"active"},{reactive:!1}).count()>0,o=Date.now();let c=null;await new Promise(i=>{setTimeout(i,0)});const d=async()=>{const i=this.syncOperations.findOne({collectionName:e,status:"done"},{sort:{end:-1},reactive:!1});if(t!=null&&t.onlyWithChanges&&this.changes.find({collectionName:e,$and:[{time:{$lte:o}}]},{sort:{time:1},reactive:!1}).count()===0)return;a||(c=this.syncOperations.insert({start:o,collectionName:e,instanceId:this.instanceId,status:"active"}));const u=await this.options.pull(s,{lastFinishedSyncStart:i==null?void 0:i.start,lastFinishedSyncEnd:i==null?void 0:i.end});await this.syncWithData(e,u)};await(t!=null&&t.force?d():this.getSyncQueue(e).add(d)).catch(i=>{throw c!=null&&(this.options.onError&&this.options.onError(s,i),this.syncOperations.updateOne({id:c},{$set:{status:"error",end:Date.now(),error:i.stack||i.message}})),i}),c!=null&&(this.syncOperations.removeMany({id:{$ne:c},collectionName:e,$or:[{end:{$lte:o}},{status:"active"}]}),this.syncOperations.updateOne({id:c},{$set:{status:"done",end:Date.now()}}))}async pushChanges(e){await this.sync(e,{onlyWithChanges:!0})}async syncWithData(e,t){const{collection:s,options:n}=this.getCollectionProperties(e),a=Date.now(),o=this.syncOperations.findOne({collectionName:e,status:"done"},{sort:{end:-1},reactive:!1}),c=this.snapshots.findOne({collectionName:e},{sort:{time:-1},reactive:!1}),d=this.changes.find({collectionName:e,$and:[{time:{$lte:a}}]},{sort:{time:1},reactive:!1}).fetch();await N({changes:d,lastSnapshot:c==null?void 0:c.items,data:t,pull:()=>this.options.pull(n,{lastFinishedSyncStart:o==null?void 0:o.start,lastFinishedSyncEnd:o==null?void 0:o.end}),push:i=>this.options.push(n,{changes:i}),insert:i=>{if(i.id&&!!s.findOne({id:i.id},{reactive:!1})){this.remoteChanges.push({collectionName:e,type:"update",data:{id:i.id,modifier:{$set:i}}}),s.updateOne({id:i.id},{$set:i});return}this.remoteChanges.push({collectionName:e,type:"insert",data:i}),s.insert(i)},update:(i,u)=>{if(i&&!s.findOne({id:i},{reactive:!1})){const r={...u.$set,id:i};this.remoteChanges.push({collectionName:e,type:"insert",data:r}),s.insert(r);return}this.remoteChanges.push({collectionName:e,type:"update",data:{id:i,modifier:u}}),s.updateOne({id:i},u)},remove:i=>{s.findOne({id:i},{reactive:!1})&&(this.remoteChanges.push({collectionName:e,type:"remove",data:i}),s.removeOne({id:i}))},batch:i=>{s.batch(()=>{i()})}}).then(async i=>{if(this.snapshots.removeMany({collectionName:e,time:{$lte:a}}),this.changes.removeMany({collectionName:e,id:{$in:d.map(r=>r.id)}}),this.snapshots.insert({time:a,collectionName:e,items:i}),await new Promise(r=>{setTimeout(r,0)}),this.changes.find({collectionName:e},{reactive:!1}).count()>0){await this.sync(e,{force:!0,onlyWithChanges:!0});return}const m=s.find({id:{$nin:i.map(r=>r.id)}},{reactive:!1}).map(r=>r.id);s.batch(()=>{i.forEach(r=>{const y=!!s.findOne({id:r.id},{reactive:!1});/* istanbul ignore else -- @preserve */y?(this.remoteChanges.push({collectionName:e,type:"update",data:{id:r.id,modifier:{$set:r}}}),s.updateOne({id:r.id},{$set:r})):(this.remoteChanges.push({collectionName:e,type:"insert",data:r}),s.insert(r))}),m.forEach(r=>{s.removeOne({id:r})})})})}}f.SyncManager=S,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
4
+ `)}`)}isSyncing(e){return this.syncOperations.findOne({...e?{collectionName:e}:{},status:"active"},{fields:{status:1}})!=null}async isReady(){await this.persistenceReady}async sync(e,t={}){if(this.isDisposed)throw new Error("SyncManager is disposed");await this.isReady();const{options:s,readyPromise:i}=this.getCollectionProperties(e);await i;const a=this.syncOperations.find({collectionName:e,instanceId:this.instanceId,status:"active"},{reactive:!1}).count()>0,o=Date.now();let c=null;await new Promise(n=>{setTimeout(n,0)});const d=async()=>{const n=this.syncOperations.findOne({collectionName:e,status:"done"},{sort:{end:-1},reactive:!1});if(t!=null&&t.onlyWithChanges&&this.changes.find({collectionName:e,time:{$lte:o}},{sort:{time:1},reactive:!1}).count()===0)return;a||(c=this.syncOperations.insert({start:o,collectionName:e,instanceId:this.instanceId,status:"active"}));const u=await this.options.pull(s,{lastFinishedSyncStart:n==null?void 0:n.start,lastFinishedSyncEnd:n==null?void 0:n.end});await this.syncWithData(e,u)};await(t!=null&&t.force?d():this.getSyncQueue(e).add(d)).catch(n=>{throw c!=null&&(this.options.onError&&this.options.onError(s,n),this.syncOperations.updateOne({id:c},{$set:{status:"error",end:Date.now(),error:n.stack||n.message}})),n}),c!=null&&(this.syncOperations.removeMany({id:{$ne:c},collectionName:e,$or:[{end:{$lte:o}},{status:"active"}]}),this.syncOperations.updateOne({id:c},{$set:{status:"done",end:Date.now()}}))}async pushChanges(e){await this.sync(e,{onlyWithChanges:!0})}async syncWithData(e,t){const{collection:s,options:i}=this.getCollectionProperties(e),a=Date.now(),o=this.syncOperations.findOne({collectionName:e,status:"done"},{sort:{end:-1},reactive:!1}),c=this.snapshots.findOne({collectionName:e},{sort:{time:-1},reactive:!1}),d=this.changes.find({collectionName:e,time:{$lte:a}},{sort:{time:1},reactive:!1}).fetch();await $({changes:d,lastSnapshot:c==null?void 0:c.items,data:t,pull:()=>this.options.pull(i,{lastFinishedSyncStart:o==null?void 0:o.start,lastFinishedSyncEnd:o==null?void 0:o.end}),push:n=>this.options.push(i,{changes:n}),insert:n=>{if(n.id&&!!s.findOne({id:n.id},{reactive:!1})){this.remoteChanges.push({collectionName:e,type:"update",data:{id:n.id,modifier:{$set:n}}}),s.updateOne({id:n.id},{$set:n});return}this.remoteChanges.push({collectionName:e,type:"insert",data:n}),s.insert(n)},update:(n,u)=>{if(n&&!s.findOne({id:n},{reactive:!1})){const h={...u.$set,id:n};this.remoteChanges.push({collectionName:e,type:"insert",data:h}),s.insert(h);return}this.remoteChanges.push({collectionName:e,type:"update",data:{id:n,modifier:u}}),s.updateOne({id:n},u)},remove:n=>{s.findOne({id:n},{reactive:!1})&&(this.remoteChanges.push({collectionName:e,type:"remove",data:n}),s.removeOne({id:n}))},batch:n=>{s.batch(()=>{n()})}}).then(async n=>{if(this.snapshots.removeMany({collectionName:e,time:{$lte:a}}),this.changes.removeMany({collectionName:e,id:{$in:d.map(h=>h.id)}}),this.snapshots.insert({time:a,collectionName:e,items:n}),await new Promise(h=>{setTimeout(h,0)}),this.changes.find({collectionName:e},{reactive:!1}).count()>0){await this.sync(e,{force:!0,onlyWithChanges:!0});return}const m=s.find({id:{$nin:n.map(h=>h.id)}},{reactive:!1}).map(h=>h.id);s.batch(()=>{n.forEach(h=>{const y=!!s.findOne({id:h.id},{reactive:!1});/* istanbul ignore else -- @preserve */y?(this.remoteChanges.push({collectionName:e,type:"update",data:{id:h.id,modifier:{$set:h}}}),s.updateOne({id:h.id},{$set:h})):(this.remoteChanges.push({collectionName:e,type:"insert",data:h}),s.insert(h))}),m.forEach(h=>{s.removeOne({id:h})})})})}}f.SyncManager=x,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
5
5
  //# sourceMappingURL=index.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","sources":["../src/utils/debounce.ts","../src/utils/PromiseQueue.ts","../src/computeChanges.ts","../src/getSnapshot.ts","../src/applyChanges.ts","../src/sync.ts","../src/SyncManager.ts"],"sourcesContent":["/**\n * Debounces a function.\n * @param fn Function to debounce\n * @param wait Time to wait before calling the function.\n * @param [options] Debounce options\n * @param [options.leading] Whether to call the function on the leading edge of the wait interval.\n * @param [options.trailing] Whether to call the function on the trailing edge of the wait interval.\n * @returns The debounced function.\n */\nexport default function debounce(fn, wait, options = {}) {\n let timeout;\n let result;\n const { leading = false, trailing = true } = options;\n /**\n * The debounced function that will be returned.\n * @param this The context to bind the function to.\n * @param args The arguments to pass to the function.\n * @returns The result of the debounced function.\n */\n function debounced(...args) {\n const shouldCallImmediately = leading && !timeout;\n const shouldCallTrailing = trailing && !timeout;\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n timeout = null;\n if (trailing && !shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n }, wait);\n if (shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n else if (!shouldCallTrailing) {\n result = null;\n }\n return result;\n }\n return debounced;\n}\n","/**\n * Class for queuing promises to be executed one after the other.\n * This is useful for tasks that should not be executed in parallel.\n * @example\n * const queue = new PromiseQueue();\n * queue.add(() => fetch('https://example.com/api/endpoint1'));\n * queue.add(() => fetch('https://example.com/api/endpoint2'));\n * // The second fetch will only be executed after the first one is done.\n */\nexport default class PromiseQueue {\n queue = [];\n pendingPromise = false;\n /**\n * Method to add a new promise to the queue and returns a promise that resolves when this task is done\n * @param task Function that returns a promise that will be added to the queue\n * @returns Promise that resolves when the task is done\n */\n add(task) {\n return new Promise((resolve, reject) => {\n // Wrap the task with the resolve and reject to control its completion from the outside\n this.queue.push(() => task()\n .then(resolve)\n .catch((error) => {\n reject(error);\n throw error;\n }));\n this.dequeue();\n });\n }\n /**\n * Method to check if there is a pending promise in the queue\n * @returns True if there is a pending promise, false otherwise\n */\n hasPendingPromise() {\n return this.pendingPromise;\n }\n /**\n * Method to process the queue\n */\n dequeue() {\n if (this.pendingPromise || this.queue.length === 0) {\n return;\n }\n const task = this.queue.shift();\n if (!task)\n return;\n this.pendingPromise = true;\n task()\n .then(() => {\n this.pendingPromise = false;\n this.dequeue();\n })\n .catch(() => {\n this.pendingPromise = false;\n this.dequeue();\n });\n }\n}\n","import { isEqual } from '@signaldb/core';\n/**\n * Compute changes between two arrays of items.\n * @param oldItems Array of the old items\n * @param newItems Array of the new items\n * @returns The changeset\n */\nexport default function computeChanges(oldItems, newItems) {\n const added = [];\n const modified = [];\n const removed = [];\n const oldItemsMap = new Map(oldItems.map(item => [item.id, item]));\n const newItemsMap = new Map(newItems.map(item => [item.id, item]));\n for (const [id, oldItem] of oldItemsMap) {\n const newItem = newItemsMap.get(id);\n if (!newItem) {\n removed.push(oldItem);\n }\n else if (!isEqual(newItem, oldItem)) {\n modified.push(newItem);\n }\n }\n for (const [id, newItem] of newItemsMap) {\n if (!oldItemsMap.has(id)) {\n added.push(newItem);\n }\n }\n return { added, modified, removed };\n}\n","/**\n * Gets the snapshot of items from the last snapshot and the changes.\n * @param lastSnapshot The last snapshot of items\n * @param data The changes to apply to the last snapshot\n * @returns The new snapshot of items\n */\nexport default function getSnapshot(lastSnapshot, data) {\n if (data.items != null)\n return data.items;\n const items = lastSnapshot || [];\n data.changes.added.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.modified.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.removed.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index !== -1)\n items.splice(index, 1);\n });\n return items;\n}\n","import { Collection, modify } from '@signaldb/core';\n/**\n * applies changes to a collection of items\n * @param items The items to apply the changes to\n * @param changes The changes to apply to the items\n * @returns The new items after applying the changes\n */\nexport default async function applyChanges(items, changes) {\n const collection = new Collection();\n collection.batch(() => {\n items.forEach(item => collection.insert(item));\n changes.forEach((change) => {\n if (change.type === 'remove') {\n collection.removeOne({ id: change.data });\n return;\n }\n const selector = { id: change.data.id };\n const itemExists = collection.findOne(selector);\n if (change.type === 'insert') {\n if (itemExists) { // update item if it alread exists\n collection.updateOne(selector, { $set: change.data });\n }\n else { // insert item if it does not exist\n collection.insert(change.data);\n }\n return;\n }\n // change.type === 'update'\n if (itemExists) { // update item if it exists\n collection.updateOne(selector, change.data.modifier);\n }\n else { // insert item if it does not exist\n collection.insert(modify(selector, change.data.modifier));\n }\n });\n });\n const result = collection.find().fetch();\n await collection.dispose();\n return result;\n}\n","import computeChanges from './computeChanges';\nimport getSnapshot from './getSnapshot';\nimport applyChanges from './applyChanges';\n/**\n * Checks if there are any changes in the given changeset.\n * @param changes The changeset to check.\n * @returns True if there are changes, false otherwise.\n */\nfunction hasChanges(changes) {\n return changes.added.length > 0\n || changes.modified.length > 0\n || changes.removed.length > 0;\n}\n/**\n * Checks if there is a difference between the old items and the new items.\n * @param oldItems The old items.\n * @param newItems The new items.\n * @returns True if there is a difference, false otherwise.\n */\nfunction hasDifference(oldItems, newItems) {\n return hasChanges(computeChanges(oldItems, newItems));\n}\n/**\n * Does a sync operation based on the provided options. If changes are supplied, these will be rebased on the new data.\n * Afterwards the push method will be called with the remaining changes. A new snapshot will be created and returned.\n * @param options Sync options\n * @param options.changes Changes to call the push method with\n * @param [options.lastSnapshot] The last snapshot\n * @param options.data The new data\n * @param options.pull Method to pull new data\n * @param options.push Method to push changes\n * @param options.insert Method to insert an item\n * @param options.update Method to update an item\n * @param options.remove Method to remove an item\n * @param options.batch Method to batch multiple operations\n * @returns The new snapshot\n */\nexport default async function sync({ changes, lastSnapshot, data, pull, push, insert, update, remove, batch, }) {\n let newData = data;\n let previousSnapshot = lastSnapshot || [];\n let newSnapshot = getSnapshot(lastSnapshot, newData);\n if (changes.length > 0) {\n // apply changes on last snapshot and check if there is a difference\n const lastSnapshotWithChanges = await applyChanges(previousSnapshot, changes);\n if (hasDifference(previousSnapshot, lastSnapshotWithChanges)) {\n // if yes, apply the changes on the newSnapshot and check if there is a difference\n const newSnapshotWithChanges = await applyChanges(newSnapshot, changes);\n const changesToPush = computeChanges(newSnapshot, newSnapshotWithChanges);\n if (hasChanges(changesToPush)) {\n // if yes, push the changes to the server\n await push(changesToPush);\n // pull new data afterwards to ensure that all server changes are applied\n newData = await pull();\n newSnapshot = getSnapshot(newSnapshot, newData);\n }\n previousSnapshot = lastSnapshotWithChanges;\n }\n }\n // apply the new changes on the collection\n const newChanges = newData.changes == null\n ? computeChanges(previousSnapshot, newData.items)\n : newData.changes;\n batch(() => {\n newChanges.added.forEach(item => insert(item));\n newChanges.modified.forEach(item => update(item.id, { $set: item }));\n newChanges.removed.forEach(item => remove(item.id));\n });\n return newSnapshot;\n}\n","import { Collection, randomId, isEqual } from '@signaldb/core';\nimport debounce from './utils/debounce';\nimport PromiseQueue from './utils/PromiseQueue';\nimport sync from './sync';\n/**\n * Class to manage syncing of collections.\n * @template CollectionOptions\n * @template ItemType\n * @template IdType\n * @example\n * const syncManager = new SyncManager({\n * pull: async (collectionOptions) => {\n * const response = await fetch(`/api/collections/${collectionOptions.name}`)\n * return await response.json()\n * },\n * push: async (collectionOptions, { changes }) => {\n * await fetch(`/api/collections/${collectionOptions.name}`, {\n * method: 'POST',\n * body: JSON.stringify(changes),\n * })\n * },\n * })\n *\n * const collection = new Collection()\n * syncManager.addCollection(collection, {\n * name: 'todos',\n * })\n *\n * syncManager.sync('todos')\n */\nexport default class SyncManager {\n options;\n collections = new Map();\n changes;\n snapshots;\n syncOperations;\n remoteChanges = [];\n syncQueues = new Map();\n persistenceReady;\n isDisposed = false;\n instanceId = randomId();\n id;\n /**\n * @param options Collection options\n * @param options.pull Function to pull data from remote source.\n * @param options.push Function to push data to remote source.\n * @param [options.registerRemoteChange] Function to register a callback for remote changes.\n * @param [options.id] Unique identifier for this sync manager. Only nessesary if you have multiple sync managers.\n * @param [options.persistenceAdapter] Persistence adapter to use for storing changes, snapshots and sync operations.\n * @param [options.reactivity] Reactivity adapter to use for reactivity.\n * @param [options.onError] Function to handle errors that occur async during syncing.\n */\n constructor(options) {\n this.options = {\n autostart: true,\n ...options,\n };\n this.id = this.options.id || 'default-sync-manager';\n const { reactivity } = this.options;\n const changesPersistence = this.createPersistenceAdapter('changes');\n const snapshotsPersistence = this.createPersistenceAdapter('snapshots');\n const syncOperationsPersistence = this.createPersistenceAdapter('sync-operations');\n this.changes = new Collection({\n name: `${this.options.id}-changes`,\n persistence: changesPersistence?.adapter,\n reactivity,\n });\n this.snapshots = new Collection({\n name: `${this.options.id}-snapshots`,\n persistence: snapshotsPersistence?.adapter,\n reactivity,\n });\n this.syncOperations = new Collection({\n name: `${this.options.id}-sync-operations`,\n persistence: syncOperationsPersistence?.adapter,\n reactivity,\n });\n this.changes.on('persistence.error', error => changesPersistence?.handler(error));\n this.snapshots.on('persistence.error', error => snapshotsPersistence?.handler(error));\n this.syncOperations.on('persistence.error', error => syncOperationsPersistence?.handler(error));\n this.persistenceReady = Promise.all([\n this.syncOperations.isReady(),\n this.changes.isReady(),\n this.snapshots.isReady(),\n ]).then(() => { });\n this.changes.setMaxListeners(1000);\n this.snapshots.setMaxListeners(1000);\n this.syncOperations.setMaxListeners(1000);\n }\n createPersistenceAdapter(name) {\n if (this.options.persistenceAdapter == null)\n return;\n let errorHandler = () => { };\n const adapter = this.options.persistenceAdapter(`${this.id}-${name}`, (handler) => {\n errorHandler = handler;\n });\n return {\n adapter,\n handler: (error) => errorHandler(error),\n };\n }\n getSyncQueue(name) {\n if (this.syncQueues.get(name) == null) {\n this.syncQueues.set(name, new PromiseQueue());\n }\n return this.syncQueues.get(name);\n }\n /**\n * Clears all internal data structures\n */\n async dispose() {\n this.collections.clear();\n this.syncQueues.clear();\n this.remoteChanges.splice(0, this.remoteChanges.length);\n await Promise.all([\n this.changes.dispose(),\n this.snapshots.dispose(),\n this.syncOperations.dispose(),\n ]);\n this.isDisposed = true;\n }\n /**\n * Gets a collection with it's options by name\n * @deprecated Use getCollectionProperties instead.\n * @param name Name of the collection\n * @throws Will throw an error if the name wasn't found\n * @returns Tuple of collection and options\n */\n getCollection(name) {\n const { collection, options } = this.getCollectionProperties(name);\n return [collection, options];\n }\n /**\n * Gets collection options by name\n * @param name Name of the collection\n * @throws Will throw an error if the name wasn't found\n * @returns An object of all properties of the collection\n */\n getCollectionProperties(name) {\n const collectionParameters = this.collections.get(name);\n if (collectionParameters == null)\n throw new Error(`Collection with id '${name}' not found`);\n return collectionParameters;\n }\n /**\n * Adds a collection to the sync manager.\n * @param collection Collection to add\n * @param options Options for the collection. The object needs at least a `name` property.\n * @param options.name Unique name of the collection\n */\n addCollection(collection, options) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n this.collections.set(options.name, {\n collection,\n options,\n readyPromise: collection.isReady(),\n syncPaused: true, // always start paused as the autostart will start it\n });\n const hasRemoteChange = (change) => {\n for (const remoteChange of this.remoteChanges) {\n if (isEqual(remoteChange, change)) {\n return true;\n }\n }\n return false;\n };\n const removeRemoteChange = (change) => {\n for (let i = 0; i < this.remoteChanges.length; i += 1) {\n if (isEqual(this.remoteChanges[i], change)) {\n this.remoteChanges.splice(i, 1);\n return;\n }\n }\n };\n collection.on('added', (item) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'insert', data: item })) {\n removeRemoteChange({ collectionName: options.name, type: 'insert', data: item });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'insert',\n data: item,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n collection.on('changed', ({ id }, modifier) => {\n const data = { id, modifier };\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'update', data })) {\n removeRemoteChange({ collectionName: options.name, type: 'update', data });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'update',\n data,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n collection.on('removed', ({ id }) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'remove', data: id })) {\n removeRemoteChange({ collectionName: options.name, type: 'remove', data: id });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'remove',\n data: id,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n if (this.options.autostart) {\n this.startSync(options.name)\n .catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n }\n }\n deboucedPush = debounce((name) => {\n this.pushChanges(name).catch(() => { });\n }, 100);\n schedulePush(name) {\n this.deboucedPush(name);\n }\n /**\n * Setup all collections to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n */\n async startAll() {\n await Promise.all([...this.collections.keys()].map(id => this.startSync(id)));\n }\n /**\n * Setup a collection to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n * @param name Name of the collection\n */\n async startSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (!collectionParameters.syncPaused)\n return; // already started\n this.schedulePush(name); // push changes that were made while paused\n const cleanupFunction = this.options.registerRemoteChange\n ? await this.options.registerRemoteChange(collectionParameters.options, async (data) => {\n if (data == null) {\n await this.sync(name);\n }\n else {\n const syncTime = Date.now();\n const syncId = this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n await this.syncWithData(name, data)\n .then(() => {\n // clean up old sync operations\n this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n })\n .catch((error) => {\n if (this.options.onError) {\n this.options.onError(this.getCollectionProperties(name).options, error);\n }\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n throw error;\n });\n }\n })\n : undefined;\n this.collections.set(name, {\n ...collectionParameters,\n syncPaused: false,\n cleanupFunction,\n });\n }\n /**\n * Pauses the sync process for all collections.\n * This means that the collections will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n */\n async pauseAll() {\n await Promise.all([...this.collections.keys()].map(id => this.pauseSync(id)));\n }\n /**\n * Pauses the sync process for a collection.\n * This means that the collection will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n * @param name Name of the collection\n */\n async pauseSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (collectionParameters.syncPaused)\n return; // already paused\n if (collectionParameters.cleanupFunction)\n await collectionParameters.cleanupFunction();\n this.collections.set(name, {\n ...collectionParameters,\n cleanupFunction: undefined,\n syncPaused: true,\n });\n }\n /**\n * Starts the sync process for all collections\n */\n async syncAll() {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n const errors = [];\n await Promise.all([...this.collections.keys()].map(id => this.sync(id).catch((error) => {\n errors.push({ id, error });\n })));\n if (errors.length > 0)\n throw new Error(`Error while syncing collections:\\n${errors.map(error => `${error.id}: ${error.error.message}`).join('\\n\\n')}`);\n }\n /**\n * Checks if a collection is currently beeing synced\n * @param [name] Name of the collection. If not provided, it will check if any collection is currently beeing synced.\n * @returns True if the collection is currently beeing synced, false otherwise.\n */\n isSyncing(name) {\n return this.syncOperations.findOne({\n ...name ? { collectionName: name } : {},\n status: 'active',\n }, { fields: { status: 1 } }) != null;\n }\n /**\n * Checks if the sync manager is ready to sync.\n * @returns A promise that resolves when the sync manager is ready to sync.\n */\n async isReady() {\n await this.persistenceReady;\n }\n /**\n * Starts the sync process for a collection\n * @param name Name of the collection\n * @param options Options for the sync process.\n * @param options.force If true, the sync process will be started even if there are no changes and onlyWithChanges is true.\n * @param options.onlyWithChanges If true, the sync process will only be started if there are changes.\n */\n async sync(name, options = {}) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n await this.isReady();\n const { options: collectionOptions, readyPromise } = this.getCollectionProperties(name);\n await readyPromise;\n const hasActiveSyncs = this.syncOperations.find({\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n }, {\n reactive: false,\n }).count() > 0;\n const syncTime = Date.now();\n let syncId = null;\n // schedule for next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const doSync = async () => {\n const lastFinishedSync = this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n });\n if (options?.onlyWithChanges) {\n const currentChanges = this.changes.find({\n collectionName: name,\n $and: [\n { time: { $lte: syncTime } },\n ],\n }, {\n sort: { time: 1 },\n reactive: false,\n }).count();\n if (currentChanges === 0)\n return;\n }\n if (!hasActiveSyncs) {\n syncId = this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n }\n const data = await this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n });\n await this.syncWithData(name, data);\n };\n await (options?.force ? doSync() : this.getSyncQueue(name).add(doSync))\n .catch((error) => {\n if (syncId != null) {\n if (this.options.onError)\n this.options.onError(collectionOptions, error);\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n }\n throw error;\n });\n if (syncId != null) {\n // clean up old sync operations\n this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n }\n }\n /**\n * Starts the push process for a collection (sync process but only if there are changes)\n * @param name Name of the collection\n */\n async pushChanges(name) {\n await this.sync(name, {\n onlyWithChanges: true,\n });\n }\n async syncWithData(name, data) {\n const { collection, options: collectionOptions } = this.getCollectionProperties(name);\n const syncTime = Date.now();\n const lastFinishedSync = this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n });\n const lastSnapshot = this.snapshots.findOne({\n collectionName: name,\n }, {\n sort: { time: -1 },\n reactive: false,\n });\n const currentChanges = this.changes.find({\n collectionName: name,\n $and: [\n { time: { $lte: syncTime } },\n ],\n }, {\n sort: { time: 1 },\n reactive: false,\n }).fetch();\n await sync({\n changes: currentChanges,\n lastSnapshot: lastSnapshot?.items,\n data,\n pull: () => this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n }),\n push: changes => this.options.push(collectionOptions, { changes }),\n insert: (item) => {\n const itemExists = item.id && !!collection.findOne({\n id: item.id,\n }, { reactive: false });\n if (itemExists) {\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // update the item if it already exists\n collection.updateOne({ id: item.id }, { $set: item });\n return;\n }\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n collection.insert(item);\n },\n update: (itemId, modifier) => {\n const itemExists = itemId && !collection.findOne({\n id: itemId,\n }, { reactive: false });\n if (itemExists) {\n const item = { ...modifier.$set, id: itemId };\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n // insert the item if it does not exist\n collection.insert(item);\n return;\n }\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: itemId, modifier },\n });\n collection.updateOne({ id: itemId }, modifier);\n },\n remove: (itemId) => {\n const itemExists = !!collection.findOne({\n id: itemId,\n }, { reactive: false });\n if (!itemExists)\n return;\n this.remoteChanges.push({\n collectionName: name,\n type: 'remove',\n data: itemId,\n });\n collection.removeOne({ id: itemId });\n },\n batch: (fn) => {\n collection.batch(() => {\n fn();\n });\n },\n })\n .then(async (snapshot) => {\n // clean up old snapshots\n this.snapshots.removeMany({\n collectionName: name,\n time: { $lte: syncTime },\n });\n // clean up processed changes\n this.changes.removeMany({\n collectionName: name,\n id: { $in: currentChanges.map(c => c.id) },\n });\n // insert new snapshot\n this.snapshots.insert({\n time: syncTime,\n collectionName: name,\n items: snapshot,\n });\n // delay sync operation update to next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const hasChanges = this.changes.find({\n collectionName: name,\n }, { reactive: false }).count() > 0;\n if (hasChanges) {\n // check if there are unsynced changes to push\n // and sync again if there are any\n await this.sync(name, {\n force: true,\n onlyWithChanges: true,\n });\n return;\n }\n // if there are no unsynced changes apply the last snapshot\n // to make sure that collection and snapshot are in sync\n // find all items that are not in the snapshot\n const nonExistingItemIds = collection.find({\n id: { $nin: snapshot.map(item => item.id) },\n }, {\n reactive: false,\n }).map(item => item.id);\n collection.batch(() => {\n // update all items that are in the snapshot\n snapshot.forEach((item) => {\n const itemExists = !!collection.findOne({\n id: item.id,\n }, {\n reactive: false,\n });\n /* istanbul ignore else -- @preserve */\n if (itemExists) {\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n collection.updateOne({ id: item.id }, { $set: item });\n }\n else { // this case should never happen\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n collection.insert(item);\n }\n });\n // remove all items that are not in the snapshot\n nonExistingItemIds.forEach((id) => {\n collection.removeOne({ id });\n });\n });\n });\n }\n}\n"],"names":["debounce","fn","wait","options","timeout","result","leading","trailing","debounced","args","shouldCallImmediately","shouldCallTrailing","PromiseQueue","__publicField","task","resolve","reject","error","computeChanges","oldItems","newItems","added","modified","removed","oldItemsMap","item","newItemsMap","id","oldItem","newItem","isEqual","getSnapshot","lastSnapshot","data","items","index","i","applyChanges","changes","collection","Collection","change","selector","itemExists","modify","hasChanges","hasDifference","sync","pull","push","insert","update","remove","batch","newData","previousSnapshot","newSnapshot","lastSnapshotWithChanges","newSnapshotWithChanges","changesToPush","newChanges","SyncManager","randomId","name","reactivity","changesPersistence","snapshotsPersistence","syncOperationsPersistence","errorHandler","handler","collectionParameters","hasRemoteChange","remoteChange","removeRemoteChange","modifier","cleanupFunction","syncTime","syncId","errors","collectionOptions","readyPromise","hasActiveSyncs","doSync","lastFinishedSync","currentChanges","itemId","snapshot","c","nonExistingItemIds"],"mappings":"wbASA,SAAwBA,EAASC,EAAIC,EAAMC,EAAU,CAAA,EAAI,CACjD,IAAAC,EACAC,EACJ,KAAM,CAAE,QAAAC,EAAU,GAAO,SAAAC,EAAW,EAAS,EAAAJ,EAO7C,SAASK,KAAaC,EAAM,CAClB,MAAAC,EAAwBJ,GAAW,CAACF,EACpCO,EAAqBJ,GAAY,CAACH,EACxC,OAAIA,GACA,aAAaA,CAAO,EAExB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debounce.ts","../src/utils/PromiseQueue.ts","../src/computeChanges.ts","../src/getSnapshot.ts","../src/applyChanges.ts","../src/sync.ts","../src/SyncManager.ts"],"sourcesContent":["/**\n * Debounces a function.\n * @param fn Function to debounce\n * @param wait Time to wait before calling the function.\n * @param [options] Debounce options\n * @param [options.leading] Whether to call the function on the leading edge of the wait interval.\n * @param [options.trailing] Whether to call the function on the trailing edge of the wait interval.\n * @returns The debounced function.\n */\nexport default function debounce(fn, wait, options = {}) {\n let timeout;\n let result;\n const { leading = false, trailing = true } = options;\n /**\n * The debounced function that will be returned.\n * @param this The context to bind the function to.\n * @param args The arguments to pass to the function.\n * @returns The result of the debounced function.\n */\n function debounced(...args) {\n const shouldCallImmediately = leading && !timeout;\n const shouldCallTrailing = trailing && !timeout;\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n timeout = null;\n if (trailing && !shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n }, wait);\n if (shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n else if (!shouldCallTrailing) {\n result = null;\n }\n return result;\n }\n return debounced;\n}\n","/**\n * Class for queuing promises to be executed one after the other.\n * This is useful for tasks that should not be executed in parallel.\n * @example\n * const queue = new PromiseQueue();\n * queue.add(() => fetch('https://example.com/api/endpoint1'));\n * queue.add(() => fetch('https://example.com/api/endpoint2'));\n * // The second fetch will only be executed after the first one is done.\n */\nexport default class PromiseQueue {\n queue = [];\n pendingPromise = false;\n /**\n * Method to add a new promise to the queue and returns a promise that resolves when this task is done\n * @param task Function that returns a promise that will be added to the queue\n * @returns Promise that resolves when the task is done\n */\n add(task) {\n return new Promise((resolve, reject) => {\n // Wrap the task with the resolve and reject to control its completion from the outside\n this.queue.push(() => task()\n .then(resolve)\n .catch((error) => {\n reject(error);\n throw error;\n }));\n this.dequeue();\n });\n }\n /**\n * Method to check if there is a pending promise in the queue\n * @returns True if there is a pending promise, false otherwise\n */\n hasPendingPromise() {\n return this.pendingPromise;\n }\n /**\n * Method to process the queue\n */\n dequeue() {\n if (this.pendingPromise || this.queue.length === 0) {\n return;\n }\n const task = this.queue.shift();\n if (!task)\n return;\n this.pendingPromise = true;\n task()\n .then(() => {\n this.pendingPromise = false;\n this.dequeue();\n })\n .catch(() => {\n this.pendingPromise = false;\n this.dequeue();\n });\n }\n}\n","import { isEqual } from '@signaldb/core';\n/**\n * Compute changes between two arrays of items.\n * @param oldItems Array of the old items\n * @param newItems Array of the new items\n * @returns The changeset\n */\nexport default function computeChanges(oldItems, newItems) {\n const added = [];\n const modified = [];\n const removed = [];\n const oldItemsMap = new Map(oldItems.map(item => [item.id, item]));\n const newItemsMap = new Map(newItems.map(item => [item.id, item]));\n for (const [id, oldItem] of oldItemsMap) {\n const newItem = newItemsMap.get(id);\n if (!newItem) {\n removed.push(oldItem);\n }\n else if (!isEqual(newItem, oldItem)) {\n modified.push(newItem);\n }\n }\n for (const [id, newItem] of newItemsMap) {\n if (!oldItemsMap.has(id)) {\n added.push(newItem);\n }\n }\n return { added, modified, removed };\n}\n","/**\n * Gets the snapshot of items from the last snapshot and the changes.\n * @param lastSnapshot The last snapshot of items\n * @param data The changes to apply to the last snapshot\n * @returns The new snapshot of items\n */\nexport default function getSnapshot(lastSnapshot, data) {\n if (data.items != null)\n return data.items;\n const items = lastSnapshot || [];\n data.changes.added.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.modified.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.removed.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index !== -1)\n items.splice(index, 1);\n });\n return items;\n}\n","import { Collection, modify } from '@signaldb/core';\n/**\n * applies changes to a collection of items\n * @param items The items to apply the changes to\n * @param changes The changes to apply to the items\n * @returns The new items after applying the changes\n */\nexport default async function applyChanges(items, changes) {\n const collection = new Collection();\n collection.batch(() => {\n items.forEach(item => collection.insert(item));\n changes.forEach((change) => {\n if (change.type === 'remove') {\n collection.removeOne({ id: change.data });\n return;\n }\n const selector = { id: change.data.id };\n const itemExists = collection.findOne(selector);\n if (change.type === 'insert') {\n if (itemExists) { // update item if it alread exists\n collection.updateOne(selector, { $set: change.data });\n }\n else { // insert item if it does not exist\n collection.insert(change.data);\n }\n return;\n }\n // change.type === 'update'\n if (itemExists) { // update item if it exists\n collection.updateOne(selector, change.data.modifier);\n }\n else { // insert item if it does not exist\n collection.insert(modify(selector, change.data.modifier));\n }\n });\n });\n const result = collection.find().fetch();\n await collection.dispose();\n return result;\n}\n","import computeChanges from './computeChanges';\nimport getSnapshot from './getSnapshot';\nimport applyChanges from './applyChanges';\n/**\n * Checks if there are any changes in the given changeset.\n * @param changes The changeset to check.\n * @returns True if there are changes, false otherwise.\n */\nfunction hasChanges(changes) {\n return changes.added.length > 0\n || changes.modified.length > 0\n || changes.removed.length > 0;\n}\n/**\n * Checks if there is a difference between the old items and the new items.\n * @param oldItems The old items.\n * @param newItems The new items.\n * @returns True if there is a difference, false otherwise.\n */\nfunction hasDifference(oldItems, newItems) {\n return hasChanges(computeChanges(oldItems, newItems));\n}\n/**\n * Does a sync operation based on the provided options. If changes are supplied, these will be rebased on the new data.\n * Afterwards the push method will be called with the remaining changes. A new snapshot will be created and returned.\n * @param options Sync options\n * @param options.changes Changes to call the push method with\n * @param [options.lastSnapshot] The last snapshot\n * @param options.data The new data\n * @param options.pull Method to pull new data\n * @param options.push Method to push changes\n * @param options.insert Method to insert an item\n * @param options.update Method to update an item\n * @param options.remove Method to remove an item\n * @param options.batch Method to batch multiple operations\n * @returns The new snapshot\n */\nexport default async function sync({ changes, lastSnapshot, data, pull, push, insert, update, remove, batch, }) {\n let newData = data;\n let previousSnapshot = lastSnapshot || [];\n let newSnapshot = getSnapshot(lastSnapshot, newData);\n if (changes.length > 0) {\n // apply changes on last snapshot and check if there is a difference\n const lastSnapshotWithChanges = await applyChanges(previousSnapshot, changes);\n if (hasDifference(previousSnapshot, lastSnapshotWithChanges)) {\n // if yes, apply the changes on the newSnapshot and check if there is a difference\n const newSnapshotWithChanges = await applyChanges(newSnapshot, changes);\n const changesToPush = computeChanges(newSnapshot, newSnapshotWithChanges);\n if (hasChanges(changesToPush)) {\n // if yes, push the changes to the server\n await push(changesToPush);\n // pull new data afterwards to ensure that all server changes are applied\n newData = await pull();\n newSnapshot = getSnapshot(newSnapshot, newData);\n }\n previousSnapshot = lastSnapshotWithChanges;\n }\n }\n // apply the new changes on the collection\n const newChanges = newData.changes == null\n ? computeChanges(previousSnapshot, newData.items)\n : newData.changes;\n batch(() => {\n newChanges.added.forEach(item => insert(item));\n newChanges.modified.forEach(item => update(item.id, { $set: item }));\n newChanges.removed.forEach(item => remove(item.id));\n });\n return newSnapshot;\n}\n","import { Collection, randomId, isEqual, createIndex } from '@signaldb/core';\nimport debounce from './utils/debounce';\nimport PromiseQueue from './utils/PromiseQueue';\nimport sync from './sync';\n/**\n * Class to manage syncing of collections.\n * @template CollectionOptions\n * @template ItemType\n * @template IdType\n * @example\n * const syncManager = new SyncManager({\n * pull: async (collectionOptions) => {\n * const response = await fetch(`/api/collections/${collectionOptions.name}`)\n * return await response.json()\n * },\n * push: async (collectionOptions, { changes }) => {\n * await fetch(`/api/collections/${collectionOptions.name}`, {\n * method: 'POST',\n * body: JSON.stringify(changes),\n * })\n * },\n * })\n *\n * const collection = new Collection()\n * syncManager.addCollection(collection, {\n * name: 'todos',\n * })\n *\n * syncManager.sync('todos')\n */\nexport default class SyncManager {\n options;\n collections = new Map();\n changes;\n snapshots;\n syncOperations;\n remoteChanges = [];\n syncQueues = new Map();\n persistenceReady;\n isDisposed = false;\n instanceId = randomId();\n id;\n /**\n * @param options Collection options\n * @param options.pull Function to pull data from remote source.\n * @param options.push Function to push data to remote source.\n * @param [options.registerRemoteChange] Function to register a callback for remote changes.\n * @param [options.id] Unique identifier for this sync manager. Only nessesary if you have multiple sync managers.\n * @param [options.persistenceAdapter] Persistence adapter to use for storing changes, snapshots and sync operations.\n * @param [options.reactivity] Reactivity adapter to use for reactivity.\n * @param [options.onError] Function to handle errors that occur async during syncing.\n */\n constructor(options) {\n this.options = {\n autostart: true,\n ...options,\n };\n this.id = this.options.id || 'default-sync-manager';\n const { reactivity } = this.options;\n const changesPersistence = this.createPersistenceAdapter('changes');\n const snapshotsPersistence = this.createPersistenceAdapter('snapshots');\n const syncOperationsPersistence = this.createPersistenceAdapter('sync-operations');\n this.changes = new Collection({\n name: `${this.options.id}-changes`,\n persistence: changesPersistence?.adapter,\n indices: [createIndex('collectionName')],\n reactivity,\n });\n this.snapshots = new Collection({\n name: `${this.options.id}-snapshots`,\n persistence: snapshotsPersistence?.adapter,\n indices: [createIndex('collectionName')],\n reactivity,\n });\n this.syncOperations = new Collection({\n name: `${this.options.id}-sync-operations`,\n persistence: syncOperationsPersistence?.adapter,\n indices: [createIndex('collectionName'), createIndex('status')],\n reactivity,\n });\n this.changes.on('persistence.error', error => changesPersistence?.handler(error));\n this.snapshots.on('persistence.error', error => snapshotsPersistence?.handler(error));\n this.syncOperations.on('persistence.error', error => syncOperationsPersistence?.handler(error));\n this.persistenceReady = Promise.all([\n this.syncOperations.isReady(),\n this.changes.isReady(),\n this.snapshots.isReady(),\n ]).then(() => { });\n this.changes.setMaxListeners(1000);\n this.snapshots.setMaxListeners(1000);\n this.syncOperations.setMaxListeners(1000);\n }\n createPersistenceAdapter(name) {\n if (this.options.persistenceAdapter == null)\n return;\n let errorHandler = () => { };\n const adapter = this.options.persistenceAdapter(`${this.id}-${name}`, (handler) => {\n errorHandler = handler;\n });\n return {\n adapter,\n handler: (error) => errorHandler(error),\n };\n }\n getSyncQueue(name) {\n if (this.syncQueues.get(name) == null) {\n this.syncQueues.set(name, new PromiseQueue());\n }\n return this.syncQueues.get(name);\n }\n /**\n * Clears all internal data structures\n */\n async dispose() {\n this.collections.clear();\n this.syncQueues.clear();\n this.remoteChanges.splice(0, this.remoteChanges.length);\n await Promise.all([\n this.changes.dispose(),\n this.snapshots.dispose(),\n this.syncOperations.dispose(),\n ]);\n this.isDisposed = true;\n }\n /**\n * Gets a collection with it's options by name\n * @deprecated Use getCollectionProperties instead.\n * @param name Name of the collection\n * @throws Will throw an error if the name wasn't found\n * @returns Tuple of collection and options\n */\n getCollection(name) {\n const { collection, options } = this.getCollectionProperties(name);\n return [collection, options];\n }\n /**\n * Gets collection options by name\n * @param name Name of the collection\n * @throws Will throw an error if the name wasn't found\n * @returns An object of all properties of the collection\n */\n getCollectionProperties(name) {\n const collectionParameters = this.collections.get(name);\n if (collectionParameters == null)\n throw new Error(`Collection with id '${name}' not found`);\n return collectionParameters;\n }\n /**\n * Adds a collection to the sync manager.\n * @param collection Collection to add\n * @param options Options for the collection. The object needs at least a `name` property.\n * @param options.name Unique name of the collection\n */\n addCollection(collection, options) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n this.collections.set(options.name, {\n collection,\n options,\n readyPromise: collection.isReady(),\n syncPaused: true, // always start paused as the autostart will start it\n });\n const hasRemoteChange = (change) => {\n for (const remoteChange of this.remoteChanges) {\n if (isEqual(remoteChange, change)) {\n return true;\n }\n }\n return false;\n };\n const removeRemoteChange = (change) => {\n for (let i = 0; i < this.remoteChanges.length; i += 1) {\n if (isEqual(this.remoteChanges[i], change)) {\n this.remoteChanges.splice(i, 1);\n return;\n }\n }\n };\n collection.on('added', (item) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'insert', data: item })) {\n removeRemoteChange({ collectionName: options.name, type: 'insert', data: item });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'insert',\n data: item,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n collection.on('changed', ({ id }, modifier) => {\n const data = { id, modifier };\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'update', data })) {\n removeRemoteChange({ collectionName: options.name, type: 'update', data });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'update',\n data,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n collection.on('removed', ({ id }) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'remove', data: id })) {\n removeRemoteChange({ collectionName: options.name, type: 'remove', data: id });\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'remove',\n data: id,\n });\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n });\n if (this.options.autostart) {\n this.startSync(options.name)\n .catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n }\n }\n deboucedPush = debounce((name) => {\n this.pushChanges(name).catch(() => { });\n }, 100);\n schedulePush(name) {\n this.deboucedPush(name);\n }\n /**\n * Setup all collections to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n */\n async startAll() {\n await Promise.all([...this.collections.keys()].map(id => this.startSync(id)));\n }\n /**\n * Setup a collection to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n * @param name Name of the collection\n */\n async startSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (!collectionParameters.syncPaused)\n return; // already started\n this.schedulePush(name); // push changes that were made while paused\n const cleanupFunction = this.options.registerRemoteChange\n ? await this.options.registerRemoteChange(collectionParameters.options, async (data) => {\n if (data == null) {\n await this.sync(name);\n }\n else {\n const syncTime = Date.now();\n const syncId = this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n await this.syncWithData(name, data)\n .then(() => {\n // clean up old sync operations\n this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n })\n .catch((error) => {\n if (this.options.onError) {\n this.options.onError(this.getCollectionProperties(name).options, error);\n }\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n throw error;\n });\n }\n })\n : undefined;\n this.collections.set(name, {\n ...collectionParameters,\n syncPaused: false,\n cleanupFunction,\n });\n }\n /**\n * Pauses the sync process for all collections.\n * This means that the collections will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n */\n async pauseAll() {\n await Promise.all([...this.collections.keys()].map(id => this.pauseSync(id)));\n }\n /**\n * Pauses the sync process for a collection.\n * This means that the collection will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n * @param name Name of the collection\n */\n async pauseSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (collectionParameters.syncPaused)\n return; // already paused\n if (collectionParameters.cleanupFunction)\n await collectionParameters.cleanupFunction();\n this.collections.set(name, {\n ...collectionParameters,\n cleanupFunction: undefined,\n syncPaused: true,\n });\n }\n /**\n * Starts the sync process for all collections\n */\n async syncAll() {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n const errors = [];\n await Promise.all([...this.collections.keys()].map(id => this.sync(id).catch((error) => {\n errors.push({ id, error });\n })));\n if (errors.length > 0)\n throw new Error(`Error while syncing collections:\\n${errors.map(error => `${error.id}: ${error.error.message}`).join('\\n\\n')}`);\n }\n /**\n * Checks if a collection is currently beeing synced\n * @param [name] Name of the collection. If not provided, it will check if any collection is currently beeing synced.\n * @returns True if the collection is currently beeing synced, false otherwise.\n */\n isSyncing(name) {\n return this.syncOperations.findOne({\n ...name ? { collectionName: name } : {},\n status: 'active',\n }, { fields: { status: 1 } }) != null;\n }\n /**\n * Checks if the sync manager is ready to sync.\n * @returns A promise that resolves when the sync manager is ready to sync.\n */\n async isReady() {\n await this.persistenceReady;\n }\n /**\n * Starts the sync process for a collection\n * @param name Name of the collection\n * @param options Options for the sync process.\n * @param options.force If true, the sync process will be started even if there are no changes and onlyWithChanges is true.\n * @param options.onlyWithChanges If true, the sync process will only be started if there are changes.\n */\n async sync(name, options = {}) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n await this.isReady();\n const { options: collectionOptions, readyPromise } = this.getCollectionProperties(name);\n await readyPromise;\n const hasActiveSyncs = this.syncOperations.find({\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n }, {\n reactive: false,\n }).count() > 0;\n const syncTime = Date.now();\n let syncId = null;\n // schedule for next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const doSync = async () => {\n const lastFinishedSync = this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n });\n if (options?.onlyWithChanges) {\n const currentChanges = this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n }).count();\n if (currentChanges === 0)\n return;\n }\n if (!hasActiveSyncs) {\n syncId = this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n }\n const data = await this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n });\n await this.syncWithData(name, data);\n };\n await (options?.force ? doSync() : this.getSyncQueue(name).add(doSync))\n .catch((error) => {\n if (syncId != null) {\n if (this.options.onError)\n this.options.onError(collectionOptions, error);\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n }\n throw error;\n });\n if (syncId != null) {\n // clean up old sync operations\n this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n }\n }\n /**\n * Starts the push process for a collection (sync process but only if there are changes)\n * @param name Name of the collection\n */\n async pushChanges(name) {\n await this.sync(name, {\n onlyWithChanges: true,\n });\n }\n async syncWithData(name, data) {\n const { collection, options: collectionOptions } = this.getCollectionProperties(name);\n const syncTime = Date.now();\n const lastFinishedSync = this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n });\n const lastSnapshot = this.snapshots.findOne({\n collectionName: name,\n }, {\n sort: { time: -1 },\n reactive: false,\n });\n const currentChanges = this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n }).fetch();\n await sync({\n changes: currentChanges,\n lastSnapshot: lastSnapshot?.items,\n data,\n pull: () => this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n }),\n push: changes => this.options.push(collectionOptions, { changes }),\n insert: (item) => {\n const itemExists = item.id && !!collection.findOne({\n id: item.id,\n }, { reactive: false });\n if (itemExists) {\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // update the item if it already exists\n collection.updateOne({ id: item.id }, { $set: item });\n return;\n }\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n collection.insert(item);\n },\n update: (itemId, modifier) => {\n const itemExists = itemId && !collection.findOne({\n id: itemId,\n }, { reactive: false });\n if (itemExists) {\n const item = { ...modifier.$set, id: itemId };\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n // insert the item if it does not exist\n collection.insert(item);\n return;\n }\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: itemId, modifier },\n });\n collection.updateOne({ id: itemId }, modifier);\n },\n remove: (itemId) => {\n const itemExists = !!collection.findOne({\n id: itemId,\n }, { reactive: false });\n if (!itemExists)\n return;\n this.remoteChanges.push({\n collectionName: name,\n type: 'remove',\n data: itemId,\n });\n collection.removeOne({ id: itemId });\n },\n batch: (fn) => {\n collection.batch(() => {\n fn();\n });\n },\n })\n .then(async (snapshot) => {\n // clean up old snapshots\n this.snapshots.removeMany({\n collectionName: name,\n time: { $lte: syncTime },\n });\n // clean up processed changes\n this.changes.removeMany({\n collectionName: name,\n id: { $in: currentChanges.map(c => c.id) },\n });\n // insert new snapshot\n this.snapshots.insert({\n time: syncTime,\n collectionName: name,\n items: snapshot,\n });\n // delay sync operation update to next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const hasChanges = this.changes.find({\n collectionName: name,\n }, { reactive: false }).count() > 0;\n if (hasChanges) {\n // check if there are unsynced changes to push\n // and sync again if there are any\n await this.sync(name, {\n force: true,\n onlyWithChanges: true,\n });\n return;\n }\n // if there are no unsynced changes apply the last snapshot\n // to make sure that collection and snapshot are in sync\n // find all items that are not in the snapshot\n const nonExistingItemIds = collection.find({\n id: { $nin: snapshot.map(item => item.id) },\n }, {\n reactive: false,\n }).map(item => item.id);\n collection.batch(() => {\n // update all items that are in the snapshot\n snapshot.forEach((item) => {\n const itemExists = !!collection.findOne({\n id: item.id,\n }, {\n reactive: false,\n });\n /* istanbul ignore else -- @preserve */\n if (itemExists) {\n this.remoteChanges.push({\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n collection.updateOne({ id: item.id }, { $set: item });\n }\n else { // this case should never happen\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n });\n collection.insert(item);\n }\n });\n // remove all items that are not in the snapshot\n nonExistingItemIds.forEach((id) => {\n collection.removeOne({ id });\n });\n });\n });\n }\n}\n"],"names":["debounce","fn","wait","options","timeout","result","leading","trailing","debounced","args","shouldCallImmediately","shouldCallTrailing","PromiseQueue","__publicField","task","resolve","reject","error","computeChanges","oldItems","newItems","added","modified","removed","oldItemsMap","item","newItemsMap","id","oldItem","newItem","isEqual","getSnapshot","lastSnapshot","data","items","index","i","applyChanges","changes","collection","Collection","change","selector","itemExists","modify","hasChanges","hasDifference","sync","pull","push","insert","update","remove","batch","newData","previousSnapshot","newSnapshot","lastSnapshotWithChanges","newSnapshotWithChanges","changesToPush","newChanges","SyncManager","randomId","name","reactivity","changesPersistence","snapshotsPersistence","syncOperationsPersistence","createIndex","errorHandler","handler","collectionParameters","hasRemoteChange","remoteChange","removeRemoteChange","modifier","cleanupFunction","syncTime","syncId","errors","collectionOptions","readyPromise","hasActiveSyncs","doSync","lastFinishedSync","currentChanges","itemId","snapshot","c","nonExistingItemIds"],"mappings":"wbASA,SAAwBA,EAASC,EAAIC,EAAMC,EAAU,CAAA,EAAI,CACjD,IAAAC,EACAC,EACJ,KAAM,CAAE,QAAAC,EAAU,GAAO,SAAAC,EAAW,EAAS,EAAAJ,EAO7C,SAASK,KAAaC,EAAM,CAClB,MAAAC,EAAwBJ,GAAW,CAACF,EACpCO,EAAqBJ,GAAY,CAACH,EACxC,OAAIA,GACA,aAAaA,CAAO,EAExBA,EAAU,WAAW,IAAM,CACbA,EAAA,KACNG,GAAY,CAACG,IACJL,EAAAJ,EAAG,MAAM,KAAMQ,CAAI,IAEjCP,CAAI,EACHQ,EACSL,EAAAJ,EAAG,MAAM,KAAMQ,CAAI,EAEtBE,IACGN,EAAA,MAENA,CAAA,CAEJ,OAAAG,CACX,CC/BA,MAAqBI,CAAa,CAAlC,cACIC,EAAA,aAAQ,CAAC,GACTA,EAAA,sBAAiB,IAMjB,IAAIC,EAAM,CACN,OAAO,IAAI,QAAQ,CAACC,EAASC,IAAW,CAE/B,KAAA,MAAM,KAAK,IAAMF,EAAK,EACtB,KAAKC,CAAO,EACZ,MAAOE,GAAU,CAClB,MAAAD,EAAOC,CAAK,EACNA,CAAA,CACT,CAAC,EACF,KAAK,QAAQ,CAAA,CAChB,CAAA,CAML,mBAAoB,CAChB,OAAO,KAAK,cAAA,CAKhB,SAAU,CACN,GAAI,KAAK,gBAAkB,KAAK,MAAM,SAAW,EAC7C,OAEE,MAAAH,EAAO,KAAK,MAAM,MAAM,EACzBA,IAEL,KAAK,eAAiB,GACjBA,EAAA,EACA,KAAK,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AAK,EAAE,EACtBc,EAAW,MAAM,IAAM,CAEVgD,EAAA,QAAS9D,GAAS,CACvB,MAAMkB,EAAa,CAAC,CAACJ,EAAW,QAAQ,CACpC,GAAId,EAAK,EAAA,EACV,CACC,SAAU,EAAA,CACb,EAAA,uCAEGkB,GACA,KAAK,cAAc,KAAK,CACpB,eAAgBoB,EAChB,KAAM,SACN,KAAM,CAAE,GAAItC,EAAK,GAAI,SAAU,CAAE,KAAMA,CAAO,CAAA,CAAA,CACjD,EACUc,EAAA,UAAU,CAAE,GAAId,EAAK,IAAM,CAAE,KAAMA,EAAM,IAGpD,KAAK,cAAc,KAAK,CACpB,eAAgBsC,EAChB,KAAM,SACN,KAAMtC,CAAA,CACT,EACDc,EAAW,OAAOd,CAAI,EAC1B,CACH,EAEkBgE,EAAA,QAAS9D,GAAO,CACpBY,EAAA,UAAU,CAAE,GAAAZ,EAAI,CAAA,CAC9B,CAAA,CACJ,CAAA,CACJ,CAAA,CAET"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@signaldb/sync",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "build": "rimraf dist && vite build"