@loro-dev/roost 0.3.1 → 0.3.2

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/README.md CHANGED
@@ -12,13 +12,14 @@ The `Inbox` module adds atomic raw receipt/cursor storage, without authenticatin
12
12
  or applying those bytes.
13
13
 
14
14
  ```sh
15
- npm install @loro-dev/roost@0.3.1
15
+ npm install @loro-dev/roost@0.3.2
16
16
  ```
17
17
 
18
- This source targets the coordinated Rust/TypeScript/Native 0.3.1 release;
19
- the registry determines npm availability. Native SQLite storage in
20
- this release accepts fresh/v10 containers only. Preserve older databases with
21
- their compatible runtime; there is no automatic migration or deletion.
18
+ The TypeScript SDK uses Streams client 0.16.0 for framed RR backward pages.
19
+ `StreamsTransport.readBackward` returns frames in stream order with opaque
20
+ start cursors and continuation flags. `HistoryReader` reassembles complete
21
+ messages within the requested byte budget and resumes existing prefix scans at
22
+ their persisted cursors. Registry availability follows the npm release.
22
23
 
23
24
  For source development and browser tests:
24
25
 
@@ -285,10 +286,11 @@ intake commits, and initialize `Link.catchUpAt` from the original window tail,
285
286
  never a later `head()` result. The Node window API is unchanged.
286
287
 
287
288
  `pnpm pack:consumer -- /absolute/output/directory` builds the npm tarball and
288
- checks its public entries. It depends on the exact registry release
289
- `@loro-dev/streams-client@0.8.0`, with no bundled SDK. `pnpm check:consumer`
290
- installs that tarball into a fresh project with a fresh npm cache and checks
291
- the root, `./sync`, and `./lody-history` exports.
289
+ checks its public entries. The package pins `@loro-dev/streams-client` to an
290
+ exact registry version in `package.json`. `pnpm check:consumer` installs the
291
+ tarball in a fresh project with a fresh npm cache, verifies the installed
292
+ Streams version against that pin, and checks the root, `./sync`, and
293
+ `./lody-history` exports.
292
294
 
293
295
  IndexedDB container version is now 2. Opening a valid version-1 database upgrades
294
296
  only its version, retaining all records; incompatible layouts abort the upgrade.
@@ -360,7 +362,9 @@ Already published incomplete Turns expose their applied prefix. Unsealed content
360
362
  remains provisional; the projected `sealed` flag is not a verification level.
361
363
 
362
364
  Node active-branch pages privately reuse sealed bodies after matching authoritative
363
- headers, including sequence, seal and parent edges. The per-history cache keeps at
365
+ headers, including sequence, seal and parent edges. Initial Native page hydration
366
+ also reuses the same Turn's already-read header for immutable parents, avoiding a
367
+ second full Create export. The per-history cache keeps at
364
368
  most 64 bodies and 8 MiB of source JSON UTF-16 bytes (an input budget, not exact
365
369
  heap usage). Oversized and unsealed bodies are not retained. Returned bodies are
366
370
  independent copies. Page membership, cursors, availability and event fences are
@@ -959,7 +959,7 @@ async function readBranchPageTurn(host, turnId, knownHeader, retained) {
959
959
  }
960
960
  return structuredClone(cached);
961
961
  }
962
- const turn = await readBranchTurn(host, turnId);
962
+ const turn = await readBranchTurn(host, turnId, header);
963
963
  if (!turn || !sameBranchHeader(turn, header) || turn.sourceBytes === undefined || turn.sourceBytes > SEALED_PAGE_BYTES)
964
964
  return turn;
965
965
  cache = sealedPageBodies.get(host);
@@ -1032,7 +1032,7 @@ async function branchLogicalCountAt(host, viewId, turnId) {
1032
1032
  throw new StoreError('stale', 'branch base is not in the active history');
1033
1033
  return BigInt(position + 1);
1034
1034
  }
1035
- async function readBranchTurn(host, turnId) {
1035
+ async function readBranchTurn(host, turnId, knownHeader) {
1036
1036
  if (host instanceof LodyHistory) {
1037
1037
  const result = await host.stream.readTurn(turnId);
1038
1038
  if (result.kind !== 'found')
@@ -1050,13 +1050,17 @@ async function readBranchTurn(host, turnId) {
1050
1050
  const result = await host.stream.readTurn(turnId);
1051
1051
  if (result.kind !== 'found')
1052
1052
  return;
1053
- const [create] = decodeBatch(await host.stream.exportUpdates(turnId, 0n, 1n));
1054
- if (!create || create.operation.kind !== 'create')
1055
- throw new StoreError('corrupt', 'branch head has no Create');
1053
+ let parents = knownHeader?.parents;
1054
+ if (!parents) {
1055
+ const [create] = decodeBatch(await host.stream.exportUpdates(turnId, 0n, 1n));
1056
+ if (!create || create.operation.kind !== 'create')
1057
+ throw new StoreError('corrupt', 'branch head has no Create');
1058
+ parents = create.operation.parents;
1059
+ }
1056
1060
  const body = decodeJson(encodeUtf8(result.turn.contentJson));
1057
1061
  return {
1058
1062
  turnId: result.turn.turnId.slice(),
1059
- parents: create.operation.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })),
1063
+ parents: parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })),
1060
1064
  identity: identityOf(body),
