@oxog/authkeeper 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +59 -2
  3. package/dist/{auth-source-CXqrhLDO.d.ts → auth-source-BwPxq1Za.d.ts} +1 -1
  4. package/dist/{auth-source-rjMWiP1Q.d.cts → auth-source-MSiTDST6.d.cts} +1 -1
  5. package/dist/{chunk-DLCD3SBV.js → chunk-K3XXGKGO.js} +2 -2
  6. package/dist/chunk-K3XXGKGO.js.map +1 -0
  7. package/dist/{chunk-XGKVBZSF.cjs → chunk-MONA6MGX.cjs} +2 -2
  8. package/dist/chunk-MONA6MGX.cjs.map +1 -0
  9. package/dist/{chunk-47JWRVTL.cjs → chunk-SI7KITBT.cjs} +319 -264
  10. package/dist/chunk-SI7KITBT.cjs.map +1 -0
  11. package/dist/{chunk-ANGR5HRJ.js → chunk-ZZMKSCXQ.js} +310 -256
  12. package/dist/chunk-ZZMKSCXQ.js.map +1 -0
  13. package/dist/{index-CQwGO-Wk.d.ts → index-BqxH4X40.d.ts} +52 -6
  14. package/dist/{index-C4pGS-TI.d.cts → index-ChJtNH74.d.cts} +52 -6
  15. package/dist/index.cjs +461 -52
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +36 -4
  18. package/dist/index.d.ts +36 -4
  19. package/dist/index.js +416 -7
  20. package/dist/index.js.map +1 -1
  21. package/dist/plugins/index.cjs +15 -15
  22. package/dist/plugins/index.d.cts +2 -2
  23. package/dist/plugins/index.d.ts +2 -2
  24. package/dist/plugins/index.js +2 -2
  25. package/dist/react/index.cjs +3 -3
  26. package/dist/react/index.d.cts +2 -2
  27. package/dist/react/index.d.ts +2 -2
  28. package/dist/react/index.js +1 -1
  29. package/dist/svelte/index.d.cts +2 -2
  30. package/dist/svelte/index.d.ts +2 -2
  31. package/dist/{types-DMPBl-Ym.d.ts → types-DWB4dbp8.d.cts} +26 -4
  32. package/dist/{types-DMPBl-Ym.d.cts → types-DWB4dbp8.d.ts} +26 -4
  33. package/dist/vue/index.cjs +2 -2
  34. package/dist/vue/index.d.cts +2 -2
  35. package/dist/vue/index.d.ts +2 -2
  36. package/dist/vue/index.js +1 -1
  37. package/package.json +5 -2
  38. package/dist/chunk-47JWRVTL.cjs.map +0 -1
  39. package/dist/chunk-ANGR5HRJ.js.map +0 -1
  40. package/dist/chunk-DLCD3SBV.js.map +0 -1
  41. package/dist/chunk-XGKVBZSF.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { createTokenStorePlugin, resolveStorage, createTokenDecoderPlugin, createRefreshEnginePlugin, createFetchInterceptorPlugin, base64UrlEncode } from './chunk-ANGR5HRJ.js';
