dexie-cloud-addon 4.0.1-beta.35 → 4.0.1-beta.37

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.
@@ -101,7 +101,7 @@ function __spreadArray$1(to, from, pack) {
101
101
  *
102
102
  * ==========================================================================
103
103
  *
104
- * Version 4.0.1-beta.35, Tue Apr 11 2023
104
+ * Version 4.0.1-beta.37, Mon Apr 17 2023
105
105
  *
106
106
  * https://dexie.org
107
107
  *
@@ -2740,7 +2740,7 @@ function login(db, hints) {
2740
2740
  }
2741
2741
  }
2742
2742
  // Already authenticated according to given hints.
2743
- return [2 /*return*/];
2743
+ return [2 /*return*/, false];
2744
2744
  }
2745
2745
  context = new AuthPersistedContext(db, {
2746
2746
  claims: {},
@@ -2773,7 +2773,7 @@ function login(db, hints) {
2773
2773
  // Make sure to resync as the new login will be authorized
2774
2774
  // for new realms.
2775
2775
  triggerSync(db, "pull");
2776
- return [2 /*return*/];
2776
+ return [2 /*return*/, true];
2777
2777
  }
2778
2778
  });
2779
2779
  });
@@ -2849,6 +2849,36 @@ var SWBroadcastChannel = /** @class */ (function () {
2849
2849
  };
2850
2850
  return SWBroadcastChannel;
2851
2851
  }());