1061
1065
  content: body instanceof Map ? body.get('content') : undefined,
1062
1066
  nextSeq: result.turn.nextSeq,
@@ -17,23 +17,11 @@ import type { WorkScope } from './work.js';
17
17
  *
18
18
  * `BackwardByteSource` is an injectable, pure-byte primitive: return the
19
19
  * ≤`limitBytes` immediately before an opaque offset (or before the tail).
20
- * **No response ever exceeds `limitBytes`** — a message larger than the
21
- * page budget is simply paged over (more requests, each bounded), never a
22
- * budget exception. The interface carries no message-boundary information
23
- * (the byte-level Durable-Streams protocol exposes none for
24
- * `application/octet-stream`, and the backend audit (N008) confirms
25
- * offsets are cumulative byte positions, not message ordinals); batch
26
- * boundaries come from the provider itself (N011): every page carries a
27
- * verifiable span list — one span per intersected message, tiling the
28
- * payload exactly, each giving the message's total length and this
29
- * fragment's offset within it. A magic/marker scan over the bytes is NOT
30
- * a boundary proof (payloads may legitimately contain batch-looking
31
- * bytes, and signature verification proves content authenticity, not
32
- * server-side boundaries); that approach was abandoned and is kept only
33
- * as a failure-study record in the goal log (N011). The client
34
- * reassembles a message from its fragments (contiguity by
35
- * msgOffset/messageLen arithmetic) and only hands COMPLETE messages to
36
- * the codec — a fragment is transport state, never framed on spec.
20
+ * Each response stays within the byte limit and provides frame boundaries
21
+ * and continuation flags. Offsets are opaque to the history reader.
22
+ * A walk chains page cursors and only admits a message after all of its
23
+ * contiguous frames have arrived. The Streams message limit bounds wire
24
+ * reassembly, while Inbox limits apply to the decoded batch.
37
25
  *
38
26
  * # Intake model: collect during the walk, receive forward at its end
39
27
  *
@@ -71,41 +59,19 @@ export declare class HistoryError extends Error {
71
59
  readonly code: 'invalid' | 'transport' | 'inbox' | 'replay' | 'retryQuota' | 'coverage' | 'store' | 'link' | 'policyDenied' | 'policy';
72
60
  constructor(code: 'invalid' | 'transport' | 'inbox' | 'replay' | 'retryQuota' | 'coverage' | 'store' | 'link' | 'policyDenied' | 'policy', message?: string, options?: ErrorOptions);
73
61
  }
