@rebasepro/client 0.31.0 → 0.32.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.
@@ -852,6 +852,115 @@ function runLocalQuery(rows, params) {
852
852
  };
853
853
  }
854
854
  //#endregion
855
+ //#region src/offline-lease.ts
856
+ /**
857
+ * A cross-tab mutex over `localStorage`, for the browsers that have no Web
858
+ * Locks: Safari before 15.4, pages served over plain http from anything but
859
+ * localhost (Web Locks is secure-context only), and embedded webviews.
860
+ *
861
+ * Without it two tabs on such a browser each replayed the whole offline queue,
862
+ * so every queued write reached the server twice. Creates survived that (the
863
+ * idempotency key dedups them) and deletes did too (a second delete's 404 is
864
+ * taken as done), but an update with `If-Match` came back `412` from its own
865
+ * twin and was reported as a conflict nobody caused.
866
+ *
867
+ * The lease is a `{ holder, until }` record under one key. A tab takes it by
868
+ * writing its own record when the key is empty, expired or already its own,
869
+ * then reading it back after `settleMs`: `localStorage` has no compare-and-set,
870
+ * but every tab reads and writes in one synchronous step, so two tabs can only
871
+ * both write within the time a write takes to reach the other process — far
872
+ * under `settleMs` — and the read-back sees whichever write landed last. Only
873
+ * that tab proceeds. The holder renews the record while it works and removes it
874
+ * when done; a tab that died holding it is outlived by `ttlMs`.
875
+ *
876
+ * It is a weaker guarantee than Web Locks, on purpose kept to what it can
877
+ * promise: a holder whose timers the browser throttles hard enough (a hidden
878
+ * tab can be held to one timer a minute) may see its lease expire mid-replay,
879
+ * and the next tab then replays what is still queued. That costs at most the
880
+ * one write in flight, not the whole queue.
881
+ */
882
+ var DEFAULT_TTL_MS = 3e4;
883
+ var DEFAULT_SETTLE_MS = 50;
884
+ var DEFAULT_POLL_MS = 200;
885
+ function readRecord(storage, key) {
886
+ let raw;
887
+ try {
888
+ raw = storage.getItem(key);
889
+ } catch {
890
+ return null;
891
+ }
892
+ if (!raw) return null;
893
+ try {
894
+ const parsed = JSON.parse(raw);
895
+ if (parsed !== null && typeof parsed === "object" && "holder" in parsed && typeof parsed.holder === "string" && "until" in parsed && typeof parsed.until === "number") return {
896
+ holder: parsed.holder,
897
+ until: parsed.until
898
+ };
899
+ } catch {}
900
+ return null;
901
+ }
902
+ /**
903
+ * `localStorage` when this page can use it, or `undefined` — a worker has none,
904
+ * and a browser with storage blocked throws on the mere access.
905
+ */
906
+ function browserLeaseStorage() {
907
+ try {
908
+ if (typeof localStorage === "undefined") return void 0;
909
+ const storage = localStorage;
910
+ const probe = "rebase-lease-probe";
911
+ storage.setItem(probe, "1");
912
+ storage.removeItem(probe);
913
+ return storage;
914
+ } catch {
915
+ return;
916
+ }
917
+ }
918
+ /**
919
+ * Run `fn` while holding the lease named `key`, waiting for another holder to
920
+ * finish first. Storage that fails mid-protocol makes the lease unenforceable,
921
+ * and then `fn` runs anyway: a queue that never drains is worse than one that
922
+ * might drain twice.
923
+ */
924
+ async function withStorageLease(storage, key, holder, fn, options = {}) {
925
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
926
+ const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
927
+ const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
928
+ const now = options.now ?? Date.now;
929
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
930
+ const write = () => {
931
+ try {
932
+ storage.setItem(key, JSON.stringify({
933
+ holder,
934
+ until: now() + ttlMs
935
+ }));
936
+ return true;
937
+ } catch {
938
+ return false;
939
+ }
940
+ };
941
+ for (;;) {
942
+ const current = readRecord(storage, key);
943
+ if (!current || current.until <= now() || current.holder === holder) {
944
+ if (!write()) return fn();
945
+ await sleep(settleMs);
946
+ if (readRecord(storage, key)?.holder === holder) break;
947
+ }
948
+ await sleep(pollMs);
949
+ }
950
+ const renew = setInterval(() => {
951
+ if (readRecord(storage, key)?.holder === holder) write();
952
+ }, Math.max(1, Math.floor(ttlMs / 3)));
953
+ unref(renew);
954
+ try {
955
+ return await fn();
956
+ } finally {
957
+ clearInterval(renew);
958
+ try {
959
+ if (readRecord(storage, key)?.holder === holder) storage.removeItem(key);
960
+ } catch {}
961
+ }
962
+ }
963
+ //#endregion
855
964
  //#region src/offline.ts
856
965
  function offlineError(message) {
857
966
  return new RebaseApiError$1(message, {
@@ -3362,7 +3471,7 @@ var OfflineManager = class {
3362
3471
  }
3363
3472
  async withLock(fn) {
3364
3473
  const locks = globalThis.navigator?.locks;
3365
- if (!locks?.request) return fn();
3474
+ if (!locks?.request) return this.withLeaseFallback(fn);
3366
3475
  let started = false;
3367
3476
  try {
3368
3477
  return await locks.request(`rebase-offline-sync:${this.scope}`, () => {
@@ -3371,9 +3480,19 @@ var OfflineManager = class {
3371
3480
  });
3372
3481
  } catch (error) {
3373
3482
  if (started) throw error;
3374
- return fn();
3483
+ return this.withLeaseFallback(fn);
3375
3484
  }
3376
3485
  }
3486
+ /**
3487
+ * Serialise replay across tabs without Web Locks — see `offline-lease.ts`.
3488
+ * Where there is no `localStorage` either (a worker), there is no other
3489
+ * tab sharing this queue through it to guard against.
3490
+ */
3491
+ withLeaseFallback(fn) {
3492
+ const storage = browserLeaseStorage();
3493
+ if (!storage) return fn();
3494
+ return withStorageLease(storage, `rebase-offline-sync:${this.scope}`, this.tabId, fn);
3495
+ }
3377
3496
  broadcast(message, scope = this.scope) {
3378
3497
  if (!this.channel) return;
3379
3498
  try {
@@ -3496,4 +3615,4 @@ var OfflineManager = class {
3496
3615
  //#endregion
3497
3616
  export { OfflineManager };
3498
3617
 
3499
- //# sourceMappingURL=offline-D_wKJcO3.js.map
3618
+ //# sourceMappingURL=offline-ET6xI1ZO.js.map