@loro-dev/roost 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +397 -0
  3. package/dist/codec.d.ts +66 -0
  4. package/dist/codec.js +275 -0
  5. package/dist/crypto.d.ts +21 -0
  6. package/dist/crypto.js +103 -0
  7. package/dist/durable-framing.d.ts +44 -0
  8. package/dist/durable-framing.js +207 -0
  9. package/dist/framing.d.ts +28 -0
  10. package/dist/framing.js +144 -0
  11. package/dist/history-publication.d.ts +58 -0
  12. package/dist/history-publication.js +234 -0
  13. package/dist/identity.d.ts +14 -0
  14. package/dist/identity.js +62 -0
  15. package/dist/inbox.d.ts +69 -0
  16. package/dist/inbox.js +262 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +6 -0
  19. package/dist/indexeddb.d.ts +38 -0
  20. package/dist/indexeddb.js +299 -0
  21. package/dist/json.d.ts +23 -0
  22. package/dist/json.js +221 -0
  23. package/dist/lody-history.d.ts +397 -0
  24. package/dist/lody-history.js +1559 -0
  25. package/dist/projection.d.ts +53 -0
  26. package/dist/projection.js +543 -0
  27. package/dist/replay.d.ts +63 -0
  28. package/dist/replay.js +201 -0
  29. package/dist/sender.d.ts +26 -0
  30. package/dist/sender.js +67 -0
  31. package/dist/store.d.ts +384 -0
  32. package/dist/store.js +1437 -0
  33. package/dist/sync/coverage.d.ts +276 -0
  34. package/dist/sync/coverage.js +1084 -0
  35. package/dist/sync/crypto.d.ts +64 -0
  36. package/dist/sync/crypto.js +155 -0
  37. package/dist/sync/execute.d.ts +142 -0
  38. package/dist/sync/execute.js +321 -0
  39. package/dist/sync/history.d.ts +214 -0
  40. package/dist/sync/history.js +786 -0
  41. package/dist/sync/index.d.ts +17 -0
  42. package/dist/sync/index.js +9 -0
  43. package/dist/sync/link.d.ts +192 -0
  44. package/dist/sync/link.js +663 -0
  45. package/dist/sync/mod.d.ts +24 -0
  46. package/dist/sync/mod.js +15 -0
  47. package/dist/sync/policy.d.ts +62 -0
  48. package/dist/sync/policy.js +128 -0
  49. package/dist/sync/registry.d.ts +129 -0
  50. package/dist/sync/registry.js +333 -0
  51. package/dist/sync/transport.d.ts +91 -0
  52. package/dist/sync/transport.js +162 -0
  53. package/dist/sync/work.d.ts +351 -0
  54. package/dist/sync/work.js +1344 -0
  55. package/package.json +47 -0