74
- /** One message's span within a `BackwardPage` (N011 provider contract):
75
- * the verifiable boundary of one intersected message. */
76
- export type MessageSpan = {
77
- /** Fragment range within the page payload (`payload.subarray(relStart,
78
- * relEnd)` are this message's bytes). Spans tile the payload ascending
79
- * without gaps or overlaps — the client verifies this. */
80
- relStart: number;
81
- /** See `relStart`. */
82
- relEnd: number;
83
- /** The message's opaque absolute start offset (fragments of one
84
- * message share it across pages; never parsed). */
85
- messageStart: string;
86
- /** Total byte length of the COMPLETE message. */
87
- messageLen: number;
88
- /** This fragment's byte offset WITHIN the message (`msgOffset +
89
- * (relEnd - relStart) <= messageLen`): reassembly contiguity is plain
90
- * arithmetic on these two integers. */
91
- msgOffset: number;
62
+ /** A message or fragment, with its provider-issued start and continuation flags. */
63
+ export type BackwardFrame = {
64
+ data: Uint8Array;
65
+ startOffset: string;
66
+ continuesBefore: boolean;
67
+ continuesAfter: boolean;
92
68
  };
93
- /** One bounded backward page from `BackwardByteSource.readBackward`. */
69
+ /** One bounded page in stream order. Continuations can only occur at its edges. */
94
70
  export type BackwardPage = {
95
- /** The raw log bytes immediately before `from` (or before the tail):
96
- * ≤ the requested `limitBytes`, always — a message larger than the
97
- * limit is fragmented across pages, never a budget exception. */
98
- payload: Uint8Array;
99
- /** The opaque offset at which `payload` ends (exclusive). */
71
+ frames: readonly BackwardFrame[];
100
72
  endOffset: string;
101
- /** The opaque offset at which `payload` starts: the `from` for the
102
- * next (older) page. */
103
73
  prevOffset: string;
104
- /** True when no bytes exist before `prevOffset` (the log's start). */
105
74
  reachedStart: boolean;
106
- /** One span per message intersecting the payload, oldest first;
107
- * verified to tile the payload (see `MessageSpan`). */
108
- messages: MessageSpan[];
109
75
  };
110
76
  /** The injectable backward byte source (N2's only backend-coupled seam).
111
77
  * Implementations perform no retries of their own and never run inside a
@@ -161,6 +127,7 @@ export declare class HistoryReader {
161
127
  readonly replay: DurableReplay;
162
128
  readonly coverage: CoverageStore;
163
129
  readonly policy: PolicyStore;
130
+ /** Maximum plaintext batch size accepted by Inbox. */
164
131
  readonly maxBatchBytes: number;
165
132
  /** The intake is the partial-replica path (N3). Coverage marks use
166
133
  * the exact local frames and bind a declared parent only where that
@@ -172,10 +139,8 @@ export declare class HistoryReader {
172
139
  readonly storage: IndexedDbStorage;
173
140
  private constructor();
174
141
  /** Open the reader for one (stream, remote-generation) scope (the scope
175
- * comes from `Executor.scope`). Reuses the link's wire-derived ledger
176
- * limits; `limits.inbox.maxBatchBytes` also bounds the
177
- * boundary-discovery buffer (a missing chain past it is typed
178
- * corruption). */
142
+ * comes from `Executor.scope`). Reuses the link's Inbox and replay limits
143
+ * for batches received after any configured decryption. */
179
144
  static open(storage: IndexedDbStorage, stream: Stream, scope: WorkScope, limits: LinkLimits): HistoryReader;