2
- export { CookieStorageAdapter, FetchInterceptorPlugin, MemoryStorageAdapter, RefreshEnginePlugin, TokenDecoderPlugin, TokenStorePlugin, WebStorageAdapter, base64UrlDecode, base64UrlDecodeToBytes, base64UrlEncode, createFetchInterceptorPlugin, createMemoryStorage, createRefreshEnginePlugin, createTokenDecoderPlugin, createTokenStorePlugin, decodeHeader, decodeJwt, decodePayload, deleteCookie, getClaim, getClaims, getCookie, getTimeUntilExpiry, getTokenExpiry, isStorageAvailable, isTokenExpired, isValidJwtFormat, parseCookies, safeGetItem, safeRemoveItem, safeSetItem, serializeCookie, setCookie, stringToBase64Url } from './chunk-ANGR5HRJ.js';
3
- import { AuthError } from './chunk-DLCD3SBV.js';
4
- export { AuthError } from './chunk-DLCD3SBV.js';
1
+ import { createTokenStorePlugin, resolveStorage, createTokenDecoderPlugin, createRefreshEnginePlugin, createFetchInterceptorPlugin, base64UrlEncode, MemoryStorageAdapter, WebStorageAdapter, CookieStorageAdapter, isStoredTokens } from './chunk-ZZMKSCXQ.js';
2
+ export { CookieStorageAdapter, FetchInterceptorPlugin, MemoryStorageAdapter, RefreshEnginePlugin, TokenDecoderPlugin, TokenStorePlugin, WebStorageAdapter, base64UrlDecode, base64UrlDecodeToBytes, base64UrlEncode, createFetchInterceptorPlugin, createMemoryStorage, createRefreshEnginePlugin, createTokenDecoderPlugin, createTokenStorePlugin, decodeHeader, decodeJwt, decodePayload, deleteCookie, getClaim, getClaims, getCookie, getTimeUntilExpiry, getTokenExpiry, isStorageAvailable, isTokenExpired, isValidJwtFormat, parseCookies, safeGetItem, safeRemoveItem, safeSetItem, serializeCookie, setCookie, stringToBase64Url } from './chunk-ZZMKSCXQ.js';
3
+ import { AuthError } from './chunk-K3XXGKGO.js';
4
+ export { AuthError } from './chunk-K3XXGKGO.js';
5
5
 
6
6
  // src/kernel/event-bus.ts
7
7
  var EventBus = class {
@@ -240,10 +240,279 @@ var PluginRegistry = class {
240
240
  }
241
241
  };
242
242
 
