ahmed-rivet-convex 2.2.5 → 2.2.6

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 {
@@ -3250,7 +3247,13 @@ var NoOp = 1;
3250
3247
  var CookieMismatch = 2;
3251
3248
 
3252
3249
  // ../replicache/src/sync/patch.ts
3250
+ import { compareUTF8 } from "compare-utf8";
3251
+ var BULK_MIN_OPS = 1024;
3252
+ var BULK_MAX_TREE_RATIO = 4;
3253
3253
  async function apply(lc, dbWrite, patch) {
3254
+ if (patch.length >= BULK_MIN_OPS && await applyBulk(dbWrite, patch)) {
3255
+ return;
3256
+ }
3254
3257
  for (const p of patch) {
3255
3258
  switch (p.op) {
3256
3259
  case "put": {
@@ -3293,6 +3296,23 @@ async function apply(lc, dbWrite, patch) {
3293
3296
  }
3294
3297
  }
3295
3298
  }
3299
+ async function applyBulk(dbWrite, patch) {
3300
+ if (dbWrite.indexes.size > 0) {
3301
+ return false;
3302
+ }
3303
+ const byKey = /* @__PURE__ */ new Map();
3304
+ for (const p of patch) {
3305
+ if (p.op === "put") {
3306
+ byKey.set(p.key, deepFreeze(p.value));
3307
+ } else if (p.op === "del") {
3308
+ byKey.set(p.key, void 0);
3309
+ } else {
3310
+ return false;
3311
+ }
3312
+ }
3313
+ const changes = [...byKey].sort((a, b) => compareUTF8(a[0], b[0]));
3314
+ return dbWrite.map.putSorted(changes, changes.length * BULK_MAX_TREE_RATIO);
3315
+ }
3296
3316
 
3297
3317
  // ../replicache/src/sync/pull-error.ts
3298
3318
  var PullError = class extends Error {
@@ -4316,11 +4336,19 @@ var GatherMemoryOnlyVisitor = class extends Visitor {
4316
4336
  };
4317
4337
 
4318
4338
  // ../replicache/src/persist/persist.ts
4339
+ var PersistBaseMovedError = class extends Error {
4340
+ constructor(expected, actual) {
4341
+ super(`perdag head moved during persist: ${expected} -> ${actual}`);
4342
+ this.expected = expected;
4343
+ this.actual = actual;
4344
+ }
4345
+ name = "PersistBaseMovedError";
4346
+ };
4319
4347
  async function persistDD31(lc, clientID, memdag, perdag, mutators, closed, formatVersion, getZeroData, onGatherMemOnlyChunksForTest = () => Promise.resolve()) {
4320
4348
  if (closed()) {
4321
4349
  return;
4322
4350
  }
4323
- const [perdagLMID, perdagBaseSnapshot, mainClientGroupID] = await withRead(
4351
+ const [perdagLMID, perdagBaseSnapshot, mainClientGroupID, perdagHeadHashAtRead] = await withRead(
4324
4352
  perdag,
4325
4353
  async (perdagRead) => {
4326
4354
  await assertHasClientState(clientID, perdagRead);
@@ -4345,7 +4373,12 @@ async function persistDD31(lc, clientID, memdag, perdag, mutators, closed, forma
4345
4373
  perdagRead
4346
4374
  );
4347
4375
  assertSnapshotCommitDD31(perdagBaseSnapshot2);
4348
- return [perdagLMID2, perdagBaseSnapshot2, mainClientGroupID2];
4376
+ return [
4377
+ perdagLMID2,
4378
+ perdagBaseSnapshot2,
4379
+ mainClientGroupID2,
4380
+ perdagMainClientGroupHeadCommit.chunk.hash
4381
+ ];
4349
4382
  }
4350
4383
  );
4351
4384
  if (closed()) {
@@ -4381,6 +4414,10 @@ async function persistDD31(lc, clientID, memdag, perdag, mutators, closed, forma
4381
4414
  }
4382
4415
  let memdagBaseSnapshotPersisted = false;
4383
4416
  const zeroDataForMemdagBaseSnapshot = getZeroData && await getZeroData(memdagBaseSnapshot.chunk.hash);
4417
+ const zeroDataForPerdagHeadAtRead = getZeroData && await getZeroData(perdagHeadHashAtRead);
4418
+ if (closed()) {
4419
+ return;
4420
+ }
4384
4421
  await withWrite(perdag, async (perdagWrite) => {
4385
4422
  const [mainClientGroup, latestPerdagMainClientGroupHeadCommit] = await getClientGroupInfo(perdagWrite, mainClientGroupID);
4386
4423
  let newMainClientGroupHeadHash = latestPerdagMainClientGroupHeadCommit.chunk.hash;
@@ -4435,10 +4472,14 @@ async function persistDD31(lc, clientID, memdag, perdag, mutators, closed, forma
4435
4472
  }
4436
4473
  }
4437
4474
  let zeroDataForPerdagHeadCommit;
4438
- if (!memdagBaseSnapshotPersisted) {
4439
- zeroDataForPerdagHeadCommit = getZeroData && await getZeroData(newMainClientGroupHeadHash, {
4440
- openLazySourceRead: perdagWrite
4441
- });
4475
+ if (!memdagBaseSnapshotPersisted && getZeroData) {
4476
+ if (newMainClientGroupHeadHash !== perdagHeadHashAtRead) {
4477
+ throw new PersistBaseMovedError(
4478
+ perdagHeadHashAtRead,
4479
+ newMainClientGroupHeadHash
4480
+ );
4481
+ }
4482
+ zeroDataForPerdagHeadCommit = zeroDataForPerdagHeadAtRead;
4442
4483
  }
4443
4484
  newMainClientGroupHeadHash = await rebase(
4444
4485
  newMemdagMutations,
@@ -4835,7 +4876,7 @@ function setIntervalWithSignal(fn, ms, signal) {
4835
4876
  }
4836
4877
 
4837
4878
  // ../replicache/src/subscriptions.ts
4838
- import { compareUTF8, greaterThan as greaterThan3, lessThan, lessThanEq } from "compare-utf8";
4879
+ import { compareUTF8 as compareUTF82, greaterThan as greaterThan3, lessThan, lessThanEq } from "compare-utf8";
4839
4880
 
4840
4881
  // ../replicache/src/invoke-kind-enum.ts
4841
4882
  var InitialRun = 0;
@@ -5178,7 +5219,7 @@ function watcherMatchesDiff(diff3, prefix, indexName) {
5178
5219
  function diffBinarySearch(diff3, prefix, compareKey) {
5179
5220
  return binarySearch(
5180
5221
  diff3.length,
5181
- (i) => compareUTF8(prefix, compareKey(diff3[i]))
5222
+ (i) => compareUTF82(prefix, compareKey(diff3[i]))
5182
5223
  );
5183
5224
  }
5184
5225
 
@@ -5263,6 +5304,9 @@ var ReplicacheImpl = class {
5263
5304
  #online = true;
5264
5305
  #clientID = makeClientID();
5265
5306
  #ready;
5307
+ /** Settles when #open finishes, succeeded OR failed — what close waits on. */
5308
+ // eslint-disable-next-line no-unused-private-class-members -- False positive, close() awaits it
5309
+ #opened;
5266
5310
  #profileIDPromise;
5267
5311
  #clientGroupIDPromise;
5268
5312
  #mutatorRegistry = {};
@@ -5484,7 +5528,7 @@ var ReplicacheImpl = class {
5484
5528
  void this.#handlePersist(persistInfo);
5485
5529
  }
5486
5530
  );
5487
- void this.#open(
5531
+ this.#opened = this.#open(
5488
5532
  indexes,
5489
5533
  enableClientGroupForking,
5490
5534
  enableMutationRecovery,
@@ -5493,27 +5537,80 @@ var ReplicacheImpl = class {
5493
5537
  clientGroupIDResolver.resolve,
5494
5538
  readyResolver.resolve,
5495
5539
  onClientsDeleted
5540
+ ).catch((e) => this.#reportOpenFailure(e));
5541
+ }
5542
+ /**
5543
+ * An open that fails leaves the instance unready until a reload (upstream
5544
+ * behaviour — nothing downstream can run without a client group). What
5545
+ * changes is that the failure is REPORTED once instead of escaping as an
5546
+ * unhandled rejection: measured 2026-09-27 (Protocolbase), aborting the
5547
+ * perdag's IndexedDB transaction during boot raised `Uncaught (in promise)
5548
+ * InvalidStateError: Failed to execute 'objectStore' on 'IDBTransaction':
5549
+ * The transaction has finished` from initClientV6 → #open.
5550
+ */
5551
+ #reportOpenFailure(e) {
5552
+ if (this.#closed || e instanceof AbortError) {
5553
+ this.#lc.debug?.("Open did not complete before close", e);
5554
+ return;
5555
+ }
5556
+ this.#lc.error?.(
5557
+ "Replicache failed to open; it stays unready until the page reloads",
5558
+ e
5496
5559
  );
5497
5560
  }
5561
+ /**
5562
+ * Runs one IndexedDB step of open, retrying when IndexedDB aborted its
5563
+ * transaction. The browser aborts transactions on events this code never
5564
+ * causes — a tab being frozen (this store's own `freeze` release aborts
5565
+ * every live transaction), storage filling up, a sibling deleting the
5566
+ * database — and every step retried here is atomic (a registry read or
5567
+ * put, `initClientV6`'s single perdag write), so a retry starts from a
5568
+ * clean transaction. The first retry is immediate: a frozen page resumes
5569
+ * straight into it. Bounded, and never after close.
5570
+ */
5571
+ async #retryTransientIdbAbort(step, fn) {
5572
+ for (let attempt = 0; ; attempt++) {
5573
+ try {
5574
+ return await fn();
5575
+ } catch (e) {
5576
+ if (this.#closed || !isTransientIdbAbort(e) || attempt >= OPEN_IDB_RETRY_DELAYS_MS.length) {
5577
+ throw e;
5578
+ }
5579
+ this.#lc.info?.(
5580
+ `IndexedDB aborted the ${step} transaction; retry ${attempt + 1}`,
5581
+ e
5582
+ );
5583
+ const delay = OPEN_IDB_RETRY_DELAYS_MS[attempt];
5584
+ if (delay > 0) {
5585
+ await sleep(delay, this.#closeAbortController.signal);
5586
+ }
5587
+ }
5588
+ }
5589
+ }
5498
5590
  async #open(indexes, enableClientGroupForking, enableMutationRecovery, clientMaxAgeMs, profileIDResolver, resolveClientGroupID, resolveReady, onClientsDeleted) {
5499
5591
  const { clientID } = this;
5500
5592
  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
5593
+ await this.#retryTransientIdbAbort("registry", async () => {
5594
+ await withRegistryDeadline(
5595
+ this.#idbDatabases.getProfileID().then(rememberProfileID),
5596
+ recalledProfileID
5597
+ ).then(profileIDResolver);
5598
+ await withRegistryDeadline(
5599
+ this.#idbDatabases.putDatabase(this.#idbDatabase),
5600
+ () => void 0
5601
+ );
5602
+ });
5603
+ const [client, headHash, , isNewClientGroup] = await this.#retryTransientIdbAbort(
5604
+ "initClient",
5605
+ () => initClientV6(
5606
+ clientID,
5607
+ this.#lc,
5608
+ this.perdag,
5609
+ Object.keys(this.#mutatorRegistry),
5610
+ indexes,
5611
+ Latest,
5612
+ enableClientGroupForking
5613
+ )
5517
5614
  );
5518
5615
  resolveClientGroupID(client.clientGroupID);
5519
5616
  await withWrite(
@@ -5660,7 +5757,7 @@ var ReplicacheImpl = class {
5660
5757
  "visibilitychange",
5661
5758
  this.#onVisibilityChange
5662
5759
  );
5663
- await this.#ready;
5760
+ await this.#opened;
5664
5761
  const closingPromises = [
5665
5762
  this.memdag.close(),
5666
5763
  this.perdag.close(),
@@ -6030,6 +6127,9 @@ var ReplicacheImpl = class {
6030
6127
  } catch (e) {
6031
6128
  if (e instanceof ClientStateNotFoundError) {
6032
6129
  this.#clientStateNotFoundOnClient(clientID);
6130
+ } else if (e instanceof PersistBaseMovedError) {
6131
+ this.#lc.debug?.("Persist base moved; rescheduling", e.message);
6132
+ void this.#schedulePersist();
6033
6133
  } else if (this.#closed) {
6034
6134
  this.#lc.debug?.("Exception persisting during close", e);
6035
6135
  } else {
@@ -6198,9 +6298,9 @@ var ReplicacheImpl = class {
6198
6298
  return this.#queryInternal(body);
6199
6299
  }
6200
6300
  /**
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.
6301
+ * The DURABLE, server-acknowledged last-mutation-IDs of this client's
6302
+ * client group, read from the PERDAG — the companion to `cookie`, and
6303
+ * required by any embedder that supplies its own pokes.
6204
6304
  *
6205
6305
  * WHY THIS HAS TO EXIST. A poke's `lastMutationIDChanges` are merged
6206
6306
  * over the base snapshot's, so naming a client with a value BELOW what
@@ -6231,10 +6331,42 @@ var ReplicacheImpl = class {
6231
6331
  const clientGroupID = await this.#clientGroupIDPromise;
6232
6332
  return withRead(this.perdag, async (perdagRead) => {
6233
6333
  const clientGroup = await getClientGroup(clientGroupID, perdagRead);
6234
- return clientGroup ? { ...clientGroup.mutationIDs } : {};
6334
+ return clientGroup ? { ...clientGroup.lastServerAckdMutationIDs } : {};
6235
6335
  });
6236
6336
  });
6237
6337
  }
6338
+ /**
6339
+ * The snapshot the next poke applies on — its cookie and every entry
6340
+ * whose key starts with `prefix`, read together. For embedders that
6341
+ * supply their own pokes and must diff against what that snapshot really
6342
+ * holds (after a sibling tab's snapshot was refreshed in underneath them,
6343
+ * or while pending mutations make the local view differ from it).
6344
+ */
6345
+ baseSnapshotEntries(prefix) {
6346
+ return this.#ready.then(
6347
+ () => withRead(this.memdag, async (dagRead) => {
6348
+ const mainHeadHash = await dagRead.getHead(DEFAULT_HEAD_NAME);
6349
+ if (!mainHeadHash) {
6350
+ throw new Error("Internal no main head found");
6351
+ }
6352
+ const base = await baseSnapshotFromHash(mainHeadHash, dagRead);
6353
+ const cookie = base.meta.cookieJSON;
6354
+ assertCookie(cookie);
6355
+ const map = new BTreeRead(
6356
+ dagRead,
6357
+ Latest,
6358
+ base.valueHash
6359
+ );
6360
+ const all = await map.scanAll(prefix);
6361
+ const entries = [];
6362
+ for (const [key, value] of all) {
6363
+ if (!key.startsWith(prefix)) break;
6364
+ entries.push([key, value]);
6365
+ }
6366
+ return { cookie, entries };
6367
+ })
6368
+ );
6369
+ }
6238
6370
  get cookie() {
6239
6371
  return this.#ready.then(
6240
6372
  () => withRead(this.memdag, async (dagRead) => {
@@ -6401,6 +6533,10 @@ var ReplicacheImpl = class {
6401
6533
  return withRead(this.memdag, pendingMutationsForAPI);
6402
6534
  }
6403
6535
  };
6536
+ var OPEN_IDB_RETRY_DELAYS_MS = [0, 100, 500, 2e3];
6537
+ function isTransientIdbAbort(e) {
6538
+ return typeof DOMException !== "undefined" && e instanceof DOMException && (e.name === "AbortError" || e.name === "InvalidStateError" || e.name === "TransactionInactiveError");
6539
+ }
6404
6540
  var closingInstances = /* @__PURE__ */ new Map();
6405
6541
  async function throwIfError(p) {
6406
6542
  const res = await p;
@@ -13104,7 +13240,7 @@ var Connecting = 1;
13104
13240
  var Connected = 2;
13105
13241
 
13106
13242
  // ../zql/src/ivm/memory-storage.ts
13107
- import { compareUTF8 as compareUTF82 } from "compare-utf8";
13243
+ import { compareUTF8 as compareUTF83 } from "compare-utf8";
13108
13244
 
13109
13245
  // ../shared/src/btree-set.ts
13110
13246
  var MAX_NODE_SIZE = 32;
@@ -13595,7 +13731,7 @@ emptyLeaf.isShared = true;
13595
13731
 
13596
13732
  // ../zql/src/ivm/memory-storage.ts
13597
13733
  function comparator(a, b) {
13598
- return compareUTF82(a[0], b[0]);
13734
+ return compareUTF83(a[0], b[0]);
13599
13735
  }
13600
13736
  var MemoryStorage = class {
13601
13737
  #data = new BTreeSet(comparator);
@@ -14277,9 +14413,7 @@ async function computeDiffs(startHash, endHash, store, readOptions) {
14277
14413
  Latest
14278
14414
  );
14279
14415
  let diffs;
14280
- if (readOptions?.openLazySourceRead) {
14281
- diffs = await using(store.read(readOptions.openLazySourceRead), readFn);
14282
- } else if (readOptions?.openLazyRead) {
14416
+ if (readOptions?.openLazyRead) {
14283
14417
  diffs = await readFn(readOptions.openLazyRead);
14284
14418
  } else {
14285
14419
  diffs = await withRead(store, readFn);
@@ -15109,7 +15243,7 @@ function makeMessage(message, context, logLevel) {
15109
15243
  }
15110
15244
 
15111
15245
  // ../zero-client/src/client/version.ts
15112
- var version2 = "2.2.5";
15246
+ var version2 = "2.2.6";
15113
15247
 
15114
15248
  // ../zero-client/src/client/log-options.ts
15115
15249
  var LevelFilterLogSink = class {
@@ -17216,10 +17350,18 @@ var Zero = class _Zero {
17216
17350
  this.#mutationTracker.lmidAdvanced(lmid);
17217
17351
  }
17218
17352
  }
17219
- this.#pokePersistChain = this.#pokePersistChain.then(() => this.#rep.persist()).catch(() => {
17353
+ if (this.#pokePersistQueued) {
17354
+ return;
17355
+ }
17356
+ this.#pokePersistQueued = true;
17357
+ this.#pokePersistChain = this.#pokePersistChain.then(() => {
17358
+ this.#pokePersistQueued = false;
17359
+ return this.#rep.persist();
17360
+ }).catch(() => {
17220
17361
  });
17221
17362
  }
17222
17363
  #pokePersistChain = Promise.resolve();
17364
+ #pokePersistQueued = false;
17223
17365
  /** Resolves when every persist queued by pokeDirect so far has landed. */
17224
17366
  persistPending() {
17225
17367
  return this.#pokePersistChain;
@@ -17265,7 +17407,8 @@ var Zero = class _Zero {
17265
17407
  return this.#rep.cookie;
17266
17408
  }
17267
17409
  /**
17268
- * The DURABLE last-mutation-IDs of this client's client group.
17410
+ * The DURABLE, server-acknowledged last-mutation-IDs of this client's
17411
+ * client group (pending local mutations are not counted).
17269
17412
  *
17270
17413
  * An adapter that supplies its own pokes MUST floor every
17271
17414
  * `lastMutationIDChanges` entry with this. A poke naming any client —
@@ -17278,6 +17421,16 @@ var Zero = class _Zero {
17278
17421
  get currentLastMutationIDs() {
17279
17422
  return this.#rep.lastMutationIDs;
17280
17423
  }
17424
+ /**
17425
+ * The snapshot the next `pokeDirect` applies on: its cookie and every
17426
+ * entry under `prefix`, read together. Lets an adapter diff against what
17427
+ * that snapshot really holds when it is not what the adapter last poked
17428
+ * (a sibling tab's snapshot refreshed in, or pending mutations that make
17429
+ * the local view differ from it on rows it cannot name).
17430
+ */
17431
+ baseSnapshotEntries(prefix) {
17432
+ return this.#rep.baseSnapshotEntries(prefix);
17433
+ }
17281
17434
  #onMessage = (e) => {
17282
17435
  const lc = this.#lc;
17283
17436
  lc.debug?.("received message", e.data);
@@ -852,6 +852,10 @@ var DataNodeImpl = class extends NodeImpl {
852
852
  if (!binarySearchFound(i, this.entries, key)) {
853
853
  deleteCount = 0;
854
854
  } else {
855
+ if (deepEqual(this.entries[i][1], value)) {
856
+ tree.putWasNoop = true;
857
+ return Promise.resolve(this);
858
+ }
855
859
  deleteCount = 1;
856
860
  }
857
861
  return Promise.resolve(
@@ -909,6 +913,9 @@ var InternalNodeImpl = class _InternalNodeImpl extends NodeImpl {
909
913
  const childHash = this.entries[i][1];
910
914
  const oldChildNode = await tree.getNode(childHash);
911
915
  const childNode = await oldChildNode.set(key, value, entrySize, tree);
916
+ if (tree.putWasNoop) {
917
+ return this;
918
+ }
912
919
  const childNodeSize = childNode.getChildNodeSize(tree);
913
920
  if (childNodeSize > tree.maxSize || childNodeSize < tree.minSize) {
914
921
  return this.#mergeAndPartition(tree, i, childNode);
@@ -1005,9 +1012,6 @@ var InternalNodeImpl = class _InternalNodeImpl extends NodeImpl {
1005
1012
  const entries = readonlySplice(this.entries, i, 1);
1006
1013
  return tree.newInternalNodeImpl(entries, this.level);
1007
1014
  }
1008
- if (i === 0 && this.entries.length === 1) {
1009
- return childNode;
1010
- }
1011
1015
  if (childNode.getChildNodeSize(tree) > tree.minSize) {
1012
1016
  const entry = createNewInternalEntryForNode(childNode, tree.getEntrySize);
1013
1017
  return this.#replaceChild(tree, i, entry);
@@ -2361,6 +2365,8 @@ function diff(oldMap, newMap) {
2361
2365
 
2362
2366
  // ../replicache/src/btree/write.ts
2363
2367
  import { Lock } from "@rocicorp/lock";
2368
+ import { compareUTF8 as compareUTF82 } from "compare-utf8";
2369
+ var REBUILD_MIN_CHANGE_RATIO = 4;
2364
2370
  var BTreeWrite = class extends BTreeRead {
2365
2371
  /**
2366
2372
  * This rw lock is used to ensure we do not mutate the btree in parallel. It
@@ -2413,45 +2419,140 @@ var BTreeWrite = class extends BTreeRead {
2413
2419
  this.#addToModified(n);
2414
2420
  return n;
2415
2421
  }
2422
+ /**
2423
+ * Set by the leaf when the put being applied stores a value equal to the
2424
+ * existing one; the nodes on the path then return themselves unchanged.
2425
+ */
2426
+ putWasNoop = false;
2416
2427
  put(key, value) {
2428
+ return this.#lock.withLock(() => this.#put(key, value));
2429
+ }
2430
+ async #put(key, value) {
2431
+ const oldRootNode = await this.getNode(this.rootHash);
2432
+ const entrySize = this.getEntrySize(key, value);
2433
+ this.putWasNoop = false;
2434
+ const rootNode = await oldRootNode.set(key, value, entrySize, this);
2435
+ if (this.putWasNoop) {
2436
+ return;
2437
+ }
2438
+ if (rootNode.getChildNodeSize(this) > this.maxSize) {
2439
+ const headerSize = this.chunkHeaderSize;
2440
+ const partitions = partition(
2441
+ rootNode.entries,
2442
+ (value2) => value2[2],
2443
+ this.minSize - headerSize,
2444
+ this.maxSize - headerSize
2445
+ );
2446
+ const { level } = rootNode;
2447
+ const entries = partitions.map((entries2) => {
2448
+ const node = this.newNodeImpl(entries2, level);
2449
+ return createNewInternalEntryForNode(node, this.getEntrySize);
2450
+ });
2451
+ const newRoot = this.newInternalNodeImpl(entries, level + 1);
2452
+ this.rootHash = newRoot.hash;
2453
+ return;
2454
+ }
2455
+ this.rootHash = rootNode.hash;
2456
+ }
2457
+ /**
2458
+ * Applies `changes` (strictly ascending by key; `undefined` deletes) by
2459
+ * merging them with the existing entries and building the tree bottom-up
2460
+ * in one pass — no per-entry lock, descent, path copy or fresh hash. For
2461
+ * large patches (a first hydrate, a bulk change) this replaces N
2462
+ * sequential puts. Returns false, having changed nothing, when the tree
2463
+ * holds more than `maxExisting` entries: then sequential puts touch less.
2464
+ */
2465
+ putSorted(changes, maxExisting) {
2417
2466
  return this.#lock.withLock(async () => {
2418
- const oldRootNode = await this.getNode(this.rootHash);
2419
- const entrySize = this.getEntrySize(key, value);
2420
- const rootNode = await oldRootNode.set(key, value, entrySize, this);
2421
- if (rootNode.getChildNodeSize(this) > this.maxSize) {
2422
- const headerSize = this.chunkHeaderSize;
2423
- const partitions = partition(
2424
- rootNode.entries,
2425
- (value2) => value2[2],
2426
- this.minSize - headerSize,
2427
- this.maxSize - headerSize
2467
+ const existing = [];
2468
+ if (!await this.#collectEntries(this.rootHash, existing, maxExisting)) {
2469
+ return false;
2470
+ }
2471
+ const entries = [];
2472
+ const effective = [];
2473
+ let i = 0;
2474
+ for (const change of changes) {
2475
+ const [key, value] = change;
2476
+ while (i < existing.length && compareUTF82(existing[i][0], key) < 0) {
2477
+ entries.push(existing[i++]);
2478
+ }
2479
+ const old = i < existing.length && existing[i][0] === key ? existing[i++] : void 0;
2480
+ if (value === void 0) {
2481
+ if (old) effective.push(change);
2482
+ } else if (old && deepEqual(old[1], value)) {
2483
+ entries.push(old);
2484
+ } else {
2485
+ entries.push([key, value, this.getEntrySize(key, value)]);
2486
+ effective.push(change);
2487
+ }
2488
+ }
2489
+ while (i < existing.length) entries.push(existing[i++]);
2490
+ if (effective.length === 0) {
2491
+ return true;
2492
+ }
2493
+ if (effective.length * REBUILD_MIN_CHANGE_RATIO < existing.length) {
2494
+ for (const [key, value] of effective) {
2495
+ if (value === void 0) await this.#del(key);
2496
+ else await this.#put(key, value);
2497
+ }
2498
+ return true;
2499
+ }
2500
+ if (entries.length === 0) {
2501
+ this.rootHash = emptyHash;
2502
+ return true;
2503
+ }
2504
+ const min = this.minSize - this.chunkHeaderSize;
2505
+ const max = this.maxSize - this.chunkHeaderSize;
2506
+ let level = 0;
2507
+ let nodes = partition(
2508
+ entries,
2509
+ (e) => e[2],
2510
+ min,
2511
+ max
2512
+ ).map((p) => this.newDataNodeImpl(p));
2513
+ while (nodes.length > 1) {
2514
+ const parents = nodes.map(
2515
+ (n) => createNewInternalEntryForNode(n, this.getEntrySize)
2428
2516
  );
2429
- const { level } = rootNode;
2430
- const entries = partitions.map((entries2) => {
2431
- const node = this.newNodeImpl(entries2, level);
2432
- return createNewInternalEntryForNode(node, this.getEntrySize);
2433
- });
2434
- const newRoot = this.newInternalNodeImpl(entries, level + 1);
2435
- this.rootHash = newRoot.hash;
2436
- return;
2517
+ let partitions = partition(parents, (e) => e[2], min, max);
2518
+ if (partitions.length >= nodes.length) {
2519
+ partitions = [parents];
2520
+ }
2521
+ level++;
2522
+ nodes = partitions.map((p) => this.newInternalNodeImpl(p, level));
2437
2523
  }
2438
- this.rootHash = rootNode.hash;
2524
+ this.rootHash = nodes[0].hash;
2525
+ return true;
2439
2526
  });
2440
2527
  }
2528
+ /** In-order leaf entries under `hash`; false once more than `max`. */
2529
+ async #collectEntries(hash2, out, max) {
2530
+ if (hash2 === emptyHash) return true;
2531
+ const node = await this.getNode(hash2);
2532
+ if (isDataNodeImpl(node)) {
2533
+ for (const e of node.entries) out.push(e);
2534
+ return out.length <= max;
2535
+ }
2536
+ for (const [, child] of node.entries) {
2537
+ if (!await this.#collectEntries(child, out, max)) return false;
2538
+ }
2539
+ return true;
2540
+ }
2441
2541
  del(key) {
2442
- return this.#lock.withLock(async () => {
2443
- const oldRootNode = await this.getNode(this.rootHash);
2444
- const newRootNode = await oldRootNode.del(key, this);
2445
- const found = this.rootHash !== newRootNode.hash;
2446
- if (found) {
2447
- if (newRootNode.level > 0 && newRootNode.entries.length === 1) {
2448
- this.rootHash = newRootNode.entries[0][1];
2449
- } else {
2450
- this.rootHash = newRootNode.hash;
2451
- }
2542
+ return this.#lock.withLock(() => this.#del(key));
2543
+ }
2544
+ async #del(key) {
2545
+ const oldRootNode = await this.getNode(this.rootHash);
2546
+ const newRootNode = await oldRootNode.del(key, this);
2547
+ const found = this.rootHash !== newRootNode.hash;
2548
+ if (found) {
2549
+ let root = newRootNode;
2550
+ while (root.level > 0 && root.entries.length === 1) {
2551
+ root = await this.getNode(root.entries[0][1]);
2452
2552
  }
2453
- return found;
2454
- });
2553
+ this.rootHash = root.hash;
2554
+ }
2555
+ return found;
2455
2556
  }
2456
2557
  clear() {
2457
2558
  return this.#lock.withLock(() => {
@@ -3265,7 +3366,7 @@ var analyzeQueryResultSchema = valita_exports.object({
3265
3366
  });
3266
3367
 
3267
3368
  // ../zero-protocol/src/ast.ts
3268
- import { compareUTF8 as compareUTF82 } from "compare-utf8";
3369
+ import { compareUTF8 as compareUTF83 } from "compare-utf8";
3269
3370
 
3270
3371
  // ../shared/src/arrays.ts
3271
3372
  function defined(arr) {
@@ -3542,15 +3643,15 @@ function cmpCondition(a, b) {
3542
3643
  }
3543
3644
  function compareValuePosition(a, b) {
3544
3645
  if (a.type !== b.type) {
3545
- return compareUTF82(a.type, b.type);
3646
+ return compareUTF83(a.type, b.type);
3546
3647
  }
3547
3648
  switch (a.type) {
3548
3649
  case "literal":
3549
3650
  assert2(b.type === "literal");
3550
- return compareUTF82(String(a.value), String(b.value));
3651
+ return compareUTF83(String(a.value), String(b.value));
3551
3652
  case "column":
3552
3653
  assert2(b.type === "column");
3553
- return compareUTF82(a.name, b.name);
3654
+ return compareUTF83(a.name, b.name);
3554
3655
  case "static":
3555
3656
  throw new Error(
3556
3657
  "Static parameters should be resolved before normalization"
@@ -3558,7 +3659,7 @@ function compareValuePosition(a, b) {
3558
3659
  }
3559
3660
  }
3560
3661
  function cmpRelated(a, b) {
3561
- return compareUTF82(must(a.subquery.alias), must(b.subquery.alias));
3662
+ return compareUTF83(must(a.subquery.alias), must(b.subquery.alias));
3562
3663
  }
3563
3664
  function flattened(cond) {
3564
3665
  if (cond.type === "simple" || cond.type === "correlatedSubquery") {
@@ -3583,7 +3684,7 @@ function flattened(cond) {
3583
3684
  }
3584
3685
  function compareUTF8MaybeNull(a, b) {
3585
3686
  if (a !== null && b !== null) {
3586
- return compareUTF82(a, b);
3687
+ return compareUTF83(a, b);
3587
3688
  }
3588
3689
  if (b !== null) {
3589
3690
  return -1;
@@ -4197,7 +4298,7 @@ function isTwoHop(r) {
4197
4298
  }
4198
4299
 
4199
4300
  // ../zql/src/ivm/data.ts
4200
- import { compareUTF8 as compareUTF83 } from "compare-utf8";
4301
+ import { compareUTF8 as compareUTF84 } from "compare-utf8";
4201
4302
  function compareValues(a, b) {
4202
4303
  a = normalizeUndefined(a);
4203
4304
  b = normalizeUndefined(b);
@@ -4220,7 +4321,7 @@ function compareValues(a, b) {
4220
4321
  }
4221
4322
  if (typeof a === "string") {
4222
4323
  assertString(b);
4223
- return compareUTF83(a, b);
4324
+ return compareUTF84(a, b);
4224
4325
  }
4225
4326
  throw new Error(`Unsupported type: ${a}`);
4226
4327
  }
@@ -8643,7 +8744,6 @@ export {
8643
8744
  withRead,
8644
8745
  withWriteNoImplicitCommit,
8645
8746
  withWrite,
8646
- using,
8647
8747
  getClientGroups,
8648
8748
  setClientGroups,
8649
8749
  setClientGroup,
@@ -22,7 +22,7 @@ import {
22
22
  unreachable,
23
23
  valita_exports,
24
24
  withRead
25
- } from "./chunk-SIMXYEFB.js";
25
+ } from "./chunk-FVFX5V7B.js";
26
26
 
27
27
  // ../zero-client/src/client/inspector/html-dialog-prompt.ts
28
28
  function canUseHTMLDialog() {
package/dist/react.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  Zero
3
- } from "./chunk-MLCRKRW5.js";
3
+ } from "./chunk-BKP7XQAL.js";
4
4
  import {
5
5
  DEFAULT_TTL_MS
6
- } from "./chunk-SIMXYEFB.js";
6
+ } from "./chunk-FVFX5V7B.js";
7
7
 
8
8
  // ../zero-react/src/use-query.tsx
9
9
  import React, { useSyncExternalStore } from "react";
@@ -18,7 +18,21 @@ export declare class BTreeWrite extends BTreeRead {
18
18
  newNodeImpl(entries: Entry<FrozenJSONValue>[], level: number): DataNodeImpl;
19
19
  newNodeImpl(entries: Entry<Hash>[], level: number): InternalNodeImpl;
20
20
  newNodeImpl(entries: Entry<Hash>[] | Entry<FrozenJSONValue>[], level: number): InternalNodeImpl | DataNodeImpl;
21
+ /**
22
+ * Set by the leaf when the put being applied stores a value equal to the
23
+ * existing one; the nodes on the path then return themselves unchanged.
24
+ */
25
+ putWasNoop: boolean;
21
26
  put(key: string, value: FrozenJSONValue): Promise<void>;
27
+ /**
28
+ * Applies `changes` (strictly ascending by key; `undefined` deletes) by
29
+ * merging them with the existing entries and building the tree bottom-up
30
+ * in one pass — no per-entry lock, descent, path copy or fresh hash. For
31
+ * large patches (a first hydrate, a bulk change) this replaces N
32
+ * sequential puts. Returns false, having changed nothing, when the tree
33
+ * holds more than `maxExisting` entries: then sequential puts touch less.
34
+ */
35
+ putSorted(changes: readonly (readonly [string, FrozenJSONValue | undefined])[], maxExisting: number): Promise<boolean>;
22
36
  del(key: string): Promise<boolean>;
23
37
  clear(): Promise<void>;
24
38
  flush(): Promise<Hash>;
@@ -3,10 +3,27 @@ import type { Enum } from '../../../shared/src/enum.ts';
3
3
  import type { LazyStore } from '../dag/lazy-store.ts';
4
4
  import type { Store } from '../dag/store.ts';
5
5
  import * as FormatVersion from '../format-version-enum.ts';
6
+ import type { Hash } from '../hash.ts';
6
7
  import type { ClientID } from '../sync/ids.ts';
7
8
  import type { MutatorDefs } from '../types.ts';
8
9
  import type { ZeroOption } from '../replicache-options.ts';
9
10
  type FormatVersion = Enum<typeof FormatVersion>;
11
+ /**
12
+ * The perdag main client group's head moved between persist's first READ and
13
+ * its WRITE transaction (another tab persisted in between), so the IVM tx data
14
+ * computed for the head seen at read time does not describe the head the write
15
+ * would rebase onto. Nothing has been written when this is thrown; the caller
16
+ * reschedules persist, and the next attempt reads the new head.
17
+ *
18
+ * Why this exists instead of computing the data inside the write: see the
19
+ * comment on `zeroDataForPerdagHeadAtRead` in `persistDD31`.
20
+ */
21
+ export declare class PersistBaseMovedError extends Error {
22
+ readonly expected: Hash;
23
+ readonly actual: Hash;
24
+ readonly name = "PersistBaseMovedError";
25
+ constructor(expected: Hash, actual: Hash);
26
+ }
10
27
  /**
11
28
  * Persists the client's memdag state to the client's perdag client group.
12
29
  *
@@ -3,6 +3,7 @@ import type { MaybePromise } from '../../shared/src/types.ts';
3
3
  import { type Cookie } from './cookies.ts';
4
4
  import { LazyStore } from './dag/lazy-store.ts';
5
5
  import { type Store } from './dag/store.ts';
6
+ import { type FrozenJSONValue } from './frozen-json.ts';
6
7
  import { type Hash } from './hash.ts';
7
8
  import { type PendingMutation } from './pending-mutations.ts';
8
9
  import { type OnClientsDeleted } from './persist/clients.ts';
@@ -317,9 +318,9 @@ export declare class ReplicacheImpl<MD extends MutatorDefs = {}> {
317
318
  */
318
319
  query<R>(body: (tx: ReadTransaction) => Promise<R> | R): Promise<R>;
319
320
  /**
320
- * The DURABLE last-mutation-IDs of this client's client group, read from
321
- * the PERDAG — the companion to `cookie`, and required by any embedder
322
- * that supplies its own pokes.
321
+ * The DURABLE, server-acknowledged last-mutation-IDs of this client's
322
+ * client group, read from the PERDAG — the companion to `cookie`, and
323
+ * required by any embedder that supplies its own pokes.
323
324
  *
324
325
  * WHY THIS HAS TO EXIST. A poke's `lastMutationIDChanges` are merged
325
326
  * over the base snapshot's, so naming a client with a value BELOW what
@@ -346,6 +347,17 @@ export declare class ReplicacheImpl<MD extends MutatorDefs = {}> {
346
347
  * appears.
347
348
  */
348
349
  get lastMutationIDs(): Promise<Record<ClientID, number>>;
350
+ /**
351
+ * The snapshot the next poke applies on — its cookie and every entry
352
+ * whose key starts with `prefix`, read together. For embedders that
353
+ * supply their own pokes and must diff against what that snapshot really
354
+ * holds (after a sibling tab's snapshot was refreshed in underneath them,
355
+ * or while pending mutations make the local view differ from it).
356
+ */
357
+ baseSnapshotEntries(prefix: string): Promise<{
358
+ cookie: Cookie;
359
+ entries: [string, FrozenJSONValue][];
360
+ }>;
349
361
  get cookie(): Promise<Cookie>;
350
362
  recoverMutations(): Promise<boolean> | void;
351
363
  /**
@@ -358,4 +370,12 @@ export declare class ReplicacheImpl<MD extends MutatorDefs = {}> {
358
370
  */
359
371
  experimentalPendingMutations(): Promise<readonly PendingMutation[]>;
360
372
  }
373
+ /**
374
+ * The DOMExceptions an IndexedDB call raises when the browser ended its
375
+ * transaction underneath it — a request in an aborted transaction
376
+ * (`AbortError`), `objectStore()` on a finished one (`InvalidStateError`), a
377
+ * request on an inactive one (`TransactionInactiveError`). Everything else —
378
+ * a missing store, bad data, quota on a fresh transaction — is not retried.
379
+ */
380
+ export declare function isTransientIdbAbort(e: unknown): boolean;
361
381
  //# sourceMappingURL=replicache-impl.d.ts.map
@@ -237,8 +237,8 @@ export interface ZeroTxData {
237
237
  token: string | undefined;
238
238
  }
239
239
  export type ZeroReadOptions = {
240
+ /** A MEMDAG read/write the caller already holds (no lock is taken). */
240
241
  openLazyRead?: Read | undefined;
241
- openLazySourceRead?: Read | undefined;
242
242
  };
243
243
  declare const idTag: unique symbol;
244
244
  export type EphemeralID = number & {
@@ -201,7 +201,8 @@ export declare class Zero<const S extends Schema, MD extends CustomMutatorDefs |
201
201
  */
202
202
  get currentCookie(): Promise<Cookie>;
203
203
  /**
204
- * The DURABLE last-mutation-IDs of this client's client group.
204
+ * The DURABLE, server-acknowledged last-mutation-IDs of this client's
205
+ * client group (pending local mutations are not counted).
205
206
  *
206
207
  * An adapter that supplies its own pokes MUST floor every
207
208
  * `lastMutationIDChanges` entry with this. A poke naming any client —
@@ -212,6 +213,17 @@ export declare class Zero<const S extends Schema, MD extends CustomMutatorDefs |
212
213
  * sibling made durable.
213
214
  */
214
215
  get currentLastMutationIDs(): Promise<Record<ClientID, number>>;
216
+ /**
217
+ * The snapshot the next `pokeDirect` applies on: its cookie and every
218
+ * entry under `prefix`, read together. Lets an adapter diff against what
219
+ * that snapshot really holds when it is not what the adapter last poked
220
+ * (a sibling tab's snapshot refreshed in, or pending mutations that make
221
+ * the local view differ from it on rows it cannot name).
222
+ */
223
+ baseSnapshotEntries(prefix: string): Promise<{
224
+ cookie: Cookie;
225
+ entries: [string, ReadonlyJSONValue][];
226
+ }>;
215
227
  /**
216
228
  * A rough heuristic for whether the client is currently online and
217
229
  * authenticated.
package/dist/zero.js CHANGED
@@ -6,8 +6,8 @@ import {
6
6
  number,
7
7
  string,
8
8
  table
9
- } from "./chunk-MLCRKRW5.js";
10
- import "./chunk-SIMXYEFB.js";
9
+ } from "./chunk-BKP7XQAL.js";
10
+ import "./chunk-FVFX5V7B.js";
11
11
 
12
12
  // src/adapters/convex.ts
13
13
  var ConvexSyncAdapter = class {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ahmed-rivet-convex",
3
- "version": "2.2.5",
3
+ "version": "2.2.6",
4
4
  "description": "Client-only local-first data runtime for the browser: reactive queries over IndexedDB with optimistic writes.",
5
5
  "author": "Ahmed Banihani",
6
6
  "license": "Apache-2.0",