180
145
  /** The partial-replica intake (N3): receipts import through the
181
146
  * partial path — parents are declared references and seals verify
@@ -1,3 +1,4 @@
1
+ import { DEFAULT_BACKWARD_MAX_MESSAGE_BYTES } from '@loro-dev/streams-client';
1
2
  import { blake3 } from '@noble/hashes/blake3.js';
2
3
  import { decodeBatch } from '../codec.js';
3
4
  import { Inbox, InboxError } from '../inbox.js';
@@ -19,23 +20,11 @@ import { generationKeyFragment } from './registry.js';
19
20
  *
20
21
  * `BackwardByteSource` is an injectable, pure-byte primitive: return the
21
22
  * ≤`limitBytes` immediately before an opaque offset (or before the tail).
22
- * **No response ever exceeds `limitBytes`** — a message larger than the
23
- * page budget is simply paged over (more requests, each bounded), never a
24
- * budget exception. The interface carries no message-boundary information
25
- * (the byte-level Durable-Streams protocol exposes none for
26
- * `application/octet-stream`, and the backend audit (N008) confirms
27
- * offsets are cumulative byte positions, not message ordinals); batch
28
- * boundaries come from the provider itself (N011): every page carries a
29
- * verifiable span list — one span per intersected message, tiling the
30
- * payload exactly, each giving the message's total length and this
31
- * fragment's offset within it. A magic/marker scan over the bytes is NOT
32
- * a boundary proof (payloads may legitimately contain batch-looking
33
- * bytes, and signature verification proves content authenticity, not
34
- * server-side boundaries); that approach was abandoned and is kept only
35
- * as a failure-study record in the goal log (N011). The client
36
- * reassembles a message from its fragments (contiguity by
37
- * msgOffset/messageLen arithmetic) and only hands COMPLETE messages to
38
- * the codec — a fragment is transport state, never framed on spec.
23
+ * Each response stays within the byte limit and provides frame boundaries
24
+ * and continuation flags. Offsets are opaque to the history reader.
25
+ * A walk chains page cursors and only admits a message after all of its
26
+ * contiguous frames have arrived. The Streams message limit bounds wire
27
+ * reassembly, while Inbox limits apply to the decoded batch.
39
28
  *
40
29
  * # Intake model: collect during the walk, receive forward at its end
41
30
  *
@@ -98,7 +87,57 @@ const rethrow = (e) => {
98
87
  throw e;
99
88
  };
100
89
  const HISTORY_SPACE = 'rsync_history';
101
- const PREFIX_RECORD_VERSION = 1;
90
+ const PREFIX_RECORD_VERSION = 2;
91
+ function messageBytes(message) {
92
+ if (message.fragments.length === 1)
93
+ return message.fragments[0];
94
+ const bytes = new Uint8Array(message.byteLength);
95
+ let offset = 0;
96
+ for (let i = message.fragments.length - 1; i >= 0; i--) {
97
+ const fragment = message.fragments[i];
98
+ bytes.set(fragment, offset);
99
+ offset += fragment.length;
100
+ }
101
+ return bytes;
102
+ }
103
+ async function collectBackwardPage(page, from, limit, partial, onMessage) {
104
+ if (from !== undefined && page.endOffset !== from)
105
+ throw invalid('provider page does not chain to the requested offset');
106
+ if ((page.frames.length === 0) !== (page.prevOffset === page.endOffset)
107
+ || (page.frames.length === 0 && !page.reachedStart))
108
+ throw invalid('backward page made no progress');
109
+ if (page.frames.length !== 0 && page.frames[0].startOffset !== page.prevOffset)
110
+ throw invalid('provider frames do not start at the previous offset');
111
+ let bytesFetched = 0;
112
+ for (const [index, frame] of page.frames.entries()) {
113
+ if (frame.data.length === 0 || (frame.continuesBefore && index !== 0)
114
+ || (frame.continuesAfter && index !== page.frames.length - 1))
115
+ throw invalid('invalid backward frame boundary');
116
+ bytesFetched += frame.data.length;
117
+ if (bytesFetched > limit)
118
+ throw invalid(`provider exceeded the page hard cap: ${bytesFetched} > ${limit}`);
119
+ }
120
+ for (let index = page.frames.length - 1; index >= 0; index--) {
121
+ const frame = page.frames[index];
122
+ if (frame.continuesAfter !== (partial !== undefined))
123
+ throw invalid('provider message fragments are not contiguous');
124
+ const message = partial ?? { fragments: [], byteLength: 0 };
125
+ if (frame.data.length > DEFAULT_BACKWARD_MAX_MESSAGE_BYTES - message.byteLength)
126
+ throw invalid('backward message exceeds the Streams message byte limit');
127
+ message.fragments.push(Uint8Array.from(frame.data));
128
+ message.byteLength += frame.data.length;
129
+ if (frame.continuesBefore) {
130
+ partial = message;
131
+ }
132
+ else {
133
+ await onMessage(frame.startOffset, messageBytes(message));
134
+ partial = undefined;
135
+ }
136
+ }
137
+ if (page.reachedStart && partial !== undefined)
138
+ throw invalid('the log starts mid-message: provider boundaries contradict the bytes');
139
+ return { bytesFetched, partial };
140
+ }
102
141
  const PREFIX_KEY_TAG = 0x01;
103
142
  const utf8 = new TextEncoder();
104
143
  const utf8d = new TextDecoder('utf-8', { fatal: true });
@@ -155,7 +194,9 @@ export class HistoryReader {
155
194
  partial;
156
195
  storage;
157
196
  #crypto;
158
- constructor(scope, stream, inbox, replay, coverage, policy, maxBatchBytes,
197
+ constructor(scope, stream, inbox, replay, coverage, policy,
198
+ /** Maximum plaintext batch size accepted by Inbox. */
199
+ maxBatchBytes,
159
200
  /** The intake is the partial-replica path (N3). Coverage marks use
160
201
  * the exact local frames and bind a declared parent only where that
161
202
  * parent's seal frame is local (N017 P1-C). A window turn whose
@@ -174,10 +215,8 @@ export class HistoryReader {
174
215
  this.storage = storage;
175
216
  }
176
217
  /** Open the reader for one (stream, remote-generation) scope (the scope
177
- * comes from `Executor.scope`). Reuses the link's wire-derived ledger
178
- * limits; `limits.inbox.maxBatchBytes` also bounds the
179
- * boundary-discovery buffer (a missing chain past it is typed
180
- * corruption). */
218
+ * comes from `Executor.scope`). Reuses the link's Inbox and replay limits
219
+ * for batches received after any configured decryption. */
181
220
  static open(storage, stream, scope, limits) {
182
221
  let fragment;
183
222
  try {
@@ -282,14 +321,8 @@ export class HistoryReader {
282
321
  // A crash between a committed receipt and its replay left durable
283
322
  // work behind: drain before any new fetch (idle when caught up).
284
323
  await this.#replayDrain(report, appliedSeen, pendingSeen);
285
- // Phase 1: the walk. Collect COMPLETE messages (newest pages
286
- // first, oldest prepended), reassembling fragments across pages
287
- // from the provider's verified spans; a fragment is transport
288
- // state, never received.
289
- let collected = [];
290
- // The in-flight partial message: id, total length, the assembled
291
- // bytes so far, and the message offset the NEXT (older) fragment
292
- // must end at.
324
+ // Collect complete messages newest-first; import them in log order after the walk.
325
+ const collected = [];
293
326
  let partial;
294
327
  let from = options.before;
295
328
  let tail;
@@ -329,82 +362,19 @@ export class HistoryReader {
329
362
  ? Math.min(pageLimitBytes, pageLimitBytes - extraFetched)
330
363
  : Math.min(pageLimitBytes, budgetBytes - report.bytesFetched);
331
364
  const page = await source.readBackward(from, limit);
332
- if (page.payload.length > limit)
333
- throw invalid(`provider exceeded the page hard cap: ${page.payload.length} > ${limit}`);
334
- if (from !== undefined && page.endOffset !== from)
335
- throw invalid('provider page does not chain to the requested offset');
336
- // Verify the span list tiles the payload exactly, oldest first.
337
- let cursor = 0;
338
- for (const span of page.messages) {
339
- if (!Number.isSafeInteger(span.relStart) || !Number.isSafeInteger(span.relEnd)
340
- || !Number.isSafeInteger(span.messageLen) || !Number.isSafeInteger(span.msgOffset)
341
- || span.relStart < 0 || span.relEnd < span.relStart || span.messageLen < 0 || span.msgOffset < 0)
342
- throw invalid('provider message span is not a safe non-negative integer');
343
- if (span.relStart !== cursor || span.relEnd > page.payload.length)
344
- throw invalid('provider message spans do not tile the page payload');
345
- cursor = span.relEnd;
346
- const fragLen = span.relEnd - span.relStart;
347
- if (fragLen === 0 || fragLen > span.messageLen)
348
- throw invalid('provider message span exceeds its message length');
349
- if (span.msgOffset > span.messageLen || fragLen > span.messageLen - span.msgOffset)
350
- throw invalid('provider message fragment overruns the message');
351
- }
352
- if (cursor !== page.payload.length)
353
- throw invalid('provider message spans do not cover the page payload');
365
+ const collectedPage = await collectBackwardPage(page, from, limit, partial, (start, bytes) => keepAssembled(this.#crypto, windowTurns, collected, (offset) => {
366
+ oldestBoundary = offset;
367
+ }, start, bytes));
368
+ partial = collectedPage.partial;
354
369
  report.pages++;
355
- report.bytesFetched += page.payload.length;
370
+ report.bytesFetched += collectedPage.bytesFetched;
356
371
  if (overBudget)
357
- extraFetched += page.payload.length;
372
+ extraFetched += collectedPage.bytesFetched;
358
373
  tail ??= page.endOffset;
359
- // Consume spans newest-first: complete-in-page messages
360
- // collect directly, fragments extend the in-flight partial.
361
- for (let spanIndex = page.messages.length - 1; spanIndex >= 0; spanIndex--) {
362
- const span = page.messages[spanIndex];
363
- const frag = page.payload.subarray(span.relStart, span.relEnd);
364
- const fragLen = frag.length;
365
- if (span.msgOffset === 0 && fragLen === span.messageLen) {
366
- // A complete message in one page. An unrelated NEWER
367
- // message's partial may legitimately be open (its
368
- // older fragments arrive in older pages).
369
- await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, span.messageStart, Uint8Array.from(frag));
370
- continue;
371
- }
372
- if (partial === undefined) {
373
- // The message's END fragment must be its last bytes
374
- // (fragLen <= messageLen is already enforced, so the
375
- // subtraction cannot go negative).
376
- if (span.msgOffset !== span.messageLen - fragLen)
377
- throw invalid('provider fragment is not contiguous with the message end');
378
- partial = { id: span.messageStart, len: span.messageLen, bytes: Uint8Array.from(frag), nextOffset: span.msgOffset };
379
- }
380
- else {
381
- if (partial.id !== span.messageStart || partial.len !== span.messageLen
382
- || fragLen > partial.nextOffset
383
- || span.msgOffset !== partial.nextOffset - fragLen)
384
- throw invalid('provider message fragments are not contiguous');
385
- // Fragments arrive newest-first: PREPEND this (older)
386
- // fragment so the bytes stay in log order.
387
- const assembled = new Uint8Array(partial.bytes.length + frag.length);
388
- assembled.set(frag, 0);
389
- assembled.set(partial.bytes, frag.length);
390
- partial.bytes = assembled;
391
- partial.nextOffset = span.msgOffset;
392
- if (partial.nextOffset === 0) {
393
- if (partial.bytes.length !== partial.len)
394
- throw invalid('reassembled message length mismatch');
395
- await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, partial.id, partial.bytes);
396
- partial = undefined;
397
- }
398
- }
399
- }
400
374
  if (page.reachedStart) {
401
- if (partial !== undefined)
402
- throw invalid('the log starts mid-message: provider boundaries contradict the bytes');
403
375
  report.reachedStart = true;
404
376
  break;
405
377
  }
406
- if (page.prevOffset === page.endOffset && page.payload.length === 0)
407
- throw invalid('backward page made no progress');
408
378
  from = page.prevOffset;
409
379
  }