2852
+ var events = globalThis['lbc-events'] || (globalThis['lbc-events'] = new Map());
2853
+ function addListener(name, listener) {
2854
+ if (events.has(name)) {
2855
+ events.get(name).push(listener);
2856
+ }
2857
+ else {
2858
+ events.set(name, [listener]);
2859
+ }
2860
+ }
2861
+ function removeListener(name, listener) {
2862
+ var listeners = events.get(name);
2863
+ if (listeners) {
2864
+ var idx = listeners.indexOf(listener);
2865
+ if (idx !== -1) {
2866
+ listeners.splice(idx, 1);
2867
+ }
2868
+ }
2869
+ }
2870
+ function dispatch(ev) {
2871
+ var listeners = events.get(ev.type);
2872
+ if (listeners) {
2873
+ listeners.forEach(function (listener) {
2874
+ try {
2875
+ listener(ev);
2876
+ }
2877
+ catch (_a) {
2878
+ }
2879
+ });
2880
+ }
2881
+ }
2852
2882
  var BroadcastedAndLocalEvent = /** @class */ (function (_super_1) {
2853
2883
  __extends$1(BroadcastedAndLocalEvent, _super_1);
2854
2884
  function BroadcastedAndLocalEvent(name) {
@@ -2864,16 +2894,24 @@ var BroadcastedAndLocalEvent = /** @class */ (function (_super_1) {
2864
2894
  subscriber.next(ev.data);
2865
2895
  }
2866
2896
  var unsubscribe;
2867
- self.addEventListener("lbc-".concat(name), onCustomEvent);
2868
- if (bc instanceof SWBroadcastChannel) {
2869
- unsubscribe = bc.subscribe(function (message) { return subscriber.next(message); });
2897
+ //self.addEventListener(`lbc-${name}`, onCustomEvent); // Fails in service workers
2898
+ addListener("lbc-".concat(name), onCustomEvent); // Works better in service worker
2899
+ try {
2900
+ if (bc instanceof SWBroadcastChannel) {
2901
+ unsubscribe = bc.subscribe(function (message) { return subscriber.next(message); });
2902
+ }
2903
+ else {
2904
+ console.debug("BroadcastedAndLocalEvent: bc.addEventListener()", name, "bc is a", bc);
2905
+ bc.addEventListener("message", onMessageEvent);
2906
+ }
2870
2907
  }
2871
- else {
2872
- console.debug("BroadcastedAndLocalEvent: bc.addEventListener()", name, "bc is a", bc);
2873
- bc.addEventListener("message", onMessageEvent);
2908
+ catch (err) {
2909
+ // Service workers might fail to subscribe outside its initial script.
2910
+ console.warn('Failed to subscribe to broadcast channel', err);
2874
2911
  }
2875
2912
  return function () {
2876
- self.removeEventListener("lbc-".concat(name), onCustomEvent);
2913
+ //self.removeEventListener(`lbc-${name}`, onCustomEvent);
2914
+ removeListener("lbc-".concat(name), onCustomEvent);
2877
2915
  if (bc instanceof SWBroadcastChannel) {
2878
2916
  unsubscribe();
2879
2917
  }
@@ -2890,7 +2928,8 @@ var BroadcastedAndLocalEvent = /** @class */ (function (_super_1) {
2890
2928
  console.debug("BroadcastedAndLocalEvent: bc.postMessage()", Object.assign({}, message), "bc is a", this.bc);
2891
2929
  this.bc.postMessage(message);
2892
2930
  var ev = new CustomEvent("lbc-".concat(this.name), { detail: message });
2893
- self.dispatchEvent(ev);
2931
+ //self.dispatchEvent(ev);
2932
+ dispatch(ev);
2894
2933
  };
2895
2934
  return BroadcastedAndLocalEvent;
2896
2935
  }(Observable$1));
@@ -3712,7 +3751,10 @@ function encodeIdsForServer(schema, currentUser, changes) {
3712
3751
  function cloneChange(change, rewriteValues) {
3713
3752
  // clone on demand:
3714
3753
  return Object.assign(Object.assign({}, change), { muts: rewriteValues
3715
- ? change.muts.map(function (m) { return (Object.assign(Object.assign({}, m), { keys: m.keys.slice(), values: m.values.slice() })); })
3754
+ ? change.muts.map(function (m) {
3755
+ return (m.type === 'insert' || m.type === 'upsert') && m.values
3756
+ ? Object.assign(Object.assign({}, m), { keys: m.keys.slice(), values: m.values.slice() }) : Object.assign(Object.assign({}, m), { keys: m.keys.slice() });
3757
+ })
3716
3758
  : change.muts.map(function (m) { return (Object.assign(Object.assign({}, m), { keys: m.keys.slice() })); }) });
3717
3759
  }
3718
3760
  //import {BisonWebStreamReader} from "dreambase-library/dist/typeson-simplified/BisonWebStreamReader";
@@ -4072,7 +4114,7 @@ function sync(db, options, schema, syncOptions) {
4072
4114
  return _sync
4073
4115
  .apply(this, arguments)
4074
4116
  .then(function () {
4075
- if (!(syncOptions === null || syncOptions === void 0 ? void 0 : syncOptions.justCheckIfNeeded)) {
4117
+ if (!(syncOptions === null || syncOptions === void 0 ? void 0 : syncOptions.justCheckIfNeeded)) { // && syncOptions?.purpose !== 'push') {
4076
4118
  db.syncStateChangedEvent.next({
4077
4119
  phase: 'in-sync',
4078
4120
  });
@@ -4130,7 +4172,7 @@ function _sync(db, options, schema, _k) {
4130
4172
  } : _k, isInitialSync = _l.isInitialSync, cancelToken = _l.cancelToken, justCheckIfNeeded = _l.justCheckIfNeeded, purpose = _l.purpose;
4131
4173
  var _a;
4132
4174
  return __awaiter(this, void 0, void 0, function () {
4133
- var databaseUrl, currentUser, tablesToSync, mutationTables, persistedSyncState, readyForSyncification, tablesToSyncify, doSyncify, _k, clientChangeSet, syncState, baseRevs, syncIsNeeded, latestRevisions, clientIdentity, res, done;
4175
+ var databaseUrl, currentUser, tablesToSync, mutationTables, persistedSyncState, readyForSyncification, tablesToSyncify, doSyncify, _k, clientChangeSet, syncState, baseRevs, pushSyncIsNeeded, latestRevisions, clientIdentity, res, done;
4134
4176
  var _this_1 = this;
4135
4177
  return __generator$1(this, function (_l) {
4136
4178
  switch (_l.label) {
@@ -4207,12 +4249,12 @@ function _sync(db, options, schema, _k) {
4207
4249
  }); })];
4208
4250
  case 5:
4209
4251
  _k = _l.sent(), clientChangeSet = _k[0], syncState = _k[1], baseRevs = _k[2];
4210
- syncIsNeeded = clientChangeSet.some(function (set) { return set.muts.some(function (mut) { return mut.keys.length > 0; }); });
4252
+ pushSyncIsNeeded = clientChangeSet.some(function (set) { return set.muts.some(function (mut) { return mut.keys.length > 0; }); });
4211
4253
  if (justCheckIfNeeded) {
4212
- console.debug('Sync is needed:', syncIsNeeded);
4213
- return [2 /*return*/, syncIsNeeded];
4254
+ console.debug('Sync is needed:', pushSyncIsNeeded);
4255
+ return [2 /*return*/, pushSyncIsNeeded];
4214
4256
  }
4215
- if (purpose === 'push' && !syncIsNeeded) {
4257
+ if (purpose === 'push' && !pushSyncIsNeeded) {
4216
4258
  // The purpose of this request was to push changes
4217
4259
  return [2 /*return*/, false];
4218
4260
  }
@@ -4387,6 +4429,7 @@ function _sync(db, options, schema, _k) {
4387
4429
  case 8: return [2 /*return*/, _l.sent()];
4388
4430
  case 9:
4389
4431
  console.debug('SYNC DONE', { isInitialSync: isInitialSync });
4432
+ db.syncCompleteEvent.next();
4390
4433
  return [2 /*return*/, false]; // Not needed anymore
4391
4434
  }
4392
4435
  });
@@ -4780,6 +4823,7 @@ function DexieCloudDB(dx) {
4780
4823
  if (!db) {
4781
4824
  var localSyncEvent = new Subject();
4782
4825
  var syncStateChangedEvent_1 = new BroadcastedAndLocalEvent("syncstatechanged-".concat(dx.name));
4826
+ var syncCompleteEvent_1 = new BroadcastedAndLocalEvent("synccomplete-".concat(dx.name));
4783
4827
  localSyncEvent['id'] = ++static_counter;
4784
4828
  var initiallySynced_1 = false;
4785
4829
  db = {
@@ -4823,6 +4867,9 @@ function DexieCloudDB(dx) {
4823
4867
  get syncStateChangedEvent() {
4824
4868
  return syncStateChangedEvent_1;
4825
4869
  },
4870
+ get syncCompleteEvent() {
4871
+ return syncCompleteEvent_1;
4872
+ },
4826
4873
  dx: dx,
4827
4874
  };
4828
4875
  var helperMethods = {
@@ -4855,6 +4902,7 @@ function DexieCloudDB(dx) {
4855
4902
  },
4856
4903
  reconfigure: function () {
4857
4904
  syncStateChangedEvent_1 = new BroadcastedAndLocalEvent("syncstatechanged-".concat(dx.name));
4905
+ syncCompleteEvent_1 = new BroadcastedAndLocalEvent("synccomplete-".concat(dx.name));
4858
4906
  },
4859
4907
  };
4860
4908
  Object.assign(db, helperMethods);
@@ -5788,6 +5836,15 @@ function connectWebSocket(db) {
5788
5836
  switchMap(function (syncState) { return db.cloud.currentUser.pipe(map(function (userLogin) { return [userLogin, syncState]; })); }), switchMap(function (_k) {
5789
5837
  var userLogin = _k[0], syncState = _k[1];
5790
5838
  return userIsReallyActive.pipe(map(function (isActive) { return [isActive ? userLogin : null, syncState]; }));
5839
+ }), switchMap(function (_k) {
5840
+ var userLogin = _k[0], syncState = _k[1];
5841
+ if ((userLogin === null || userLogin === void 0 ? void 0 : userLogin.isLoggedIn) && !(syncState === null || syncState === void 0 ? void 0 : syncState.realms.includes(userLogin.userId))) {
5842
+ // We're in an in-between state when user is logged in but the user's realms are not yet synced.
5843
+ // Don't make this change reconnect the websocket just yet. Wait till syncState is updated
5844
+ // to iclude the user's realm.
5845
+ return db.cloud.persistedSyncState.pipe(filter(function (syncState) { return (syncState === null || syncState === void 0 ? void 0 : syncState.realms.includes(userLogin.userId)) || false; }), take(1), map(function (syncState) { return [userLogin, syncState]; }));
5846
+ }
5847
+ return new BehaviorSubject([userLogin, syncState]);
5791
5848
  }), switchMap(function (_k) {
5792
5849
  var userLogin = _k[0], syncState = _k[1];
5793
5850
  return __awaiter(_this_1, void 0, void 0, function () { var _k; return __generator$1(this, function (_l) {
@@ -6983,8 +7040,9 @@ function dexieCloud(dexie) {
6983
7040
  localSyncWorker = null;
6984
7041
  currentUserEmitter.next(UNAUTHORIZED_USER);
6985
7042
  });
7043
+ var syncComplete = new Subject();
6986
7044
  dexie.cloud = {
6987
- version: '4.0.1-beta.35',
7045
+ version: '4.0.1-beta.37',
6988
7046
  options: Object.assign({}, DEFAULT_OPTIONS),
6989
7047
  schema: null,
6990
7048
  get currentUserId() {
@@ -6995,6 +7053,9 @@ function dexieCloud(dexie) {
6995
7053
  phase: 'initial',
6996
7054
  status: 'not-started',
6997
7055
  }),
7056
+ events: {
7057
+ syncComplete: syncComplete,
7058
+ },
6998
7059
  persistedSyncState: new BehaviorSubject(undefined),
6999
7060
  userInteraction: new BehaviorSubject(undefined),
7000
7061
  webSocketStatus: new BehaviorSubject('not-started'),
@@ -7112,7 +7173,7 @@ function dexieCloud(dexie) {
7112
7173
  function onDbReady(dexie) {
7113
7174
  var _a, _b, _c, _d, _e, _f, _g;
7114
7175
  return __awaiter(this, void 0, void 0, function () {
7115
- var db, swRegistrations, _k, initiallySynced;
7176
+ var db, swRegistrations, _k, initiallySynced, changedUser;
7116
7177
  var _this_1 = this;
7117
7178
  return __generator$1(this, function (_l) {
7118
7179
  switch (_l.label) {
@@ -7128,6 +7189,8 @@ function dexieCloud(dexie) {
7128
7189
  if (!db.cloud.isServiceWorkerDB) {
7129
7190
  subscriptions.push(computeSyncState(db).subscribe(dexie.cloud.syncState));
7130
7191
  }
7192
+ // Forward db.syncCompleteEvent to be publicly consumable via db.cloud.events.syncComplete:
7193
+ subscriptions.push(db.syncCompleteEvent.subscribe(syncComplete));
7131
7194
  //verifyConfig(db.cloud.options); Not needed (yet at least!)
7132
7195
  // Verify the user has allowed version increment.
7133
7196
  if (!db.tables.every(function (table) { return table.core; })) {
@@ -7267,10 +7330,11 @@ function dexieCloud(dexie) {
7267
7330
  _l.sent();
7268
7331
  _l.label = 8;
7269
7332
  case 8:
7333
+ changedUser = false;
7270
7334
  if (!((_c = db.cloud.options) === null || _c === void 0 ? void 0 : _c.requireAuth)) return [3 /*break*/, 10];
7271
7335
  return [4 /*yield*/, login(db)];
7272
7336
  case 9:
7273
- _l.sent();
7337
+ changedUser = _l.sent();
7274
7338
  _l.label = 10;
7275
7339
  case 10:
7276
7340
  if (localSyncWorker)
@@ -7278,7 +7342,7 @@ function dexieCloud(dexie) {
7278
7342
  localSyncWorker = null;
7279
7343
  throwIfClosed();
7280
7344
  if (db.cloud.usingServiceWorker && ((_d = db.cloud.options) === null || _d === void 0 ? void 0 : _d.databaseUrl)) {
7281
- registerSyncEvent(db, 'push').catch(function () { });
7345
+ registerSyncEvent(db, changedUser ? 'pull' : 'push').catch(function () { });
7282
7346
  registerPeriodicSyncEvent(db).catch(function () { });
7283
7347
  }
7284
7348
  else if (((_e = db.cloud.options) === null || _e === void 0 ? void 0 : _e.databaseUrl) &&
@@ -7287,7 +7351,7 @@ function dexieCloud(dexie) {
7287
7351
  // There's no SW. Start SyncWorker instead.
7288
7352
  localSyncWorker = LocalSyncWorker(db, db.cloud.options, db.cloud.schema);
7289
7353
  localSyncWorker.start();
7290
- triggerSync(db, 'push');
7354
+ triggerSync(db, changedUser ? 'pull' : 'push');
7291
7355
  }
7292
7356
  // Listen to online event and do sync.
7293
7357
  throwIfClosed();
@@ -7317,7 +7381,7 @@ function dexieCloud(dexie) {
7317
7381
  });
7318
7382
  }
7319
7383
  }
7320
- dexieCloud.version = '4.0.1-beta.35';
7384
+ dexieCloud.version = '4.0.1-beta.37';
7321
7385
  Dexie.Cloud = dexieCloud;
7322
7386
 
7323
7387
  export { dexieCloud as default, dexieCloud, getTiedObjectId, getTiedRealmId };