243
+ // src/kernel/tab-sync.ts
244
+ var LEASE_TTL = 5e3;
245
+ var LEASE_RENEW = 1500;
246
+ var LEASE_POLL = 50;
247
+ var LEASE_SETTLE = 25;
248
+ var MAX_LOCK_HOLD = 3e4;
249
+ var ACTIONS = ["login", "refresh", "logout"];
250
+ function describeSyncScope(storage) {
251
+ if (!storage || typeof window === "undefined") return null;
252
+ const { adapter, key } = storage;
253
+ if (adapter instanceof MemoryStorageAdapter) return null;
254
+ const localStorage = getLocalStorage();
255
+ if (adapter instanceof WebStorageAdapter) {
256
+ if (localStorage === null || adapter.storage !== localStorage) return null;
257
+ return { name: adapter.prefix + key, localStorage, messagesInStorage: true };
258
+ }
259
+ const prefix = adapter instanceof CookieStorageAdapter ? adapter.prefix : "";
260
+ return { name: prefix + key, localStorage, messagesInStorage: false };
261
+ }
262
+ function getLocalStorage() {
263
+ try {
264
+ return window.localStorage;
265
+ } catch {
266
+ return null;
267
+ }
268
+ }
269
+ function closedError() {
270
+ return new AuthError("REFRESH_FAILED", "AuthKeeper was destroyed while refreshing", {
271
+ context: { superseded: true }
272
+ });
273
+ }
274
+ function isSyncMessage(value) {
275
+ if (value === null || typeof value !== "object") return false;
276
+ const m = value;
277
+ return m["v"] === 1 && typeof m["source"] === "string" && typeof m["seq"] === "number" && typeof m["gen"] === "number" && typeof m["action"] === "string" && ACTIONS.includes(m["action"]) && (m["action"] === "logout" ? m["tokens"] === null : isStoredTokens(m["tokens"]));
278
+ }
279
+ function readLease(storage, key) {
280
+ try {
281
+ const lease = JSON.parse(storage.getItem(key) ?? "null");
282
+ return lease && typeof lease.owner === "string" && typeof lease.expires === "number" ? lease : null;
283
+ } catch {
284
+ return null;
285
+ }
286
+ }
287
+ var TabSync = class _TabSync {
288
+ constructor(config) {
289
+ this.seq = 0;
290
+ this.gen = 0;
291
+ this.genSource = "";
292
+ this.lastSeq = /* @__PURE__ */ new Map();
293
+ this.channel = null;
294
+ this.storageListener = null;
295
+ this.closed = false;
296
+ /** Run by close(): end waits, abort lock requests, release held locks */
297
+ this.closeHandlers = /* @__PURE__ */ new Set();
298
+ this.leaseSerial = 0;
299
+ this.config = config;
300
+ this.key = `authkeeper-sync:${config.name}`;
301
+ this.id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
302
+ }
303
+ /**
304
+ * Start syncing; null when there is no way to reach the other tabs
305
+ * (no BroadcastChannel and no storage transport)
306
+ */
307
+ static open(config) {
308
+ const sync = new _TabSync(config);
309
+ return sync.connect() ? sync : null;
310
+ }
311
+ connect() {
312
+ const Channel = globalThis.BroadcastChannel;
313
+ if (typeof Channel === "function") {
314
+ try {
315
+ this.channel = new Channel(this.key);
316
+ this.channel.onmessage = (event) => this.receive(event.data);
317
+ return true;
318
+ } catch {
319
+ }
320
+ }
321
+ const storage = this.config.localStorage;
322
+ if (!this.config.messagesInStorage || !storage) return false;
323
+ this.storageListener = (event) => {
324
+ if (event.key !== this.key || event.newValue === null) return;
325
+ let data;
326
+ try {
327
+ data = JSON.parse(event.newValue);
328
+ } catch {
329
+ return;
330
+ }
331
+ this.receive(data);
332
+ };
333
+ window.addEventListener("storage", this.storageListener);
334
+ return true;
335
+ }
336
+ /** Tell the other tabs about a change made in this one */
337
+ publish(action, tokens) {
338
+ if (this.closed) return;
339
+ this.touch();
340
+ const message = {
341
+ v: 1,
342
+ source: this.id,
343
+ seq: ++this.seq,
344
+ gen: this.gen,
345
+ action,
346
+ tokens
347
+ };
348
+ try {
349
+ if (this.channel) {
350
+ this.channel.postMessage(message);
351
+ } else {
352
+ const storage = this.config.localStorage;
353
+ storage.setItem(this.key, JSON.stringify(message));
354
+ storage.removeItem(this.key);
355
+ }
356
+ } catch {
357
+ }
358
+ }
359
+ /** A change made in this tab that the others are not told about (local logout) */
360
+ touch() {
361
+ this.gen = Math.max(Date.now(), this.gen + 1);
362
+ this.genSource = this.id;
363
+ }
364
+ receive(data) {
365
+ if (this.closed || !isSyncMessage(data) || data.source === this.id) return;
366
+ if (data.seq <= (this.lastSeq.get(data.source) ?? 0)) return;
367
+ this.lastSeq.set(data.source, data.seq);
368
+ if (data.gen < this.gen || data.gen === this.gen && data.source <= this.genSource) return;
369
+ this.gen = data.gen;
370
+ this.genSource = data.source;
371
+ this.config.onMessage(data);
372
+ }
373
+ /**
374
+ * Run `task` while holding the refresh lock of this app (one tab at a
375
+ * time). Without a lock mechanism, or when the lock cannot be taken, the
376
+ * task runs right away. Rejects (superseded) when the instance is closed
377
+ * while waiting for the lock.
378
+ */
379
+ exclusive(task) {
380
+ return new Promise((resolve, reject) => {
381
+ let started = false;
382
+ const run = () => {
383
+ started = true;
384
+ const work = task();
385
+ work.then(resolve, reject);
386
+ return this.hold(work);
387
+ };
388
+ this.acquire(run).catch(() => {
389
+ if (started) return;
390
+ if (this.closed) {
391
+ reject(closedError());
392
+ } else {
393
+ void run();
394
+ }
395
+ });
396
+ });
397
+ }
398
+ /** Settles when the lock is to be released: work done, held too long, or closed */
399
+ hold(work) {
400
+ return new Promise((resolve) => {
401
+ const done = () => {
402
+ clearTimeout(timer);
403
+ this.closeHandlers.delete(done);
404
+ resolve();
405
+ };
406
+ const timer = setTimeout(done, MAX_LOCK_HOLD);
407
+ this.closeHandlers.add(done);
408
+ work.then(done, done);
409
+ });
410
+ }
411
+ acquire(run) {
412
+ if (this.closed) return Promise.reject(closedError());
413
+ const locks = typeof navigator === "undefined" ? void 0 : navigator.locks;
414
+ if (locks && typeof locks.request === "function") {
415
+ const controller = new AbortController();
416
+ const abort = () => controller.abort();
417
+ this.closeHandlers.add(abort);
418
+ return locks.request(`${this.key}:refresh`, { signal: controller.signal }, () => {
419
+ this.closeHandlers.delete(abort);
420
+ return run();
421
+ }).finally(() => this.closeHandlers.delete(abort));
422
+ }
423
+ const storage = this.config.localStorage;
424
+ return storage ? this.lease(storage, run) : run();
425
+ }
426
+ /** The localStorage lease lock */
427
+ async lease(storage, run) {
428
+ const key = `${this.key}:lease`;
429
+ const owner = `${this.id}:${++this.leaseSerial}`;
430
+ const write = () => {
431
+ storage.setItem(key, JSON.stringify({ owner, expires: Date.now() + LEASE_TTL }));
432
+ };
433
+ const release = () => {
434
+ try {
435
+ if (readLease(storage, key)?.owner === owner) storage.removeItem(key);
436
+ } catch {
437
+ }
438
+ };
439
+ for (; ; ) {
440
+ const current = readLease(storage, key);
441
+ const free = current === null || current.expires <= Date.now();
442
+ if (free) {
443
+ write();
444
+ }
445
+ await this.wait(free ? LEASE_SETTLE : LEASE_POLL);
446
+ if (this.closed) {
447
+ release();
448
+ throw closedError();
449
+ }
450
+ if (free && readLease(storage, key)?.owner === owner) break;
451
+ }
452
+ const renew = setInterval(() => {
453
+ try {
454
+ write();
455
+ } catch {
456
+ }
457
+ }, LEASE_RENEW);
458
+ try {
459
+ await run();
460
+ } finally {
461
+ clearInterval(renew);
462
+ release();
463
+ }
464
+ }
465
+ /** Resolves after `ms`, or at once when closed */
466
+ wait(ms) {
467
+ return new Promise((resolve) => {
468
+ const done = () => {
469
+ clearTimeout(timer);
470
+ this.closeHandlers.delete(done);
471
+ resolve();
472
+ };
473
+ const timer = setTimeout(done, ms);
474
+ this.closeHandlers.add(done);
475
+ });
476
+ }
477
+ /** Stop syncing: close the channel, remove the listener, release / give up locks */
478
+ close() {
479
+ if (this.closed) return;
480
+ this.closed = true;
481
+ if (this.channel) {
482
+ this.channel.onmessage = null;
483
+ this.channel.close();
484
+ this.channel = null;
485
+ }
486
+ if (this.storageListener) {
487
+ window.removeEventListener("storage", this.storageListener);
488
+ this.storageListener = null;
489
+ }
490
+ Array.from(this.closeHandlers).forEach((handler) => handler());
491
+ this.closeHandlers.clear();
492
+ }
493
+ };
494
+
243
495
  // src/kernel/kernel.ts