410
380
  // A partial left at the walk's edge is transport state: not
@@ -499,69 +469,17 @@ export class HistoryReader {
499
469
  }
500
470
  const limit = Math.min(pageLimitBytes, budgetBytes - report.bytesFetched);
501
471
  const page = await source.readBackward(from, limit);
502
- if (page.payload.length > limit)
503
- throw invalid(`provider exceeded the page hard cap: ${page.payload.length} > ${limit}`);
504
- if (from !== undefined && page.endOffset !== from)
505
- throw invalid('provider page does not chain to the requested offset');
506
- let cursor = 0;
507
- for (const span of page.messages) {
508
- if (!Number.isSafeInteger(span.relStart) || !Number.isSafeInteger(span.relEnd)
509
- || !Number.isSafeInteger(span.messageLen) || !Number.isSafeInteger(span.msgOffset)
510
- || span.relStart < 0 || span.relEnd < span.relStart || span.messageLen < 0 || span.msgOffset < 0)
511
- throw invalid('provider message span is not a safe non-negative integer');
512
- if (span.relStart !== cursor || span.relEnd > page.payload.length)
513
- throw invalid('provider message spans do not tile the page payload');
514
- cursor = span.relEnd;
515
- const fragLen = span.relEnd - span.relStart;
516
- if (fragLen === 0 || fragLen > span.messageLen)
517
- throw invalid('provider message span exceeds its message length');
518
- if (span.msgOffset > span.messageLen || fragLen > span.messageLen - span.msgOffset)
519
- throw invalid('provider message fragment overruns the message');
520
- }
521
- if (cursor !== page.payload.length)
522
- throw invalid('provider message spans do not cover the page payload');
472
+ const collectedPage = await collectBackwardPage(page, from, limit, partial, (start, bytes) => keepAssembled(this.#crypto, windowTurns, collected, (offset) => {
473
+ oldestBoundary = offset;
474
+ }, start, bytes));
475
+ partial = collectedPage.partial;
523
476
  report.pages++;
