js-bao 0.12.0-alpha.7 → 0.12.0-alpha.9

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.
package/dist/browser.cjs CHANGED
@@ -257,6 +257,8 @@ var init_queryTypes = __esm({
257
257
  }
258
258
  };
259
259
  InvalidCursorError = class _InvalidCursorError extends DocumentQueryError {
260
+ code = "INVALID_CURSOR";
261
+ status = 400;
260
262
  cursor;
261
263
  constructor(message, cursor) {
262
264
  super(message);
@@ -292,7 +294,7 @@ function stripCursorSortValues(row, aliasedFields) {
292
294
  }
293
295
  return stripped ?? row;
294
296
  }
295
- var base64Encode, base64Decode, CURSOR_SORT_ALIAS_PREFIX, CursorManager;
297
+ var base64Encode, asciiJson, base64Decode, CURSOR_SORT_ALIAS_PREFIX, CursorManager;
296
298
  var init_CursorManager = __esm({
297
299
  "src/query/CursorManager.ts"() {
298
300
  "use strict";
@@ -306,6 +308,10 @@ var init_CursorManager = __esm({
306
308
  throw new Error("No base64 encoding available");
307
309
  }
308
310
  };
311
+ asciiJson = (json) => json.replace(
312
+ /[\u0080-\uffff]/g,
313
+ (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
314
+ );
309
315
  base64Decode = (str) => {
310
316
  if (typeof atob !== "undefined") {
311
317
  return atob(str);
@@ -323,7 +329,7 @@ var init_CursorManager = __esm({
323
329
  static encodeCursor(cursorData) {
324
330
  try {
325
331
  const jsonString = JSON.stringify(cursorData);
326
- return base64Encode(jsonString);
332
+ return base64Encode(asciiJson(jsonString));
327
333
  } catch (error) {
328
334
  throw new InvalidCursorError(
329
335
  `Failed to encode cursor: ${error instanceof Error ? error.message : "Unknown error"}`,
@@ -350,6 +356,11 @@ var init_CursorManager = __esm({
350
356
  if (parsed.direction !== 1 && parsed.direction !== -1) {
351
357
  throw new Error("Cursor direction must be 1 or -1");
352
358
  }
359
+ if (parsed.sortDirections !== void 0 && (!Array.isArray(parsed.sortDirections) || parsed.sortDirections.length !== parsed.sortFields.length || !parsed.sortDirections.every((d) => d === 1 || d === -1))) {
360
+ throw new Error(
361
+ "Cursor sortDirections must be 1 or -1 for each sort field"
362
+ );
363
+ }
353
364
  return parsed;
354
365
  } catch (error) {
355
366
  throw new InvalidCursorError(
@@ -369,8 +380,13 @@ var init_CursorManager = __esm({
369
380
  * engine. `null` rather than `undefined` because `JSON.stringify` drops a key
370
381
  * whose value is `undefined`, and the payload's shape is the wire contract
371
382
  * the Swift port reads.
383
+ *
384
+ * `sortDirections` are the query's declared per-field directions (as
385
+ * {@link CursorManager.buildOrderClause} returns them). They are written into
386
+ * the cursor so {@link CursorManager.buildPaginationConditions} can refuse it
387
+ * under any other sort.
372
388
  */
373
- static generateCursor(record, sortFields, direction) {
389
+ static generateCursor(record, sortFields, direction, sortDirections) {
374
390
  const values = {};
375
391
  for (const field of sortFields) {
376
392
  const value = Object.prototype.hasOwnProperty.call(record, field) ? record[field] : void 0;
@@ -379,7 +395,8 @@ var init_CursorManager = __esm({
379
395
  const cursorData = {
380
396
  values,
381
397
  sortFields,
382
- direction
398
+ direction,
399
+ ...sortDirections ? { sortDirections } : {}
383
400
  };
384
401
  return this.encodeCursor(cursorData);
385
402
  }
@@ -408,16 +425,36 @@ var init_CursorManager = __esm({
408
425
  * receives `IS NULL` handling and the default `sort: {id}` pagination SQL
409
426
  * stays byte-identical to what it was. So does every non-null `>` level, so
410
427
  * an ascending page over an old-format cursor compiles exactly as before.
428
+ *
429
+ * A cursor is valid only under the sort that minted it. One whose
430
+ * `sortFields` differ from the query's, or whose `sortDirections` differ
431
+ * from the query's declared directions, is refused with
432
+ * {@link InvalidCursorError}: paging from it would skip and repeat rows. A
433
+ * cursor without `sortDirections` predates them and is checked on its
434
+ * fields only.
411
435
  */
412
436
  static buildPaginationConditions(cursor, currentSortFields, sortDirections, requestedDirection, fieldFormatter = (field) => field) {
413
437
  if (!this.arraysEqual(cursor.sortFields, currentSortFields)) {
414
438
  throw new InvalidCursorError(
415
- `Cursor sort fields [${cursor.sortFields.join(
439
+ `Invalid cursor: its sort fields [${cursor.sortFields.join(
416
440
  ", "
417
441
  )}] don't match query sort fields [${currentSortFields.join(", ")}]`,
418
442
  JSON.stringify(cursor)
419
443
  );
420
444
  }
445
+ if (cursor.sortDirections) {
446
+ const declared = currentSortFields.map(
447
+ (_, i) => sortDirections[i] ?? 1
448
+ );
449
+ if (!this.arraysEqual(cursor.sortDirections, declared)) {
450
+ throw new InvalidCursorError(
451
+ `Invalid cursor: its sort directions [${cursor.sortDirections.join(
452
+ ", "
453
+ )}] don't match query sort directions [${declared.join(", ")}]`,
454
+ JSON.stringify(cursor)
455
+ );
456
+ }
457
+ }
421
458
  const conditions = [];
422
459
  const params = [];
423
460
  const sortFields = cursor.sortFields;
@@ -506,11 +543,9 @@ var init_CursorManager = __esm({
506
543
  directions.push(dir);
507
544
  }
508
545
  }
509
- if (!sort || !sort.hasOwnProperty("id")) {
546
+ if (!sort || !Object.prototype.hasOwnProperty.call(sort, "id")) {
510
547
  clauses.push(`${fieldFormatter("id")} ${sqlDir(1)}`);
511
548
  directions.push(1);
512
- } else if (sort && sort.hasOwnProperty("id")) {
513
- directions.push(sort["id"]);
514
549
  }
515
550
  return {
516
551
  sql: clauses.join(", "),
@@ -528,9 +563,11 @@ var init_CursorManager = __esm({
528
563
  return actualResultCount >= requestedLimit;
529
564
  }
530
565
  /**
531
- * Generate next and previous cursors from result set
566
+ * Generate next and previous cursors from result set. `sortDirections` are
567
+ * the query's declared per-field directions, written into each cursor (see
568
+ * {@link CursorManager.generateCursor}).
532
569
  */
533
- static generateResultCursors(results, sortFields, requestedDirection, hasMore, isFirstPage = false) {
570
+ static generateResultCursors(results, sortFields, requestedDirection, hasMore, isFirstPage = false, sortDirections) {
534
571
  if (results.length === 0) {
535
572
  return {};
536
573
  }
@@ -540,7 +577,8 @@ var init_CursorManager = __esm({
540
577
  cursors.nextCursor = this.generateCursor(
541
578
  lastResult,
542
579
  sortFields,
543
- requestedDirection
580
+ requestedDirection,
581
+ sortDirections
544
582
  );
545
583
  }
546
584
  if (results.length > 0 && !isFirstPage) {
@@ -549,7 +587,8 @@ var init_CursorManager = __esm({
549
587
  cursors.prevCursor = this.generateCursor(
550
588
  firstResult,
551
589
  sortFields,
552
- opposite
590
+ opposite,
591
+ sortDirections
553
592
  );
554
593
  }
555
594
  return cursors;
@@ -922,7 +961,7 @@ var init_DocumentQueryTranslator = __esm({
922
961
  /**
923
962
  * Translate document filter and options to SQL for find operations
924
963
  */
925
- translateFind(filter, options) {
964
+ translateFind(filter, options, internal) {
926
965
  if (options?.projection) {
927
966
  this.validateProjection(options.projection);
928
967
  }
@@ -948,7 +987,8 @@ var init_DocumentQueryTranslator = __esm({
948
987
  );
949
988
  const selectClause = this.buildSelectClause(
950
989
  options?.projection,
951
- cursorSortValueFields
990
+ cursorSortValueFields,
991
+ internal?.selectDocument === true
952
992
  );
953
993
  let sql = `SELECT ${selectClause} FROM ${this.quotedTableName}`;
954
994
  const params = [];
@@ -1423,8 +1463,12 @@ var init_DocumentQueryTranslator = __esm({
1423
1463
  * ({@link cursorSortValueFields}, #3228) so the cursor carries the row's real
1424
1464
  * value rather than a false null; `BaseModel.query` strips those columns
1425
1465
  * before the rows leave it, so response shapes are unchanged.
1466
+ *
1467
+ * `selectDocument` adds the row's document column to an inclusion
1468
+ * projection for a consumer that reads per-document data after the query
1469
+ * ({@link FindInternals}); it is never added unasked.
1426
1470
  */
1427
- buildSelectClause(projection, aliasedSortFields) {
1471
+ buildSelectClause(projection, aliasedSortFields, selectDocument = false) {
1428
1472
  if (!projection || Object.keys(projection).length === 0) {
1429
1473
  return "*";
1430
1474
  }
@@ -1453,6 +1497,9 @@ var init_DocumentQueryTranslator = __esm({
1453
1497
  includeFields.unshift("id");
1454
1498
  }
1455
1499
  const quoted = includeFields.map((field) => this.getQuotedField(field));
1500
+ if (selectDocument) {
1501
+ quoted.push(quoteIdentifier(DOCUMENT_TIEBREAKER));
1502
+ }
1456
1503
  for (const field of aliasedSortFields ?? []) {
1457
1504
  quoted.push(
1458
1505
  `${this.quotedSortField(field)} AS ${quoteIdentifier(
@@ -1494,26 +1541,26 @@ var init_DocumentQueryTranslator = __esm({
1494
1541
  if (!options?.uniqueStartKey || !sortFields || !sortDirections) {
1495
1542
  return { sql: "", params: [] };
1496
1543
  }
1544
+ let cursor;
1497
1545
  try {
1498
- const cursor = CursorManager.decodeCursor(options.uniqueStartKey);
1499
- const direction = options.direction || 1;
1500
- const fields = sortFields.slice();
1501
- const directions = sortDirections.slice();
1502
- if (fields[fields.length - 1] === DOCUMENT_TIEBREAKER && cursor.sortFields.length === fields.length - 1) {
1503
- fields.pop();
1504
- directions.pop();
1505
- }
1506
- return CursorManager.buildPaginationConditions(
1507
- cursor,
1508
- fields,
1509
- directions,
1510
- direction,
1511
- (field) => this.quotedSortField(field)
1512
- );
1546
+ cursor = CursorManager.decodeCursor(options.uniqueStartKey);
1513
1547
  } catch (error) {
1514
1548
  console.warn("Invalid cursor provided, ignoring pagination:", error);
1515
1549
  return { sql: "", params: [] };
1516
1550
  }
1551
+ const fields = sortFields.slice();
1552
+ const directions = sortDirections.slice();
1553
+ if (fields[fields.length - 1] === DOCUMENT_TIEBREAKER && cursor.sortFields.length === fields.length - 1) {
1554
+ fields.pop();
1555
+ directions.pop();
1556
+ }
1557
+ return CursorManager.buildPaginationConditions(
1558
+ cursor,
1559
+ fields,
1560
+ directions,
1561
+ options.direction || 1,
1562
+ (field) => this.quotedSortField(field)
1563
+ );
1517
1564
  }
1518
1565
  /**
1519
1566
  * Validate that field exists in schema
@@ -1673,6 +1720,51 @@ var init_DocumentQueryTranslator = __esm({
1673
1720
  }
1674
1721
  });
1675
1722
 
1723
+ // src/query/projectedRows.ts
1724
+ function projectedStringSetFields(projection, schema) {
1725
+ if (!projection) return [];
1726
+ return Object.entries(projection).filter(
1727
+ ([field, include]) => include === 1 && schema.get(field)?.type === "stringset"
1728
+ ).map(([field]) => field);
1729
+ }
1730
+ function projectedFieldValue(fieldOptions, value) {
1731
+ if (fieldOptions?.type === "boolean" && typeof value === "number") {
1732
+ return value !== 0;
1733
+ }
1734
+ return value;
1735
+ }
1736
+ async function attachStringSetMembers(engine, junctions, rows) {
1737
+ if (junctions.length === 0 || rows.length === 0) return;
1738
+ const key = (id, doc) => JSON.stringify([String(id), doc ?? null]);
1739
+ const ids = [...new Set(rows.map((row) => String(row.id)))];
1740
+ for (const { field, table, foreignKey } of junctions) {
1741
+ const members = /* @__PURE__ */ new Map();
1742
+ const quotedForeignKey = quoteIdentifier(foreignKey);
1743
+ for (let i = 0; i < ids.length; i += CHUNK_SIZE) {
1744
+ const chunk = ids.slice(i, i + CHUNK_SIZE);
1745
+ const sql = `SELECT ${quotedForeignKey} AS "record_id", "value", ${quoteIdentifier(DOC2)} AS "doc" FROM ${quoteIdentifier(table)} WHERE ${quotedForeignKey} IN (${chunk.map(() => "?").join(", ")}) ORDER BY "value"`;
1746
+ for (const member of await engine.query(sql, chunk)) {
1747
+ const at = key(member.record_id, member.doc);
1748
+ const list = members.get(at);
1749
+ if (list) list.push(String(member.value));
1750
+ else members.set(at, [String(member.value)]);
1751
+ }
1752
+ }
1753
+ for (const row of rows) {
1754
+ row[field] = members.get(key(row.id, row[DOC2])) ?? [];
1755
+ }
1756
+ }
1757
+ }
1758
+ var DOC2, CHUNK_SIZE;
1759
+ var init_projectedRows = __esm({
1760
+ "src/query/projectedRows.ts"() {
1761
+ "use strict";
1762
+ init_sql();
1763
+ DOC2 = "_meta_doc_id";
1764
+ CHUNK_SIZE = 99;
1765
+ }
1766
+ });
1767
+
1676
1768
  // src/utils/yjsValues.ts
1677
1769
  function isYjsComposite(value) {
1678
1770
  return value instanceof Y.Map || value instanceof Y.Array || value instanceof Y.Text;
@@ -2459,6 +2551,225 @@ var init_OrmContext = __esm({
2459
2551
  }
2460
2552
  });
2461
2553
 
2554
+ // src/utils/reservedFieldNames.json
2555
+ var reservedFieldNames_default;
2556
+ var init_reservedFieldNames = __esm({
2557
+ "src/utils/reservedFieldNames.json"() {
2558
+ reservedFieldNames_default = {
2559
+ reserved: {
2560
+ CodingKeys: {
2561
+ breaks: ["swift"],
2562
+ reason: "the generated struct's coding keys on the Swift client"
2563
+ },
2564
+ applyAutoStampsForSave: {
2565
+ breaks: ["js"],
2566
+ reason: "a record method on the JavaScript client",
2567
+ jsEvidence: "compile"
2568
+ },
2569
+ applyStringSetChangeToYMap: {
2570
+ breaks: ["js"],
2571
+ reason: "a record method on the JavaScript client",
2572
+ jsEvidence: "compile"
2573
+ },
2574
+ clearLocalChanges: {
2575
+ breaks: ["js"],
2576
+ reason: "a record method on the JavaScript client",
2577
+ jsEvidence: "compile"
2578
+ },
2579
+ constructor: {
2580
+ breaks: ["js"],
2581
+ reason: "the JavaScript client reads a record's class through it",
2582
+ jsEvidence: "runtime"
2583
+ },
2584
+ delete: {
2585
+ breaks: ["js"],
2586
+ reason: "a record method on the JavaScript client",
2587
+ jsEvidence: "compile"
2588
+ },
2589
+ deleteRecordLog: {
2590
+ breaks: ["js"],
2591
+ reason: "a record method on the JavaScript client",
2592
+ jsEvidence: "compile"
2593
+ },
2594
+ discardChanges: {
2595
+ breaks: ["js", "swift"],
2596
+ reason: "a record method on the JavaScript and Swift clients",
2597
+ jsEvidence: "compile"
2598
+ },
2599
+ ensureLocalChanges: {
2600
+ breaks: ["js"],
2601
+ reason: "a record method on the JavaScript client",
2602
+ jsEvidence: "compile"
2603
+ },
2604
+ getChangedFields: {
2605
+ breaks: ["js"],
2606
+ reason: "a record method on the JavaScript client",
2607
+ jsEvidence: "compile"
2608
+ },
2609
+ getCurrentJSState: {
2610
+ breaks: ["js"],
2611
+ reason: "a record method on the JavaScript client",
2612
+ jsEvidence: "compile"
2613
+ },
2614
+ getCurrentValue: {
2615
+ breaks: ["js"],
2616
+ reason: "a record method on the JavaScript client",
2617
+ jsEvidence: "compile"
2618
+ },
2619
+ getDocumentId: {
2620
+ breaks: ["js"],
2621
+ reason: "a record method on the JavaScript client",
2622
+ jsEvidence: "compile"
2623
+ },
2624
+ getFromYjs: {
2625
+ breaks: ["js"],
2626
+ reason: "a record method on the JavaScript client",
2627
+ jsEvidence: "compile"
2628
+ },
2629
+ getOrCreateStringSet: {
2630
+ breaks: ["js"],
2631
+ reason: "a record method on the JavaScript client",
2632
+ jsEvidence: "compile"
2633
+ },
2634
+ getOriginalValue: {
2635
+ breaks: ["js"],
2636
+ reason: "a record method on the JavaScript client",
2637
+ jsEvidence: "compile"
2638
+ },
2639
+ getStringSetCurrentValues: {
2640
+ breaks: ["js"],
2641
+ reason: "a record method on the JavaScript client",
2642
+ jsEvidence: "compile"
2643
+ },
2644
+ getStringSetFromYjs: {
2645
+ breaks: ["js"],
2646
+ reason: "a record method on the JavaScript client",
2647
+ jsEvidence: "compile"
2648
+ },
2649
+ getValue: {
2650
+ breaks: ["js"],
2651
+ reason: "a record method on the JavaScript client",
2652
+ jsEvidence: "compile"
2653
+ },
2654
+ hasFieldChanged: {
2655
+ breaks: ["js"],
2656
+ reason: "a record method on the JavaScript client",
2657
+ jsEvidence: "compile"
2658
+ },
2659
+ hasLocalChange: {
2660
+ breaks: ["js"],
2661
+ reason: "a record method on the JavaScript client",
2662
+ jsEvidence: "compile"
2663
+ },
2664
+ hasUnsavedChanges: {
2665
+ breaks: ["js"],
2666
+ reason: "a record property on the JavaScript client",
2667
+ jsEvidence: "compile"
2668
+ },
2669
+ hashValue: {
2670
+ breaks: ["swift"],
2671
+ reason: "a Hashable requirement on the Swift client"
2672
+ },
2673
+ isDirty: {
2674
+ breaks: ["js"],
2675
+ reason: "a record property on the JavaScript client",
2676
+ jsEvidence: "compile"
2677
+ },
2678
+ markAllChanged: {
2679
+ breaks: ["swift"],
2680
+ reason: "a record method on the Swift client"
2681
+ },
2682
+ markStringSetChange: {
2683
+ breaks: ["js"],
2684
+ reason: "a record method on the JavaScript client",
2685
+ jsEvidence: "compile"
2686
+ },
2687
+ normalizeNonStringSetValue: {
2688
+ breaks: ["js"],
2689
+ reason: "a record method on the JavaScript client",
2690
+ jsEvidence: "compile"
2691
+ },
2692
+ primitiveValues: {
2693
+ breaks: ["swift"],
2694
+ reason: "a record method on the Swift client"
2695
+ },
2696
+ related: {
2697
+ breaks: ["swift"],
2698
+ reason: "the generated struct's query-time includes on the Swift client"
2699
+ },
2700
+ resolveUnresolvedFormat2Document: {
2701
+ breaks: ["js"],
2702
+ reason: "a record method on the JavaScript client",
2703
+ jsEvidence: "compile"
2704
+ },
2705
+ save: {
2706
+ breaks: ["js"],
2707
+ reason: "a record method on the JavaScript client",
2708
+ jsEvidence: "compile"
2709
+ },
2710
+ saveRecordLog: {
2711
+ breaks: ["js"],
2712
+ reason: "a record method on the JavaScript client",
2713
+ jsEvidence: "compile"
2714
+ },
2715
+ schemaDefaultFor: {
2716
+ breaks: ["js"],
2717
+ reason: "a record method on the JavaScript client",
2718
+ jsEvidence: "compile"
2719
+ },
2720
+ setValue: {
2721
+ breaks: ["js"],
2722
+ reason: "a record method on the JavaScript client",
2723
+ jsEvidence: "compile"
2724
+ },
2725
+ syncState: {
2726
+ breaks: ["js"],
2727
+ reason: "a record property on the JavaScript client",
2728
+ jsEvidence: "compile"
2729
+ },
2730
+ toJSON: {
2731
+ breaks: ["js"],
2732
+ reason: "a record method on the JavaScript client",
2733
+ jsEvidence: "compile"
2734
+ },
2735
+ validateBeforeSave: {
2736
+ breaks: ["js"],
2737
+ reason: "a record method on the JavaScript client",
2738
+ jsEvidence: "compile"
2739
+ },
2740
+ validateFieldValue: {
2741
+ breaks: ["js"],
2742
+ reason: "a record method on the JavaScript client",
2743
+ jsEvidence: "compile"
2744
+ }
2745
+ },
2746
+ exempt: {
2747
+ aggregate: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2748
+ autoStampFields: "a static on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2749
+ count: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2750
+ encode: "the Swift model's labelled encode(to:), which a field of the same name coexists with; not a JavaScript record member",
2751
+ find: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2752
+ findAll: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2753
+ findByUnique: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2754
+ hasOwnProperty: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients",
2755
+ hash: "the Swift model's labelled hash(into:), which a field of the same name coexists with; not a JavaScript record member",
2756
+ isPrototypeOf: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients",
2757
+ modelName: "a static on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2758
+ primitiveSchema: "a static on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2759
+ propertyIsEnumerable: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients",
2760
+ query: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2761
+ queryOne: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2762
+ queryPaged: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2763
+ subscribe: "a static on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
2764
+ toLocaleString: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients",
2765
+ toString: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients",
2766
+ upsertByUnique: "the Swift model's labelled upsertByUnique(_:mode:in:) methods, which a field of the same name coexists with; not a JavaScript record member",
2767
+ valueOf: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients"
2768
+ }
2769
+ };
2770
+ }
2771
+ });
2772
+
2462
2773
  // src/utils/reservedFields.ts
2463
2774
  function checkReservedFieldName(fieldName) {
2464
2775
  if (fieldName === "id") return null;
@@ -2468,12 +2779,18 @@ function checkReservedFieldName(fieldName) {
2468
2779
  if (fieldName.startsWith("_")) {
2469
2780
  return `Field '${fieldName}' is reserved (fields starting with '_' are internal)`;
2470
2781
  }
2782
+ if (Object.prototype.hasOwnProperty.call(RESERVED_FIELD_NAMES, fieldName)) {
2783
+ return `Field '${fieldName}' is reserved (${RESERVED_FIELD_NAMES[fieldName].reason})`;
2784
+ }
2471
2785
  return null;
2472
2786
  }
2473
- var ReservedFieldNameError;
2787
+ var RESERVED_FIELD_NAMES, EXEMPT_FIELD_NAMES, ReservedFieldNameError;
2474
2788
  var init_reservedFields = __esm({
2475
2789
  "src/utils/reservedFields.ts"() {
2476
2790
  "use strict";
2791
+ init_reservedFieldNames();
2792
+ RESERVED_FIELD_NAMES = reservedFieldNames_default.reserved;
2793
+ EXEMPT_FIELD_NAMES = reservedFieldNames_default.exempt;
2477
2794
  ReservedFieldNameError = class extends Error {
2478
2795
  constructor(message) {
2479
2796
  super(message);
@@ -2484,6 +2801,9 @@ var init_reservedFields = __esm({
2484
2801
  });
2485
2802
 
2486
2803
  // src/record-log-client/types.ts
2804
+ function recordLogSegmentChunkObject(segmentId, chunk) {
2805
+ return `${chunk.source?.segmentId ?? segmentId}/${chunk.model}/${chunk.index}`;
2806
+ }
2487
2807
  function refusedWritesOf(entry) {
2488
2808
  return [entry.m, ...entry.also ?? []].map((m) => ({
2489
2809
  model: m.model,
@@ -2768,6 +3088,34 @@ var init_resolve = __esm({
2768
3088
  }
2769
3089
  });
2770
3090
 
3091
+ // src/record-log/results.ts
3092
+ function plainRowAfter(row, m) {
3093
+ if (m.kind === "delete") return null;
3094
+ const prior = m.kind === "create" ? { id: m.id } : row;
3095
+ if (!prior) return null;
3096
+ const next = { ...prior };
3097
+ for (const [field, v] of Object.entries(m.fields ?? {})) {
3098
+ if (v === void 0) delete next[field];
3099
+ else next[field] = v;
3100
+ }
3101
+ for (const [field, deltas] of Object.entries(m.stringSetDeltas ?? {})) {
3102
+ const members = new Set(Array.isArray(next[field]) ? next[field] : []);
3103
+ for (const [member, present] of Object.entries(deltas)) {
3104
+ if (present) members.add(member);
3105
+ else members.delete(member);
3106
+ }
3107
+ next[field] = canonicalStringSet(members);
3108
+ }
3109
+ return next;
3110
+ }
3111
+ var init_results = __esm({
3112
+ "src/record-log/results.ts"() {
3113
+ "use strict";
3114
+ init_stringSetOrder();
3115
+ init_types2();
3116
+ }
3117
+ });
3118
+
2771
3119
  // src/record-log-client/guess.ts
2772
3120
  function upsertConstraints(entry) {
2773
3121
  if (entry.upsertOn === void 0) return [];
@@ -2778,26 +3126,9 @@ function applyGuess(table, entry) {
2778
3126
  for (const m of resolveEntry(table, entry, upsertConstraints(entry)).mutations) {
2779
3127
  const key = { model: m.model, id: m.id };
2780
3128
  touched.push(key);
2781
- if (m.kind === "delete") {
2782
- table.delete(key);
2783
- continue;
2784
- }
2785
- const prior = m.kind === "create" ? { id: m.id } : table.row(key);
2786
- if (!prior) continue;
2787
- const row = { ...prior };
2788
- for (const [field, v] of Object.entries(m.fields ?? {})) {
2789
- if (v === void 0) delete row[field];
2790
- else row[field] = v;
2791
- }
2792
- for (const [field, deltas] of Object.entries(m.stringSetDeltas ?? {})) {
2793
- const members = new Set(Array.isArray(row[field]) ? row[field] : []);
2794
- for (const [member, present] of Object.entries(deltas)) {
2795
- if (present) members.add(member);
2796
- else members.delete(member);
2797
- }
2798
- row[field] = canonicalStringSet(members);
2799
- }
2800
- table.set(key, row);
3129
+ const row = plainRowAfter(table.row(key), m);
3130
+ if (row) table.set(key, row);
3131
+ else if (m.kind === "delete") table.delete(key);
2801
3132
  }
2802
3133
  return touched;
2803
3134
  }
@@ -2814,8 +3145,8 @@ var MapRowTable;
2814
3145
  var init_guess = __esm({
2815
3146
  "src/record-log-client/guess.ts"() {
2816
3147
  "use strict";
2817
- init_stringSetOrder();
2818
3148
  init_resolve();
3149
+ init_results();
2819
3150
  MapRowTable = class _MapRowTable {
2820
3151
  /**
2821
3152
  * @param rows - The rows by `model` NUL `id`; the table keeps this map.
@@ -3805,6 +4136,7 @@ var init_IncludeResolver = __esm({
3805
4136
  "use strict";
3806
4137
  init_ModelRegistry();
3807
4138
  init_DocumentQueryTranslator();
4139
+ init_projectedRows();
3808
4140
  init_sql();
3809
4141
  IncludeResolver = class {
3810
4142
  db;
@@ -4003,6 +4335,7 @@ var init_IncludeResolver = __esm({
4003
4335
  grouped.get(fk).push(r);
4004
4336
  }
4005
4337
  if (spec.projection) {
4338
+ await this._fillProjectedValues(spec.model, related, spec.projection);
4006
4339
  for (const [key, list] of grouped) {
4007
4340
  grouped.set(
4008
4341
  key,
@@ -4101,6 +4434,7 @@ var init_IncludeResolver = __esm({
4101
4434
  return [];
4102
4435
  }
4103
4436
  const translator = new DocumentQueryTranslator(model, modelInfo.fields);
4437
+ const selectDocument = projectedStringSetFields(extraOptions?.projection, modelInfo.fields).length > 0;
4104
4438
  let filterParamCount = 0;
4105
4439
  if (extraFilter) {
4106
4440
  const translated = translator.translateFilter(extraFilter);
@@ -4120,12 +4454,53 @@ var init_IncludeResolver = __esm({
4120
4454
  if (extraOptions?.sort) options.sort = extraOptions.sort;
4121
4455
  if (extraOptions?.projection) options.projection = extraOptions.projection;
4122
4456
  if (this.documents !== null) options.documents = [...this.documents];
4123
- const { sql, params } = translator.translateFind(filter, options);
4457
+ const { sql, params } = translator.translateFind(filter, options, {
4458
+ selectDocument
4459
+ });
4124
4460
  const rows = await db.query(sql, params);
4125
4461
  allResults.push(...rows);
4126
4462
  }
4463
+ if (extraOptions?.projection) {
4464
+ await this._fillProjectedValues(
4465
+ model,
4466
+ allResults,
4467
+ extraOptions.projection,
4468
+ modelInfo.fields
4469
+ );
4470
+ }
4471
+ if (selectDocument) {
4472
+ for (const row of allResults) delete row._meta_doc_id;
4473
+ }
4127
4474
  return allResults;
4128
4475
  }
4476
+ /**
4477
+ * Give rows read under an inclusion `projection` the values the records
4478
+ * hold (#4501): each projected string set's members from its junction table,
4479
+ * matched on the row's id and `_meta_doc_id`, and each projected boolean as
4480
+ * `true`/`false` rather than the stored 0/1.
4481
+ */
4482
+ async _fillProjectedValues(model, rows, projection, fields) {
4483
+ const schema = fields ?? this.registry.getModelInfo(model)?.fields;
4484
+ if (!schema || rows.length === 0) return;
4485
+ const tableName = `model_${model.toLowerCase()}`;
4486
+ await attachStringSetMembers(
4487
+ await this.engineFor(model),
4488
+ projectedStringSetFields(projection, schema).map((field) => ({
4489
+ field,
4490
+ table: `${tableName}_${field}`,
4491
+ foreignKey: `${model.toLowerCase()}_id`
4492
+ })),
4493
+ rows
4494
+ );
4495
+ for (const [field, include] of Object.entries(projection)) {
4496
+ if (include !== 1) continue;
4497
+ for (const row of rows) {
4498
+ if (Object.prototype.hasOwnProperty.call(row, field)) {
4499
+ row[field] = projectedFieldValue(schema.get(field), row[field]);
4500
+ }
4501
+ }
4502
+ }
4503
+ }
4129
4504
  /** Validate an include spec, returning an error string or null if valid. */
4130
4505
  _validateIncludeSpec(spec) {
4131
4506
  if (!spec.model || typeof spec.model !== "string") {
@@ -4258,6 +4633,7 @@ var init_BaseModel = __esm({
4258
4633
  init_documentTypes();
4259
4634
  init_DocumentQueryTranslator();
4260
4635
  init_CursorManager();
4636
+ init_projectedRows();
4261
4637
  init_sql();
4262
4638
  init_metaSync();
4263
4639
  init_writeLifecycle();
@@ -7222,7 +7598,9 @@ var init_BaseModel = __esm({
7222
7598
  translatorOptions = { ...translatorOptions || {}, documents: scope };
7223
7599
  }
7224
7600
  const translator = new DocumentQueryTranslator(modelName, schema.fields);
7225
- const translatedQuery = translator.translateFind(filter, translatorOptions);
7601
+ const translatedQuery = translator.translateFind(filter, translatorOptions, {
7602
+ selectDocument: projectedStringSetFields(translatorOptions?.projection, schema.fields).length > 0
7603
+ });
7226
7604
  Logger.verbose(`[${modelName}] Translated SQL:`, translatedQuery.sql);
7227
7605
  Logger.verbose(`[${modelName}] SQL params:`, translatedQuery.params);
7228
7606
  const queryEngine = await this.queryEngineFor(
@@ -7257,7 +7635,8 @@ var init_BaseModel = __esm({
7257
7635
  translatedQuery.sortFields,
7258
7636
  direction,
7259
7637
  hasMore,
7260
- isFirstPage
7638
+ isFirstPage,
7639
+ translatedQuery.sortDirections
7261
7640
  );
7262
7641
  results = results.map(
7263
7642
  (row) => stripCursorSortValues(row, aliasedSortFields)
@@ -7267,6 +7646,21 @@ var init_BaseModel = __esm({
7267
7646
  }
7268
7647
  let transformedData;
7269
7648
  if (options?.projection && Object.keys(options.projection).length > 0) {
7649
+ const modelConstructor = this;
7650
+ await attachStringSetMembers(
7651
+ queryEngine,
7652
+ projectedStringSetFields(options.projection, schema.fields).map(
7653
+ (field) => ({
7654
+ field,
7655
+ table: modelConstructor.getDatabaseJunctionTableName(
7656
+ modelName,
7657
+ field
7658
+ ),
7659
+ foreignKey: `${modelName.toLowerCase()}_id`
7660
+ })
7661
+ ),
7662
+ results
7663
+ );
7270
7664
  transformedData = results.map((row) => {
7271
7665
  const projected = {};
7272
7666
  if (row.hasOwnProperty("id")) {
@@ -7274,7 +7668,10 @@ var init_BaseModel = __esm({
7274
7668
  }
7275
7669
  for (const [field, include] of Object.entries(options.projection)) {
7276
7670
  if (include === 1 && row.hasOwnProperty(field)) {
7277
- projected[field] = row[field];
7671
+ projected[field] = projectedFieldValue(
7672
+ schema.fields.get(field),
7673
+ row[field]
7674
+ );
7278
7675
  }
7279
7676
  }
7280
7677
  if (row._related) projected._related = row._related;
@@ -8820,6 +9217,7 @@ __export(browser_exports, {
8820
9217
  recordLogFieldIndexName: () => recordLogFieldIndexName,
8821
9218
  recordLogJsonBytes: () => recordLogJsonBytes,
8822
9219
  recordLogRowRevision: () => recordLogRowRevision,
9220
+ recordLogSegmentChunkObject: () => recordLogSegmentChunkObject,
8823
9221
  refusedWritesOf: () => refusedWritesOf,
8824
9222
  registerFunctionDefault: () => registerFunctionDefault,
8825
9223
  requestStoragePersistence: () => requestStoragePersistence,
@@ -8970,7 +9368,7 @@ var DatabaseEngine = class {
8970
9368
  };
8971
9369
 
8972
9370
  // src/engines/SqljsEngine.ts
8973
- var import_sql6 = __toESM(require("sql.js"), 1);
9371
+ var import_sql7 = __toESM(require("sql.js"), 1);
8974
9372
 
8975
9373
  // src/engines/sqliteQueryEngine.ts
8976
9374
  init_logger();
@@ -9357,7 +9755,7 @@ async function loadSqlJsModule(locateFile) {
9357
9755
  abortGuard.catch(() => {
9358
9756
  });
9359
9757
  try {
9360
- const initPromise = (0, import_sql6.default)({
9758
+ const initPromise = (0, import_sql7.default)({
9361
9759
  locateFile,
9362
9760
  // Layer 1: emscripten onAbort.
9363
9761
  onAbort: (reason) => abortReject?.(toError(reason))
@@ -10362,6 +10760,9 @@ function dispatchRecordLogStoreCommand(store, command) {
10362
10760
  case "applySegmentChunk":
10363
10761
  value = store.applySegmentChunk({ ...c, rows: c.rows ?? undecoded(c.kind) });
10364
10762
  break;
10763
+ case "keepSegmentChunk":
10764
+ value = store.keepSegmentChunk(c);
10765
+ break;
10365
10766
  case "applySegmentCorrections":
10366
10767
  value = store.applySegmentCorrections({ ...c, lines: c.lines ?? undecoded(c.kind) });
10367
10768
  break;
@@ -10572,6 +10973,7 @@ init_sql();
10572
10973
  init_logger();
10573
10974
 
10574
10975
  // src/record-log-client/client.ts
10976
+ init_results();
10575
10977
  init_types2();
10576
10978
  init_guess();
10577
10979
  init_types();
@@ -10687,6 +11089,12 @@ var RecordLogClient = class {
10687
11089
  * this store acknowledges that writer's entry at once; the entry leaves
10688
11090
  * the pending log, and its guess the view, once its result's row is
10689
11091
  * applied. `void` and `duplicate` items settle the entry they name.
11092
+ *
11093
+ * A compact acknowledgement (no `changes`) is applied, in its turn, by its
11094
+ * pending entry's mutations as plain row operations, the rule by which the
11095
+ * room vouched for it. With no unwithdrawn pending entry for its `seq` it
11096
+ * stays buffered, the cursor stops below it, and the outcome names it
11097
+ * (`underivable`).
10690
11098
  */
10691
11099
  receive(item) {
10692
11100
  const out = { touched: [], acknowledged: [], settled: [] };
@@ -10720,9 +11128,14 @@ var RecordLogClient = class {
10720
11128
  if (item.l > this.tables.cursor()) {
10721
11129
  this.tables.buffer(item);
10722
11130
  for (let next = this.tables.buffered(this.tables.cursor() + 1); next; next = this.tables.buffered(this.tables.cursor() + 1)) {
10723
- for (const change of next.changes) {
10724
- applyChange(confirmed, change);
10725
- out.touched.push({ model: change.model, id: change.id });
11131
+ if (next.changes) {
11132
+ for (const change of next.changes) {
11133
+ applyChange(confirmed, change);
11134
+ out.touched.push({ model: change.model, id: change.id });
11135
+ }
11136
+ } else if (!this.applyOwnEntry(confirmed, next, out)) {
11137
+ out.underivable = { l: next.l, writer: next.w ?? "", seq: next.seq ?? 0 };
11138
+ break;
10726
11139
  }
10727
11140
  this.tables.setCursor(next.l);
10728
11141
  this.tables.dropBufferedThrough(next.l);
@@ -10736,6 +11149,25 @@ var RecordLogClient = class {
10736
11149
  this.settleAcknowledged(out);
10737
11150
  return out;
10738
11151
  }
11152
+ /**
11153
+ * A compact acknowledgement's changes, derived: the mutations of the
11154
+ * pending entry it names applied in order to the confirmed rows as plain
11155
+ * row operations. Answers `false`, changing nothing, when no unwithdrawn
11156
+ * pending entry of a writer of this store has its `seq`.
11157
+ */
11158
+ applyOwnEntry(confirmed, item, out) {
11159
+ if (item.w === void 0 || item.seq === void 0 || !this.tables.isWriter(item.w)) return false;
11160
+ const entry = this.entryOf(item.w, item.seq);
11161
+ if (!entry || entry.void) return false;
11162
+ for (const m of mutationsOf(entry)) {
11163
+ const key = { model: m.model, id: m.id };
11164
+ const row = plainRowAfter(confirmed.row(key), m);
11165
+ if (row) confirmed.set(key, row);
11166
+ else if (m.kind === "delete") confirmed.delete(key);
11167
+ out.touched.push(key);
11168
+ }
11169
+ return true;
11170
+ }
10739
11171
  /**
10740
11172
  * Acknowledged entries whose result's row the cursor has passed leave the
10741
11173
  * pending log: their row was applied, here or by another writer of this
@@ -10888,7 +11320,10 @@ var RecordLogClient = class {
10888
11320
  completeCatchUp(done) {
10889
11321
  this.assertGeneration(done.generation);
10890
11322
  const out = { touched: [], acknowledged: [], settled: [] };
10891
- if (done.full) out.touched.push(...this.tables.completeReplace());
11323
+ if (done.full) {
11324
+ out.touched.push(...this.tables.completeReplace());
11325
+ this.tables.setHeldSegment?.(done.segment ?? null);
11326
+ }
10892
11327
  this.settleReceipts(done.full === true, done.receipt);
10893
11328
  this.tables.setCursor(done.lsn);
10894
11329
  this.tables.dropBufferedThrough(done.lsn);
@@ -10899,6 +11334,7 @@ var RecordLogClient = class {
10899
11334
  out.touched.push(...replay.touched);
10900
11335
  out.acknowledged.push(...replay.acknowledged);
10901
11336
  out.settled.push(...replay.settled);
11337
+ if (replay.underivable) out.underivable = replay.underivable;
10902
11338
  }
10903
11339
  this.settleAcknowledged(out);
10904
11340
  return out;
@@ -11041,6 +11477,31 @@ var RecordLogClient = class {
11041
11477
  }
11042
11478
  return { touched };
11043
11479
  }
11480
+ /**
11481
+ * Keep one chunk of a segment from the rows the store holds instead of
11482
+ * reading it, under the replacement `generation` as receipt `attempt`. The
11483
+ * rows are kept only when the held segment's marker lists the same object
11484
+ * with the same digest, row count and range, no other receipt attempt is in
11485
+ * progress, and the confirmed rows of that range number exactly `rows`;
11486
+ * otherwise nothing changes and it answers `mismatch`, and the chunk is
11487
+ * read. A kept row the room changed after the new segment began is
11488
+ * corrected by its corrections or the pages after them.
11489
+ *
11490
+ * @throws RecordLogStaleReplacementError under a superseded generation.
11491
+ * @throws RecordLogStaleReceiptError for an attempt no longer in progress.
11492
+ */
11493
+ keepSegmentChunk(chunk) {
11494
+ this.assertGeneration(chunk.generation);
11495
+ const state = this.receiptTables().receipts();
11496
+ if (!state || !state.attempts.some((a) => a.attempt === chunk.attempt)) throw new RecordLogStaleReceiptError(chunk.attempt);
11497
+ const entry = this.tables.heldSegment?.()?.chunks.find((c) => c.object === chunk.object);
11498
+ const same = entry !== void 0 && entry.model === chunk.model && entry.sha256 === chunk.sha256 && entry.rows === chunk.rows && entry.firstId === chunk.firstId && entry.lastId === chunk.lastId;
11499
+ const alone = state.attempts.every((a) => a.attempt === chunk.attempt);
11500
+ const range = { model: chunk.model, firstId: chunk.firstId, lastId: chunk.lastId };
11501
+ if (!same || !alone || !this.tables.keepConfirmedRange?.({ ...range, rows: chunk.rows })) return { mismatch: true };
11502
+ this.touchReceipt(chunk.attempt);
11503
+ return { kept: chunk.rows, ranges: [range] };
11504
+ }
11044
11505
  /**
11045
11506
  * Apply a segment's corrections under the replacement `generation`: a row
11046
11507
  * replaces the record's, a `null` deletes it (one the chunks did not carry
@@ -11080,8 +11541,11 @@ var MemoryRecordLogTables = class {
11080
11541
  constraintList = [];
11081
11542
  rows;
11082
11543
  replacingKeys = null;
11544
+ /** The records interrupted replacements put since the last completion: not of the confirmed generation. */
11545
+ interruptedKeys = /* @__PURE__ */ new Set();
11083
11546
  generationValue = 0;
11084
11547
  receiptValue = null;
11548
+ heldValue = null;
11085
11549
  loadKeys = /* @__PURE__ */ new Map();
11086
11550
  held = /* @__PURE__ */ new Map();
11087
11551
  writers = /* @__PURE__ */ new Map();
@@ -11138,6 +11602,7 @@ var MemoryRecordLogTables = class {
11138
11602
  };
11139
11603
  }
11140
11604
  beginReplace() {
11605
+ for (const text of this.replacingKeys ?? []) this.interruptedKeys.add(text);
11141
11606
  this.replacingKeys = /* @__PURE__ */ new Set();
11142
11607
  this.generationValue++;
11143
11608
  }
@@ -11147,6 +11612,7 @@ var MemoryRecordLogTables = class {
11147
11612
  completeReplace() {
11148
11613
  const kept = this.replacingKeys ?? /* @__PURE__ */ new Set();
11149
11614
  this.replacingKeys = null;
11615
+ this.interruptedKeys = /* @__PURE__ */ new Set();
11150
11616
  const removed = [];
11151
11617
  const next = /* @__PURE__ */ new Map();
11152
11618
  for (const text of kept) {
@@ -11193,6 +11659,27 @@ var MemoryRecordLogTables = class {
11193
11659
  const kept = new Set(attempts);
11194
11660
  for (const attempt of [...this.loadKeys.keys()]) if (!kept.has(attempt)) this.loadKeys.delete(attempt);
11195
11661
  }
11662
+ heldSegment() {
11663
+ return this.heldValue ? JSON.parse(JSON.stringify(this.heldValue)) : null;
11664
+ }
11665
+ setHeldSegment(segment) {
11666
+ this.heldValue = segment ? JSON.parse(JSON.stringify(segment)) : null;
11667
+ }
11668
+ keepConfirmedRange(range) {
11669
+ const replacing = this.replacingKeys;
11670
+ if (!replacing) return false;
11671
+ const within = [];
11672
+ for (const text of this.rows.rows.keys()) {
11673
+ const at = text.indexOf("\0");
11674
+ const id = text.slice(at + 1);
11675
+ if (text.slice(0, at) !== range.model || replacing.has(text) || this.interruptedKeys.has(text)) continue;
11676
+ if (compareRecordIds(id, range.firstId) >= 0 && compareRecordIds(id, range.lastId) <= 0) within.push({ text, id });
11677
+ }
11678
+ if (within.length !== range.rows) return false;
11679
+ within.sort((a, b) => compareRecordIds(a.id, b.id));
11680
+ for (const { text } of within) replacing.add(text);
11681
+ return true;
11682
+ }
11196
11683
  /** The receipt attempts whose load keys are kept: a check that none outlives its receipt. */
11197
11684
  loadKeyAttempts() {
11198
11685
  return [...this.loadKeys.keys()];
@@ -11327,7 +11814,8 @@ function recordLogClientDDL() {
11327
11814
  permission TEXT,
11328
11815
  rows_gen INTEGER NOT NULL DEFAULT 0,
11329
11816
  replacing INTEGER,
11330
- receipt TEXT
11817
+ receipt TEXT,
11818
+ segment TEXT
11331
11819
  )`,
11332
11820
  `CREATE TABLE IF NOT EXISTS record_log_writers (
11333
11821
  doc_id TEXT NOT NULL,
@@ -11409,7 +11897,8 @@ function recordLogClientDDL() {
11409
11897
  ];
11410
11898
  }
11411
11899
  var RECORD_LOG_CLIENT_ADDED_COLUMNS = Object.freeze([
11412
- { table: "record_log_state", column: "receipt", add: `ALTER TABLE record_log_state ADD COLUMN receipt TEXT` }
11900
+ { table: "record_log_state", column: "receipt", add: `ALTER TABLE record_log_state ADD COLUMN receipt TEXT` },
11901
+ { table: "record_log_state", column: "segment", add: `ALTER TABLE record_log_state ADD COLUMN segment TEXT` }
11413
11902
  ]);
11414
11903
  function recordLogFieldIndexName(kind, model, name, table = "view") {
11415
11904
  const tag = kind === "field" ? "f" : "u";
@@ -11559,6 +12048,24 @@ var SqlRecordLogTables = class {
11559
12048
  this.ensureState();
11560
12049
  this.sql.exec(`UPDATE record_log_state SET receipt = ? WHERE doc_id = ?`, state ? JSON.stringify(state) : null, this.docId);
11561
12050
  }
12051
+ heldSegment() {
12052
+ const text = this.state()?.segment;
12053
+ return text ? JSON.parse(String(text)) : null;
12054
+ }
12055
+ setHeldSegment(segment) {
12056
+ this.ensureState();
12057
+ this.sql.exec(`UPDATE record_log_state SET segment = ? WHERE doc_id = ?`, segment ? JSON.stringify(segment) : null, this.docId);
12058
+ }
12059
+ keepConfirmedRange(range) {
12060
+ const state = this.state();
12061
+ if (state?.replacing === null || state?.replacing === void 0) return false;
12062
+ const where = `WHERE doc_id = ? AND _type = ? AND _id >= ? AND _id <= ? AND _gen = ?`;
12063
+ const bindings = [this.docId, range.model, range.firstId, range.lastId, Number(state.rows_gen ?? 0)];
12064
+ const [count] = rowsOf(this.sql, `SELECT COUNT(*) AS n FROM record_log_rows ${where}`, ...bindings);
12065
+ if (Number(count?.n ?? 0) !== range.rows) return false;
12066
+ this.sql.exec(`UPDATE record_log_rows SET _gen = ? ${where}`, Number(state.replacing), ...bindings);
12067
+ return true;
12068
+ }
11562
12069
  noteLoadKeys(attempt, keys) {
11563
12070
  for (const key of keys) {
11564
12071
  this.sql.exec(
@@ -12104,6 +12611,7 @@ var RecordLogStore = class {
12104
12611
  const epochs = this.tables.epochs();
12105
12612
  const [state] = rowsOf(this.sql, `SELECT * FROM record_log_state WHERE doc_id = ?`, this.docId);
12106
12613
  const writer = this.writer();
12614
+ const writerState = writer ? this.tables.writerState(writer) : null;
12107
12615
  const [pending] = writer ? rowsOf(
12108
12616
  this.sql,
12109
12617
  `SELECT MIN(seq) AS lowest, COUNT(*) AS n FROM record_log_pending WHERE doc_id = ? AND writer = ?`,
@@ -12119,11 +12627,13 @@ var RecordLogStore = class {
12119
12627
  replacement: this.tables.replacing(),
12120
12628
  lastCatchUpAt: state?.last_catch_up_at ?? null,
12121
12629
  writer,
12122
- nextSeq: writer ? this.tables.writerState(writer).nextSeq : 1,
12630
+ nextSeq: writerState?.nextSeq ?? 1,
12631
+ resumedAt: writerState?.resumedAt ?? 0,
12123
12632
  lowestPending: pending && pending.lowest !== null && pending.lowest !== void 0 ? Number(pending.lowest) : null,
12124
12633
  pending: Number(pending?.n ?? 0),
12125
12634
  unacked: writer ? this.unackedOf(writer) : [],
12126
- receipt: latestReceipt(this.tables.receipts())
12635
+ receipt: latestReceipt(this.tables.receipts()),
12636
+ segment: this.tables.heldSegment()
12127
12637
  };
12128
12638
  }
12129
12639
  /** A writer's unacknowledged, unwithdrawn entries and the records each touches. */
@@ -12548,14 +13058,16 @@ var RecordLogStore = class {
12548
13058
  const touched = [];
12549
13059
  const acknowledged = [];
12550
13060
  const settled = [];
13061
+ let underivable;
12551
13062
  for (const item of command.items) {
12552
13063
  const out = client.receive(item);
12553
13064
  touched.push(...out.touched);
12554
13065
  acknowledged.push(...out.acknowledged);
12555
13066
  settled.push(...out.settled);
13067
+ underivable ??= out.underivable;
12556
13068
  }
12557
13069
  const changed = this.settleView(touched, command.project ?? []);
12558
- return { acknowledged, settled, changed, cursor: this.tables.cursor() };
13070
+ return { acknowledged, settled, changed, cursor: this.tables.cursor(), ...underivable ? { underivable } : {} };
12559
13071
  });
12560
13072
  }
12561
13073
  /** Act on a refusal: hand back what it reaches and answer the frames that move the room past it. */
@@ -12580,7 +13092,10 @@ var RecordLogStore = class {
12580
13092
  * the store beginning a replacement makes it stale.
12581
13093
  */
12582
13094
  beginFencedCatchUp(command) {
12583
- return this.sql.transaction(() => ({ generation: this.client(command.writer).beginFencedCatchUp(command.full) }));
13095
+ return this.sql.transaction(() => {
13096
+ const generation = this.client(command.writer).beginFencedCatchUp(command.full);
13097
+ return command.full ? { generation, held: this.tables.heldSegment() } : { generation };
13098
+ });
12584
13099
  }
12585
13100
  /** Whether `generation` is not the replacement the store is in. */
12586
13101
  staleGeneration(generation) {
@@ -12621,11 +13136,18 @@ var RecordLogStore = class {
12621
13136
  high: command.high,
12622
13137
  full: command.full,
12623
13138
  ...command.generation !== void 0 ? { generation: command.generation } : {},
12624
- ...command.receipt !== void 0 ? { receipt: command.receipt } : {}
13139
+ ...command.receipt !== void 0 ? { receipt: command.receipt } : {},
13140
+ ...command.segment !== void 0 ? { segment: command.segment } : {}
12625
13141
  });
12626
13142
  this.tables.setLastCatchUpAt(command.at ?? Date.now());
12627
13143
  const changed = this.settleView(out.touched, command.project ?? []);
12628
- return { acknowledged: out.acknowledged, settled: out.settled, changed, cursor: this.tables.cursor() };
13144
+ return {
13145
+ acknowledged: out.acknowledged,
13146
+ settled: out.settled,
13147
+ changed,
13148
+ cursor: this.tables.cursor(),
13149
+ ...out.underivable ? { underivable: out.underivable } : {}
13150
+ };
12629
13151
  });
12630
13152
  }
12631
13153
  // ── Receipts of chunks ────────────────────────────────────────────
@@ -12735,6 +13257,25 @@ var RecordLogStore = class {
12735
13257
  };
12736
13258
  });
12737
13259
  }
13260
+ /**
13261
+ * Keep one chunk of segment `segmentId` from the confirmed rows instead of
13262
+ * reading it, in one transaction, as {@link RecordLogClient.keepSegmentChunk}
13263
+ * decides: the reply's `applied` is the rows kept, or it answers
13264
+ * `mismatch` and nothing changed. `stale` as {@link applySegmentChunk}, and
13265
+ * for an attempt no longer in progress. The view and query rows are
13266
+ * already the kept rows'.
13267
+ */
13268
+ keepSegmentChunk(command) {
13269
+ return this.sql.transaction(() => {
13270
+ const cursor = this.tables.cursor();
13271
+ if (this.staleGeneration(command.generation)) return { applied: 0, removed: 0, changed: [], models: [], cursor, stale: true };
13272
+ const stale = this.staleReceipt(command.writer, command.attempt);
13273
+ if (stale) return stale;
13274
+ const out = this.client(command.writer).keepSegmentChunk(command);
13275
+ if ("mismatch" in out) return { applied: 0, removed: 0, changed: [], models: [], cursor, mismatch: true };
13276
+ return { applied: out.kept, removed: 0, changed: [], models: [], ranges: out.ranges, cursor };
13277
+ });
13278
+ }
12738
13279
  /** Apply a segment's corrections under the replacement `generation`; `stale` as {@link applySegmentChunk}. */
12739
13280
  applySegmentCorrections(command) {
12740
13281
  return this.sql.transaction(() => {
@@ -16222,6 +16763,17 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
16222
16763
  return typeof generation === "number" ? generation : null;
16223
16764
  });
16224
16765
  }
16766
+ /**
16767
+ * Begin a segment's full replacement: its generation, and the segment the
16768
+ * store's rows were last replaced from, read in the same transaction (the
16769
+ * mirror's may be older). The receipt tries to keep only those chunks.
16770
+ */
16771
+ beginSegmentReplacement(writer = this.writer()) {
16772
+ return this.run("beginCatchUp", async () => {
16773
+ const reply = await this.host.dispatch({ kind: "beginCatchUp", writer, full: true });
16774
+ return { generation: typeof reply?.generation === "number" ? reply.generation : null, held: reply?.held ?? null };
16775
+ });
16776
+ }
16225
16777
  /** Apply one catch-up page, read by the room at log number `lsn`; answered `stale` when the store is past it. */
16226
16778
  applyCatchUpPage(page, project = [], writer = this.writer()) {
16227
16779
  return this.run("applyCatchUpPage", async () => {
@@ -16263,6 +16815,14 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
16263
16815
  applySegmentChunk(chunk, project = [], writer = this.writer()) {
16264
16816
  return this.bulk("applySegmentChunk", { kind: "applySegmentChunk", writer, ...chunk, ...project.length ? { project } : {} });
16265
16817
  }
16818
+ /**
16819
+ * Keep one chunk of a segment from the rows the store holds instead of
16820
+ * reading it: `applied` is the rows kept, or the reply is `mismatch` (the
16821
+ * chunk is read instead) or `stale`. Nothing the views show changes.
16822
+ */
16823
+ keepSegmentChunk(chunk, writer = this.writer()) {
16824
+ return this.run("keepSegmentChunk", () => this.host.dispatch({ kind: "keepSegmentChunk", writer, ...chunk }));
16825
+ }
16266
16826
  /** Apply a segment's corrections under the replacement `generation`; answered `stale` when it was superseded. */
16267
16827
  applySegmentCorrections(corrections, project = [], writer = this.writer()) {
16268
16828
  return this.bulk("applySegmentCorrections", {
@@ -16393,6 +16953,10 @@ var RecordLogSender = class {
16393
16953
  inFlightCount() {
16394
16954
  return this.inFlight.size;
16395
16955
  }
16956
+ /** The numbers of the entries sent and not yet acknowledged. */
16957
+ inFlightSeqs() {
16958
+ return [...this.inFlight];
16959
+ }
16396
16960
  /** `record.entries` frames that hold the next back: sent, not answered in full, and within their wait. */
16397
16961
  framesInFlight() {
16398
16962
  return this.frames.length;
@@ -16567,7 +17131,11 @@ var RECORD_LOG_DRAIN_WAIT_MS = 15e3;
16567
17131
  var RECORD_LOG_RESULT_GAP_MS = 2e3;
16568
17132
  var WRITER_TAKEN_RETRY_MS = 500;
16569
17133
  var CATCH_UP_RETRY_MS = 250;
16570
- var RECORD_LOG_ACCEPTS = ["load", "segment"];
17134
+ var RECORD_LOG_ACCEPTS = ["load", "segment", "building"];
17135
+ var RECORD_LOG_STREAM_CREDIT_PAGES = 4;
17136
+ var RECORD_LOG_BUILDING_MAX_WAIT_MS = 6e4;
17137
+ var BUILDING_RETRY_MS = 1e3;
17138
+ var streamIds = 0;
16571
17139
  var RECORD_LOG_RECEIPT_FAILURES_BEFORE_ROWS = 2;
16572
17140
  var RECORD_LOG_REPLACEMENT_WAIT_MS = 3e4;
16573
17141
  var REPLACEMENT_POLL_MS = 100;
@@ -16582,6 +17150,14 @@ function isChunkIntegrityError(error) {
16582
17150
  return name === "IngestChunkError" || name === "SnapshotChunkIntegrityError";
16583
17151
  }
16584
17152
  var errorText = (error) => error instanceof Error ? error.message : String(error);
17153
+ function answeredSeqs(items, writer) {
17154
+ const seqs = [];
17155
+ for (const item of items) {
17156
+ if ("void" in item || "duplicate" in item) seqs.push(item.seq);
17157
+ else if (item.w === writer && item.seq !== void 0) seqs.push(item.seq);
17158
+ }
17159
+ return seqs;
17160
+ }
16585
17161
  var shownPath = (path) => path.replace(/\/doc-artifact\/[^/]+/, "/doc-artifact/\u2026");
16586
17162
  function loadManifestOf(bytes, pointer) {
16587
17163
  let manifest;
@@ -16618,15 +17194,17 @@ var RecordLogDocumentSession = class {
16618
17194
  * @param store - Its store.
16619
17195
  * @param host - The instance's side.
16620
17196
  * @param senderOptions - How entries are batched.
17197
+ * @param history - What the document's earlier sessions on this connection id left.
16621
17198
  */
16622
- constructor(docId, store, host, senderOptions = {}) {
17199
+ constructor(docId, store, host, senderOptions = {}, history = { opened: /* @__PURE__ */ new Set(), stale: null }) {
16623
17200
  this.docId = docId;
16624
17201
  this.store = store;
16625
17202
  this.host = host;
17203
+ this.history = history;
16626
17204
  this.sender = new RecordLogSender(
16627
17205
  {
16628
17206
  send: (frame) => this.sendFrame(frame),
16629
- connected: () => this.phase === "open" && this.connected()
17207
+ connected: () => (this.phase === "open" || this.sendingAhead) && this.connected()
16630
17208
  },
16631
17209
  senderOptions
16632
17210
  );
@@ -16643,14 +17221,38 @@ var RecordLogDocumentSession = class {
16643
17221
  /** The orphan writer's entries the room has not answered yet. */
16644
17222
  outstanding = /* @__PURE__ */ new Set();
16645
17223
  drainDone = null;
16646
- /** Result frames that arrived while a catch-up was being read. */
16647
- heldResults = [];
16648
17224
  /**
16649
- * The paged catch-up in progress. `released` once the room dropped the
16650
- * subscription while a page request was out: the open goes again when that
16651
- * request is answered.
17225
+ * Result frames that arrived while a catch-up was being read; for an open
17226
+ * that sent frames ahead, also their answers (results and refusals) that
17227
+ * arrived while it was opening.
16652
17228
  */
17229
+ held = [];
17230
+ /** The open in progress sent its declaration and entries ahead of `record.opened`, or `null`. */
17231
+ ahead = null;
17232
+ /** `record.open` frames sent on this connection; only its first may send frames ahead. */
17233
+ openedOnConnection = 0;
17234
+ /** Set while the frames sent ahead are flushed: the sender may send before the open completes. */
17235
+ sendingAhead = false;
17236
+ /** The wait past which a re-minted writer's open asks the old id's stream for a barrier. */
17237
+ staleTimer = null;
17238
+ /**
17239
+ * A `record.open` of the re-minted writer's old id is out on this
17240
+ * connection: its `record.opened`, queued on the old id's stream behind
17241
+ * every answer queued there before it, ends the wait.
17242
+ */
17243
+ barrier = false;
17244
+ /** The paged catch-up in progress. */
16653
17245
  paging = null;
17246
+ /**
17247
+ * The room streams: its last `record.opened` said so (`streams: true`), or
17248
+ * a page marked with a stream id arrived on this connection. A stream start
17249
+ * then has no answer out; an older room answers it with an unmarked page.
17250
+ */
17251
+ roomStreams = false;
17252
+ /** When the first of the `building` answers in a row arrived; `null` when the last answer was another form. */
17253
+ buildingSince = null;
17254
+ /** Streamed catch-ups: pages applied, pages ignored as another stream's, credits sent. */
17255
+ streamCounters = { pages: 0, stalePages: 0, credits: 0 };
16654
17256
  /** The load the room said is applying (`record.load started`): results stall behind its numbers on purpose. */
16655
17257
  loadInProgress = null;
16656
17258
  /** Completed loads announced while the session was not open, received once it is. */
@@ -16715,6 +17317,13 @@ var RecordLogDocumentSession = class {
16715
17317
  this.host.synced(this.docId);
16716
17318
  return;
16717
17319
  }
17320
+ if ((this.phase === "catchingUp" || this.phase === "loading") && this.paging?.stream !== void 0 && (this.paging.streamed || this.roomStreams)) {
17321
+ Logger.info(`[record-log] ${this.docId}: the streamed catch-up ${this.paging.stream} stopped; opening again from the cursor`);
17322
+ this.paging = null;
17323
+ this.receipt = null;
17324
+ await this.sendOpen();
17325
+ return;
17326
+ }
16718
17327
  if (this.phase !== "idle") return;
16719
17328
  if (!this.connected()) {
16720
17329
  this.host.syncFailed(this.docId, "not connected");
@@ -16729,6 +17338,7 @@ var RecordLogDocumentSession = class {
16729
17338
  if (this.orphans.length) {
16730
17339
  Logger.info(`[record-log] ${this.docId}: draining ${this.orphans.length} earlier session writer(s) before opening`);
16731
17340
  }
17341
+ if (this.history.stale) return this.sendBarrier();
16732
17342
  await this.openNext();
16733
17343
  });
16734
17344
  }
@@ -16741,6 +17351,10 @@ var RecordLogDocumentSession = class {
16741
17351
  const current = this.current;
16742
17352
  const generation = this.generation;
16743
17353
  this.opens++;
17354
+ if (this.ahead) {
17355
+ this.ahead = null;
17356
+ this.held = [];
17357
+ }
16744
17358
  const marks = await this.store.refreshMarks();
16745
17359
  const pending = await this.store.pendingOf(current.writer);
16746
17360
  if (generation !== this.generation) return;
@@ -16748,7 +17362,17 @@ var RecordLogDocumentSession = class {
16748
17362
  const nextSeq = unacked.length ? unacked[0].seq : current.orphan ? Math.max(1, ...pending.map((p) => p.seq + 1)) : marks.nextSeq;
16749
17363
  this.phase = "opening";
16750
17364
  this.loadInProgress = null;
17365
+ const sendAhead = !current.orphan && this.openedOnConnection === 0 && [...this.history.opened].every((writer) => writer === current.writer) && nextSeq > marks.resumedAt;
17366
+ this.openedOnConnection++;
17367
+ this.history.opened.add(current.writer);
16751
17368
  const fetches = typeof this.host.connection()?.fetchArtifact === "function";
17369
+ const waited = this.buildingSince !== null && Date.now() - this.buildingSince >= RECORD_LOG_BUILDING_MAX_WAIT_MS;
17370
+ if (fetches && waited) {
17371
+ Logger.info(
17372
+ `[record-log] ${this.docId}: waited ${RECORD_LOG_BUILDING_MAX_WAIT_MS} ms for a segment being built; opening for pages instead`
17373
+ );
17374
+ }
17375
+ const accepts = RECORD_LOG_ACCEPTS.filter((token) => token !== "building" || !waited);
16752
17376
  this.sendFrame({
16753
17377
  type: "record.open",
16754
17378
  writer: current.writer,
@@ -16757,8 +17381,106 @@ var RecordLogDocumentSession = class {
16757
17381
  open: marks.open,
16758
17382
  formats: [3],
16759
17383
  documentFormat: 3,
16760
- ...fetches ? { accepts: this.failedReceipts >= RECORD_LOG_RECEIPT_FAILURES_BEFORE_ROWS ? [] : [...RECORD_LOG_ACCEPTS] } : {}
17384
+ // Own entries the room applied as written come back as {l, e, w, seq}:
17385
+ // the store derives their rows from its pending entries.
17386
+ acks: "compact",
17387
+ ...fetches ? { accepts: this.failedReceipts >= RECORD_LOG_RECEIPT_FAILURES_BEFORE_ROWS ? [] : accepts } : {}
16761
17388
  });
17389
+ if (!sendAhead) return;
17390
+ const models = this.host.declarations();
17391
+ const ahead = { declarations: JSON.stringify(models), refused: false, seqs: [] };
17392
+ this.ahead = ahead;
17393
+ this.sender.enqueueControl({ type: "record.declare", models });
17394
+ for (const entry of unacked) this.sender.enqueue(wireEntryOf(entry));
17395
+ this.sendingAhead = true;
17396
+ try {
17397
+ this.sender.flush();
17398
+ } finally {
17399
+ this.sendingAhead = false;
17400
+ }
17401
+ ahead.seqs = this.sender.inFlightSeqs();
17402
+ }
17403
+ /**
17404
+ * The numbers sent ahead under the writer being opened that the room has
17405
+ * not answered: none once it refused them, and none an answer held so far
17406
+ * names.
17407
+ */
17408
+ owedAhead(writer) {
17409
+ const owed = new Set(this.ahead && !this.ahead.refused ? this.ahead.seqs : []);
17410
+ for (const answer of this.held) {
17411
+ if (answer.kind === "refused") owed.delete(answer.refusal.seq);
17412
+ else for (const seq of answeredSeqs(answer.items, writer)) owed.delete(seq);
17413
+ }
17414
+ return owed;
17415
+ }
17416
+ /**
17417
+ * A restored store's writer was re-minted while the room owed answers to
17418
+ * entries sent ahead under its old id. The room queues those answers on
17419
+ * the old subscription's stream, which the new open's does not wait for,
17420
+ * and a `void` or `duplicate` names no writer: one arriving once the new
17421
+ * id's renumbered entries went would be read as theirs. So the new id
17422
+ * opens once every owed number is answered (the answers are dropped), the
17423
+ * entries frame is refused, or the subscription is released. Past
17424
+ * {@link RECORD_LOG_DRAIN_WAIT_MS} the old id is opened again
17425
+ * ({@link sendBarrier}): its `record.opened` follows what is queued for it.
17426
+ */
17427
+ waitForStale(writer, nextSeq, owed) {
17428
+ this.ahead = null;
17429
+ this.held = [];
17430
+ this.history.stale = { writer, nextSeq, seqs: owed };
17431
+ const timer = setTimeout(() => {
17432
+ void this.serially(async () => {
17433
+ if (this.staleTimer !== timer || !this.history.stale) return;
17434
+ this.staleTimer = null;
17435
+ Logger.warn(
17436
+ `[record-log] ${this.docId}: the room has not answered ${this.history.stale.seqs.size} entr(ies) sent under the re-minted writer's old id; opening the old id again so its answer follows them`
17437
+ );
17438
+ this.sendBarrier();
17439
+ });
17440
+ }, RECORD_LOG_DRAIN_WAIT_MS);
17441
+ timer.unref?.();
17442
+ this.staleTimer = timer;
17443
+ }
17444
+ /**
17445
+ * Open the re-minted writer's old id again. The room queues the answer on
17446
+ * that id's stream, behind every answer queued there before it; a room
17447
+ * that lost them (stopped, or its delivery failed) answers on a stream
17448
+ * that never carries them. A wait past which answers are taken to be lost
17449
+ * would let a late one settle the new id's numbers. Answers that arrive
17450
+ * meanwhile are dropped; only this open's answer ends the wait.
17451
+ */
17452
+ sendBarrier() {
17453
+ const stale = this.history.stale;
17454
+ const marks = this.store.marks();
17455
+ this.barrier = true;
17456
+ this.openedOnConnection++;
17457
+ this.history.opened.add(stale.writer);
17458
+ this.sendFrame({
17459
+ type: "record.open",
17460
+ writer: stale.writer,
17461
+ cursor: marks.cursor,
17462
+ nextSeq: stale.nextSeq,
17463
+ open: marks.open,
17464
+ formats: [3],
17465
+ documentFormat: 3,
17466
+ acks: "compact"
17467
+ });
17468
+ }
17469
+ /** Answers to the old id's entries arrived: dropped, and the new id opens once none is owed. */
17470
+ async staleAnswered(seqs) {
17471
+ const stale = this.history.stale;
17472
+ if (!stale || this.barrier) return;
17473
+ for (const seq of seqs) stale.seqs.delete(seq);
17474
+ if (stale.seqs.size === 0) await this.endStale();
17475
+ }
17476
+ /** Nothing more of the old id can come: the document opens (orphans first, on a new connection). */
17477
+ async endStale() {
17478
+ if (!this.history.stale) return;
17479
+ if (this.staleTimer) clearTimeout(this.staleTimer);
17480
+ this.staleTimer = null;
17481
+ this.barrier = false;
17482
+ this.history.stale = null;
17483
+ await this.openNext();
16762
17484
  }
16763
17485
  /** The socket closed: everything in flight is gone, and the next open starts over. */
16764
17486
  disconnected() {
@@ -16768,7 +17490,14 @@ var RecordLogDocumentSession = class {
16768
17490
  this.current = null;
16769
17491
  this.orphans = [];
16770
17492
  this.paging = null;
16771
- this.heldResults = [];
17493
+ this.roomStreams = false;
17494
+ this.buildingSince = null;
17495
+ this.held = [];
17496
+ this.ahead = null;
17497
+ this.openedOnConnection = 0;
17498
+ if (this.staleTimer) clearTimeout(this.staleTimer);
17499
+ this.staleTimer = null;
17500
+ this.barrier = false;
16772
17501
  this.receipt = null;
16773
17502
  this.queuedLoads = [];
16774
17503
  this.loadInProgress = null;
@@ -16874,11 +17603,17 @@ var RecordLogDocumentSession = class {
16874
17603
  });
16875
17604
  }
16876
17605
  async opened(frame) {
17606
+ if (this.history.stale) {
17607
+ if (this.barrier && this.phase === "opening") return this.endStale();
17608
+ Logger.debug(`[record-log] ${this.docId}: record.opened while a re-minted writer waits for its old id; ignored`);
17609
+ return;
17610
+ }
16877
17611
  if (this.phase !== "opening" || !this.current) {
16878
17612
  Logger.debug(`[record-log] ${this.docId}: record.opened outside an open; ignored`);
16879
17613
  return;
16880
17614
  }
16881
17615
  this.takenRetryMs = WRITER_TAKEN_RETRY_MS;
17616
+ this.roomStreams = frame.streams === true;
16882
17617
  const generation = this.generation;
16883
17618
  const epochs = frame.epochs ?? {};
16884
17619
  const current = Number(epochs.current ?? 1);
@@ -16897,16 +17632,22 @@ var RecordLogDocumentSession = class {
16897
17632
  Logger.warn(
16898
17633
  `[record-log] ${this.docId}: the room has judged writer ${this.current.writer} up to ${this.lastSeq}, past the ${this.store.marks().nextSeq - 1} it minted (a restored store); re-minting`
16899
17634
  );
17635
+ const old = this.current.writer;
17636
+ const owed = this.owedAhead(old);
16900
17637
  const { writer, renumbered } = await this.store.dispatch({ kind: "remintWriter", writer: this.current.writer });
16901
17638
  this.store.renumbered(renumbered);
16902
17639
  await this.store.refreshMarks();
16903
17640
  if (generation !== this.generation) return;
16904
17641
  this.current = { writer, orphan: false };
16905
17642
  this.sender.reset();
17643
+ if (owed.size) return this.waitForStale(old, this.lastSeq + 1, owed);
16906
17644
  await this.sendOpen();
16907
17645
  return;
16908
17646
  }
17647
+ if (!this.current.orphan) this.history.opened = /* @__PURE__ */ new Set([this.current.writer]);
16909
17648
  const catchUp = frame.catchUp ?? { mode: "inline", rows: [], gone: [], lsn: frame.lsn };
17649
+ if (catchUp.mode === "building") return this.waitForSegment(catchUp);
17650
+ this.buildingSince = null;
16910
17651
  this.phase = "catchingUp";
16911
17652
  const specs = this.host.projectionSpecs();
16912
17653
  if (catchUp.mode === "load") {
@@ -16928,22 +17669,20 @@ var RecordLogDocumentSession = class {
16928
17669
  );
16929
17670
  const replacing2 = await this.store.beginFencedCatchUp(true, this.current.writer);
16930
17671
  if (generation !== this.generation) return;
16931
- this.paging = { cursor: 0, upTo, full: true, high, ...replacing2 !== null ? { generation: replacing2 } : {} };
16932
- this.sendFrame({ type: "record.catchUp", cursor: 0, upTo, full: true });
17672
+ this.beginPaging({ cursor: 0, upTo, full: true, high, ...replacing2 !== null ? { generation: replacing2 } : {} });
16933
17673
  return;
16934
17674
  }
16935
17675
  if (catchUp.mode === "paged") {
16936
17676
  const full2 = catchUp.full === true;
16937
17677
  const replacing2 = await this.store.beginFencedCatchUp(full2, this.current.writer);
16938
17678
  if (generation !== this.generation) return;
16939
- this.paging = {
17679
+ this.beginPaging({
16940
17680
  cursor: Number(catchUp.cursor),
16941
17681
  upTo: Number(catchUp.upTo),
16942
17682
  full: full2,
16943
17683
  high,
16944
17684
  ...replacing2 !== null ? { generation: replacing2 } : {}
16945
- };
16946
- this.sendFrame({ type: "record.catchUp", cursor: this.paging.cursor, upTo: this.paging.upTo, ...full2 ? { full: true } : {} });
17685
+ });
16947
17686
  return;
16948
17687
  }
16949
17688
  const full = catchUp.mode === "full";
@@ -16964,7 +17703,7 @@ var RecordLogDocumentSession = class {
16964
17703
  return;
16965
17704
  }
16966
17705
  if (done.stale) return this.overtaken(lsn, done.cursor, replacing);
16967
- await this.caughtUp(done.acknowledged);
17706
+ await this.caughtUp(done.acknowledged, done.underivable);
16968
17707
  }
16969
17708
  /**
16970
17709
  * Another client of this store applied results past the log number the
@@ -17015,8 +17754,71 @@ var RecordLogDocumentSession = class {
17015
17754
  }
17016
17755
  /** The room's `lastSeq` for the writer being opened, from its `record.opened`. */
17017
17756
  lastSeq = 0;
17757
+ /**
17758
+ * Begin a paged catch-up as a stream: the start carries a fresh id, and the
17759
+ * room pushes every page marked with it. An older room answers the start
17760
+ * with an unmarked page, and the rest are asked for one at a time.
17761
+ */
17762
+ beginPaging(paging, extra = {}) {
17763
+ const stream = String(++streamIds);
17764
+ this.paging = { ...paging, stream, pages: 0 };
17765
+ this.sendFrame({
17766
+ type: "record.catchUp",
17767
+ stream,
17768
+ cursor: paging.cursor,
17769
+ upTo: paging.upTo,
17770
+ ...paging.full ? { full: true } : {},
17771
+ ...extra
17772
+ });
17773
+ }
17774
+ /** A page of a stream this session is not running (ended, replaced or released): it applies to nothing. */
17775
+ stalePage(frame, why) {
17776
+ this.streamCounters.stalePages++;
17777
+ Logger.debug(`[record-log] ${this.docId}: catch-up page of stream ${String(frame.stream ?? "(none)")} ignored: ${why}`);
17778
+ }
17779
+ /**
17780
+ * The room is building a segment for this open (`mode: "building"`): the
17781
+ * subscription is registered, but nothing is caught up. Results that
17782
+ * arrive meanwhile are dropped (the next open's catch-up carries them),
17783
+ * progress is reported so the open's watchdog waits, and the document is
17784
+ * opened again after `retryMs`. Past {@link RECORD_LOG_BUILDING_MAX_WAIT_MS}
17785
+ * of such answers, the open no longer declares `building`.
17786
+ */
17787
+ waitForSegment(catchUp) {
17788
+ this.buildingSince ??= Date.now();
17789
+ const retryMs = Number.isFinite(Number(catchUp.retryMs)) ? Math.max(0, Number(catchUp.retryMs)) : BUILDING_RETRY_MS;
17790
+ Logger.info(
17791
+ `[record-log] ${this.docId}: the room is building segment ${String(catchUp.segmentId ?? "")} for this open; opening again in ${retryMs} ms`
17792
+ );
17793
+ this.phase = "opening";
17794
+ this.host.progress?.(this.docId);
17795
+ const connection = this.generation;
17796
+ const opens = this.opens;
17797
+ const timer = setTimeout(() => {
17798
+ void this.serially(async () => {
17799
+ if (connection !== this.generation || opens !== this.opens || this.phase !== "opening" || !this.current) return;
17800
+ await this.sendOpen();
17801
+ });
17802
+ }, retryMs);
17803
+ timer.unref?.();
17804
+ }
17018
17805
  async catchUpPage(frame) {
17019
- if (this.phase !== "catchingUp" && this.phase !== "loading" || !this.paging || !this.current) return;
17806
+ const marked = typeof frame.stream === "string";
17807
+ if (this.phase !== "catchingUp" && this.phase !== "loading" || !this.paging || !this.current) {
17808
+ if (marked) this.stalePage(frame, "no catch-up is in progress");
17809
+ return;
17810
+ }
17811
+ if (marked) {
17812
+ if (frame.stream !== this.paging.stream) return this.stalePage(frame, `the catch-up in progress is ${this.paging.stream ?? "paged per request"}`);
17813
+ this.paging.streamed = true;
17814
+ this.roomStreams = true;
17815
+ this.streamCounters.pages++;
17816
+ } else if (this.paging.stream !== void 0 && (this.paging.streamed || this.roomStreams)) {
17817
+ return this.stalePage(frame, "an unmarked page during a stream");
17818
+ } else if (this.paging.stream !== void 0) {
17819
+ Logger.debug(`[record-log] ${this.docId}: the room answered a stream start with a page per request; asking for each page`);
17820
+ delete this.paging.stream;
17821
+ }
17020
17822
  const receipt = this.paging.receipt;
17021
17823
  if (this.paging.released) {
17022
17824
  Logger.info(`[record-log] ${this.docId}: a catch-up page requested before the room released the subscription; discarded`);
@@ -17043,6 +17845,14 @@ var RecordLogDocumentSession = class {
17043
17845
  if (page.stale) return this.overtaken(lsn, page.cursor, this.paging.generation ?? null);
17044
17846
  if (receipt) receipt.remainderRows += rows.length + gone.length;
17045
17847
  this.host.progress?.(this.docId);
17848
+ if (frame.next && this.paging.stream !== void 0) {
17849
+ this.paging.pages = (this.paging.pages ?? 0) + 1;
17850
+ if (this.paging.pages % RECORD_LOG_STREAM_CREDIT_PAGES === 0) {
17851
+ this.streamCounters.credits++;
17852
+ this.sendFrame({ type: "record.catchUp", stream: this.paging.stream, credit: frame.next });
17853
+ }
17854
+ return;
17855
+ }
17046
17856
  if (frame.next) {
17047
17857
  this.sendFrame({
17048
17858
  type: "record.catchUp",
@@ -17059,7 +17869,14 @@ var RecordLogDocumentSession = class {
17059
17869
  const replacing = this.paging.generation ?? null;
17060
17870
  this.paging = null;
17061
17871
  const done = await this.store.completeCatchUp(
17062
- { lsn, high, full, ...fence, ...receipt?.attempt !== void 0 ? { receipt: receipt.attempt } : {} },
17872
+ {
17873
+ lsn,
17874
+ high,
17875
+ full,
17876
+ ...fence,
17877
+ ...receipt?.attempt !== void 0 ? { receipt: receipt.attempt } : {},
17878
+ ...receipt?.segment ? { segment: receipt.segment } : {}
17879
+ },
17063
17880
  specs,
17064
17881
  this.current.writer
17065
17882
  );
@@ -17070,7 +17887,7 @@ var RecordLogDocumentSession = class {
17070
17887
  if (done.stale) return this.overtaken(lsn, done.cursor, replacing);
17071
17888
  if (full) this.failedReceipts = 0;
17072
17889
  if (receipt) this.receiptDone(receipt);
17073
- await this.caughtUp(done.acknowledged);
17890
+ await this.caughtUp(done.acknowledged, done.underivable);
17074
17891
  }
17075
17892
  // ── Receipts of chunks ────────────────────────────────────────────
17076
17893
  /** The connection's artifact fetch; a receipt fails without one. */
@@ -17208,8 +18025,7 @@ var RecordLogDocumentSession = class {
17208
18025
  await this.serially(async () => {
17209
18026
  if (!this.receiving(receipt)) return;
17210
18027
  if (receipt.released) return this.abandonReceipt(receipt, "the room released the subscription");
17211
- this.paging = { cursor: remainder.cursor, upTo: remainder.upTo, full: false, high: remainder.high, receipt };
17212
- this.sendFrame({ type: "record.catchUp", cursor: remainder.cursor, upTo: remainder.upTo, load: pointer.sessionId });
18028
+ this.beginPaging({ cursor: remainder.cursor, upTo: remainder.upTo, full: false, high: remainder.high, receipt }, { load: pointer.sessionId });
17213
18029
  });
17214
18030
  } catch (error) {
17215
18031
  await this.serially(() => this.receiptFailed(receipt, errorText(error)));
@@ -17248,11 +18064,44 @@ var RecordLogDocumentSession = class {
17248
18064
  this.fetcher();
17249
18065
  const attempt = await this.store.beginReceipt({ kind: "segment", id: segment.segmentId }, receipt.writer);
17250
18066
  receipt.attempt = attempt;
17251
- const generation = await this.store.beginFencedCatchUp(true, receipt.writer);
18067
+ const { generation, held } = await this.store.beginSegmentReplacement(receipt.writer);
17252
18068
  if (generation === null) throw new ReceiptFailure("the store handed out no replacement generation");
17253
18069
  const overtaken = () => this.serially(() => this.abandonReceipt(receipt, "another client of the store began replacing it", generation));
17254
- for (const chunk of segment.chunks) {
18070
+ const holds = new Map((held?.chunks ?? []).map((c) => [c.object, c]));
18071
+ receipt.kept = 0;
18072
+ receipt.segment = {
18073
+ segmentId: segment.segmentId,
18074
+ chunks: segment.chunks.map((chunk) => ({
18075
+ object: recordLogSegmentChunkObject(segment.segmentId, chunk),
18076
+ model: chunk.model,
18077
+ index: chunk.index,
18078
+ firstId: chunk.firstId,
18079
+ lastId: chunk.lastId,
18080
+ rows: chunk.rows,
18081
+ sha256: chunk.sha256
18082
+ }))
18083
+ };
18084
+ for (const [at, chunk] of segment.chunks.entries()) {
17255
18085
  if (!this.receiving(receipt)) return;
18086
+ const mine = receipt.segment.chunks[at];
18087
+ const had = holds.get(mine.object);
18088
+ if (had && had.sha256 === mine.sha256 && had.rows === mine.rows && had.firstId === mine.firstId && had.lastId === mine.lastId) {
18089
+ const { index: _index, ...range } = mine;
18090
+ void _index;
18091
+ const kept = await this.store.keepSegmentChunk(
18092
+ { generation, attempt, segmentId: segment.segmentId, ...range },
18093
+ receipt.writer
18094
+ );
18095
+ if (!this.receiving(receipt)) return;
18096
+ if (kept.stale) return overtaken();
18097
+ if (!kept.mismatch) {
18098
+ receipt.kept++;
18099
+ this.host.progress?.(this.docId);
18100
+ if (receipt.released) return this.serially(() => this.abandonReceipt(receipt, "the room released the subscription"));
18101
+ continue;
18102
+ }
18103
+ Logger.debug(`[record-log] ${this.docId}: the held chunk ${mine.object} could not be kept; fetching it`);
18104
+ }
17256
18105
  const reply = await this.applyChunk(
17257
18106
  receipt,
17258
18107
  `${base}/${chunk.path}`,
@@ -17278,8 +18127,7 @@ var RecordLogDocumentSession = class {
17278
18127
  await this.serially(async () => {
17279
18128
  if (!this.receiving(receipt) || !this.current) return;
17280
18129
  if (receipt.released) return this.abandonReceipt(receipt, "the room released the subscription");
17281
- this.paging = { cursor: segment.completedLsn, upTo, full: false, high, generation, receipt };
17282
- this.sendFrame({ type: "record.catchUp", cursor: segment.completedLsn, upTo });
18130
+ this.beginPaging({ cursor: segment.completedLsn, upTo, full: false, high, generation, receipt });
17283
18131
  });
17284
18132
  } catch (error) {
17285
18133
  await this.serially(() => this.receiptFailed(receipt, errorText(error)));
@@ -17290,8 +18138,9 @@ var RecordLogDocumentSession = class {
17290
18138
  if (this.receipt === receipt) this.receipt = null;
17291
18139
  this.failedReceipts = 0;
17292
18140
  if (this.loadInProgress === receipt.id) this.loadInProgress = null;
18141
+ const kept = receipt.kept !== void 0 ? `; ${receipt.kept} kept, ${receipt.chunks - receipt.kept} fetched` : "";
17293
18142
  Logger.info(
17294
- `[record-log] ${receipt.kind} received ${this.docId}: ${receipt.id} ${receipt.rows} rows in ${receipt.chunks} chunks, remainder ${receipt.remainderRows} rows, ${Date.now() - receipt.startedAt} ms`
18143
+ `[record-log] ${receipt.kind} received ${this.docId}: ${receipt.id} ${receipt.rows} rows in ${receipt.chunks} chunks, remainder ${receipt.remainderRows} rows, ${Date.now() - receipt.startedAt} ms${kept}`
17295
18144
  );
17296
18145
  }
17297
18146
  /**
@@ -17305,7 +18154,7 @@ var RecordLogDocumentSession = class {
17305
18154
  Logger.warn(`[record-log] ${receipt.kind} receipt failed ${this.docId}: ${receipt.id} ${reason}; opening again from the cursor`);
17306
18155
  this.receipt = null;
17307
18156
  this.paging = null;
17308
- this.heldResults = [];
18157
+ this.held = [];
17309
18158
  if (this.loadInProgress === receipt.id) this.loadInProgress = null;
17310
18159
  if (this.current) await this.sendOpen();
17311
18160
  }
@@ -17320,7 +18169,7 @@ var RecordLogDocumentSession = class {
17320
18169
  Logger.info(`[record-log] ${this.docId}: ${receipt.kind} receipt ${receipt.id} abandoned (${why}); opening again from the cursor`);
17321
18170
  this.receipt = null;
17322
18171
  this.paging = null;
17323
- this.heldResults = [];
18172
+ this.held = [];
17324
18173
  if (!this.current) return;
17325
18174
  if (replacing !== void 0) await this.openAfterReplacement(replacing);
17326
18175
  else await this.sendOpen();
@@ -17395,7 +18244,8 @@ var RecordLogDocumentSession = class {
17395
18244
  `[record-log] catch-up failed ${this.docId}: record.catchUp answered ${frame.code ?? frame.detail ?? "an error"}; opening again from the cursor in ${wait} ms`
17396
18245
  );
17397
18246
  this.paging = null;
17398
- this.heldResults = [];
18247
+ this.held = [];
18248
+ this.ahead = null;
17399
18249
  this.phase = "idle";
17400
18250
  this.current = null;
17401
18251
  if (this.retryTimer) clearTimeout(this.retryTimer);
@@ -17404,19 +18254,41 @@ var RecordLogDocumentSession = class {
17404
18254
  void this.start();
17405
18255
  }, wait);
17406
18256
  }
17407
- /** The catch-up is complete: results held meanwhile apply, then the writer's entries go. */
17408
- async caughtUp(acknowledged) {
18257
+ /**
18258
+ * The catch-up is complete: answers held meanwhile apply, then the writer's
18259
+ * entries go. A compact acknowledgement left underivable (by the
18260
+ * completion or a held result) opens the document again once they have.
18261
+ */
18262
+ async caughtUp(acknowledged, underivable) {
17409
18263
  const current = this.current;
17410
18264
  const generation = this.generation;
18265
+ const ahead = this.ahead;
18266
+ this.ahead = null;
18267
+ if (ahead?.refused) this.sender.reset();
17411
18268
  this.catchUpRetryMs = CATCH_UP_RETRY_MS;
17412
18269
  this.clearGap();
17413
18270
  this.settleAcknowledged(acknowledged);
17414
- const held = this.heldResults;
17415
- this.heldResults = [];
18271
+ const held = this.held;
18272
+ this.held = [];
17416
18273
  this.phase = current.orphan ? "draining" : "open";
17417
- for (const items of held) await this.applyResults(items);
18274
+ for (const answer of held) {
18275
+ if (answer.kind === "results") underivable = await this.applyResults(answer.items) ?? underivable;
18276
+ else await this.applyRefusal(answer.refusal);
18277
+ }
18278
+ if (underivable) {
18279
+ this.logUnderivable(underivable);
18280
+ this.reopenAfterCatchUp = true;
18281
+ }
17418
18282
  const pending = await this.store.pendingOf(current.writer);
17419
18283
  const unsent = pending.filter((p) => p.acked === void 0);
18284
+ if (ahead && !ahead.refused) {
18285
+ if (!unsent.length) await this.store.refreshMarks();
18286
+ if (generation !== this.generation) return;
18287
+ const models = this.host.declarations();
18288
+ if (JSON.stringify(models) !== ahead.declarations) this.sender.enqueueControl({ type: "record.declare", models });
18289
+ for (const entry of unsent) this.sender.enqueue(wireEntryOf(entry));
18290
+ return this.synced();
18291
+ }
17420
18292
  const first = unsent.length ? unsent[0].seq : (await this.store.refreshMarks()).nextSeq;
17421
18293
  if (generation !== this.generation) return;
17422
18294
  const resumeAt = current.orphan ? unsent.length ? first : 0 : first;
@@ -17430,6 +18302,10 @@ var RecordLogDocumentSession = class {
17430
18302
  this.sender.requeueInFlight(unsent.map(wireEntryOf));
17431
18303
  this.sender.enqueueControl({ type: "record.declare", models: this.host.declarations() });
17432
18304
  for (const entry of unsent) this.sender.enqueue(wireEntryOf(entry));
18305
+ return this.synced();
18306
+ }
18307
+ /** The own writer is open: what waits leaves, the open is reported, and loads announced meanwhile are received. */
18308
+ async synced() {
17433
18309
  this.sender.kick();
17434
18310
  this.host.synced(this.docId);
17435
18311
  if (this.reopenAfterCatchUp) {
@@ -17482,28 +18358,48 @@ var RecordLogDocumentSession = class {
17482
18358
  if (this.current?.writer !== writer) return null;
17483
18359
  return this.current.orphan ? this.orphanSender : this.sender;
17484
18360
  }
18361
+ /**
18362
+ * Whether answers are held until the catch-up completes: during it, and
18363
+ * while an open that sent frames ahead waits for `record.opened` (a server
18364
+ * can answer those frames before it).
18365
+ */
18366
+ holding() {
18367
+ return this.phase === "catchingUp" || this.phase === "loading" || this.ahead !== null && this.phase === "opening";
18368
+ }
17485
18369
  async results(items) {
17486
18370
  if (!Array.isArray(items) || !items.length) return;
17487
- if (this.phase === "catchingUp" || this.phase === "loading") {
17488
- this.heldResults.push(items);
18371
+ if (this.history.stale) {
18372
+ return this.staleAnswered(answeredSeqs(items, this.history.stale.writer));
18373
+ }
18374
+ if (this.holding()) {
18375
+ this.held.push({ kind: "results", items });
17489
18376
  return;
17490
18377
  }
17491
18378
  if (this.phase !== "open" && this.phase !== "draining") return;
17492
- await this.applyResults(items);
18379
+ const underivable = await this.applyResults(items);
18380
+ if (underivable) {
18381
+ this.logUnderivable(underivable);
18382
+ this.clearGap();
18383
+ await this.sendOpen();
18384
+ }
17493
18385
  }
18386
+ /** A compact acknowledgement the store could not derive: the open that follows brings its row. */
18387
+ logUnderivable({ l, writer, seq }) {
18388
+ Logger.warn(
18389
+ `[record-log] ${this.docId}: the compact acknowledgement of writer ${writer} seq ${seq} (log number ${l}) names no pending entry to derive its rows from; opening again from the cursor`
18390
+ );
18391
+ }
18392
+ /** Apply relayed items; answers a compact acknowledgement the store could not derive, if one holds the cursor back. */
17494
18393
  async applyResults(items) {
17495
18394
  const writer = this.current?.writer ?? this.store.writer();
17496
18395
  const reply = await this.store.receive(items, this.host.projectionSpecs(), writer);
17497
- const answered = [];
17498
- for (const item of items) {
17499
- if ("void" in item || "duplicate" in item) answered.push(item.seq);
17500
- else if (item.w === writer && item.seq !== void 0) answered.push(item.seq);
17501
- }
18396
+ const answered = answeredSeqs(items, writer);
17502
18397
  const sender = this.senderOf(writer);
17503
18398
  for (const seq of answered) sender?.acknowledged(seq);
17504
18399
  this.answered(answered);
17505
18400
  this.settleAcknowledged(reply.acknowledged);
17506
18401
  this.watchGap(reply.cursor, items);
18402
+ return reply.underivable;
17507
18403
  }
17508
18404
  /** This client's writer's entries the room acknowledged: confirmed, and their waiters resolve. */
17509
18405
  settleAcknowledged(acknowledged) {
@@ -17514,11 +18410,20 @@ var RecordLogDocumentSession = class {
17514
18410
  if (touched.length) this.host.notify(touched);
17515
18411
  }
17516
18412
  async refused(refusal) {
18413
+ if (this.history.stale) return this.staleAnswered([refusal.seq]);
17517
18414
  if (!this.current) return;
18415
+ if (this.ahead && this.holding()) {
18416
+ this.held.push({ kind: "refused", refusal });
18417
+ return;
18418
+ }
17518
18419
  if (this.phase === "opening" || this.phase === "idle") {
17519
18420
  Logger.debug(`[record-log] ${this.docId}: dropped a refusal of ${refusal.seq} that arrived before record.opened`);
17520
18421
  return;
17521
18422
  }
18423
+ await this.applyRefusal(refusal);
18424
+ }
18425
+ async applyRefusal(refusal) {
18426
+ if (!this.current) return;
17522
18427
  const writer = this.current.writer;
17523
18428
  const reply = await this.store.refused(refusal, this.host.projectionSpecs(), writer);
17524
18429
  const sender = this.senderOf(writer);
@@ -17581,6 +18486,7 @@ var RecordLogDocumentSession = class {
17581
18486
  return refusal.scope === "record" ? "DOCUMENT_CONSTRAINT_VIOLATED" : "DOCUMENT_OFFLINE_WINDOW_EXPIRED";
17582
18487
  }
17583
18488
  async gap(expected) {
18489
+ if (this.history.stale) return this.barrier ? void 0 : this.endStale();
17584
18490
  if (!this.current || !Number.isInteger(expected)) return;
17585
18491
  Logger.info(`[record-log] ${this.docId}: the room is missing entries from ${expected}; resending`);
17586
18492
  const pending = await this.store.pendingOf(this.current.writer);
@@ -17601,16 +18507,27 @@ var RecordLogDocumentSession = class {
17601
18507
  * naming the attempt it was for: arriving after the replacement's
17602
18508
  * `record.opened`, it would be read as that catch-up's, and a full one would
17603
18509
  * then drop every row the replacement had not yet sent. The open goes again
17604
- * once that answer is in (a page is discarded, an error starts over).
18510
+ * once that answer is in (a page is discarded, an error starts over). A
18511
+ * streamed catch-up has no request out once the room is known to stream
18512
+ * (its `record.opened` said so, or a marked page arrived): it dropped the
18513
+ * stream with the subscription, and the open goes at once (a page of that
18514
+ * stream arriving later is ignored by its id).
17605
18515
  */
17606
18516
  async released(frame) {
18517
+ if (this.history.stale) return this.phase === "opening" ? this.endStale() : void 0;
17607
18518
  if (!this.current || this.phase === "idle" || this.phase === "closed") return;
17608
18519
  Logger.warn(
17609
18520
  `[record-log] ${this.docId}: the room released this connection's subscription (${frame.reason ?? "no reason given"}); opening again from the cursor`
17610
18521
  );
17611
18522
  this.clearGap();
17612
18523
  if ((this.phase === "catchingUp" || this.phase === "loading") && this.paging) {
17613
- this.paging.released = true;
18524
+ if (this.paging.stream === void 0 || !(this.paging.streamed || this.roomStreams)) {
18525
+ this.paging.released = true;
18526
+ return;
18527
+ }
18528
+ this.paging = null;
18529
+ this.receipt = null;
18530
+ await this.sendOpen();
17614
18531
  return;
17615
18532
  }
17616
18533
  if (this.receipt && !this.paging) {
@@ -17624,6 +18541,14 @@ var RecordLogDocumentSession = class {
17624
18541
  const code = String(frame.code ?? "");
17625
18542
  const current = this.current;
17626
18543
  Logger.warn(`[record-log] ${this.docId}: ${frame.messageType ?? "record frame"} answered ${code}: ${frame.message ?? ""}`);
18544
+ if (this.history.stale && this.barrier) {
18545
+ if (frame.messageType === "record.open" && this.phase === "opening") await this.endStale();
18546
+ return;
18547
+ }
18548
+ if (this.history.stale && (frame.messageType === "record.entries" || frame.messageType === "record.declare")) {
18549
+ if (frame.messageType === "record.entries") await this.endStale();
18550
+ return;
18551
+ }
17627
18552
  if (!current) return;
17628
18553
  if (frame.messageType === "record.catchUp" && this.paging?.receipt) {
17629
18554
  return this.receiptFailed(this.paging.receipt, `the remainder was answered ${code || "an error"}`);
@@ -17657,6 +18582,8 @@ var RecordLogDocumentSession = class {
17657
18582
  this.takenRetryMs = Math.min(this.takenRetryMs * 2, 3e4);
17658
18583
  this.phase = "idle";
17659
18584
  this.current = null;
18585
+ this.held = [];
18586
+ this.ahead = null;
17660
18587
  this.retryTimer = setTimeout(() => {
17661
18588
  this.retryTimer = null;
17662
18589
  void this.start();
@@ -17666,6 +18593,8 @@ var RecordLogDocumentSession = class {
17666
18593
  case "DOCUMENT_NOT_OPEN": {
17667
18594
  if (this.phase === "open" || this.phase === "draining") {
17668
18595
  await this.sendOpen();
18596
+ } else if (this.ahead && (frame.messageType === "record.entries" || frame.messageType === "record.declare")) {
18597
+ this.ahead.refused = true;
17669
18598
  }
17670
18599
  return;
17671
18600
  }
@@ -17697,9 +18626,12 @@ var RecordLogDocumentSession = class {
17697
18626
  return;
17698
18627
  }
17699
18628
  default:
18629
+ if (this.ahead && (frame.messageType === "record.entries" || frame.messageType === "record.declare")) return;
17700
18630
  if (this.phase === "opening") {
17701
18631
  this.phase = "idle";
17702
18632
  this.current = null;
18633
+ this.held = [];
18634
+ this.ahead = null;
17703
18635
  this.host.syncFailed(this.docId, code || "error");
17704
18636
  }
17705
18637
  }
@@ -17727,6 +18659,8 @@ var RecordLogSessions = class {
17727
18659
  this.senderOptions = senderOptions;
17728
18660
  }
17729
18661
  sessions = /* @__PURE__ */ new Map();
18662
+ /** Each document's {@link RecordLogWriterHistory}, kept while the client keeps its connection id. */
18663
+ histories = /* @__PURE__ */ new Map();
17730
18664
  connection = null;
17731
18665
  syncedListeners = /* @__PURE__ */ new Set();
17732
18666
  failedListeners = /* @__PURE__ */ new Set();
@@ -17757,6 +18691,8 @@ var RecordLogSessions = class {
17757
18691
  /** Begin a session for an opened store. */
17758
18692
  attach(docId, store) {
17759
18693
  this.sessions.get(docId)?.close();
18694
+ let history = this.histories.get(docId);
18695
+ if (!history) this.histories.set(docId, history = { opened: /* @__PURE__ */ new Set(), stale: null });
17760
18696
  const session = new RecordLogDocumentSession(
17761
18697
  docId,
17762
18698
  store,
@@ -17776,7 +18712,8 @@ var RecordLogSessions = class {
17776
18712
  for (const listener of [...this.progressListeners]) listener(id);
17777
18713
  }
17778
18714
  },
17779
- this.senderOptions
18715
+ this.senderOptions,
18716
+ history
17780
18717
  );
17781
18718
  this.sessions.set(docId, session);
17782
18719
  return session;