ahmed-rivet-convex 2.2.5 → 2.2.7

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.
@@ -133,14 +133,13 @@ import {
133
133
  toPrimaryKeyString,
134
134
  transformFilters,
135
135
  unreachable,
136
- using,
137
136
  valita_exports,
138
137
  valuesEqual,
139
138
  withRead,
140
139
  withWrite,
141
140
  withWriteNoImplicitCommit,
142
141
  wrapIterable
143
- } from "./chunk-SIMXYEFB.js";
142
+ } from "./chunk-FVFX5V7B.js";
144
143
 
145
144
  // ../zero-schema/src/builder/table-builder.ts
146
145
  function table(name) {
@@ -581,40 +580,6 @@ var promiseVoid = Promise.resolve();
581
580
  var promiseNever = new Promise(() => {
582
581
  });
583
582
 
584
- // ../replicache/src/connection-loop-delegates.ts
585
- var ConnectionLoopDelegateImpl = class {
586
- rep;
587
- invokeSend;
588
- // TODO: Remove the ability to have more than one concurrent connection and update tests.
589
- // Bug: https://github.com/rocicorp/replicache-internal/issues/303
590
- maxConnections = 1;
591
- constructor(rep, invokeSend) {
592
- this.rep = rep;
593
- this.invokeSend = invokeSend;
594
- }
595
- get maxDelayMs() {
596
- return this.rep.requestOptions.maxDelayMs;
597
- }
598
- get minDelayMs() {
599
- return this.rep.requestOptions.minDelayMs;
600
- }
601
- };
602
- var PullDelegate = class extends ConnectionLoopDelegateImpl {
603
- debounceDelay = 0;
604
- get watchdogTimer() {
605
- return this.rep.pullInterval;
606
- }
607
- };
608
- var PushDelegate = class extends ConnectionLoopDelegateImpl {
609
- get debounceDelay() {
610
- return this.rep.pushDelay;
611
- }
612
- watchdogTimer = null;
613
- };
614
-
615
- // ../replicache/src/connection-loop.ts
616
- import { resolver as resolver3 } from "@rocicorp/resolver";
617
-
618
583
  // ../shared/src/sleep.ts
619
584
  import { resolver as resolver2 } from "@rocicorp/resolver";
620
585
  var promiseVoid2 = Promise.resolve();
@@ -661,7 +626,39 @@ function sleepWithAbort(ms, signal) {
661
626
  return [sleepPromise, abortedPromise];
662
627
  }
663
628
 
629
+ // ../replicache/src/connection-loop-delegates.ts
630
+ var ConnectionLoopDelegateImpl = class {
631
+ rep;
632
+ invokeSend;
633
+ // TODO: Remove the ability to have more than one concurrent connection and update tests.
634
+ // Bug: https://github.com/rocicorp/replicache-internal/issues/303
635
+ maxConnections = 1;
636
+ constructor(rep, invokeSend) {
637
+ this.rep = rep;
638
+ this.invokeSend = invokeSend;
639
+ }
640
+ get maxDelayMs() {
641
+ return this.rep.requestOptions.maxDelayMs;
642
+ }
643
+ get minDelayMs() {
644
+ return this.rep.requestOptions.minDelayMs;
645
+ }
646
+ };
647
+ var PullDelegate = class extends ConnectionLoopDelegateImpl {
648
+ debounceDelay = 0;
649
+ get watchdogTimer() {
650
+ return this.rep.pullInterval;
651
+ }
652
+ };
653
+ var PushDelegate = class extends ConnectionLoopDelegateImpl {
654
+ get debounceDelay() {
655
+ return this.rep.pushDelay;
656
+ }
657
+ watchdogTimer = null;
658
+ };
659
+
664
660
  // ../replicache/src/connection-loop.ts
661
+ import { resolver as resolver3 } from "@rocicorp/resolver";
665
662
  var MIN_DELAY_MS = 30;
666
663
  var MAX_DELAY_MS = 6e4;
667
664
  var ConnectionLoop = class {
@@ -943,6 +940,9 @@ var RefCountUpdates = class {
943
940
  this.#refsCounted = this.#isLazyDelegate ? /* @__PURE__ */ new Set() : null;
944
941
  }
945
942
  async compute() {
943
+ if (!this.#isLazyDelegate) {
944
+ return this.#computeNet();
945
+ }
946
946
  for (const n of this.#newHeads) {
947
947
  await this.#changeRefCount(n, 1);
948
948
  }
@@ -980,6 +980,153 @@ var RefCountUpdates = class {
980
980
  }
981
981
  return this.#refCountUpdates;
982
982
  }
983
+ /**
984
+ * For stores that count every ref eagerly (the IndexedDB perdag). A
985
+ * persist replaces one path of a tree: the new root counts each of its
986
+ * children +1 and the old root -1, so nearly every child ends where it
987
+ * started. Counting them one by one loaded and rewrote each child's ref
988
+ * count — an IndexedDB get and put per child, ~300 of each per persist
989
+ * at 50k rows, the long-lived tab's write storm. Here deltas are summed
990
+ * first: a count is loaded only when it can matter, and only counts that
991
+ * changed (plus every put chunk, as documented) are returned. A chunk
992
+ * passes a change on to its refs when its count crosses zero — the same
993
+ * result as counting one by one.
994
+ *
995
+ * Order matters for cost, not for the result. Increments are passed on
996
+ * first and decrements held back until no increment is left: a persist
997
+ * of N writes puts a chain of N new commits whose first sits on the old
998
+ * head, so the chain's +1 reaches the old head N levels after the old
999
+ * head's own -1. Passing the -1 on at once dropped the whole old tree to
1000
+ * zero, then back.
1001
+ *
1002
+ * A +1 to a stored chunk this write did not put cannot make it newly
1003
+ * reachable: the store deletes a chunk whose count reaches 0, so every
1004
+ * chunk it holds has a count of at least 1. Such a count is not loaded
1005
+ * until the end (it is needed then only if it changed), and if it turns
1006
+ * out to be 0 after all, the change is passed on then.
1007
+ *
1008
+ * INVARIANT the assumed >= 1 shortcut depends on: the eager store deletes
1009
+ * any chunk whose count reaches 0. `StoreImpl.#applyRefCountUpdates`
1010
+ * does that for every returned entry with a count of 0
1011
+ * (`#removeAllRelatedKeys`), and it is safe that only changed counts and
1012
+ * put chunks are returned, because an unreturned count is by definition
1013
+ * unchanged and so already stored correctly. The quiescence check below
1014
+ * verifies the invariant instead of trusting it: every assumed chunk
1015
+ * whose net is not 0 is loaded, and a stored 0 is passed on as a real
1016
+ * 0 -> positive change. An assumed chunk whose net returns to 0 is never
1017
+ * loaded and never returned.
1018
+ */
1019
+ async #computeNet() {
1020
+ const delegate = this.#delegate;
1021
+ const putChunks = this.#putChunks;
1022
+ const net = /* @__PURE__ */ new Map();
1023
+ const loaded = /* @__PURE__ */ new Map();
1024
+ const propagated = /* @__PURE__ */ new Map();
1025
+ const assumed = /* @__PURE__ */ new Set();
1026
+ const held = /* @__PURE__ */ new Set();
1027
+ let dirty = /* @__PURE__ */ new Set();
1028
+ const add = (hash, delta) => {
1029
+ net.set(hash, (net.get(hash) ?? 0) + delta);
1030
+ dirty.add(hash);
1031
+ };
1032
+ const load = (hashes) => Promise.all(
1033
+ Array.from(hashes, async (hash) => {
1034
+ if (!loaded.has(hash)) {
1035
+ loaded.set(hash, await delegate.getRefCount(hash) || 0);
1036
+ }
1037
+ })
1038
+ );
1039
+ const want = (hash) => {
1040
+ const old = loaded.get(hash);
1041
+ if (old === void 0 || hash === emptyHash) {
1042
+ return 0;
1043
+ }
1044
+ const now = old + (net.get(hash) ?? 0);
1045
+ return old === 0 && now > 0 ? 1 : old > 0 && now === 0 ? -1 : 0;
1046
+ };
1047
+ const passOn = async (hashes) => {
1048
+ const changes = [];
1049
+ for (const hash of hashes) {
1050
+ const w = want(hash);
1051
+ const d = w - (propagated.get(hash) ?? 0);
1052
+ if (d !== 0) {
1053
+ propagated.set(hash, w);
1054
+ changes.push([hash, d]);
1055
+ }
1056
+ }
1057
+ const refs = await Promise.all(
1058
+ changes.map(([hash]) => delegate.getRefs(hash))
1059
+ );
1060
+ for (let i = 0; i < changes.length; i++) {
1061
+ if (!isProd) {
1062
+ assert(refs[i], "refs must be defined");
1063
+ }
1064
+ for (const ref of refs[i] ?? []) add(ref, changes[i][1]);
1065
+ }
1066
+ };
1067
+ for (const n of this.#newHeads) add(n, 1);
1068
+ for (const o of this.#oldHeads) add(o, -1);
1069
+ for (; ; ) {
1070
+ if (dirty.size > 0) {
1071
+ const current = dirty;
1072
+ dirty = /* @__PURE__ */ new Set();
1073
+ const toLoad = [];
1074
+ for (const hash of current) {
1075
+ const n = net.get(hash) ?? 0;
1076
+ if (loaded.has(hash) || n === 0) {
1077
+ continue;
1078
+ }
1079
+ if (n < 0 || putChunks.has(hash)) {
1080
+ toLoad.push(hash);
1081
+ } else {
1082
+ assumed.add(hash);
1083
+ }
1084
+ }
1085
+ await load(toLoad);
1086
+ const up = [];
1087
+ for (const hash of current) {
1088
+ const d = want(hash) - (propagated.get(hash) ?? 0);
1089
+ if (d > 0) {
1090
+ up.push(hash);
1091
+ } else if (d < 0) {
1092
+ held.add(hash);
1093
+ }
1094
+ }
1095
+ await passOn(up);
1096
+ continue;
1097
+ }
1098
+ if (held.size > 0) {
1099
+ const down = [...held];
1100
+ held.clear();
1101
+ await passOn(down);
1102
+ continue;
1103
+ }
1104
+ const unverified = [...assumed].filter(
1105
+ (hash) => !loaded.has(hash) && (net.get(hash) ?? 0) !== 0
1106
+ );
1107
+ assumed.clear();
1108
+ if (unverified.length === 0) {
1109
+ break;
1110
+ }
1111
+ await load(unverified);
1112
+ for (const hash of unverified) dirty.add(hash);
1113
+ }
1114
+ await load(putChunks);
1115
+ const updates = this.#refCountUpdates;
1116
+ for (const [hash, old] of loaded) {
1117
+ const now = old + (net.get(hash) ?? 0);
1118
+ if (now !== old || putChunks.has(hash)) {
1119
+ if (!isProd) {
1120
+ assert(
1121
+ now >= 0,
1122
+ `ref count update must be non-negative. ${hash}:${now}`
1123
+ );
1124
+ }
1125
+ updates.set(hash, now);
1126
+ }
1127
+ }
1128
+ return updates;
1129
+ }
983
1130
  async #changeRefCount(hash, delta) {
984
1131
  await this.#ensureRefCountLoaded(hash);
985
1132
  if (this.#updateRefCount(hash, delta)) {
@@ -2906,24 +3053,36 @@ var liveTransactions = /* @__PURE__ */ new Set();
2906
3053
  function txFailure(tx) {
2907
3054
  return tx.error ?? new DOMException("IndexedDB transaction aborted", "AbortError");
2908
3055
  }
2909
- var freezeReleaseInstalled = false;
2910
- function track(tx) {
2911
- if (!freezeReleaseInstalled) {
2912
- freezeReleaseInstalled = true;
2913
- globalThis.document?.addEventListener(
2914
- "freeze",
2915
- () => {
2916
- for (const open of liveTransactions) {
2917
- try {
2918
- open.abort();
2919
- } catch {
2920
- }
3056
+ var frozen;
3057
+ function whenPageResumed() {
3058
+ return frozen ? frozen.promise : promiseVoid;
3059
+ }
3060
+ function installFreezeListeners() {
3061
+ globalThis.document?.addEventListener(
3062
+ "freeze",
3063
+ () => {
3064
+ frozen ??= resolver4();
3065
+ for (const open of liveTransactions) {
3066
+ try {
3067
+ open.abort();
3068
+ } catch {
2921
3069
  }
2922
- liveTransactions.clear();
2923
- },
2924
- { capture: true }
2925
- );
2926
- }
3070
+ }
3071
+ liveTransactions.clear();
3072
+ },
3073
+ { capture: true }
3074
+ );
3075
+ globalThis.document?.addEventListener(
3076
+ "resume",
3077
+ () => {
3078
+ frozen?.resolve();
3079
+ frozen = void 0;
3080
+ },
3081
+ { capture: true }
3082
+ );
3083
+ }
3084
+ installFreezeListeners();
3085
+ function track(tx) {
2927
3086
  liveTransactions.add(tx);
2928
3087
  const done = () => liveTransactions.delete(tx);
2929
3088
  tx.addEventListener("complete", done);
@@ -3023,6 +3182,9 @@ function openDatabaseOnce(name) {
3023
3182
  var IDBNotFoundError = class extends Error {
3024
3183
  name = "IDBNotFoundError";
3025
3184
  };
3185
+ function isIDBNotFoundError(e) {
3186
+ return e instanceof IDBNotFoundError;
3187
+ }
3026
3188
 
3027
3189
  // ../replicache/src/kv/mem-store.ts
3028
3190
  import { RWLock as RWLock2 } from "@rocicorp/lock";
@@ -3250,12 +3412,18 @@ var NoOp = 1;
3250
3412
  var CookieMismatch = 2;
3251
3413
 
3252
3414
  // ../replicache/src/sync/patch.ts
3415
+ import { compareUTF8 } from "compare-utf8";
3416
+ var BULK_MIN_OPS = 1024;
3417
+ var BULK_MAX_TREE_RATIO = 4;
3253
3418
  async function apply(lc, dbWrite, patch) {
3419
+ if (patch.length >= BULK_MIN_OPS && await applyBulk(dbWrite, patch)) {
3420
+ return;
3421
+ }
3254
3422
  for (const p of patch) {
3255
3423
  switch (p.op) {
3256
3424
  case "put": {
3257
- const frozen = deepFreeze(p.value);
3258
- await dbWrite.put(lc, p.key, frozen);
3425
+ const frozen2 = deepFreeze(p.value);
3426
+ await dbWrite.put(lc, p.key, frozen2);
3259
3427
  break;
3260
3428
  }
3261
3429
  case "update": {
@@ -3275,8 +3443,8 @@ async function apply(lc, dbWrite, patch) {
3275
3443
  if (p.merge) {
3276
3444
  addToEntries(p.merge);
3277
3445
  }
3278
- const frozen = deepFreeze(Object.fromEntries(entries));
3279
- await dbWrite.put(lc, p.key, frozen);
3446
+ const frozen2 = deepFreeze(Object.fromEntries(entries));
3447
+ await dbWrite.put(lc, p.key, frozen2);
3280
3448
  break;
3281
3449
  }
3282
3450
  case "del": {
@@ -3293,6 +3461,23 @@ async function apply(lc, dbWrite, patch) {
3293
3461
  }
3294
3462
  }
3295
3463
  }
3464
+ async function applyBulk(dbWrite, patch) {
3465
+ if (dbWrite.indexes.size > 0) {
3466
+ return false;
3467
+ }
3468
+ const byKey = /* @__PURE__ */ new Map();
3469
+ for (const p of patch) {
3470
+ if (p.op === "put") {
3471
+ byKey.set(p.key, deepFreeze(p.value));
3472
+ } else if (p.op === "del") {
3473
+ byKey.set(p.key, void 0);
3474
+ } else {
3475
+ return false;
3476
+ }
3477
+ }
3478
+ const changes = [...byKey].sort((a, b) => compareUTF8(a[0], b[0]));
3479
+ return dbWrite.map.putSorted(changes, changes.length * BULK_MAX_TREE_RATIO);
3480
+ }
3296
3481
 
3297
3482
  // ../replicache/src/sync/pull-error.ts
3298
3483
  var PullError = class extends Error {
@@ -3725,7 +3910,7 @@ function makeChannelNameV1(replicacheName) {
3725
3910
  function isNewClientChannelMessageV1(message) {
3726
3911
  return typeof message === "object" && typeof message.clientGroupID === "string" && typeof message.idbName === "string";
3727
3912
  }
3728
- function initNewClientChannel(replicacheName, idbName, signal, clientGroupID, isNewClientGroup, onUpdateNeeded, perdag) {
3913
+ function initNewClientChannel(replicacheName, idbName, signal, clientGroupID, isNewClientGroup, onUpdateNeeded, perdag, onError) {
3729
3914
  if (signal.aborted) {
3730
3915
  return;
3731
3916
  }
@@ -3736,7 +3921,7 @@ function initNewClientChannel(replicacheName, idbName, signal, clientGroupID, is
3736
3921
  channelV0.postMessage([clientGroupID]);
3737
3922
  channelV0.close();
3738
3923
  }
3739
- channelV1.onmessage = async (e) => {
3924
+ const handleMessage = async (e) => {
3740
3925
  const { data } = e;
3741
3926
  if (isNewClientChannelMessageV1(data)) {
3742
3927
  const { clientGroupID: newClientGroupID, idbName: newClientIDBName } = data;
@@ -3756,6 +3941,16 @@ function initNewClientChannel(replicacheName, idbName, signal, clientGroupID, is
3756
3941
  }
3757
3942
  }
3758
3943
  };
3944
+ channelV1.onmessage = async (e) => {
3945
+ try {
3946
+ await handleMessage(e);
3947
+ } catch (err2) {
3948
+ if (!onError) {
3949
+ throw err2;
3950
+ }
3951
+ onError(err2);
3952
+ }
3953
+ };
3759
3954
  signal.addEventListener("abort", () => channelV1.close(), { once: true });
3760
3955
  }
3761
3956
 
@@ -3804,10 +3999,10 @@ async function pendingMutationsForAPI(dagRead) {
3804
3999
  }
3805
4000
 
3806
4001
  // ../replicache/src/bg-interval.ts
3807
- function initBgIntervalProcess(processName, process2, delayMs, lc, signal) {
3808
- void runBgIntervalProcess(processName, process2, delayMs, lc, signal);
4002
+ function initBgIntervalProcess(processName, process2, delayMs, lc, signal, stopOn) {
4003
+ void runBgIntervalProcess(processName, process2, delayMs, lc, signal, stopOn);
3809
4004
  }
3810
- async function runBgIntervalProcess(processName, process2, delayMs, lc, signal) {
4005
+ async function runBgIntervalProcess(processName, process2, delayMs, lc, signal, stopOn) {
3811
4006
  if (signal.aborted) {
3812
4007
  return;
3813
4008
  }
@@ -3828,6 +4023,9 @@ async function runBgIntervalProcess(processName, process2, delayMs, lc, signal)
3828
4023
  } catch (e) {
3829
4024
  if (signal.aborted) {
3830
4025
  lc.debug?.("Error running most likely due to close.", e);
4026
+ } else if (stopOn?.(e)) {
4027
+ lc.debug?.("Stopping: every later run would fail the same way.", e);
4028
+ break;
3831
4029
  } else {
3832
4030
  lc.error?.("Error running.", e);
3833
4031
  }
@@ -3855,7 +4053,9 @@ function initClientGC(clientID, dagStore, clientMaxInactiveTime, gcInterval, onC
3855
4053
  },
3856
4054
  () => gcInterval,
3857
4055
  lc,
3858
- signal
4056
+ signal,
4057
+ // Works on this instance's own database: once it is gone, stop.
4058
+ isIDBNotFoundError
3859
4059
  );
3860
4060
  }
3861
4061
  function gcClients(clientID, dagStore, clientMaxInactiveTime, onClientsDeleted) {
@@ -3899,7 +4099,9 @@ function initClientGroupGC(dagStore, enableMutationRecovery, lc, signal) {
3899
4099
  },
3900
4100
  () => GC_INTERVAL_MS,
3901
4101
  lc,
3902
- signal
4102
+ signal,
4103
+ // Works on this instance's own database: once it is gone, stop.
4104
+ isIDBNotFoundError
3903
4105
  );
3904
4106
  }
3905
4107
  function gcClientGroups(dagStore, enableMutationRecovery) {
@@ -4141,16 +4343,22 @@ async function collectIDBDatabases(idbDatabasesStore, now, maxAge, kvDropStore,
4141
4343
  if (deletedClientsToRemove.length > 0) {
4142
4344
  let allDeletedClients = deletedClientsToRemove;
4143
4345
  for (const name of dbNamesToKeep) {
4144
- await withWrite(newDagStore(name), async (dagWrite) => {
4145
- const newDeletedClients = await addDeletedClients(
4146
- dagWrite,
4147
- deletedClientsToRemove
4148
- );
4149
- allDeletedClients = mergeDeletedClients(
4150
- allDeletedClients,
4151
- newDeletedClients
4152
- );
4153
- });
4346
+ try {
4347
+ await withWrite(newDagStore(name), async (dagWrite) => {
4348
+ const newDeletedClients = await addDeletedClients(
4349
+ dagWrite,
4350
+ deletedClientsToRemove
4351
+ );
4352
+ allDeletedClients = mergeDeletedClients(
4353
+ allDeletedClients,
4354
+ newDeletedClients
4355
+ );
4356
+ });
4357
+ } catch (e) {
4358
+ if (!isIDBNotFoundError(e)) {
4359
+ throw e;
4360
+ }
4361
+ }
4154
4362
  }
4155
4363
  const normalizedDeletedClients = normalizeDeletedClients(allDeletedClients);
4156
4364
  await onClientsDeleted(normalizedDeletedClients);
@@ -4196,7 +4404,12 @@ function gatherDatabaseInfoForCollect(db, now, maxAge, enableMutationRecovery, n
4196
4404
  return canDatabaseBeCollectedAndGetDeletedClientIDs(
4197
4405
  enableMutationRecovery,
4198
4406
  newDagStore(db.name)
4199
- );
4407
+ ).catch((e) => {
4408
+ if (isIDBNotFoundError(e)) {
4409
+ return [true, []];
4410
+ }
4411
+ throw e;
4412
+ });
4200
4413
  }
4201
4414
  async function dropDatabase(dbName, opts) {
4202
4415
  const logContext = createLogContext(opts?.logLevel, opts?.logSinks, {
@@ -4247,12 +4460,17 @@ function startHeartbeats(clientID, dagStore, onClientStateNotFound, heartbeatInt
4247
4460
  onClientStateNotFound();
4248
4461
  return;
4249
4462
  }
4463
+ if (e instanceof IDBNotFoundError && !signal.aborted) {
4464
+ onClientStateNotFound(e);
4465
+ }
4250
4466
  throw e;
4251
4467
  }
4252
4468
  },
4253
4469
  () => heartbeatIntervalMs,
4254
4470
  lc,
4255
- signal
4471
+ signal,
4472
+ // Works on this instance's own database: once it is gone, stop.
4473
+ isIDBNotFoundError
4256
4474
  );
4257
4475
  }
4258
4476
  function writeHeartbeat(clientID, dagStore) {
@@ -4316,11 +4534,19 @@ var GatherMemoryOnlyVisitor = class extends Visitor {
4316
4534
  };
4317
4535
 
4318
4536
  // ../replicache/src/persist/persist.ts
4537
+ var PersistBaseMovedError = class extends Error {
4538
+ constructor(expected, actual) {
4539
+ super(`perdag head moved during persist: ${expected} -> ${actual}`);
4540
+ this.expected = expected;
4541
+ this.actual = actual;
4542
+ }
4543
+ name = "PersistBaseMovedError";
4544
+ };
4319
4545
  async function persistDD31(lc, clientID, memdag, perdag, mutators, closed, formatVersion, getZeroData, onGatherMemOnlyChunksForTest = () => Promise.resolve()) {
4320
4546
  if (closed()) {
4321
4547
  return;
4322
4548
  }
4323
- const [perdagLMID, perdagBaseSnapshot, mainClientGroupID] = await withRead(
4549
+ const [perdagLMID, perdagBaseSnapshot, mainClientGroupID, perdagHeadHashAtRead] = await withRead(
4324
4550
  perdag,
4325
4551
  async (perdagRead) => {
4326
4552
  await assertHasClientState(clientID, perdagRead);
@@ -4345,7 +4571,12 @@ async function persistDD31(lc, clientID, memdag, perdag, mutators, closed, forma
4345
4571
  perdagRead
4346
4572
  );
4347
4573
  assertSnapshotCommitDD31(perdagBaseSnapshot2);
4348
- return [perdagLMID2, perdagBaseSnapshot2, mainClientGroupID2];
4574
+ return [
4575
+ perdagLMID2,
4576
+ perdagBaseSnapshot2,
4577
+ mainClientGroupID2,
4578
+ perdagMainClientGroupHeadCommit.chunk.hash
4579
+ ];
4349
4580
  }
4350
4581
  );
4351
4582
  if (closed()) {
@@ -4381,6 +4612,10 @@ async function persistDD31(lc, clientID, memdag, perdag, mutators, closed, forma
4381
4612
  }
4382
4613
  let memdagBaseSnapshotPersisted = false;
4383
4614
  const zeroDataForMemdagBaseSnapshot = getZeroData && await getZeroData(memdagBaseSnapshot.chunk.hash);
4615
+ const zeroDataForPerdagHeadAtRead = getZeroData && await getZeroData(perdagHeadHashAtRead);
4616
+ if (closed()) {
4617
+ return;
4618
+ }
4384
4619
  await withWrite(perdag, async (perdagWrite) => {
4385
4620
  const [mainClientGroup, latestPerdagMainClientGroupHeadCommit] = await getClientGroupInfo(perdagWrite, mainClientGroupID);
4386
4621
  let newMainClientGroupHeadHash = latestPerdagMainClientGroupHeadCommit.chunk.hash;
@@ -4435,10 +4670,14 @@ async function persistDD31(lc, clientID, memdag, perdag, mutators, closed, forma
4435
4670
  }
4436
4671
  }
4437
4672
  let zeroDataForPerdagHeadCommit;
4438
- if (!memdagBaseSnapshotPersisted) {
4439
- zeroDataForPerdagHeadCommit = getZeroData && await getZeroData(newMainClientGroupHeadHash, {
4440
- openLazySourceRead: perdagWrite
4441
- });
4673
+ if (!memdagBaseSnapshotPersisted && getZeroData) {
4674
+ if (newMainClientGroupHeadHash !== perdagHeadHashAtRead) {
4675
+ throw new PersistBaseMovedError(
4676
+ perdagHeadHashAtRead,
4677
+ newMainClientGroupHeadHash
4678
+ );
4679
+ }
4680
+ zeroDataForPerdagHeadCommit = zeroDataForPerdagHeadAtRead;
4442
4681
  }
4443
4682
  newMainClientGroupHeadHash = await rebase(
4444
4683
  newMemdagMutations,
@@ -4835,7 +5074,7 @@ function setIntervalWithSignal(fn, ms, signal) {
4835
5074
  }
4836
5075
 
4837
5076
  // ../replicache/src/subscriptions.ts
4838
- import { compareUTF8, greaterThan as greaterThan3, lessThan, lessThanEq } from "compare-utf8";
5077
+ import { compareUTF8 as compareUTF82, greaterThan as greaterThan3, lessThan, lessThanEq } from "compare-utf8";
4839
5078
 
4840
5079
  // ../replicache/src/invoke-kind-enum.ts
4841
5080
  var InitialRun = 0;
@@ -5032,18 +5271,26 @@ var SubscriptionsManagerImpl = class {
5032
5271
  if (subs.length === 0) {
5033
5272
  return;
5034
5273
  }
5035
- const results = await this.#queryInternal(
5036
- (tx) => Promise.allSettled(
5037
- subs.map(async (s) => {
5038
- const stx = new SubscriptionTransactionWrapper(tx);
5039
- try {
5040
- return await s.invoke(stx, kind, diffs);
5041
- } finally {
5042
- s.updateDeps(stx.keys, stx.scans);
5043
- }
5044
- })
5045
- )
5046
- );
5274
+ let results;
5275
+ try {
5276
+ results = await this.#queryInternal(
5277
+ (tx) => Promise.allSettled(
5278
+ subs.map(async (s) => {
5279
+ const stx = new SubscriptionTransactionWrapper(tx);
5280
+ try {
5281
+ return await s.invoke(stx, kind, diffs);
5282
+ } finally {
5283
+ s.updateDeps(stx.keys, stx.scans);
5284
+ }
5285
+ })
5286
+ )
5287
+ );
5288
+ } catch (e) {
5289
+ if (this.#signal.aborted) {
5290
+ return;
5291
+ }
5292
+ throw e;
5293
+ }
5047
5294
  this.callCallbacks(subs, results);
5048
5295
  }
5049
5296
  // Public method so that ZQL can wrap it in a transaction.
@@ -5070,11 +5317,15 @@ var SubscriptionsManagerImpl = class {
5070
5317
  this.hasPendingSubscriptionRuns = false;
5071
5318
  const subscriptions = [...this.#pendingSubscriptions];
5072
5319
  this.#pendingSubscriptions.clear();
5073
- await this.#fireSubscriptions(
5074
- subscriptions,
5075
- InitialRun,
5076
- void 0
5077
- );
5320
+ try {
5321
+ await this.#fireSubscriptions(
5322
+ subscriptions,
5323
+ InitialRun,
5324
+ void 0
5325
+ );
5326
+ } catch (e) {
5327
+ this.#lc.error?.("Error in initial subscription run:", e);
5328
+ }
5078
5329
  }
5079
5330
  }
5080
5331
  shouldComputeDiffs() {
@@ -5178,7 +5429,7 @@ function watcherMatchesDiff(diff3, prefix, indexName) {
5178
5429
  function diffBinarySearch(diff3, prefix, compareKey) {
5179
5430
  return binarySearch(
5180
5431
  diff3.length,
5181
- (i) => compareUTF8(prefix, compareKey(diff3[i]))
5432
+ (i) => compareUTF82(prefix, compareKey(diff3[i]))
5182
5433
  );
5183
5434
  }
5184
5435
 
@@ -5260,9 +5511,13 @@ var ReplicacheImpl = class {
5260
5511
  };
5261
5512
  }
5262
5513
  #closed = false;
5514
+ #idbNotFoundReported = false;
5263
5515
  #online = true;
5264
5516
  #clientID = makeClientID();
5265
5517
  #ready;
5518
+ /** Settles when #open finishes, succeeded OR failed — what close waits on. */
5519
+ // eslint-disable-next-line no-unused-private-class-members -- False positive, close() awaits it
5520
+ #opened;
5266
5521
  #profileIDPromise;
5267
5522
  #clientGroupIDPromise;
5268
5523
  #mutatorRegistry = {};
@@ -5348,9 +5603,22 @@ var ReplicacheImpl = class {
5348
5603
  *
5349
5604
  * The default behavior is to reload the page (using `location.reload()`). Set
5350
5605
  * this to `null` or provide your own function to prevent the page from
5351
- * reloading automatically.
5606
+ * reloading automatically. The default reloads at most once per 10 seconds
5607
+ * for a given database (tracked in `sessionStorage`): a reload that lands
5608
+ * straight back here warns once and the page keeps running in memory
5609
+ * instead of looping.
5610
+ *
5611
+ * `reason` is `'idb-deleted'` when this instance's IndexedDB database was
5612
+ * deleted under it (another tab's collector dropped it, or site data was
5613
+ * cleared); it is `undefined` for the other causes.
5352
5614
  */
5353
- onClientStateNotFound = reload;
5615
+ onClientStateNotFound = () => {
5616
+ if (allowClientStateNotFoundReload(this.idbName)) {
5617
+ reload();
5618
+ } else {
5619
+ this.#warnReloadSuppressed();
5620
+ }
5621
+ };
5354
5622
  /**
5355
5623
  * `onUpdateNeeded` is called when a code update is needed.
5356
5624
  *
@@ -5484,7 +5752,7 @@ var ReplicacheImpl = class {
5484
5752
  void this.#handlePersist(persistInfo);
5485
5753
  }
5486
5754
  );
5487
- void this.#open(
5755
+ this.#opened = this.#open(
5488
5756
  indexes,
5489
5757
  enableClientGroupForking,
5490
5758
  enableMutationRecovery,
@@ -5493,34 +5761,113 @@ var ReplicacheImpl = class {
5493
5761
  clientGroupIDResolver.resolve,
5494
5762
  readyResolver.resolve,
5495
5763
  onClientsDeleted
5764
+ ).catch((e) => this.#reportOpenFailure(e));
5765
+ }
5766
+ /**
5767
+ * An open that fails leaves the instance unready until a reload (upstream
5768
+ * behaviour — nothing downstream can run without a client group). What
5769
+ * changes is that the failure is REPORTED once instead of escaping as an
5770
+ * unhandled rejection: measured 2026-09-27 (Protocolbase), aborting the
5771
+ * perdag's IndexedDB transaction during boot raised `Uncaught (in promise)
5772
+ * InvalidStateError: Failed to execute 'objectStore' on 'IDBTransaction':
5773
+ * The transaction has finished` from initClientV6 → #open.
5774
+ */
5775
+ #reportOpenFailure(e) {
5776
+ if (this.#closed || e instanceof AbortError) {
5777
+ this.#lc.debug?.("Open did not complete before close", e);
5778
+ return;
5779
+ }
5780
+ this.#lc.error?.(
5781
+ "Replicache failed to open; it stays unready until the page reloads",
5782
+ e
5496
5783
  );
5497
5784
  }
5785
+ /**
5786
+ * Runs one IndexedDB step of open, retrying when IndexedDB aborted its
5787
+ * transaction. The browser aborts transactions on events this code never
5788
+ * causes: a tab being frozen (this store's own `freeze` release aborts
5789
+ * every live transaction), storage filling up, a sibling deleting the
5790
+ * database. Every step retried here is atomic (a registry read or put,
5791
+ * `initClientV6`'s single perdag write, Zero's `init` read — see
5792
+ * {@link ZeroOption.init}), so a retry starts from a clean transaction.
5793
+ *
5794
+ * Each retry consumes one of the {@link OPEN_IDB_RETRY_DELAYS_MS} attempts
5795
+ * of its step (attempts are per step, not per open). Before retrying, the
5796
+ * step waits for the page to resume — at most
5797
+ * {@link FREEZE_RESUME_WAIT_CAP_MS}, so a `resume` that is never delivered
5798
+ * cannot hang open — then backs off 0 / 100 / 500 / 2000 ms. Bounded, and
5799
+ * never after close.
5800
+ */
5801
+ async #retryTransientIdbAbort(step, fn) {
5802
+ for (let attempt = 0; ; attempt++) {
5803
+ try {
5804
+ return await fn();
5805
+ } catch (e) {
5806
+ if (this.#closed || !isTransientIdbAbort(e) || attempt >= OPEN_IDB_RETRY_DELAYS_MS.length) {
5807
+ throw e;
5808
+ }
5809
+ this.#lc.info?.(
5810
+ `IndexedDB aborted the ${step} transaction; retry ${attempt + 1}`,
5811
+ e
5812
+ );
5813
+ const { signal } = this.#closeAbortController;
5814
+ await new Promise((resolve) => {
5815
+ const capTimer = setTimeout(resolve, FREEZE_RESUME_WAIT_CAP_MS);
5816
+ const done = () => {
5817
+ clearTimeout(capTimer);
5818
+ signal.removeEventListener("abort", done);
5819
+ resolve();
5820
+ };
5821
+ void whenPageResumed().then(done);
5822
+ signal.addEventListener("abort", done, { once: true });
5823
+ });
5824
+ if (this.#closed) {
5825
+ throw e;
5826
+ }
5827
+ const delay = OPEN_IDB_RETRY_DELAYS_MS[attempt];
5828
+ if (delay > 0) {
5829
+ await sleep(delay, this.#closeAbortController.signal);
5830
+ }
5831
+ }
5832
+ }
5833
+ }
5498
5834
  async #open(indexes, enableClientGroupForking, enableMutationRecovery, clientMaxAgeMs, profileIDResolver, resolveClientGroupID, resolveReady, onClientsDeleted) {
5499
5835
  const { clientID } = this;
5500
5836
  await closingInstances.get(this.name);
5501
- await withRegistryDeadline(
5502
- this.#idbDatabases.getProfileID().then(rememberProfileID),
5503
- recalledProfileID
5504
- ).then(profileIDResolver);
5505
- await withRegistryDeadline(
5506
- this.#idbDatabases.putDatabase(this.#idbDatabase),
5507
- () => void 0
5508
- );
5509
- const [client, headHash, , isNewClientGroup] = await initClientV6(
5510
- clientID,
5511
- this.#lc,
5512
- this.perdag,
5513
- Object.keys(this.#mutatorRegistry),
5514
- indexes,
5515
- Latest,
5516
- enableClientGroupForking
5837
+ await this.#retryTransientIdbAbort("registry", async () => {
5838
+ await withRegistryDeadline(
5839
+ this.#idbDatabases.getProfileID().then(rememberProfileID),
5840
+ recalledProfileID
5841
+ ).then(profileIDResolver);
5842
+ await withRegistryDeadline(
5843
+ this.#idbDatabases.putDatabase(this.#idbDatabase),
5844
+ () => void 0
5845
+ );
5846
+ });
5847
+ const [client, headHash, , isNewClientGroup] = await this.#retryTransientIdbAbort(
5848
+ "initClient",
5849
+ () => initClientV6(
5850
+ clientID,
5851
+ this.#lc,
5852
+ this.perdag,
5853
+ Object.keys(this.#mutatorRegistry),
5854
+ indexes,
5855
+ Latest,
5856
+ enableClientGroupForking
5857
+ )
5517
5858
  );
5518
5859
  resolveClientGroupID(client.clientGroupID);
5519
5860
  await withWrite(
5520
5861
  this.memdag,
5521
5862
  (write) => write.setHead(DEFAULT_HEAD_NAME, headHash)
5522
5863
  );
5523
- await this.#zero?.init(headHash, this.memdag);
5864
+ const zero2 = this.#zero;
5865
+ if (zero2) {
5866
+ await this.#retryTransientIdbAbort(
5867
+ "Zero init",
5868
+ () => zero2.init(headHash, this.memdag)
5869
+ );
5870
+ }
5524
5871
  resolveReady();
5525
5872
  if (this.#enablePullAndPushInOpen) {
5526
5873
  this.pull().catch(noop2);
@@ -5530,8 +5877,12 @@ var ReplicacheImpl = class {
5530
5877
  startHeartbeats(
5531
5878
  clientID,
5532
5879
  this.perdag,
5533
- () => {
5534
- this.#clientStateNotFoundOnClient(clientID);
5880
+ (cause) => {
5881
+ if (cause) {
5882
+ this.#idbNotFound(cause);
5883
+ } else {
5884
+ this.#clientStateNotFoundOnClient(clientID);
5885
+ }
5535
5886
  },
5536
5887
  HEARTBEAT_INTERVAL,
5537
5888
  this.#lc,
@@ -5567,7 +5918,14 @@ var ReplicacheImpl = class {
5567
5918
  () => {
5568
5919
  this.#fireOnUpdateNeeded(updateNeededReasonNewClientGroup);
5569
5920
  },
5570
- this.perdag
5921
+ this.perdag,
5922
+ (e) => {
5923
+ if (isIDBNotFoundError(e)) {
5924
+ this.#idbNotFound(e);
5925
+ } else {
5926
+ this.#lc.error?.("Error handling a new-client message", e);
5927
+ }
5928
+ }
5571
5929
  );
5572
5930
  setIntervalWithSignal(
5573
5931
  () => this.recoverMutations(),
@@ -5587,7 +5945,15 @@ var ReplicacheImpl = class {
5587
5945
  if (getBrowserGlobal("document")?.visibilityState !== "visible") {
5588
5946
  return;
5589
5947
  }
5590
- await this.#checkForClientStateNotFoundAndCallHandler();
5948
+ try {
5949
+ await this.#checkForClientStateNotFoundAndCallHandler();
5950
+ } catch (e) {
5951
+ if (e instanceof IDBNotFoundError) {
5952
+ this.#idbNotFound(e);
5953
+ } else {
5954
+ this.#lc.error?.("Error checking client state on visibility change", e);
5955
+ }
5956
+ }
5591
5957
  };
5592
5958
  async #checkForClientStateNotFoundAndCallHandler() {
5593
5959
  const { clientID } = this;
@@ -5600,6 +5966,14 @@ var ReplicacheImpl = class {
5600
5966
  }
5601
5967
  return !hasClientState2;
5602
5968
  }
5969
+ /**
5970
+ * `#ready` itself: resolves when open has completed (after Zero's `init`,
5971
+ * when there is one); never, if open failed. For tests that measure boot,
5972
+ * which must not read anything themselves to find out.
5973
+ */
5974
+ get readyForTesting() {
5975
+ return this.#ready;
5976
+ }
5603
5977
  /**
5604
5978
  * The browser profile ID for this browser profile. Every instance of Replicache
5605
5979
  * browser-profile-wide shares the same profile ID.
@@ -5660,7 +6034,7 @@ var ReplicacheImpl = class {
5660
6034
  "visibilitychange",
5661
6035
  this.#onVisibilityChange
5662
6036
  );
5663
- await this.#ready;
6037
+ await this.#opened;
5664
6038
  const closingPromises = [
5665
6039
  this.memdag.close(),
5666
6040
  this.perdag.close(),
@@ -6009,6 +6383,16 @@ var ReplicacheImpl = class {
6009
6383
  const { syncHead, httpRequestInfo } = beginPullResponse;
6010
6384
  return { requestID, syncHead, ok: httpRequestInfo.httpStatusCode === 200 };
6011
6385
  }
6386
+ /**
6387
+ * Writes the in-memory state to IndexedDB.
6388
+ *
6389
+ * Behaviour change: if this instance's IndexedDB database was deleted under
6390
+ * it (another tab's collector, or cleared site data), this no longer rejects
6391
+ * with `IDBNotFoundError`. It reports the loss once through
6392
+ * `onClientStateNotFound('idb-deleted')` and resolves; nothing was persisted.
6393
+ * `refresh()` behaves the same way. Callers that need to know the write did
6394
+ * not land must use `onClientStateNotFound`.
6395
+ */
6012
6396
  persist() {
6013
6397
  return this.#persistLock.withLock(async () => {
6014
6398
  const { clientID } = this;
@@ -6030,6 +6414,12 @@ var ReplicacheImpl = class {
6030
6414
  } catch (e) {
6031
6415
  if (e instanceof ClientStateNotFoundError) {
6032
6416
  this.#clientStateNotFoundOnClient(clientID);
6417
+ } else if (e instanceof IDBNotFoundError) {
6418
+ this.#idbNotFound(e);
6419
+ return;
6420
+ } else if (e instanceof PersistBaseMovedError) {
6421
+ this.#lc.debug?.("Persist base moved; rescheduling", e.message);
6422
+ void this.#schedulePersist();
6033
6423
  } else if (this.#closed) {
6034
6424
  this.#lc.debug?.("Exception persisting during close", e);
6035
6425
  } else {
@@ -6041,6 +6431,11 @@ var ReplicacheImpl = class {
6041
6431
  this.#onPersist({ clientID, clientGroupID });
6042
6432
  });
6043
6433
  }
6434
+ /**
6435
+ * Pulls the latest persisted state from IndexedDB. Like `persist()`, a
6436
+ * deleted database reports `onClientStateNotFound('idb-deleted')` and
6437
+ * resolves instead of rejecting.
6438
+ */
6044
6439
  async refresh() {
6045
6440
  await this.#ready;
6046
6441
  const { clientID } = this;
@@ -6063,6 +6458,8 @@ var ReplicacheImpl = class {
6063
6458
  } catch (e) {
6064
6459
  if (e instanceof ClientStateNotFoundError) {
6065
6460
  this.#clientStateNotFoundOnClient(clientID);
6461
+ } else if (e instanceof IDBNotFoundError) {
6462
+ this.#idbNotFound(e);
6066
6463
  } else if (this.#closed) {
6067
6464
  this.#lc.debug?.("Exception refreshing during close", e);
6068
6465
  } else {
@@ -6073,8 +6470,48 @@ var ReplicacheImpl = class {
6073
6470
  await this.#subscriptions.fire(refreshResult.diffs);
6074
6471
  }
6075
6472
  }
6076
- #fireOnClientStateNotFound() {
6077
- this.onClientStateNotFound?.();
6473
+ #reloadSuppressedWarned = false;
6474
+ #warnReloadSuppressed() {
6475
+ if (this.#reloadSuppressedWarned) {
6476
+ return;
6477
+ }
6478
+ this.#reloadSuppressedWarned = true;
6479
+ this.#lc.warn?.(
6480
+ `Client state not found again within ${RELOAD_LOOP_WINDOW_MS / 1e3}s of the last reload; not reloading again. This page keeps running in memory until it is reloaded.`
6481
+ );
6482
+ }
6483
+ #fireOnClientStateNotFound(reason) {
6484
+ try {
6485
+ if (reason === void 0) {
6486
+ this.onClientStateNotFound?.();
6487
+ } else {
6488
+ this.onClientStateNotFound?.(reason);
6489
+ }
6490
+ } catch (e) {
6491
+ this.#lc.error?.("onClientStateNotFound threw", e);
6492
+ }
6493
+ }
6494
+ /**
6495
+ * This instance's IndexedDB database is gone under it: another tab's
6496
+ * collector deleted it (it looked abandoned), or site data was cleared.
6497
+ * The client's state went with it, so this is the client-state-not-found
6498
+ * path, taken once: one warning, one `onClientStateNotFound`. The
6499
+ * background processes stop on their own (see `initBgIntervalProcess`).
6500
+ */
6501
+ #idbNotFound(e) {
6502
+ if (this.#closed) {
6503
+ this.#lc.debug?.("IndexedDB gone after close; ignoring.", e.message);
6504
+ return;
6505
+ }
6506
+ if (this.#idbNotFoundReported) {
6507
+ return;
6508
+ }
6509
+ this.#idbNotFoundReported = true;
6510
+ this.#lc.warn?.(
6511
+ `IndexedDB database ${this.idbName} was deleted while this client was running (another tab collected it, or site data was cleared). Its state is gone: calling onClientStateNotFound('${CLIENT_STATE_NOT_FOUND_REASON_IDB_DELETED}'), which reloads the page by default.`
6512
+ );
6513
+ this.#lc.debug?.(e);
6514
+ this.#fireOnClientStateNotFound(CLIENT_STATE_NOT_FOUND_REASON_IDB_DELETED);
6078
6515
  }
6079
6516
  #clientStateNotFoundOnClient(clientID) {
6080
6517
  this.#lc.error?.(`Client state not found on client, clientID: ${clientID}`);
@@ -6198,9 +6635,9 @@ var ReplicacheImpl = class {
6198
6635
  return this.#queryInternal(body);
6199
6636
  }
6200
6637
  /**
6201
- * The DURABLE last-mutation-IDs of this client's client group, read from
6202
- * the PERDAG — the companion to `cookie`, and required by any embedder
6203
- * that supplies its own pokes.
6638
+ * The DURABLE, server-acknowledged last-mutation-IDs of this client's
6639
+ * client group, read from the PERDAG — the companion to `cookie`, and
6640
+ * required by any embedder that supplies its own pokes.
6204
6641
  *
6205
6642
  * WHY THIS HAS TO EXIST. A poke's `lastMutationIDChanges` are merged
6206
6643
  * over the base snapshot's, so naming a client with a value BELOW what
@@ -6231,10 +6668,42 @@ var ReplicacheImpl = class {
6231
6668
  const clientGroupID = await this.#clientGroupIDPromise;
6232
6669
  return withRead(this.perdag, async (perdagRead) => {
6233
6670
  const clientGroup = await getClientGroup(clientGroupID, perdagRead);
6234
- return clientGroup ? { ...clientGroup.mutationIDs } : {};
6671
+ return clientGroup ? { ...clientGroup.lastServerAckdMutationIDs } : {};
6235
6672
  });
6236
6673
  });
6237
6674
  }
6675
+ /**
6676
+ * The snapshot the next poke applies on — its cookie and every entry
6677
+ * whose key starts with `prefix`, read together. For embedders that
6678
+ * supply their own pokes and must diff against what that snapshot really
6679
+ * holds (after a sibling tab's snapshot was refreshed in underneath them,
6680
+ * or while pending mutations make the local view differ from it).
6681
+ */
6682
+ baseSnapshotEntries(prefix) {
6683
+ return this.#ready.then(
6684
+ () => withRead(this.memdag, async (dagRead) => {
6685
+ const mainHeadHash = await dagRead.getHead(DEFAULT_HEAD_NAME);
6686
+ if (!mainHeadHash) {
6687
+ throw new Error("Internal no main head found");
6688
+ }
6689
+ const base = await baseSnapshotFromHash(mainHeadHash, dagRead);
6690
+ const cookie = base.meta.cookieJSON;
6691
+ assertCookie(cookie);
6692
+ const map = new BTreeRead(
6693
+ dagRead,
6694
+ Latest,
6695
+ base.valueHash
6696
+ );
6697
+ const all = await map.scanAll(prefix);
6698
+ const entries = [];
6699
+ for (const [key, value] of all) {
6700
+ if (!key.startsWith(prefix)) break;
6701
+ entries.push([key, value]);
6702
+ }
6703
+ return { cookie, entries };
6704
+ })
6705
+ );
6706
+ }
6238
6707
  get cookie() {
6239
6708
  return this.#ready.then(
6240
6709
  () => withRead(this.memdag, async (dagRead) => {
@@ -6401,6 +6870,12 @@ var ReplicacheImpl = class {
6401
6870
  return withRead(this.memdag, pendingMutationsForAPI);
6402
6871
  }
6403
6872
  };
6873
+ var CLIENT_STATE_NOT_FOUND_REASON_IDB_DELETED = "idb-deleted";
6874
+ var OPEN_IDB_RETRY_DELAYS_MS = [0, 100, 500, 2e3];
6875
+ var FREEZE_RESUME_WAIT_CAP_MS = 1e4;
6876
+ function isTransientIdbAbort(e) {
6877
+ return typeof DOMException !== "undefined" && e instanceof DOMException && (e.name === "AbortError" || e.name === "InvalidStateError" || e.name === "TransactionInactiveError");
6878
+ }
6404
6879
  var closingInstances = /* @__PURE__ */ new Map();
6405
6880
  async function throwIfError(p) {
6406
6881
  const res = await p;
@@ -6408,6 +6883,19 @@ async function throwIfError(p) {
6408
6883
  throw res.error;
6409
6884
  }
6410
6885
  }
6886
+ var RELOAD_LOOP_WINDOW_MS = 1e4;
6887
+ function allowClientStateNotFoundReload(idbName, now = Date.now()) {
6888
+ try {
6889
+ const key = `replicache-client-state-not-found-reload:${idbName}`;
6890
+ const last = Number(sessionStorage.getItem(key));
6891
+ if (last > 0 && now - last >= 0 && now - last < RELOAD_LOOP_WINDOW_MS) {
6892
+ return false;
6893
+ }
6894
+ sessionStorage.setItem(key, String(now));
6895
+ } catch {
6896
+ }
6897
+ return true;
6898
+ }
6411
6899
  function reload() {
6412
6900
  if (typeof location !== "undefined") {
6413
6901
  location.reload();
@@ -13104,7 +13592,7 @@ var Connecting = 1;
13104
13592
  var Connected = 2;
13105
13593
 
13106
13594
  // ../zql/src/ivm/memory-storage.ts
13107
- import { compareUTF8 as compareUTF82 } from "compare-utf8";
13595
+ import { compareUTF8 as compareUTF83 } from "compare-utf8";
13108
13596
 
13109
13597
  // ../shared/src/btree-set.ts
13110
13598
  var MAX_NODE_SIZE = 32;
@@ -13595,7 +14083,7 @@ emptyLeaf.isShared = true;
13595
14083
 
13596
14084
  // ../zql/src/ivm/memory-storage.ts
13597
14085
  function comparator(a, b) {
13598
- return compareUTF82(a[0], b[0]);
14086
+ return compareUTF83(a[0], b[0]);
13599
14087
  }
13600
14088
  var MemoryStorage = class {
13601
14089
  #data = new BTreeSet(comparator);
@@ -14277,9 +14765,7 @@ async function computeDiffs(startHash, endHash, store, readOptions) {
14277
14765
  Latest
14278
14766
  );
14279
14767
  let diffs;
14280
- if (readOptions?.openLazySourceRead) {
14281
- diffs = await using(store.read(readOptions.openLazySourceRead), readFn);
14282
- } else if (readOptions?.openLazyRead) {
14768
+ if (readOptions?.openLazyRead) {
14283
14769
  diffs = await readFn(readOptions.openLazyRead);
14284
14770
  } else {
14285
14771
  diffs = await withRead(store, readFn);
@@ -15109,7 +15595,7 @@ function makeMessage(message, context, logLevel) {
15109
15595
  }
15110
15596
 
15111
15597
  // ../zero-client/src/client/version.ts
15112
- var version2 = "2.2.5";
15598
+ var version2 = "2.2.7";
15113
15599
 
15114
15600
  // ../zero-client/src/client/log-options.ts
15115
15601
  var LevelFilterLogSink = class {
@@ -16487,6 +16973,7 @@ var ZeroRep = class {
16487
16973
  #onLocalHydrationComplete;
16488
16974
  #store;
16489
16975
  #auth;
16976
+ #initialized = false;
16490
16977
  constructor(context, ivmMain, customMutatorsEnabled, mutationTracker, onLocalHydrationComplete) {
16491
16978
  this.#context = context;
16492
16979
  this.#ivmMain = ivmMain;
@@ -16501,7 +16988,16 @@ var ZeroRep = class {
16501
16988
  this.#auth = auth;
16502
16989
  }
16503
16990
  }
16991
+ /**
16992
+ * Safe to call again: Replicache retries it when IndexedDB aborts its read
16993
+ * (a tab frozen while it boots). A call that fails applies nothing (the
16994
+ * rows are applied only after the whole read); once one has applied its
16995
+ * result, later calls do nothing.
16996
+ */
16504
16997
  async init(hash, store) {
16998
+ if (this.#initialized) {
16999
+ return;
17000
+ }
16505
17001
  const t0 = nowMs();
16506
17002
  const ts = () => Math.round(nowMs() - t0);
16507
17003
  const diffs = [];
@@ -16558,21 +17054,34 @@ var ZeroRep = class {
16558
17054
  console.log(`[ZERO-INIT] scan: ${diffs.length} entities at +${ts()}ms`);
16559
17055
  }
16560
17056
  });
16561
- this.#store = store;
16562
- const ivmT0 = nowMs();
16563
- this.#context.processChanges(void 0, hash, diffs);
16564
- if (shouldLogColdIdb()) {
16565
- logColdIdbStage("init-processChanges", {
16566
- entities: diffs.length,
16567
- ms: Math.round(nowMs() - ivmT0),
16568
- atMs: ts()
16569
- });
16570
- logColdIdbStage("init-done", { ms: ts(), entities: diffs.length });
17057
+ if (this.#initialized) {
17058
+ return;
16571
17059
  }
16572
- if (shouldLogColdIdb()) {
16573
- console.log(`[ZERO-INIT] done at +${ts()}ms`);
17060
+ this.#store = store;
17061
+ try {
17062
+ const ivmT0 = nowMs();
17063
+ this.#context.processChanges(void 0, hash, diffs);
17064
+ if (shouldLogColdIdb()) {
17065
+ logColdIdbStage("init-processChanges", {
17066
+ entities: diffs.length,
17067
+ ms: Math.round(nowMs() - ivmT0),
17068
+ atMs: ts()
17069
+ });
17070
+ logColdIdbStage("init-done", { ms: ts(), entities: diffs.length });
17071
+ }
17072
+ if (shouldLogColdIdb()) {
17073
+ console.log(`[ZERO-INIT] done at +${ts()}ms`);
17074
+ }
17075
+ this.#onLocalHydrationComplete();
17076
+ this.#initialized = true;
17077
+ } catch (e) {
17078
+ if (typeof DOMException !== "undefined" && e instanceof DOMException) {
17079
+ throw new Error(`Zero init failed applying persisted rows: ${e.name}`, {
17080
+ cause: e
17081
+ });
17082
+ }
17083
+ throw e;
16574
17084
  }
16575
- this.#onLocalHydrationComplete();
16576
17085
  }
16577
17086
  getTxData = (desiredHead, readOptions) => {
16578
17087
  if (!this.#customMutatorsEnabled) {
@@ -17216,10 +17725,18 @@ var Zero = class _Zero {
17216
17725
  this.#mutationTracker.lmidAdvanced(lmid);
17217
17726
  }
17218
17727
  }
17219
- this.#pokePersistChain = this.#pokePersistChain.then(() => this.#rep.persist()).catch(() => {
17728
+ if (this.#pokePersistQueued) {
17729
+ return;
17730
+ }
17731
+ this.#pokePersistQueued = true;
17732
+ this.#pokePersistChain = this.#pokePersistChain.then(() => {
17733
+ this.#pokePersistQueued = false;
17734
+ return this.#rep.persist();
17735
+ }).catch(() => {
17220
17736
  });
17221
17737
  }
17222
17738
  #pokePersistChain = Promise.resolve();
17739
+ #pokePersistQueued = false;
17223
17740
  /** Resolves when every persist queued by pokeDirect so far has landed. */
17224
17741
  persistPending() {
17225
17742
  return this.#pokePersistChain;
@@ -17265,7 +17782,8 @@ var Zero = class _Zero {
17265
17782
  return this.#rep.cookie;
17266
17783
  }
17267
17784
  /**
17268
- * The DURABLE last-mutation-IDs of this client's client group.
17785
+ * The DURABLE, server-acknowledged last-mutation-IDs of this client's
17786
+ * client group (pending local mutations are not counted).
17269
17787
  *
17270
17788
  * An adapter that supplies its own pokes MUST floor every
17271
17789
  * `lastMutationIDChanges` entry with this. A poke naming any client —
@@ -17278,6 +17796,16 @@ var Zero = class _Zero {
17278
17796
  get currentLastMutationIDs() {
17279
17797
  return this.#rep.lastMutationIDs;
17280
17798
  }
17799
+ /**
17800
+ * The snapshot the next `pokeDirect` applies on: its cookie and every
17801
+ * entry under `prefix`, read together. Lets an adapter diff against what
17802
+ * that snapshot really holds when it is not what the adapter last poked
17803
+ * (a sibling tab's snapshot refreshed in, or pending mutations that make
17804
+ * the local view differ from it on rows it cannot name).
17805
+ */
17806
+ baseSnapshotEntries(prefix) {
17807
+ return this.#rep.baseSnapshotEntries(prefix);
17808
+ }
17281
17809
  #onMessage = (e) => {
17282
17810
  const lc = this.#lc;
17283
17811
  lc.debug?.("received message", e.data);