524
- report.bytesFetched += page.payload.length;
477
+ report.bytesFetched += collectedPage.bytesFetched;
525
478
  tail ??= page.endOffset;
526
- for (let spanIndex = page.messages.length - 1; spanIndex >= 0; spanIndex--) {
527
- const span = page.messages[spanIndex];
528
- const frag = page.payload.subarray(span.relStart, span.relEnd);
529
- const fragLen = frag.length;
530
- if (span.msgOffset === 0 && fragLen === span.messageLen) {
531
- await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, span.messageStart, Uint8Array.from(frag));
532
- continue;
533
- }
534
- if (partial === undefined) {
535
- if (span.msgOffset !== span.messageLen - fragLen)
536
- throw invalid('provider fragment is not contiguous with the message end');
537
- partial = { id: span.messageStart, len: span.messageLen, bytes: Uint8Array.from(frag), nextOffset: span.msgOffset };
538
- }
539
- else {
540
- if (partial.id !== span.messageStart || partial.len !== span.messageLen
541
- || fragLen > partial.nextOffset
542
- || span.msgOffset !== partial.nextOffset - fragLen)
543
- throw invalid('provider message fragments are not contiguous');
544
- const assembled = new Uint8Array(partial.bytes.length + frag.length);
545
- assembled.set(frag, 0);
546
- assembled.set(partial.bytes, frag.length);
547
- partial.bytes = assembled;
548
- partial.nextOffset = span.msgOffset;
549
- if (partial.nextOffset === 0) {
550
- if (partial.bytes.length !== partial.len)
551
- throw invalid('reassembled message length mismatch');
552
- await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, partial.id, partial.bytes);
553
- partial = undefined;
554
- }
555
- }
556
- }
557
479
  if (page.reachedStart) {
558
- if (partial !== undefined)
559
- throw invalid('the log starts mid-message: provider boundaries contradict the bytes');
560
480
  report.reachedStart = true;
561
481
  break;
562
482
  }
563
- if (page.prevOffset === page.endOffset && page.payload.length === 0)
564
- throw invalid('backward page made no progress');
565
483
  from = page.prevOffset;
566
484
  }
567
485
  if (tail !== undefined)
