@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/inbox.js ADDED
@@ -0,0 +1,262 @@
1
+ const STATE = 'browser_inbox_state_v1';
2
+ const RECORDS = 'browser_inbox_records_v1';
3
+ const CURSORS = 'browser_inbox_cursors_v1';
4
+ const U64_MAX = (1n << 64n) - 1n;
5
+ const utf8 = new TextEncoder();
6
+ export class InboxError extends Error {
7
+ code;
8
+ name = 'InboxError';
9
+ constructor(code, message) {
10
+ super(message);
11
+ this.code = code;
12
+ }
13
+ }
14
+ const fail = (code, message) => { throw new InboxError(code, message); };
15
+ const equal = (a, b) => a === null || b === null ? a === b : a.length === b.length && a.every((v, i) => v === b[i]);
16
+ const concat = (...chunks) => {
17
+ const out = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
18
+ let offset = 0;
19
+ for (const chunk of chunks) {
20
+ out.set(chunk, offset);
21
+ offset += chunk.length;
22
+ }
23
+ return out;
24
+ };
25
+ function u64(value) {
26
+ const out = new Uint8Array(8);
27
+ new DataView(out.buffer).setBigUint64(0, value, false);
28
+ return out;
29
+ }
30
+ function checkedU64(value, name, zero = true) {
31
+ if (typeof value !== 'bigint' || value < (zero ? 0n : 1n) || value > U64_MAX)
32
+ fail('invalid', name);
33
+ }
34
+ function namespacePart(value, max) {
35
+ if (typeof value !== 'string' || value.length === 0 || value.length > max)
36
+ fail('invalid', 'namespace length');
37
+ // JS alone can represent lone surrogates. Rust str cannot; never silently
38
+ // replace them with U+FFFD and alias a different namespace.
39
+ for (let i = 0; i < value.length; ++i) {
40
+ const c = value.charCodeAt(i);
41
+ if (c >= 0xd800 && c <= 0xdbff) {
42
+ const next = value.charCodeAt(++i);
43
+ if (!(next >= 0xdc00 && next <= 0xdfff))
44
+ fail('invalid', 'namespace Unicode');
45
+ }
46
+ else if (c >= 0xdc00 && c <= 0xdfff)
47
+ fail('invalid', 'namespace Unicode');
48
+ }
49
+ const content = utf8.encode(value);
50
+ if (content.length > max || content.length > 0xffffffff)
51
+ fail('invalid', 'namespace length');
52
+ const length = new Uint8Array(4);
53
+ new DataView(length.buffer).setUint32(0, content.length, false);
54
+ return concat(length, content);
55
+ }
56
+ function upperBound(prefix) {
57
+ let end = prefix.length;
58
+ while (end > 0 && prefix[end - 1] === 255)
59
+ --end;
60
+ if (end === 0)
61
+ return fail('invalid', 'namespace upper bound');
62
+ const result = prefix.slice(0, end);
63
+ result[end - 1] = result[end - 1] + 1;
64
+ return result;
65
+ }
66
+ const sized = (value) => concat(u64(BigInt(value.length)), value);
67
+ const optional = (value) => value === null ? new Uint8Array([0]) : concat(new Uint8Array([1]), sized(value));
68
+ class Reader {
69
+ bytes;
70
+ offset = 0;
71
+ constructor(bytes) {
72
+ this.bytes = bytes;
73
+ }
74
+ take(length) {
75
+ if (!Number.isSafeInteger(length) || length < 0 || length > this.bytes.length - this.offset)
76
+ fail('corrupt', 'truncated inbox value');
77
+ const part = this.bytes.slice(this.offset, this.offset + length);
78
+ this.offset += length;
79
+ return part;
80
+ }
81
+ integer() { const bytes = this.take(8); return new DataView(bytes.buffer).getBigUint64(0, false); }
82
+ sized() {
83
+ const length = this.integer();
84
+ if (length > BigInt(this.bytes.length - this.offset))
85
+ fail('corrupt', 'cursor length');
86
+ return this.take(Number(length));
87
+ }
88
+ optional() {
89
+ const tag = this.take(1)[0];
90
+ if (tag === 0)
91
+ return null;
92
+ if (tag === 1)
93
+ return this.sized();
94
+ return fail('corrupt', 'cursor option tag');
95
+ }
96
+ end() { if (this.offset !== this.bytes.length)
97
+ fail('corrupt', 'trailing inbox metadata'); }
98
+ }
99
+ function sequence(bytes) { const reader = new Reader(bytes); const value = reader.integer(); reader.end(); return value; }
100
+ function encodeState(state) { return concat(u64(state.nextSequence), u64(state.retainedBytes), optional(state.cursor)); }
101
+ function decodeState(bytes) {
102
+ const reader = new Reader(bytes);
103
+ const result = { nextSequence: reader.integer(), retainedBytes: reader.integer(), cursor: reader.optional() };
104
+ reader.end();
105
+ return result;
106
+ }
107
+ function encodeRecord(record) {
108
+ return concat(u64(record.sequence), optional(record.previousCursor), sized(record.nextCursor), record.bytes);
109
+ }
110
+ function decodeRecord(bytes, expected) {
111
+ const reader = new Reader(bytes);
112
+ const seq = reader.integer();
113
+ if (seq !== expected)
114
+ fail('corrupt', 'record sequence');
115
+ const previousCursor = reader.optional(), nextCursor = reader.sized();
116
+ return { sequence: seq, previousCursor, nextCursor, bytes: reader.take(bytes.length - reader.offset) };
117
+ }
118
+ /** Share the application's storage owner. No GC, implicit reset or default limits.
119
+ * This browser-private layout is not Rust inbox state or a wire/snapshot format. */
120
+ export class Inbox {
121
+ storage;
122
+ stream;
123
+ #namespace;
124
+ #end;
125
+ #limits;
126
+ constructor(storage, stream, source, limits) {
127
+ this.storage = storage;
128
+ this.stream = stream;
129
+ for (const value of [limits.maxBatchBytes, limits.maxCursorBytes, limits.maxNamespaceBytes, limits.maxPageRecords]) {
130
+ if (!Number.isSafeInteger(value) || value <= 0)
131
+ fail('invalid', 'limits must be positive safe integers');
132
+ }
133
+ checkedU64(limits.maxRecords, 'maxRecords', false);
134
+ checkedU64(limits.maxRetainedBytes, 'maxRetainedBytes', false);
135
+ this.#limits = Object.freeze({ ...limits });
136
+ this.#namespace = concat(namespacePart(stream, limits.maxNamespaceBytes), namespacePart(source, limits.maxNamespaceBytes));
137
+ this.#end = upperBound(this.#namespace);
138
+ }
139
+ static open(storage, stream, source, limits) {
140
+ return new Inbox(storage, stream, source, limits);
141
+ }
142
+ /** Internal replay boundary: one physical storage owner and matching logical stream.
143
+ * Namespace bytes are copied so callers cannot mutate Inbox identity. */
144
+ _replayTransact(writable, targetStorage, targetStreamId, program) {
145
+ if (targetStorage !== this.storage || targetStreamId !== this.stream)
146
+ fail('invalid', 'replay target must share Inbox storage and stream');
147
+ const key = this.#namespace.slice();
148
+ return this.storage.transact(writable, tx => program(tx, key));
149
+ }
150
+ #key(suffix) { return concat(this.#namespace, suffix); }
151
+ *#state(tx) {
152
+ const bytes = yield* tx.get(STATE, this.#namespace);
153
+ return bytes === undefined ? { cursor: null, nextSequence: 0n, retainedBytes: 0n } : decodeState(bytes);
154
+ }
155
+ async state() {
156
+ const self = this;
157
+ return this.storage.transact(false, function* (tx) { return yield* self.#state(tx); });
158
+ }
159
+ /** Successful receipt means only that exact bytes and cursor committed together.
160
+ * Exact historical retries do not rewind the head. Input length limits apply
161
+ * before retry detection; record/byte capacity applies only to new receipts. */
162
+ async receive(expectedPriorCursor, nextCursor, bytes) {
163
+ if (!(nextCursor instanceof Uint8Array) || !(bytes instanceof Uint8Array) || (expectedPriorCursor !== null && !(expectedPriorCursor instanceof Uint8Array)))
164
+ fail('invalid', 'cursor/payload must be bytes');
165
+ if (bytes.length > this.#limits.maxBatchBytes)
166
+ fail('invalid', 'batch length');
167
+ if (nextCursor.length > this.#limits.maxCursorBytes || (expectedPriorCursor?.length ?? 0) > this.#limits.maxCursorBytes)
168
+ fail('invalid', 'cursor length');
169
+ const prior = expectedPriorCursor === null ? null : new Uint8Array(expectedPriorCursor);
170
+ const next = new Uint8Array(nextCursor), raw = new Uint8Array(bytes);
171
+ const self = this;
172
+ return this.storage.transact(true, function* (tx) { return yield* self.#receive(tx, prior, next, raw); });
173
+ }
174
+ *#receive(tx, prior, next, raw) {
175
+ const key = this.#key(next);
176
+ const indexed = yield* tx.get(CURSORS, key);
177
+ if (indexed !== undefined) {
178
+ const seq = sequence(indexed);
179
+ const stored = yield* tx.get(RECORDS, this.#key(u64(seq)));
180
+ if (stored === undefined)
181
+ return fail('corrupt', 'cursor without record');
182
+ const record = decodeRecord(stored, seq);
183
+ if (equal(record.previousCursor, prior) && equal(record.nextCursor, next) && equal(record.bytes, raw))
184
+ return { kind: 'duplicate', sequence: seq };
185
+ return fail('conflict', 'cursor identifies a different receipt');
186
+ }
187
+ const state = yield* this.#state(tx);
188
+ if (!equal(state.cursor, prior))
189
+ return fail('stale', 'receive cursor changed');
190
+ if (equal(prior, next))
191
+ return fail('invalid', 'cursor must advance');
192
+ if (state.nextSequence >= this.#limits.maxRecords || state.nextSequence === U64_MAX)
193
+ return fail('capacity', 'record capacity');
194
+ const seq = state.nextSequence;
195
+ const recordKey = this.#key(u64(seq));
196
+ const recordValue = encodeRecord({ sequence: seq, previousCursor: prior, nextCursor: next, bytes: raw });
197
+ const added = BigInt(recordKey.length) + BigInt(recordValue.length) + BigInt(key.length) + 8n;
198
+ const retainedBytes = state.retainedBytes + added;
199
+ if (retainedBytes > this.#limits.maxRetainedBytes || retainedBytes > U64_MAX)
200
+ return fail('capacity', 'byte capacity');
201
+ yield* tx.put(RECORDS, recordKey, recordValue);
202
+ yield* tx.put(CURSORS, key, u64(seq));
203
+ yield* tx.put(STATE, this.#namespace, encodeState({ cursor: next, nextSequence: seq + 1n, retainedBytes }));
204
+ return { kind: 'received', sequence: seq };
205
+ }
206
+ /** Internal framing boundary; the two ledgers share an owner and route, never identity. */
207
+ _framingTransact(writable, derived, program) {
208
+ if (this.storage !== derived.storage || this.stream !== derived.stream || equal(this.#namespace, derived.#namespace))
209
+ fail('invalid', 'framing requires same storage/stream and different namespaces');
210
+ const view = (inbox, tx) => ({
211
+ namespace: inbox.#namespace.slice(),
212
+ state: () => inbox.#state(tx),
213
+ record: function* (seq) {
214
+ checkedU64(seq, 'record sequence');
215
+ const stored = yield* tx.get(RECORDS, inbox.#key(u64(seq)));
216
+ return stored === undefined ? undefined : decodeRecord(stored, seq);
217
+ },
218
+ receive: function* (prior, next, raw) {
219
+ if (!(next instanceof Uint8Array) || !(raw instanceof Uint8Array) || (prior !== null && !(prior instanceof Uint8Array)))
220
+ fail('invalid', 'cursor/payload must be bytes');
221
+ if (raw.length > inbox.#limits.maxBatchBytes)
222
+ fail('invalid', 'batch length');
223
+ if (next.length > inbox.#limits.maxCursorBytes || (prior?.length ?? 0) > inbox.#limits.maxCursorBytes)
224
+ fail('invalid', 'cursor length');
225
+ return yield* inbox.#receive(tx, prior === null ? null : new Uint8Array(prior), new Uint8Array(next), new Uint8Array(raw));
226
+ },
227
+ });
228
+ return this.storage.transact(writable, tx => program(tx, view(this, tx), view(derived, tx)));
229
+ }
230
+ /** Whether a receipt with exactly this cursor was ever persisted
231
+ * (read-only). The content-addressed history reader (N2) uses it to skip
232
+ * already-held batches without touching the receipt chain: its cursors
233
+ * are batch-content hashes, so presence is dedupe evidence. Mirror of
234
+ * `Inbox::contains_cursor` in src/inbox.rs. */
235
+ async containsCursor(cursor) {
236
+ if (!(cursor instanceof Uint8Array))
237
+ fail('invalid', 'cursor must be bytes');
238
+ if (cursor.length > this.#limits.maxCursorBytes)
239
+ fail('invalid', 'cursor length');
240
+ const key = this.#key(new Uint8Array(cursor));
241
+ return this.storage.transact(false, function* (tx) {
242
+ return (yield* tx.get(CURSORS, key)) !== undefined;
243
+ });
244
+ }
245
+ async records(afterSequence, limit) {
246
+ if (!Number.isSafeInteger(limit) || limit <= 0 || limit > this.#limits.maxPageRecords)
247
+ fail('invalid', 'page length');
248
+ if (afterSequence !== null)
249
+ checkedU64(afterSequence, 'afterSequence');
250
+ if (afterSequence === U64_MAX)
251
+ return [];
252
+ const start = this.#key(u64(afterSequence === null ? 0n : afterSequence + 1n)), self = this;
253
+ return this.storage.transact(false, function* (tx) {
254
+ const rows = yield* tx.scan(RECORDS, start, self.#end, limit);
255
+ return rows.map(([key, value]) => {
256
+ if (!equal(key.slice(0, self.#namespace.length), self.#namespace))
257
+ fail('corrupt', 'record namespace');
258
+ return decodeRecord(value, sequence(key.slice(self.#namespace.length)));
259
+ });
260
+ });
261
+ }
262
+ }
@@ -0,0 +1,9 @@
1
+ /** Application entry point. Experimental: pin the package and storage writer revision. */
2
+ export { IndexedDbStorage } from './indexeddb.js';
3
+ export { Identity } from './identity.js';
4
+ export { Store, Stream, Writer, StoreError, MAX_PAGE_HEADERS } from './store.js';
5
+ export type { StoreOptions, TurnSnapshot, TurnHeader, TurnReadResult, TurnHeaderResult, Verification, ParentConflict, ImportReport, ImportStatus, UpdateRef, Commit, Write, Event, EventRecord, MissingDependencies, StreamSnapshot, } from './store.js';
6
+ export { encodeJson, decodeJson } from './json.js';
7
+ export type { JsonValue, JsonNumber } from './json.js';
8
+ export { encodeBatch, decodeBatch } from './codec.js';
9
+ export type { ContentOp, ValuePath, PathSegment, ParentRef, Update } from './codec.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ /** Application entry point. Experimental: pin the package and storage writer revision. */
2
+ export { IndexedDbStorage } from './indexeddb.js';
3
+ export { Identity } from './identity.js';
4
+ export { Store, Stream, Writer, StoreError, MAX_PAGE_HEADERS } from './store.js';
5
+ export { encodeJson, decodeJson } from './json.js';
6
+ export { encodeBatch, decodeBatch } from './codec.js';
@@ -0,0 +1,38 @@
1
+ /** Experimental ordered byte KV boundary; not the eventual Roost message API. */
2
+ export type Row = readonly [Uint8Array, Uint8Array];
3
+ export type Step<T> = Generator<Operation, T, unknown>;
4
+ export type Program<T> = (tx: KvTransaction) => Step<T>;
5
+ export interface Operation {
6
+ readonly operation: unique symbol;
7
+ }
8
+ export declare class KvTransaction {
9
+ #private;
10
+ private readonly writable;
11
+ private readonly cancel;
12
+ constructor(writable: boolean, cancel: (error: unknown) => void);
13
+ /** Internal lifetime closure, never exposes the native transaction. */
14
+ finish(): void;
15
+ get(space: string, key: Uint8Array): Step<Uint8Array | undefined>;
16
+ put(space: string, key: Uint8Array, value: Uint8Array): Step<void>;
17
+ delete(space: string, key: Uint8Array): Step<void>;
18
+ /** Ascending byte order; start inclusive, end exclusive; bounded results. */
19
+ scan(space: string, start: Uint8Array, end: Uint8Array | undefined, limit: number): Step<Row[]>;
20
+ /** Descending byte order (newest first); end exclusive; bounded results. */
21
+ scanReverse(space: string, end: Uint8Array | undefined, limit: number): Step<Row[]>;
22
+ /** Aborts the whole program, including earlier successful requests. */
23
+ abort(message?: string): never;
24
+ }
25
+ /** One private v1 store containing all logical namespaces atomically. */
26
+ export declare class IndexedDbStorage {
27
+ #private;
28
+ private readonly db;
29
+ private constructor();
30
+ static open(name: string): Promise<IndexedDbStorage>;
31
+ get closed(): boolean;
32
+ /** Run once. Only yield* this transaction's operations; never await in the program.
33
+ * Resolves on native complete, rejects on abort, never on request success alone.
34
+ */
35
+ transact<T>(write: boolean, program: Program<T>): Promise<T>;
36
+ /** Reject new work immediately; let already-created transactions finish. */
37
+ close(): Promise<void>;
38
+ }
@@ -0,0 +1,299 @@
1
+ const operations = new WeakMap();
2
+ const bytes = (value) => new Uint8Array(value).buffer;
3
+ const failure = (name, message) => new DOMException(message, name);
4
+ export class KvTransaction {
5
+ writable;
6
+ cancel;
7
+ #live = true;
8
+ constructor(writable, cancel) {
9
+ this.writable = writable;
10
+ this.cancel = cancel;
11
+ }
12
+ /** Internal lifetime closure, never exposes the native transaction. */
13
+ finish() { this.#live = false; }
14
+ #check(write = false) {
15
+ if (!this.#live)
16
+ throw failure('TransactionInactiveError', 'transaction program has ended');
17
+ if (write && !this.writable)
18
+ throw failure('ReadOnlyError', 'read-only transaction');
19
+ }
20
+ *#step(run, write = false) {
21
+ this.#check(write);
22
+ const token = Object.freeze({});
23
+ operations.set(token, { owner: this, run });
24
+ return (yield token);
25
+ }
26
+ get(space, key) {
27
+ const copied = bytes(key);
28
+ return this.#step((store, done) => {
29
+ const request = store.get([space, copied]);
30
+ request.onsuccess = () => done(request.result === undefined ? undefined : new Uint8Array(request.result));
31
+ });
32
+ }
33
+ put(space, key, value) {
34
+ const copiedKey = bytes(key), copiedValue = bytes(value);
35
+ return this.#step((store, done) => {
36
+ const request = store.put(copiedValue, [space, copiedKey]);
37
+ request.onsuccess = () => done(undefined);
38
+ }, true);
39
+ }
40
+ delete(space, key) {
41
+ const copied = bytes(key);
42
+ return this.#step((store, done) => {
43
+ const request = store.delete([space, copied]);
44
+ request.onsuccess = () => done(undefined);
45
+ }, true);
46
+ }
47
+ /** Ascending byte order; start inclusive, end exclusive; bounded results. */
48
+ scan(space, start, end, limit) {
49
+ const low = bytes(start), high = end === undefined ? undefined : bytes(end);
50
+ return this.#step((store, done) => {
51
+ if (!Number.isSafeInteger(limit) || limit < 0)
52
+ throw new RangeError('limit must be a non-negative safe integer');
53
+ if (limit === 0 || (high !== undefined && indexedDB.cmp(low, high) >= 0)) {
54
+ done([]);
55
+ return;
56
+ }
57
+ // Array sorts after every binary key. No string successor or unbounded cross-space scan.
58
+ const range = IDBKeyRange.bound([space, low], [space, high ?? []], false, true);
59
+ const rows = [];
60
+ const request = store.openCursor(range);
61
+ request.onsuccess = () => {
62
+ const cursor = request.result;
63
+ if (!cursor) {
64
+ done(rows);
65
+ return;
66
+ }
67
+ const key = cursor.key;
68
+ rows.push([new Uint8Array(key[1]), new Uint8Array(cursor.value)]);
69
+ if (rows.length === limit)
70
+ done(rows);
71
+ else
72
+ cursor.continue();
73
+ };
74
+ });
75
+ }
76
+ /** Descending byte order (newest first); end exclusive; bounded results. */
77
+ scanReverse(space, end, limit) {
78
+ const high = end === undefined ? undefined : bytes(end);
79
+ return this.#step((store, done) => {
80
+ if (!Number.isSafeInteger(limit) || limit < 0)
81
+ throw new RangeError('limit must be a non-negative safe integer');
82
+ if (limit === 0) {
83
+ done([]);
84
+ return;
85
+ }
86
+ // Rows are [space, binary] keys. The lower bound [space] is a proper
87
+ // prefix of every row, so it admits this space only; with `end` the
88
+ // upper bound [space, end] is open (excluded); without one, the
89
+ // boundary [space, []] is closed and sits above every row (arrays sort
90
+ // after binary) and below greater spaces.
91
+ const range = IDBKeyRange.bound([space], [space, high ?? []], false, high !== undefined);
92
+ const rows = [];
93
+ const request = store.openCursor(range, 'prev');
94
+ request.onsuccess = () => {
95
+ const cursor = request.result;
96
+ if (!cursor) {
97
+ done(rows);
98
+ return;
99
+ }
100
+ const key = cursor.key;
101
+ rows.push([new Uint8Array(key[1]), new Uint8Array(cursor.value)]);
102
+ if (rows.length === limit)
103
+ done(rows);
104
+ else
105
+ cursor.continue();
106
+ };
107
+ });
108
+ }
109
+ /** Aborts the whole program, including earlier successful requests. */
110
+ abort(message = 'transaction aborted by caller') {
111
+ this.#check();
112
+ const error = failure('AbortError', message);
113
+ this.cancel(error);
114
+ throw error;
115
+ }
116
+ }
117
+ /** One private v1 store containing all logical namespaces atomically. */
118
+ export class IndexedDbStorage {
119
+ db;
120
+ #closed = false;
121
+ #pending = new Set();
122
+ #closing;
123
+ constructor(db) {
124
+ this.db = db;
125
+ db.onversionchange = () => { void this.close(); };
126
+ db.onclose = () => { this.#closed = true; };
127
+ }
128
+ static open(name) {
129
+ return new Promise((resolve, reject) => {
130
+ let abandoned = false;
131
+ const request = indexedDB.open(name, 2);
132
+ request.onblocked = () => {
133
+ abandoned = true;
134
+ reject(failure('InvalidStateError', 'database open blocked by another connection'));
135
+ };
136
+ request.onupgradeneeded = event => {
137
+ if (abandoned || (event.oldVersion !== 0 && event.oldVersion !== 1)) {
138
+ request.transaction.abort();
139
+ return;
140
+ }
141
+ if (event.oldVersion === 0) {
142
+ request.result.createObjectStore('kv');
143
+ }
144
+ else {
145
+ // Validate before committing the version upgrade: incompatible legacy
146
+ // layouts must remain untouched, including their database version.
147
+ const db = request.result;
148
+ if (db.objectStoreNames.length !== 1 || !db.objectStoreNames.contains('kv')) {
149
+ request.transaction.abort();
150
+ return;
151
+ }
152
+ const store = request.transaction.objectStore('kv');
153
+ if (store.keyPath !== null || store.autoIncrement || store.indexNames.length !== 0) {
154
+ request.transaction.abort();
155
+ return;
156
+ }
157
+ }
158
+ };
159
+ request.onerror = () => reject(request.error);
160
+ request.onsuccess = () => {
161
+ const db = request.result;
162
+ if (abandoned) {
163
+ db.close();
164
+ return;
165
+ }
166
+ if (db.objectStoreNames.length !== 1 || !db.objectStoreNames.contains('kv')) {
167
+ db.close();
168
+ reject(failure('VersionError', 'unsupported database layout'));
169
+ return;
170
+ }
171
+ const transaction = db.transaction('kv', 'readonly');
172
+ const store = transaction.objectStore('kv');
173
+ if (store.keyPath !== null || store.autoIncrement || store.indexNames.length !== 0) {
174
+ db.close();
175
+ reject(failure('VersionError', 'unsupported database layout'));
176
+ return;
177
+ }
178
+ const storage = new IndexedDbStorage(db);
179
+ transaction.oncomplete = () => resolve(storage);
180
+ transaction.onabort = () => { void storage.close(); reject(transaction.error); };
181
+ };
182
+ });
183
+ }
184
+ get closed() { return this.#closed; }
185
+ /** Run once. Only yield* this transaction's operations; never await in the program.
186
+ * Resolves on native complete, rejects on abort, never on request success alone.
187
+ */
188
+ transact(write, program) {
189
+ if (this.#closed)
190
+ return Promise.reject(failure('InvalidStateError', 'storage is closed'));
191
+ let resolve;
192
+ let reject;
193
+ const promise = new Promise((ok, no) => { resolve = ok; reject = no; });
194
+ // Register before invoking user code: it may itself call close().
195
+ this.#pending.add(promise);
196
+ void promise.then(() => this.#pending.delete(promise), () => this.#pending.delete(promise));
197
+ try {
198
+ const native = this.db.transaction('kv', write ? 'readwrite' : 'readonly', { durability: 'strict' });
199
+ const view = new KvTransaction(write, error => abort(error));
200
+ let result;
201
+ let ended = false;
202
+ let cause;
203
+ let failed = false;
204
+ let iterator;
205
+ const abort = (error) => {
206
+ if (!failed) {
207
+ failed = true;
208
+ cause = error;
209
+ }
210
+ view.finish();
211
+ try {
212
+ native.abort();
213
+ }
214
+ catch { /* oncomplete handles a late failure defensively */ }
215
+ };
216
+ native.onabort = () => { view.finish(); reject(failed ? cause : native.error ?? failure('AbortError', 'database transaction aborted')); };
217
+ native.onerror = () => { };
218
+ native.oncomplete = () => {
219
+ view.finish();
220
+ if (failed)
221
+ reject(cause);
222
+ else if (!ended)
223
+ reject(failure('TransactionInactiveError', 'program did not finish before commit'));
224
+ else
225
+ resolve(result);
226
+ };
227
+ const step = (value) => {
228
+ try {
229
+ const next = iterator.next(value);
230
+ if (next.done) {
231
+ if (next.value !== null && (typeof next.value === 'object' || typeof next.value === 'function') && 'then' in next.value) {
232
+ void Promise.resolve(next.value).catch(() => { });
233
+ throw new TypeError('transaction result cannot be a Promise');
234
+ }
235
+ result = next.value;
236
+ ended = true;
237
+ view.finish();
238
+ return;
239
+ }
240
+ const operation = typeof next.value === 'object' && next.value !== null ? operations.get(next.value) : undefined;
241
+ if (!operation || operation.owner !== view)
242
+ throw new TypeError('only this transaction\'s operations may be yielded');
243
+ operations.delete(next.value);
244
+ operation.run(native.objectStore('kv'), advance);
245
+ }
246
+ catch (error) {
247
+ abort(error);
248
+ }
249
+ };
250
+ // Empty scans finish synchronously. Trampoline them instead of recursing
251
+ // once per operation; real IDB results still resume in their success event.
252
+ let advancing = false;
253
+ let queued = false;
254
+ let input;
255
+ const advance = (value) => {
256
+ input = value;
257
+ queued = true;
258
+ if (advancing)
259
+ return;
260
+ advancing = true;
261
+ try {
262
+ while (queued && !ended && !failed) {
263
+ queued = false;
264
+ step(input);
265
+ }
266
+ }
267
+ finally {
268
+ advancing = false;
269
+ }
270
+ };
271
+ try {
272
+ iterator = program(view);
273
+ if (!iterator || typeof iterator.next !== 'function' || Symbol.asyncIterator in iterator) {
274
+ // Reject async callbacks, including their eventual rejection, without allowing commit.
275
+ if (iterator && typeof iterator.catch === 'function')
276
+ void iterator.catch(() => { });
277
+ throw new TypeError('transaction program must be a synchronous generator');
278
+ }
279
+ advance();
280
+ }
281
+ catch (error) {
282
+ abort(error);
283
+ }
284
+ }
285
+ catch (error) {
286
+ reject(error);
287
+ }
288
+ return promise;
289
+ }
290
+ /** Reject new work immediately; let already-created transactions finish. */
291
+ close() {
292
+ if (!this.#closing) {
293
+ this.#closed = true;
294
+ this.db.close();
295
+ this.#closing = Promise.allSettled([...this.#pending]).then(() => { });
296
+ }
297
+ return this.#closing;
298
+ }
299
+ }
package/dist/json.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ /** Lossless internal JSON, not a native-JS-number interoperability contract. */
2
+ export type JsonNumber = {
3
+ kind: 'u64' | 'i64';
4
+ value: bigint;
5
+ } | {
6
+ kind: 'f64';
7
+ value: number;
8
+ };
9
+ export type JsonValue = null | boolean | string | JsonNumber | JsonValue[] | Map<string, JsonValue>;
10
+ export declare const MAX_JSON_DEPTH = 127;
11
+ export declare const MAX_JSON_BYTES: number;
12
+ export declare const U64_MAX: bigint;
13
+ export declare function assertScalars(value: string): void;
14
+ export declare function encodeUtf8(value: string): Uint8Array;
15
+ export declare function decodeUtf8(value: Uint8Array): string;
16
+ export declare function compareScalarKeys(a: string, b: string): number;
17
+ /** Shortest IEEE digits with zmij 1.0.23's f64 presentation, including float .0.
18
+ * Number#toString supplies correctly rounded shortest digits; JSON.stringify
19
+ * does not supply the required integer/float distinction or exponent layout.
20
+ */
21
+ export declare function formatFloat(value: number): string;
22
+ export declare function encodeJson(value: JsonValue): Uint8Array;
23
+ export declare function decodeJson(bytes: Uint8Array): JsonValue;