496
+ var REMOTE_SESSION_WAIT = 1e3;
497
+ var MAX_REPLACED = 16;
498
+ function isSyncableStore(store) {
499
+ return typeof store?.replace === "function" && typeof store.readPersisted === "function" && typeof store.getStorage === "function";
500
+ }
501
+ function toTokenSet(tokens) {
502
+ const set = { accessToken: tokens.accessToken, tokenType: tokens.tokenType };
503
+ if (tokens.refreshToken !== null) set.refreshToken = tokens.refreshToken;
504
+ if (tokens.expiresAt !== null) set.expiresAt = tokens.expiresAt / 1e3;
505
+ return set;
506
+ }
244
507
  var AuthKeeperKernel = class {
245
508
  constructor(options) {
246
509
  this.initialized = false;
510
+ /** Cross-tab sync, while `syncTabs` is on and the storage is shared */
511
+ this.tabSync = null;
512
+ /** Refresh tokens another tab replaced (refreshed or signed out) */
513
+ this.replacedRemotely = /* @__PURE__ */ new Set();
514
+ /** Waiting for the next change adopted from another tab */
515
+ this.remoteWaiters = /* @__PURE__ */ new Set();
247
516
  this.options = {
248
517
  autoRefresh: true,
249
518
  refreshThreshold: 60,
@@ -273,12 +542,14 @@ var AuthKeeperKernel = class {
273
542
  }
274
543
  }
275
544
  this.initialized = true;
545
+ this.updateTabSync();
276
546
  }
277
547
  /**
278
548
  * Destroy the kernel and cleanup
279
549
  */
280
550
  destroy() {
281
551
  this.cancelScheduledRefresh();
552
+ this.stopTabSync();
282
553
  this.eventBus.clear();
283
554
  const pluginNames = this.pluginRegistry.getNames();
284
555
  for (const name of pluginNames) {
@@ -302,13 +573,16 @@ var AuthKeeperKernel = class {
302
573
  }
303
574
  tokenStore.set(tokens);
304
575
  const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
305
- if (refreshEngine?.isApplyingRefresh?.() !== true) {
576
+ const isRefresh = refreshEngine?.isApplyingRefresh?.() === true;
577
+ if (!isRefresh) {
578
+ this.replacedRemotely.clear();
306
579
  this.emit({
307
580
  type: "login",
308
581
  tokens,
309
582
  timestamp: Date.now()
310
583
  });
311
584
  }
585
+ this.tabSync?.publish(isRefresh ? "refresh" : "login", tokenStore.get());
312
586
  if (this.options.autoRefresh && !this.isExpired()) {
313
587
  this.scheduleRefresh();
314
588
  }
@@ -346,6 +620,8 @@ var AuthKeeperKernel = class {
346
620
  if (tokenStore) {
347
621
  tokenStore.clear();
348
622
  }
623
+ this.replacedRemotely.clear();
624
+ this.tabSync?.touch();
349
625
  }
350
626
  // ============================================================================
351
627
  // Auth State
@@ -478,11 +754,15 @@ var AuthKeeperKernel = class {
478
754
  /**
479
755
  * Logout user
480
756
  *
481
- * Clears tokens and emits logout event.
757
+ * Clears tokens and emits logout event. Only this tab is signed out unless
758
+ * `allTabs` is set (and `syncTabs` is active).
482
759
  */
483
760
  logout(options = {}) {
484
761
  this.cancelScheduledRefresh();
485
762
  this.clearTokens();
763
+ if (options.allTabs) {
764
+ this.tabSync?.publish("logout", null);
765
+ }
486
766
  this.emit({
487
767
  type: "logout",
488
768
  reason: "manual",
@@ -598,6 +878,9 @@ var AuthKeeperKernel = class {
598
878
  ...this.options,
599
879
  ...options
600
880
  };
881
+ if (options.syncTabs !== void 0) {
882
+ this.updateTabSync();
883
+ }
601
884
  if (options.refreshThreshold !== void 0) {
602
885
  const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
603
886
  if (refreshEngine && refreshEngine.setThreshold) {
@@ -609,7 +892,133 @@ var AuthKeeperKernel = class {
609
892
  * Get current configuration
610
893
  */
611
894
  getOptions() {
612
- return { ...this.options, syncTabs: false };
895
+ return { ...this.options, syncTabs: this.tabSync !== null };
896
+ }
897
+ // ============================================================================
898
+ // Tab Sync
899
+ // ============================================================================
900
+ /** Start or stop cross-tab sync to match `syncTabs` */
901
+ updateTabSync() {
902
+ if (!this.initialized || this.options.syncTabs !== true) {
903
+ this.stopTabSync();
904
+ return;
905
+ }
906
+ if (this.tabSync) return;
907
+ const store = this.pluginRegistry.getApi("token-store");
908
+ if (!isSyncableStore(store)) return;
909
+ const scope = describeSyncScope(store.getStorage());
910
+ if (!scope) return;
911
+ const sync = TabSync.open({
912
+ ...scope,
913
+ onMessage: (message) => this.applyRemote(store, message)
914
+ });
915
+ if (!sync) return;
916
+ this.tabSync = sync;
917
+ const coordinator = {
918
+ exclusive: (task) => sync.exclusive(task),
919
+ beforeRefresh: (refreshToken) => this.awaitNewerSession(store, refreshToken),
920
+ replacement: (refreshToken) => this.replacementFor(store, refreshToken)
921
+ };
922
+ this.pluginRegistry.getApi("refresh-engine")?.setCoordinator?.(coordinator);
923
+ }
924
+ stopTabSync() {
925
+ if (!this.tabSync) return;
926
+ this.tabSync.close();
927
+ this.tabSync = null;
928
+ this.pluginRegistry.getApi("refresh-engine")?.setCoordinator?.(null);
929
+ this.replacedRemotely.clear();
930
+ this.remoteWaiters.forEach((wake) => wake());
931
+ }
932
+ /**
933
+ * Adopt a change made in another tab: update the in-memory session (the
934
+ * other tab has already written the storage) and emit the same event as
935
+ * there, marked `remote`, followed by a 'tab-sync' event
936
+ */
937
+ applyRemote(tokenStore, message) {
938
+ const current = tokenStore.get();
939
+ const timestamp = Date.now();
940
+ const remote = { remote: true, sourceTabId: message.source };
941
+ if (message.tokens === null) {
942
+ if (!current) return;
943
+ this.noteReplaced(current.refreshToken);
944
+ this.cancelScheduledRefresh();
945
+ tokenStore.replace(null);
946
+ this.emit({ type: "logout", reason: "tab-sync", timestamp, ...remote });
947
+ } else {
948
+ const tokens = message.tokens;
949
+ if (message.action === "refresh" && !current) return;
950
+ if (current && current.accessToken === tokens.accessToken && current.refreshToken === tokens.refreshToken) {
951
+ return;
952
+ }
953
+ const previousExpiresAt = this.getExpiresAt();
954
+ this.noteReplaced(current?.refreshToken ?? null);
955
+ tokenStore.replace(tokens);
956
+ const tokenSet = toTokenSet(tokens);
957
+ if (message.action === "refresh") {
958
+ this.emit({
959
+ type: "refresh",
960
+ tokens: tokenSet,
961
+ previousExpiresAt,
962
+ newExpiresAt: this.getExpiresAt(),
963
+ timestamp,
964
+ ...remote
965
+ });
966
+ } else {
967
+ this.emit({ type: "login", tokens: tokenSet, timestamp, ...remote });
968
+ }
969
+ this.cancelScheduledRefresh();
970
+ if (!this.isExpired()) {
971
+ this.scheduleRefresh();
972
+ }
973
+ }
974
+ this.emit({
975
+ type: "tab-sync",
976
+ action: message.action,
977
+ sourceTabId: message.source,
978
+ timestamp
979
+ });
980
+ this.remoteWaiters.forEach((wake) => wake());
981
+ }
982
+ noteReplaced(refreshToken) {
983
+ if (refreshToken === null) return;
984
+ this.replacedRemotely.delete(refreshToken);
985
+ this.replacedRemotely.add(refreshToken);
986
+ if (this.replacedRemotely.size > MAX_REPLACED) {
987
+ const oldest = this.replacedRemotely.values().next().value;
988
+ this.replacedRemotely.delete(oldest);
989
+ }
990
+ }
991
+ /** The session another tab replaced `refreshToken` with (null if none) */
992
+ replacementFor(tokenStore, refreshToken) {
993
+ if (!this.replacedRemotely.has(refreshToken)) return null;
994
+ const current = tokenStore.get();
995
+ return current ? toTokenSet(current) : null;
996
+ }
997
+ /**
998
+ * Before refreshing with `refreshToken` (refresh lock held): if the storage
999
+ * already holds a newer session from another tab, its message is on the
1000
+ * way - wait for it (up to REMOTE_SESSION_WAIT) instead of refreshing with a
1001
+ * refresh token that may have been rotated out.
1002
+ */
1003
+ async awaitNewerSession(tokenStore, refreshToken) {
1004
+ const persisted = tokenStore.readPersisted();
1005
+ const current = tokenStore.get();
1006
+ if (persisted !== null && persisted.refreshToken !== refreshToken && persisted.setAt > current.setAt) {
1007
+ await this.waitForRemote(REMOTE_SESSION_WAIT);
1008
+ }
1009
+ return this.replacementFor(tokenStore, refreshToken);
1010
+ }
1011
+ /** Resolves on the next change adopted from another tab, after `ms`, or when sync stops */
1012
+ waitForRemote(ms) {
1013
+ return new Promise((resolve) => {
1014
+ const wake = () => {
1015
+ clearTimeout(timer);
1016
+ this.remoteWaiters.delete(wake);
1017
+ resolve();
1018
+ };
1019
+ const timer = setTimeout(wake, ms);
1020
+ this.remoteWaiters.add(wake);
1021
+ });
613
1022
  }
614
1023
  };
615
1024