@@ -671,10 +589,11 @@ export class HistoryReader {
671
589
  return undefined;
672
590
  if (raw.length === 0)
673
591
  throw invalid('empty prefix-scan record');
674
- if (raw[0] !== PREFIX_RECORD_VERSION)
675
- throw invalid(`unsupported prefix-scan version ${raw[0]}`);
592
+ const version = raw[0];
593
+ if (version !== 1 && version !== PREFIX_RECORD_VERSION)
594
+ throw invalid(`unsupported prefix-scan version ${version}`);
676
595
  const dto = JSON.parse(utf8d.decode(raw.subarray(1)));
677
- if (dto.v !== PREFIX_RECORD_VERSION)
596
+ if (dto.v !== version)
678
597
  throw invalid(`unsupported prefix-scan version ${dto.v}`);
679
598
  if (typeof dto.from !== 'string' || !Array.isArray(dto.wanted))
680
599
  throw invalid('prefix-scan JSON');
@@ -683,22 +602,27 @@ export class HistoryReader {
683
602
  throw invalid('prefix-scan turn id');
684
603
  return parseUuid(id);
685
604
  });
686
- const partial = dto.partial === undefined ? undefined : {
687
- id: dto.partial.id,
688
- len: dto.partial.len,
689
- bytes: unhex(dto.partial.bytes),
690
- nextOffset: dto.partial.next_offset,
691
- };
605
+ let partial;
606
+ if (dto.partial !== undefined) {
607
+ const fragment = dto.partial?.bytes;
608
+ if (typeof fragment !== 'string')
609
+ throw invalid('prefix-scan fragment');
610
+ // Both record formats store the contiguous wire suffix as hex.
611
+ if (fragment.length === 0 || fragment.length > DEFAULT_BACKWARD_MAX_MESSAGE_BYTES * 2)
612
+ throw invalid('prefix-scan fragment length');
613
+ const bytes = unhex(fragment);
614
+ partial = { fragments: [bytes], byteLength: bytes.length };
615
+ }
692
616
  return { from: dto.from, wanted, partial };
693
617
  }
694
618
  async #storePrefixScan(scan) {
695
619
  const key = this.#prefixKey();
696
- const wantedJson = scan.wanted.map(id => JSON.stringify(uuidString(id))).join(',');
697
- let json = `{"v":1,"from":${JSON.stringify(scan.from)},"wanted":[${wantedJson}]`;
698
- if (scan.partial !== undefined)
699
- json += `,"partial":{"id":${JSON.stringify(scan.partial.id)},"len":${scan.partial.len},"bytes":${JSON.stringify(hex(scan.partial.bytes))},"next_offset":${scan.partial.nextOffset}}`;
700
- json += '}';
701
- const payload = utf8.encode(json);
620
+ const payload = utf8.encode(JSON.stringify({
621
+ v: PREFIX_RECORD_VERSION,
622
+ from: scan.from,
623
+ wanted: scan.wanted.map(uuidString),
624
+ partial: scan.partial === undefined ? undefined : { bytes: hex(messageBytes(scan.partial)) },
625
+ }));
702
626
  const bytes = new Uint8Array(1 + payload.length);
703
627
  bytes[0] = PREFIX_RECORD_VERSION;
704
628
  bytes.set(payload, 1);
@@ -8,7 +8,7 @@ export type { HeadInfo, ReadPage, ReadTransport } from './transport.js';
8
8
  export { Link, LinkError, linkLimitsForSync } from './link.js';
9
9
  export type { BridgeReport, DownloadReport, LinkLimits, StopToken } from './link.js';
10
10
  export { HistoryReader, HistoryError } from './history.js';
11
- export type { BackwardByteSource, BackwardPage, HistoryReport, PrefixScan } from './history.js';
11
+ export type { BackwardByteSource, BackwardFrame, BackwardPage, HistoryReport, PrefixScan } from './history.js';
12
12
  export { PolicyStore, PolicyError, DEFAULT_MIRROR_POLICY } from './policy.js';
13
13
  export type { MirrorDirection, MirrorPolicy } from './policy.js';
14
14
  export { CryptoError } from './crypto.js';
@@ -20,5 +20,5 @@ export type { MirrorDirection, MirrorPolicy } from './policy.js';
20
20
  export { Link, LinkError, linkLimitsForSync } from './link.js';
21
21
  export type { BridgeReport, DownloadReport, LinkLimits, StopToken } from './link.js';
22
22
  export { HistoryError, HistoryReader } from './history.js';
23
- export type { BackwardByteSource, BackwardPage, HistoryReport, PrefixScan } from './history.js';
23
+ export type { BackwardByteSource, BackwardFrame, BackwardPage, HistoryReport, PrefixScan } from './history.js';
24
24
  export { sealEnvelopeAsync, openEnvelopeAsync, openFirstEnvelopeAsync, openConcatenatedAsync, openConcatenatedPrefixAsync } from './crypto.js';
@@ -74,10 +74,7 @@ export declare class StreamsTransport implements SendTransport, ReadTransport, B
74
74
  createStream(): Promise<void>;
75
75
  /** Stream-tail metadata (opaque tail offset and the closed flag). */