package/dist/codec.js ADDED
@@ -0,0 +1,275 @@
1
+ import { decodeJson, decodeUtf8, encodeJson, encodeUtf8, U64_MAX } from './json.js';
2
+ export const MAX_FRAME = 16 * 1024 * 1024;
3
+ export const MAX_BATCH = 64 * 1024 * 1024;
4
+ export const MAX_UPDATES = 4096;
5
+ export const MAX_PATH_SEGMENTS = 128;
6
+ class Writer {
7
+ limit;
8
+ parts = [];
9
+ size = 0;
10
+ constructor(limit) {
11
+ this.limit = limit;
12
+ }
13
+ raw(bytes) {
14
+ if (this.size + bytes.length > this.limit)
15
+ throw new Error('encoded size limit');
16
+ this.parts.push(bytes);
17
+ this.size += bytes.length;
18
+ }
19
+ byte(value) { this.raw(new Uint8Array([value])); }
20
+ var(value) {
21
+ if (typeof value !== 'bigint' || value < 0n || value > U64_MAX)
22
+ throw new RangeError('u64 varint');
23
+ const parts = [];
24
+ while (value >= 128n) {
25
+ parts.push(Number(value & 127n) | 128);
26
+ value >>= 7n;
27
+ }
28
+ parts.push(Number(value));
29
+ this.raw(new Uint8Array(parts));
30
+ }
31
+ bytes(value) { this.var(BigInt(value.length)); this.raw(value); }
32
+ fixed(value, length) { if (!(value instanceof Uint8Array) || value.length !== length)
33
+ throw new Error('fixed byte length'); this.raw(value); }
34
+ finish() { const out = new Uint8Array(this.size); let pos = 0; for (const part of this.parts) {
35
+ out.set(part, pos);
36
+ pos += part.length;
37
+ } return out; }
38
+ }
39
+ function writePath(writer, path) {
40
+ if (path.length > MAX_PATH_SEGMENTS)
41
+ throw new Error('path too deep');
42
+ writer.var(BigInt(path.length));
43
+ for (const segment of path) {
44
+ if ('key' in segment) {
45
+ writer.byte(0);
46
+ writer.bytes(encodeUtf8(segment.key));
47
+ }
48
+ else {
49
+ writer.byte(1);
50
+ writer.var(segment.index);
51
+ }
52
+ }
53
+ }
54
+ export function encodeFrame(update) {
55
+ const writer = new Writer(MAX_FRAME);
56
+ writer.byte(1);
57
+ writer.fixed(update.turnId, 16);
58
+ writer.var(update.seq);
59
+ writer.fixed(update.owner, 32);
60
+ const operation = update.operation;
61
+ switch (operation.kind) {
62
+ case 'create':
63
+ writer.byte(0);
64
+ writer.var(BigInt(operation.parents.length));
65
+ for (const parent of operation.parents) {
66
+ writer.fixed(parent.id, 16);
67
+ writer.fixed(parent.hash, 32);
68
+ }
69
+ writer.bytes(encodeJson(operation.content));
70
+ break;
71
+ case 'edit': {
72
+ writer.byte(1);
73
+ writer.var(1n);
74
+ const op = operation.op;
75
+ const tag = { set: 0, remove: 1, appendText: 2, spliceText: 3, spliceArray: 4 }[op.kind];
76
+ if (tag === undefined)
77
+ throw new Error('operation tag');
78
+ writer.byte(tag);
79
+ writePath(writer, op.path);
80
+ switch (op.kind) {
81
+ case 'set':
82
+ writer.bytes(encodeJson(op.value));
83
+ break;
84
+ case 'remove': break;
85
+ case 'appendText':
86
+ writer.bytes(encodeUtf8(op.text));
87
+ break;
88
+ case 'spliceText':
89
+ writer.var(op.index);
90
+ writer.var(op.delete);
91
+ writer.bytes(encodeUtf8(op.text));
92
+ break;
93
+ case 'spliceArray':
94
+ writer.var(op.index);
95
+ writer.var(op.delete);
96
+ writer.bytes(encodeJson(op.values));
97
+ break;
98
+ }
99
+ break;
100
+ }
101
+ case 'seal':
102
+ writer.byte(2);
103
+ writer.fixed(operation.hash, 32);
104
+ break;
105
+ default: throw new Error('update tag');
106
+ }
107
+ if (operation.kind === 'seal') {
108
+ if (update.signature === undefined)
109
+ throw new Error('seal signature required');
110
+ writer.fixed(update.signature, 64);
111
+ }
112
+ else if (update.signature !== undefined)
113
+ throw new Error('only seals carry signatures');
114
+ return writer.finish();
115
+ }
116
+ function batchWriter(count) {
117
+ if (count > MAX_UPDATES)
118
+ throw new Error('too many updates');
119
+ const writer = new Writer(MAX_BATCH);
120
+ writer.raw(new Uint8Array([82, 83, 84, 49]));
121
+ writer.var(BigInt(count));
122
+ return writer;
123
+ }
124
+ function appendFrame(writer, frame) {
125
+ if (!(frame instanceof Uint8Array) || frame.length > MAX_FRAME)
126
+ throw new Error('frame too large');
127
+ writer.bytes(frame);
128
+ }
129
+ /** Adds bounded batch framing; does not decode or verify the supplied frames. */
130
+ export function assembleFrames(frames) {
131
+ const writer = batchWriter(frames.length);
132
+ for (const frame of frames)
133
+ appendFrame(writer, frame);
134
+ return writer.finish();
135
+ }
136
+ export function encodeBatch(updates) {
137
+ const writer = batchWriter(updates.length);
138
+ // Enforce aggregate size as each frame is produced, not after materializing all frames.
139
+ for (const update of updates)
140
+ appendFrame(writer, encodeFrame(update));
141
+ return writer.finish();
142
+ }
143
+ class Reader {
144
+ bytes;
145
+ pos = 0;
146
+ constructor(bytes) {
147
+ this.bytes = bytes;
148
+ }
149
+ take(size) {
150
+ if (!Number.isSafeInteger(size) || size < 0 || size > this.bytes.length - this.pos)
151
+ throw new Error('truncated frame');
152
+ const value = this.bytes.subarray(this.pos, this.pos + size);
153
+ this.pos += size;
154
+ return value;
155
+ }
156
+ byte() { return this.take(1)[0]; }
157
+ var() {
158
+ let value = 0n;
159
+ for (let shift = 0; shift < 70; shift += 7) {
160
+ const byte = this.byte();
161
+ if (shift === 63 && byte > 1)
162
+ throw new Error('varint overflow');
163
+ value |= BigInt(byte & 127) << BigInt(shift);
164
+ if (byte < 128) {
165
+ if (shift > 0 && byte === 0)
166
+ throw new Error('noncanonical varint');
167
+ return value;
168
+ }
169
+ }
170
+ throw new Error('varint overflow');
171
+ }
172
+ lengthPrefixed() { const length = this.var(); if (length > BigInt(this.bytes.length - this.pos))
173
+ throw new Error('truncated length'); return this.take(Number(length)); }
174
+ string() { return decodeUtf8(this.lengthPrefixed()); }
175
+ path() {
176
+ const count = this.var();
177
+ if (count > BigInt(MAX_PATH_SEGMENTS))
178
+ throw new Error('path too deep');
179
+ const path = [];
180
+ for (let i = 0n; i < count; i++) {
181
+ const tag = this.byte();
182
+ if (tag === 0)
183
+ path.push({ key: this.string() });
184
+ else if (tag === 1)
185
+ path.push({ index: this.var() });
186
+ else
187
+ throw new Error('path tag');
188
+ }
189
+ return path;
190
+ }
191
+ end() { if (this.pos !== this.bytes.length)
192
+ throw new Error('trailing bytes'); }
193
+ }
194
+ export function decodeFrame(bytes) {
195
+ if (bytes.length > MAX_FRAME)
196
+ throw new Error('frame too large');
197
+ const reader = new Reader(bytes);
198
+ if (reader.byte() !== 1)
199
+ throw new Error('unsupported wire version');
200
+ const turnId = reader.take(16).slice(), seq = reader.var(), owner = reader.take(32).slice();
201
+ const tag = reader.byte();
202
+ let operation;
203
+ if (tag === 0) {
204
+ const count = reader.var();
205
+ if (count > BigInt(Math.floor(bytes.length / 48)))
206
+ throw new Error('parent length');
207
+ const parents = [];
208
+ for (let i = 0n; i < count; i++)
209
+ parents.push({ id: reader.take(16).slice(), hash: reader.take(32).slice() });
210
+ operation = { kind: 'create', parents, content: decodeJson(reader.lengthPrefixed()) };
211
+ }
212
+ else if (tag === 1) {
213
+ if (reader.var() !== 1n)
214
+ throw new Error('each edit update contains exactly one operation');
215
+ const opTag = reader.byte(), path = reader.path();
216
+ let op;
217
+ switch (opTag) {
218
+ case 0:
219
+ op = { kind: 'set', path, value: decodeJson(reader.lengthPrefixed()) };
220
+ break;
221
+ case 1:
222
+ op = { kind: 'remove', path };
223
+ break;
224
+ case 2:
225
+ op = { kind: 'appendText', path, text: reader.string() };
226
+ break;
227
+ case 3:
228
+ op = { kind: 'spliceText', path, index: reader.var(), delete: reader.var(), text: reader.string() };
229
+ break;
230
+ case 4: {
231
+ const index = reader.var(), removed = reader.var(), values = decodeJson(reader.lengthPrefixed());
232
+ if (!Array.isArray(values))
233
+ throw new Error('array payload');
234
+ op = { kind: 'spliceArray', path, index, delete: removed, values };
235
+ break;
236
+ }
237
+ default: throw new Error('operation tag');
238
+ }
239
+ operation = { kind: 'edit', op };
240
+ }
241
+ else if (tag === 2)
242
+ operation = { kind: 'seal', hash: reader.take(32).slice() };
243
+ else
244
+ throw new Error('update tag');
245
+ const result = { turnId, seq, owner, operation };
246
+ if (operation.kind === 'seal')
247
+ result.signature = reader.take(64).slice();
248
+ reader.end();
249
+ return result;
250
+ }
251
+ /** Validates outer framing, total size and count; decodeFrame enforces each frame limit. */
252
+ function splitBatchViews(bytes) {
253
+ if (bytes.length > MAX_BATCH)
254
+ throw new Error('batch too large');
255
+ const reader = new Reader(bytes);
256
+ if (!reader.take(4).every((v, i) => v === [82, 83, 84, 49][i]))
257
+ throw new Error('batch magic');
258
+ const count = reader.var();
259
+ if (count > BigInt(MAX_UPDATES))
260
+ throw new Error('too many updates');
261
+ const result = [];
262
+ for (let i = 0n; i < count; i++) {
263
+ result.push(reader.lengthPrefixed());
264
+ }
265
+ reader.end();
266
+ return result;
267
+ }
268
+ /** Validates outer framing and returns owned frame copies for callers that retain them. */
269
+ export function splitBatch(bytes) {
270
+ return splitBatchViews(bytes).map(frame => frame.slice());
271
+ }
272
+ /** Syntax and canonical bytes only. Import applies owner admission and seal verification; unsealed authorship remains provisional. */
273
+ export function decodeBatch(bytes) {
274
+ return splitBatchViews(bytes).map(decodeFrame);
275
+ }
@@ -0,0 +1,21 @@
1
+ import { type JsonValue } from './json.js';
2
+ export type ParentRef = {
3
+ id: Uint8Array;
4
+ hash: Uint8Array;
5
+ };
6
+ /** Preimage only; does not establish parent existence, signature validity or trust. */
7
+ export declare function nodePreimage(stream: string, id: Uint8Array, owner: Uint8Array, parents: readonly ParentRef[], content: JsonValue): Uint8Array;
8
+ export declare function nodeHash(stream: string, id: Uint8Array, owner: Uint8Array, parents: readonly ParentRef[], content: JsonValue): Uint8Array;
9
+ /** Matches dalek VerifyingKey::from_bytes: a 32-byte decodable Edwards point.
10
+ * Small-order and noncanonical encodings may pass. This is NOT source
11
+ * authorization or signature verification; unsigned updates stay provisional.
12
+ */
13
+ export declare function isValidOwner(owner: Uint8Array): boolean;
14
+ /** Only verifies a seal signature over the supplied 32-byte hash.
15
+ * Matches ed25519-dalek 2.2 verify_strict, not noble's cofactored verify:
16
+ * accept dalek-compatible A decoding; canonical S; reject small-order A and R;
17
+ * compare compressed [S]B - [H(R||A||hash)]A against the ORIGINAL R bytes.
18
+ * All point/scalar/hash operations use noble primitives; no curve arithmetic here.
19
+ * A true result says nothing about recomputed content hash or source authorization.
20
+ */
21
+ export declare function verifySealSignature(owner: Uint8Array, hash: Uint8Array, signature: Uint8Array): boolean;
package/dist/crypto.js ADDED
@@ -0,0 +1,103 @@
1
+ import { ed25519 } from '@noble/curves/ed25519.js';
2
+ import { bytesToNumberLE, equalBytes } from '@noble/curves/utils.js';
3
+ import { blake3 } from '@noble/hashes/blake3.js';
4
+ import { sha512 } from '@noble/hashes/sha2.js';
5
+ import { concatBytes } from '@noble/hashes/utils.js';
6
+ import { encodeJson, encodeUtf8 } from './json.js';
7
+ import { checkTurnId } from './identity.js';
8
+ const DOMAIN = new TextEncoder().encode('loro-roost/node/v1\0'); // 18 ASCII + NUL.
9
+ function bytes(value, length, name) {
10
+ if (!(value instanceof Uint8Array) || value.length !== length)
11
+ throw new Error(`${name} must be ${length} bytes`);
12
+ }
13
+ function varint(value) {
14
+ let n = BigInt(value);
15
+ const out = [];
16
+ do {
17
+ const low = Number(n & 127n);
18
+ n >>= 7n;
19
+ out.push(low | (n === 0n ? 0 : 128));
20
+ } while (n !== 0n);
21
+ return Uint8Array.from(out);
22
+ }
23
+ function compare(a, b) {
24
+ for (let i = 0; i < a.length; i++)
25
+ if (a[i] !== b[i])
26
+ return a[i] - b[i];
27
+ return 0;
28
+ }
29
+ /** Preimage only; does not establish parent existence, signature validity or trust. */
30
+ export function nodePreimage(stream, id, owner, parents, content) {
31
+ checkTurnId(id);
32
+ bytes(owner, 32, 'owner');
33
+ const name = encodeUtf8(stream), json = encodeJson(content);
34
+ const chunks = [DOMAIN, varint(name.length), name, id, owner, varint(parents.length)];
35
+ let prior;
36
+ for (const parent of parents) {
37
+ checkTurnId(parent.id);
38
+ bytes(parent.hash, 32, 'parent hash');
39
+ if (prior && compare(prior, parent.id) >= 0)
40
+ throw new Error('parents must be sorted and unique');
41
+ chunks.push(parent.id, parent.hash);
42
+ prior = parent.id;
43
+ }
44
+ chunks.push(varint(json.length), json);
45
+ return concatBytes(...chunks);
46
+ }
47
+ export function nodeHash(stream, id, owner, parents, content) {
48
+ checkTurnId(id);
49
+ bytes(owner, 32, 'owner');
50
+ const name = encodeUtf8(stream), json = encodeJson(content), hasher = blake3.create();
51
+ hasher.update(DOMAIN).update(varint(name.length)).update(name).update(id).update(owner).update(varint(parents.length));
52
+ let prior;
53
+ for (const parent of parents) {
54
+ checkTurnId(parent.id);
55
+ bytes(parent.hash, 32, 'parent hash');
56
+ if (prior && compare(prior, parent.id) >= 0)
57
+ throw new Error('parents must be sorted and unique');
58
+ hasher.update(parent.id).update(parent.hash);
59
+ prior = parent.id;
60
+ }
61
+ hasher.update(varint(json.length)).update(json);
62
+ return hasher.digest();
63
+ }
64
+ /** Matches dalek VerifyingKey::from_bytes: a 32-byte decodable Edwards point.
65
+ * Small-order and noncanonical encodings may pass. This is NOT source
66
+ * authorization or signature verification; unsigned updates stay provisional.
67
+ */
68
+ export function isValidOwner(owner) {
69
+ try {
70
+ bytes(owner, 32, 'owner');
71
+ ed25519.Point.fromBytes(owner, true);
72
+ return true;
73
+ }
74
+ catch {
75
+ return false;
76
+ }
77
+ }
78
+ /** Only verifies a seal signature over the supplied 32-byte hash.
79
+ * Matches ed25519-dalek 2.2 verify_strict, not noble's cofactored verify:
80
+ * accept dalek-compatible A decoding; canonical S; reject small-order A and R;
81
+ * compare compressed [S]B - [H(R||A||hash)]A against the ORIGINAL R bytes.
82
+ * All point/scalar/hash operations use noble primitives; no curve arithmetic here.
83
+ * A true result says nothing about recomputed content hash or source authorization.
84
+ */
85
+ export function verifySealSignature(owner, hash, signature) {
86
+ try {
87
+ bytes(owner, 32, 'owner');
88
+ bytes(hash, 32, 'hash');
89
+ bytes(signature, 64, 'signature');
90
+ const { Point } = ed25519;
91
+ const r = signature.subarray(0, 32), encodedS = signature.subarray(32);
92
+ const a = Point.fromBytes(owner, true), R = Point.fromBytes(r, true);
93
+ const s = Point.Fn.fromBytes(encodedS);
94
+ if (!equalBytes(Point.Fn.toBytes(s), encodedS) || a.isSmallOrder() || R.isSmallOrder())
95
+ return false;
96
+ const k = Point.Fn.create(bytesToNumberLE(sha512(concatBytes(r, owner, hash))));
97
+ const expected = Point.BASE.multiplyUnsafe(s).subtract(a.multiplyUnsafe(k)).toBytes();
98
+ return equalBytes(expected, r);
99
+ }
100
+ catch {
101
+ return false;
102
+ }
103
+ }
@@ -0,0 +1,44 @@
1
+ import { Inbox } from './inbox.js';
2
+ import { type FramingFailure } from './framing.js';
3
+ export interface RawPosition {
4
+ sequence: bigint;
5
+ offset: number;
6
+ }
7
+ export interface FramingState {
8
+ generation: bigint;
9
+ batchStart: RawPosition;
10
+ scanEnd: RawPosition;
11
+ tailBytes: number;
12
+ batches: bigint;
13
+ cursor: Uint8Array | null;
14
+ terminal: 'end' | FramingFailure | null;
15
+ }
16
+ export declare class DurableFramingError extends Error {
17
+ readonly code: 'corrupt' | 'busy' | 'invalid';
18
+ readonly name = "DurableFramingError";
19
+ constructor(code: 'corrupt' | 'busy' | 'invalid', message: string);
20
+ }
21
+ export type FramingStep = {
22
+ kind: 'idle' | 'restoring' | 'progress' | 'batch' | 'end';
23
+ } | {
24
+ kind: 'invalid';
25
+ reason: FramingFailure;
26
+ };
27
+ /** One explicit step, no network or background worker. The derived cursor is a LOCAL
28
+ * receipt/byte position; it is never a fabricated remote offset. Stop/await callers
29
+ * before closing storage. Raw receipts and complete batches are retained, no GC. */
30
+ export declare class DurableFraming {
31
+ #private;
32
+ private readonly raw;
33
+ private readonly derived;
34
+ private constructor();
35
+ static open(raw: Inbox, derived: Inbox): DurableFraming;
36
+ state(): Promise<FramingState>;
37
+ /** At most one 64KiB parse window or one receipt-boundary transition. Restart
38
+ * reconstruction uses the same bound and returns restoring. The parser/raw
39
+ * receipt cache is retained only after native commit; failures discard it. */
40
+ step(): Promise<FramingStep>;
41
+ /** Call only for a confirmed FINAL EOF. If raw/recovery work remains, returns
42
+ * progress/restoring/batch instead: caller repeats until end/invalid. */
43
+ finish(): Promise<FramingStep>;
44
+ }
@@ -0,0 +1,207 @@
1
+ import { BatchFramer, FRAMING_WINDOW } from './framing.js';
2
+ import { MAX_BATCH } from './codec.js';
3
+ const TABLE = 'browser_framing_state_v1';
4
+ const MAX = (1n << 64n) - 1n;
5
+ const encoder = new TextEncoder(), decoder = new TextDecoder('utf-8', { fatal: true });
6
+ export class DurableFramingError extends Error {
7
+ code;
8
+ name = 'DurableFramingError';
9
+ constructor(code, message) {
10
+ super(message);
11
+ this.code = code;
12
+ }
13
+ }
14
+ const fail = (message) => { throw new DurableFramingError('corrupt', message); };
15
+ const same = (a, b) => a.sequence === b.sequence && a.offset === b.offset;
16
+ const compare = (a, b) => a.sequence < b.sequence ? -1 : a.sequence > b.sequence ? 1 : a.offset - b.offset;
17
+ const byteEqual = (a, b) => a === null || b === null ? a === b : a.length === b.length && a.every((v, i) => v === b[i]);
18
+ const integer = (v) => {
19
+ if (typeof v !== 'string' || !/^(0|[1-9][0-9]*)$/.test(v))
20
+ return fail('invalid counter');
21
+ const n = BigInt(v);
22
+ if (n > MAX)
23
+ return fail('counter overflow');
24
+ return n;
25
+ };
26
+ const position = (v) => {
27
+ if (!Array.isArray(v) || v.length !== 2 || !Number.isSafeInteger(v[1]) || v[1] < 0)
28
+ return fail('invalid raw position');
29
+ return { sequence: integer(v[0]), offset: v[1] };
30
+ };
31
+ function localCursor(p) {
32
+ const bytes = new Uint8Array(16), view = new DataView(bytes.buffer);
33
+ view.setBigUint64(0, p.sequence);
34
+ view.setBigUint64(8, BigInt(p.offset));
35
+ return bytes;
36
+ }
37
+ function pack(s, binding) {
38
+ return encoder.encode(JSON.stringify([1, [...binding], String(s.generation), [String(s.batchStart.sequence), s.batchStart.offset], [String(s.scanEnd.sequence), s.scanEnd.offset], s.tailBytes, String(s.batches), s.cursor === null ? null : [...s.cursor], s.terminal]));
39
+ }
40
+ function unpack(bytes, binding) {
41
+ try {
42
+ const v = JSON.parse(decoder.decode(bytes));
43
+ if (!Array.isArray(v) || v.length !== 9 || v[0] !== 1 || JSON.stringify(v[1]) !== JSON.stringify([...binding]))
44
+ return fail('framing binding/version');
45
+ const s = { generation: integer(v[2]), batchStart: position(v[3]), scanEnd: position(v[4]), tailBytes: v[5], batches: integer(v[6]), cursor: v[7] === null ? null : new Uint8Array(v[7]), terminal: v[8] };
46
+ if (!Number.isSafeInteger(s.tailBytes) || s.tailBytes < 0 || s.tailBytes > MAX_BATCH || compare(s.batchStart, s.scanEnd) > 0 || (s.tailBytes === 0 && !same(s.batchStart, s.scanEnd)))
47
+ return fail('framing tail range');
48
+ if (v[7] !== null && (!Array.isArray(v[7]) || v[7].length !== 16 || !v[7].every((n) => Number.isInteger(n) && Number(n) >= 0 && Number(n) <= 255)))
49
+ return fail('framing cursor');
50
+ if (![null, 'end', 'magic', 'varint', 'countLimit', 'batchLimit', 'truncated'].includes(s.terminal))
51
+ return fail('framing terminal');
52
+ if (s.terminal === 'end' && s.tailBytes !== 0)
53
+ return fail('final EOF with partial batch');
54
+ if ((s.batches === 0n) !== (s.cursor === null))
55
+ return fail('framing output count');
56
+ return s;
57
+ }
58
+ catch (error) {
59
+ if (error instanceof DurableFramingError)
60
+ throw error;
61
+ return fail('invalid framing metadata');
62
+ }
63
+ }
64
+ /** One explicit step, no network or background worker. The derived cursor is a LOCAL
65
+ * receipt/byte position; it is never a fabricated remote offset. Stop/await callers
66
+ * before closing storage. Raw receipts and complete batches are retained, no GC. */
67
+ export class DurableFraming {
68
+ raw;
69
+ derived;
70
+ #cache;
71
+ #busy = false;
72
+ constructor(raw, derived) {
73
+ this.raw = raw;
74
+ this.derived = derived;
75
+ }
76
+ static open(raw, derived) { return new DurableFraming(raw, derived); }
77
+ *#load(tx, raw, out) {
78
+ const stored = yield* tx.get(TABLE, raw.namespace), head = yield* out.state();
79
+ const s = stored === undefined ? { generation: 0n, batchStart: { sequence: 0n, offset: 0 }, scanEnd: { sequence: 0n, offset: 0 }, tailBytes: 0, batches: 0n, cursor: null, terminal: null } : unpack(stored, out.namespace);
80
+ if (head.nextSequence !== s.batches || !byteEqual(head.cursor, s.cursor))
81
+ return fail('derived ledger/checkpoint disagree');
82
+ // Immutable receipt validation is reused only with this committed generation.
83
+ // Avoid rereading a prior 64MiB batch for every following 64KiB window.
84
+ if (s.batches > 0n && this.#cache?.generation !== s.generation) {
85
+ const last = yield* out.record(s.batches - 1n);
86
+ if (!last || !byteEqual(last.nextCursor, s.cursor))
87
+ return fail('missing derived receipt');
88
+ }
89
+ const rawHead = yield* raw.state();
90
+ if (s.scanEnd.sequence > rawHead.nextSequence || (s.scanEnd.sequence === rawHead.nextSequence && s.scanEnd.offset !== 0))
91
+ return fail('framing beyond raw head');
92
+ if (s.terminal === 'end' && (s.scanEnd.sequence !== rawHead.nextSequence || s.scanEnd.offset !== 0))
93
+ return fail('raw receipt arrived after final EOF');
94
+ return s;
95
+ }
96
+ async state() {
97
+ const self = this;
98
+ return this.raw._framingTransact(false, this.derived, function* (tx, raw, out) { return yield* self.#load(tx, raw, out); });
99
+ }
100
+ /** At most one 64KiB parse window or one receipt-boundary transition. Restart
101
+ * reconstruction uses the same bound and returns restoring. The parser/raw
102
+ * receipt cache is retained only after native commit; failures discard it. */
103
+ async step() { return this.#run(false); }
104
+ /** Call only for a confirmed FINAL EOF. If raw/recovery work remains, returns
105
+ * progress/restoring/batch instead: caller repeats until end/invalid. */
106
+ async finish() { return this.#run(true); }
107
+ async #run(final) {
108
+ if (this.#busy)
109
+ throw new DurableFramingError('busy', 'framing step already active');
110
+ this.#busy = true;
111
+ let nextCache;
112
+ const self = this;
113
+ try {
114
+ const result = await this.raw._framingTransact(true, this.derived, function* (tx, raw, out) {
115
+ const s = yield* self.#load(tx, raw, out);
116
+ if (s.terminal !== null)
117
+ return s.terminal === 'end' ? { kind: 'end' } : { kind: 'invalid', reason: s.terminal };
118
+ const cache = self.#cache?.generation === s.generation ? self.#cache : { generation: s.generation, parser: new BatchFramer(), position: { ...s.batchStart }, bytes: 0 };
119
+ nextCache = cache;
120
+ const restoring = !same(cache.position, s.scanEnd);
121
+ if (!restoring && cache.bytes !== s.tailBytes)
122
+ return fail('tail bytes disagree');
123
+ const head = yield* raw.state();
124
+ if (cache.position.sequence === head.nextSequence) {
125
+ if (restoring)
126
+ return fail('missing raw tail');
127
+ if (!final)
128
+ return { kind: 'idle' };
129
+ const end = cache.parser.finish();
130
+ s.terminal = end.kind === 'end' ? 'end' : end.reason;
131
+ if (s.generation === MAX)
132
+ return fail('generation overflow');
133
+ s.generation++;
134
+ yield* tx.put(TABLE, raw.namespace, pack(s, out.namespace));
135
+ nextCache = undefined;
136
+ return end;
137
+ }
138
+ let record = cache.record;
139
+ if (!record || record.sequence !== cache.position.sequence)
140
+ record = yield* raw.record(cache.position.sequence);
141
+ if (!record)
142
+ return fail('missing raw receipt');
143
+ cache.record = record;
144
+ if (cache.position.offset > record.bytes.length)
145
+ return fail('raw offset outside receipt');
146
+ let outcome = { kind: restoring ? 'restoring' : 'progress' };
147
+ if (cache.position.offset === record.bytes.length) {
148
+ if (cache.position.sequence === MAX)
149
+ return fail('raw sequence overflow');
150
+ cache.position = { sequence: cache.position.sequence + 1n, offset: 0 };
151
+ cache.record = undefined;
152
+ }
153
+ else {
154
+ let limit = Math.min(record.bytes.length, cache.position.offset + FRAMING_WINDOW);
155
+ if (restoring && cache.position.sequence === s.scanEnd.sequence)
156
+ limit = Math.min(limit, s.scanEnd.offset);
157
+ const parsed = cache.parser.push(record.bytes.subarray(cache.position.offset, limit));
158
+ cache.position.offset += parsed.consumed;
159
+ cache.bytes += parsed.consumed;
160
+ if (restoring && parsed.kind !== 'needMore')
161
+ return fail('saved tail contains boundary/failure');
162
+ if (!restoring && parsed.kind === 'batch') {
163
+ const cursor = localCursor(cache.position);
164
+ const receipt = yield* out.receive(s.cursor, cursor, parsed.bytes);
165
+ if (receipt.kind !== 'received' || receipt.sequence !== s.batches)
166
+ return fail('derived receipt sequence');
167
+ s.batches++;
168
+ s.cursor = cursor;
169
+ s.batchStart = { ...cache.position };
170
+ cache.bytes = 0;
171
+ outcome = { kind: 'batch' };
172
+ }
173
+ else if (!restoring && parsed.kind === 'invalid') {
174
+ s.terminal = parsed.reason;
175
+ outcome = { kind: 'invalid', reason: parsed.reason };
176
+ }
177
+ }
178
+ if (restoring) {
179
+ if (compare(cache.position, s.scanEnd) > 0 || cache.bytes > s.tailBytes)
180
+ return fail('tail range crossed');
181
+ if (same(cache.position, s.scanEnd) && cache.bytes !== s.tailBytes)
182
+ return fail('tail byte accounting');
183
+ return outcome;
184
+ }
185
+ s.scanEnd = { ...cache.position };
186
+ s.tailBytes = cache.bytes;
187
+ if (cache.bytes === 0)
188
+ s.batchStart = { ...cache.position };
189
+ if (s.generation === MAX)
190
+ return fail('generation overflow');
191
+ s.generation++;
192
+ cache.generation = s.generation;
193
+ yield* tx.put(TABLE, raw.namespace, pack(s, out.namespace));
194
+ return outcome;
195
+ });
196
+ self.#cache = nextCache;
197
+ return result;
198
+ }
199
+ catch (error) {
200
+ self.#cache = undefined;
201
+ throw error;
202
+ }
203
+ finally {
204
+ self.#busy = false;
205
+ }
206
+ }
207
+ }
@@ -0,0 +1,28 @@
1
+ export declare const FRAMING_WINDOW: number;
2
+ export type FramingFailure = 'magic' | 'varint' | 'countLimit' | 'batchLimit' | 'truncated';
3
+ export type PushResult = {
4
+ kind: 'needMore';
5
+ consumed: number;
6
+ } | {
7
+ kind: 'batch';
8
+ consumed: number;
9
+ bytes: Uint8Array;
10
+ } | {
11
+ kind: 'invalid';
12
+ consumed: number;
13
+ reason: FramingFailure;
14
+ };
15
+ export type FinishResult = {
16
+ kind: 'end';
17
+ } | {
18
+ kind: 'invalid';
19
+ reason: FramingFailure;
20
+ };
21
+ /** Outer RST1 framing only. Frame syntax, size, admission and seals belong to import. */
22
+ export declare class BatchFramer {
23
+ #private;
24
+ /** Copies consumed input; returns at the first batch boundary and leaves its suffix untouched. */
25
+ push(input: Uint8Array): PushResult;
26
+ /** Only a confirmed final EOF closes the parser. A live pause must not call this. */
27
+ finish(): FinishResult;
28
+ }