76
76
  head(): Promise<HeadInfo>;
77
- /** One bounded backward page immediately before `from` (omitted reads
78
- * before the current tail). The service supplies the message-span list;
79
- * this adapter never infers boundaries from payload bytes. Requires a
80
- * streams-client build that exports `readBackward` (sibling package). */
77
+ /** One bounded page decoded and validated by the Streams client. */
81
78
  readBackward(from: string | undefined, limitBytes: number): Promise<BackwardPage>;
82
79
  /** One catch-up page from `offset` (opaque; omitted reads from the
83
80
  * beginning). No long-poll here: the caller's loop decides when to poll
@@ -80,34 +80,24 @@ export class StreamsTransport {
80
80
  const out = unwrap(await this.#client.head());
81
81
  return { nextOffset: out.nextOffset, closed: out.closed };
82
82
  }
83
- /** One bounded backward page immediately before `from` (omitted reads
84
- * before the current tail). The service supplies the message-span list;
85
- * this adapter never infers boundaries from payload bytes. Requires a
86
- * streams-client build that exports `readBackward` (sibling package). */
83
+ /** One bounded page decoded and validated by the Streams client. */
87
84
  async readBackward(from, limitBytes) {
88
- if (!Number.isSafeInteger(limitBytes) || limitBytes <= 0)
89
- throw new TransportError('rejected', 'backward page limit must be a positive safe integer');
90
- const out = unwrap(await this.#client.readBackward(from === undefined ? { limitBytes } : { before: from, limitBytes }));
91
- const messages = out.messages.map((span) => {
92
- const messageLen = Number(span.messageLen);
93
- const msgOffset = Number(span.msgOffset);
94
- if (!Number.isSafeInteger(messageLen) || !Number.isSafeInteger(msgOffset)
95
- || !Number.isSafeInteger(span.relStart) || !Number.isSafeInteger(span.relEnd))
96
- throw new TransportError('rejected', 'backward span integer exceeds a safe integer');
97
- return {
98
- relStart: span.relStart,
99
- relEnd: span.relEnd,
100
- messageStart: span.messageStart,
101
- messageLen,
102
- msgOffset,
103
- };
85
+ const page = unwrap(await this.#client.readBackward({ before: from, limitBytes }));
86
+ if (page.frames.length === 0 && page.atRetainedStart && !page.atStart)
87
+ throw new TransportError('rejected', 'backward history starts at a retention floor');
88
+ // RR cursors are canonical 20-digit byte offsets. Only the transport
89
+ // interprets them; the history reader chains opaque provider offsets.
90
+ let offset = BigInt(page.prevOffset);
91
+ const frames = page.frames.map((frame) => {
92
+ const startOffset = offset.toString().padStart(page.prevOffset.length, '0');
93
+ offset += BigInt(frame.data.length);
94
+ return { ...frame, startOffset };
104
95
  });
105
96
  return {
106
- payload: out.payload,
107
- endOffset: out.endOffset,
108
- prevOffset: out.prevOffset,
109
- reachedStart: out.atStart,
110
- messages,
97
+ frames,
98
+ endOffset: page.endOffset,
99
+ prevOffset: page.prevOffset,
100
+ reachedStart: page.atStart,
111
101
  };
112
102
  }
113
103
  /** One catch-up page from `offset` (opaque; omitted reads from the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loro-dev/roost",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Browser conversation history and sync for Loro Roost",
5
5
  "license": "MIT",
6
6
  "publishConfig": { "access": "public" },
@@ -9,10 +9,10 @@
9
9
  "scripts": {
10
10
  "check": "tsc --noEmit",
11
11
  "build": "tsc",
12
- "prepack": "pnpm build",
13
- "test": "pnpm build && node --test tests/*.test.mjs",
14
- "pack:consumer": "pnpm build && node scripts/pack-consumer.mjs",
15
- "check:consumer": "pnpm build && node scripts/check-consumer.mjs"
12
+ "prepack": "npm run build",
13
+ "test": "npm run build && node --test tests/*.test.mjs",
14
+ "pack:consumer": "npm run build && node scripts/pack-consumer.mjs",
15
+ "check:consumer": "npm run build && node scripts/check-consumer.mjs"
16
16
  },
17
17
  "devDependencies": {
18
18
  "playwright": "1.58.2",
@@ -21,7 +21,7 @@
21
21
  "dependencies": {
22
22
  "@noble/curves": "2.4.0",
23
23
  "@noble/hashes": "2.4.0",
24
- "@loro-dev/streams-client": "0.8.0"
24
+ "@loro-dev/streams-client": "0.16.0"
25
25
  },
26
26
  "main": "./dist/index.js",
27
27
  "types": "./dist/index.d.ts",