sproutboat 0.27.0 → 0.29.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 (36) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/SURFACE.md +4 -4
  3. package/THIRD_PARTY_NOTICES.md +9 -0
  4. package/package.json +8 -8
  5. package/src/build.ts +12 -2
  6. package/src/compile.ts +23 -1
  7. package/src/main.ts +13 -2
  8. package/src/native-restore-sources.ts +48 -0
  9. package/src/native-restore.ts +155 -0
  10. package/src/surface.ts +3 -3
  11. package/vendor/ltx-restore/LICENSE +202 -0
  12. package/vendor/ltx-restore/NOTICE +32 -0
  13. package/vendor/ltx-restore/crc64-native.ts.txt +7 -0
  14. package/vendor/ltx-restore/errors.ts.txt +74 -0
  15. package/vendor/ltx-restore/file-io.ts.txt +54 -0
  16. package/vendor/ltx-restore/ltx/byte-reader.ts.txt +46 -0
  17. package/vendor/ltx-restore/ltx/bytes.ts.txt +87 -0
  18. package/vendor/ltx-restore/ltx/checksum.ts.txt +46 -0
  19. package/vendor/ltx-restore/ltx/constants.ts.txt +71 -0
  20. package/vendor/ltx-restore/ltx/crc64.ts.txt +73 -0
  21. package/vendor/ltx-restore/ltx/decoder.ts.txt +285 -0
  22. package/vendor/ltx-restore/ltx/header.ts.txt +126 -0
  23. package/vendor/ltx-restore/ltx/lz4.ts.txt +260 -0
  24. package/vendor/ltx-restore/ltx/page-index.ts.txt +140 -0
  25. package/vendor/ltx-restore/ltx/page.ts.txt +80 -0
  26. package/vendor/ltx-restore/ltx/sink.ts.txt +33 -0
  27. package/vendor/ltx-restore/ltx/trailer.ts.txt +58 -0
  28. package/vendor/ltx-restore/ltx/types.ts.txt +152 -0
  29. package/vendor/ltx-restore/lz4js/README.md +39 -0
  30. package/vendor/ltx-restore/lz4js/lz4.js.txt +560 -0
  31. package/vendor/ltx-restore/lz4js/package.json +36 -0
  32. package/vendor/ltx-restore/lz4js/util.js.txt +54 -0
  33. package/vendor/ltx-restore/lz4js/xxh32.js.txt +102 -0
  34. package/vendor/ltx-restore/program.ts.txt +3 -0
  35. package/vendor/ltx-restore/restore-native.ts.txt +120 -0
  36. package/vendor/ltx-restore/restore.ts.txt +96 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,32 @@
1
+ sqlite-js-stream
2
+ Copyright Platformatic
3
+
4
+ This product is a port of Litestream:
5
+
6
+ Litestream
7
+ https://github.com/benbjohnson/litestream
8
+ Copyright 2018-2025 Ben Johnson
9
+ Licensed under the Apache License, Version 2.0.
10
+
11
+ The LTX file format and related design are derived from:
12
+
13
+ ltx (superfly) - https://github.com/superfly/ltx
14
+ Copyright the ltx authors
15
+ Licensed under the Apache License, Version 2.0.
16
+
17
+ This product includes adaptations of documentation from the litestream repository
18
+ (docs/ARCHITECTURE.md, docs/SQLITE_INTERNALS.md, docs/LTX_FORMAT.md, docs/PATTERNS.md),
19
+ used under the Apache License, Version 2.0, with attribution.
20
+
21
+ Portions of the WAL / LTX format descriptions are based on the SQLite documentation
22
+ (https://www.sqlite.org/wal.html), which is in the public domain.
23
+
24
+ Workspace modifications to ltx/crc64.ts include the two-word CRC reference loop
25
+ and an optional bridge to Sproutboat's existing native capture CRC kernel.
26
+ The bridge is prototype code by OpenAI Codex (GPT-6.1), not an upstream API.
27
+
28
+ Native restore adaptation in Sproutboat CLI:
29
+ - Streaming reader and bounded decoder, checksum and native bytes ABI integration.
30
+ - Separate trusted startup/controller and publication checks.
31
+ AI assistance: OpenAI Codex (GPT-6.1).
32
+ Upstream snapshot: platformatic/sqlite-js-stream a5b830d5f1e408c54a04285c2199019b40154c25.
@@ -0,0 +1,7 @@
1
+ declare function __Porffor_sproutboat_crc64_v1(state: Uint8Array, data: Uint8Array, offset: number, length: number): void;
2
+
3
+ // The compiler owns the versioned view validation and CRC boundary.
4
+ // Only the trusted restore build enables --sb-native-bytes-v1.
5
+ export function updateNativeCrc64(state: Uint8Array, data: Uint8Array): void {
6
+ __Porffor_sproutboat_crc64_v1(state, data, 0, data.length);
7
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Shared error base for sqlite-js-stream.
3
+ *
4
+ * Every typed library error extends {@link SqliteJsStreamError} and carries a
5
+ * stable, Node-style `code` string (e.g. `ERR_NO_MATCHING_BACKUP`). This lets
6
+ * callers catch any library error with a single `instanceof`, and branch on the
7
+ * precise failure via `err.code` without matching message text.
8
+ */
9
+ export class SqliteJsStreamError extends Error {
10
+ /** Stable, machine-readable error code (Node.js convention). */
11
+ readonly code: string;
12
+
13
+ constructor(code: string, message: string) {
14
+ super(message);
15
+ this.name = 'SqliteJsStreamError';
16
+ this.code = code;
17
+ }
18
+ }
19
+
20
+ /** A required function argument is missing or invalid (`ERR_INVALID_ARGUMENT`). */
21
+ export class InvalidArgumentError extends SqliteJsStreamError {
22
+ constructor(message: string) {
23
+ super('ERR_INVALID_ARGUMENT', message);
24
+ this.name = 'InvalidArgumentError';
25
+ }
26
+ }
27
+
28
+ /** An incremental LTX file's page size differs from the base database. */
29
+ export class PageSizeMismatchError extends SqliteJsStreamError {
30
+ constructor(message: string) {
31
+ super('ERR_PAGE_SIZE_MISMATCH', message);
32
+ this.name = 'PageSizeMismatchError';
33
+ }
34
+ }
35
+
36
+ /** An LTX file is malformed/corrupt or violates the format (`ERR_LTX_FORMAT`). */
37
+ export class LTXFormatError extends SqliteJsStreamError {
38
+ constructor(message: string) {
39
+ super('ERR_LTX_FORMAT', message);
40
+ this.name = 'LTXFormatError';
41
+ }
42
+ }
43
+
44
+ /** A SQLite WAL file is malformed/corrupt (`ERR_WAL_FORMAT`). */
45
+ export class WALFormatError extends SqliteJsStreamError {
46
+ constructor(message: string) {
47
+ super('ERR_WAL_FORMAT', message);
48
+ this.name = 'WALFormatError';
49
+ }
50
+ }
51
+
52
+ /** A replica URL is malformed or uses an unsupported scheme (`ERR_REPLICA_URL`). */
53
+ export class ReplicaURLError extends SqliteJsStreamError {
54
+ constructor(message: string) {
55
+ super('ERR_REPLICA_URL', message);
56
+ this.name = 'ReplicaURLError';
57
+ }
58
+ }
59
+
60
+ /** A file/backend replica operation failed (`ERR_FILE_REPLICA`). */
61
+ export class FileReplicaError extends SqliteJsStreamError {
62
+ constructor(message: string) {
63
+ super('ERR_FILE_REPLICA', message);
64
+ this.name = 'FileReplicaError';
65
+ }
66
+ }
67
+
68
+ /** A SQLite database file is missing/invalid or could not be read (`ERR_DATABASE`). */
69
+ export class DatabaseError extends SqliteJsStreamError {
70
+ constructor(message: string) {
71
+ super('ERR_DATABASE', message);
72
+ this.name = 'DatabaseError';
73
+ }
74
+ }
@@ -0,0 +1,54 @@
1
+ import { ByteReader } from './ltx/byte-reader.ts';
2
+
3
+ // Explicit build-only ABI. The toolchain validates buffers, paths and offsets.
4
+ declare function __Porffor_sproutboat_file_ctl_v1(operation: number, path: string, fd: number, position: number): number;
5
+ declare function __Porffor_sproutboat_file_io_v1(operation: number, fd: number, data: Uint8Array, offset: number, length: number, position: number): number;
6
+
7
+ export class FileSink {
8
+ fd: number;
9
+ pos = 0;
10
+ constructor(path: string) {
11
+ this.fd = __Porffor_sproutboat_file_ctl_v1(1, path, 0, 0);
12
+ if (this.fd < 0) throw new Error('cannot open output');
13
+ }
14
+ write(data: Uint8Array): void {
15
+ if (__Porffor_sproutboat_file_io_v1(1, this.fd, data, 0, data.length, this.pos) !== data.length) throw new Error('short file write');
16
+ this.pos += data.length;
17
+ }
18
+ sync(): void { if (__Porffor_sproutboat_file_ctl_v1(4, '', this.fd, 0) !== 0) throw new Error('fsync failed'); }
19
+ readAt(data: Uint8Array, offset: number): void {
20
+ if (__Porffor_sproutboat_file_io_v1(0, this.fd, data, 0, data.length, offset) !== data.length) throw new Error('short output read');
21
+ }
22
+ writeAt(data: Uint8Array, offset: number): void {
23
+ if (__Porffor_sproutboat_file_io_v1(1, this.fd, data, 0, data.length, offset) !== data.length) throw new Error('short output write');
24
+ }
25
+ truncate(size: number): void {
26
+ if (__Porffor_sproutboat_file_ctl_v1(5, '', this.fd, size) !== 0) throw new Error('truncate failed');
27
+ this.pos = size;
28
+ }
29
+ close(): void { if (this.fd >= 0) { __Porffor_sproutboat_file_ctl_v1(3, '', this.fd, 0); this.fd = -1; } }
30
+ }
31
+
32
+ export class FileReader extends ByteReader {
33
+ fd: number;
34
+ private size: number;
35
+ constructor(path: string) {
36
+ super(new Uint8Array(0));
37
+ this.fd = __Porffor_sproutboat_file_ctl_v1(0, path, 0, 0);
38
+ if (this.fd < 0) throw new Error('cannot open input');
39
+ this.size = __Porffor_sproutboat_file_ctl_v1(2, '', this.fd, 0);
40
+ if (this.size < 0) { this.close(); throw new Error('cannot stat input'); }
41
+ }
42
+ get length(): number { return this.size; }
43
+ get remaining(): number { return this.size - this.pos; }
44
+ slice(start: number, end: number): Uint8Array {
45
+ const n = end - start;
46
+ if (start < 0 || n < 0 || n > 131072 || end > this.size) throw new Error('invalid bounded file read');
47
+ const data = new Uint8Array(n);
48
+ if (__Porffor_sproutboat_file_io_v1(0, this.fd, data, 0, data.length, start) !== n) throw new Error('short file read');
49
+ return data;
50
+ }
51
+ readFull(n: number): Uint8Array { const data = this.slice(this.pos, this.pos + n); this.pos += n; return data; }
52
+ readByte(): number { return this.readFull(1)[0]; }
53
+ close(): void { if (this.fd >= 0) { __Porffor_sproutboat_file_ctl_v1(3, '', this.fd, 0); this.fd = -1; } }
54
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A sequential byte reader over an in-memory buffer. Used by the LTX decoder
3
+ * to walk the page block, page index, and trailer while tracking position.
4
+ */
5
+
6
+ import { assertFull } from './bytes.ts';
7
+ import { LTXFormatError } from '../errors.ts';
8
+
9
+ export class ByteReader {
10
+ private buf: Uint8Array;
11
+ pos: number;
12
+
13
+ constructor(buf: Uint8Array, start = 0) {
14
+ this.buf = buf;
15
+ this.pos = start;
16
+ }
17
+
18
+ get length(): number {
19
+ return this.buf.length;
20
+ }
21
+
22
+ get remaining(): number {
23
+ return this.buf.length - this.pos;
24
+ }
25
+
26
+ /** Reads one byte, advancing the position. Throws on EOF. */
27
+ readByte(): number {
28
+ if (this.pos >= this.buf.length) {
29
+ throw new LTXFormatError('unexpected end of input');
30
+ }
31
+ return this.buf[this.pos++];
32
+ }
33
+
34
+ /** Reads exactly `n` bytes, advancing the position. Throws on short input. */
35
+ readFull(n: number): Uint8Array {
36
+ assertFull(this.buf, this.pos, n);
37
+ const out = this.buf.subarray(this.pos, this.pos + n);
38
+ this.pos += n;
39
+ return out;
40
+ }
41
+
42
+ /** Returns a view of the bytes in [start, end) without moving the position. */
43
+ slice(start: number, end: number): Uint8Array {
44
+ return this.buf.subarray(start, end);
45
+ }
46
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Big-endian byte helpers for LTX marshalling.
3
+ */
4
+
5
+ export function writeU8(buf: Uint8Array, off: number, v: number): void {
6
+ buf[off] = v & 0xff;
7
+ }
8
+
9
+ export function writeU16BE(buf: Uint8Array, off: number, v: number): void {
10
+ buf[off] = (v >>> 8) & 0xff;
11
+ buf[off + 1] = v & 0xff;
12
+ }
13
+
14
+ export function writeU32BE(buf: Uint8Array, off: number, v: number): void {
15
+ buf[off] = (v >>> 24) & 0xff;
16
+ buf[off + 1] = (v >>> 16) & 0xff;
17
+ buf[off + 2] = (v >>> 8) & 0xff;
18
+ buf[off + 3] = v & 0xff;
19
+ }
20
+
21
+ export function writeU64BE(buf: Uint8Array, off: number, v: bigint): void {
22
+ let n = v;
23
+ for (let i = 0; i < 8; i++) {
24
+ buf[off + (7 - i)] = Number(n & 0xffn);
25
+ n >>= 8n;
26
+ }
27
+ }
28
+
29
+ export function readU16BE(buf: Uint8Array, off: number): number {
30
+ return (buf[off] << 8) | buf[off + 1];
31
+ }
32
+
33
+ export function readU32BE(buf: Uint8Array, off: number): number {
34
+ return (
35
+ ((buf[off] | 0) << 24) >>> 0 |
36
+ (buf[off + 1] << 16) |
37
+ (buf[off + 2] << 8) |
38
+ buf[off + 3]
39
+ ) >>> 0;
40
+ }
41
+
42
+ export function readU32LE(buf: Uint8Array, off: number): number {
43
+ return (
44
+ buf[off] |
45
+ (buf[off + 1] << 8) |
46
+ (buf[off + 2] << 16) |
47
+ ((buf[off + 3] | 0) << 24)
48
+ ) >>> 0;
49
+ }
50
+
51
+ export function readU64BE(buf: Uint8Array, off: number): bigint {
52
+ let n = 0n;
53
+ for (let i = 0; i < 8; i++) {
54
+ n = (n << 8n) | BigInt(buf[off + i]);
55
+ }
56
+ return n;
57
+ }
58
+
59
+ /** Converts a number to a big-endian 4-byte array. */
60
+ export function u32BE(v: number): Uint8Array {
61
+ const b = new Uint8Array(4);
62
+ writeU32BE(b, 0, v);
63
+ return b;
64
+ }
65
+
66
+ /** Converts a number to a big-endian 8-byte array. */
67
+ export function u64BE(v: bigint): Uint8Array {
68
+ const b = new Uint8Array(8);
69
+ writeU64BE(b, 0, v);
70
+ return b;
71
+ }
72
+
73
+ /** Converts a number to a big-endian 2-byte array. */
74
+ export function u16BE(v: number): Uint8Array {
75
+ const b = new Uint8Array(2);
76
+ writeU16BE(b, 0, v);
77
+ return b;
78
+ }
79
+
80
+ /** Throws unless exactly `n` bytes are available to read. */
81
+ export function assertFull(buf: Uint8Array, off: number, n: number): void {
82
+ if (off + n > buf.length) {
83
+ throw new RangeError(
84
+ `short buffer: need ${n} bytes at offset ${off}, have ${buf.length - off}`,
85
+ );
86
+ }
87
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * LTX checksum helpers: per-page checksums and the rolling DB checksum.
3
+ */
4
+
5
+ import { ChecksumFlag, lockPgno } from './constants.ts';
6
+ import { Crc64 } from './crc64.ts';
7
+ import { u32BE } from './bytes.ts';
8
+
9
+ /**
10
+ * ChecksumPage returns a CRC-64 checksum that combines the page number with
11
+ * the page data: `ChecksumFlag | CRC64-ISO(pgno_be4 ++ data)`.
12
+ */
13
+ export function checksumPage(pgno: number, data: Uint8Array): bigint {
14
+ const h = new Crc64();
15
+ h.update(u32BE(pgno));
16
+ h.update(data);
17
+ return ChecksumFlag | h.sum64();
18
+ }
19
+
20
+ export function checksumPageWithHasher(h: Crc64, pgno: number, data: Uint8Array): bigint {
21
+ h.reset();
22
+ h.update(u32BE(pgno));
23
+ h.update(data);
24
+ return ChecksumFlag | h.sum64();
25
+ }
26
+
27
+ /**
28
+ * ChecksumReader computes the rolling DB checksum over a byte buffer split
29
+ * into pages of `pageSize`. The "lock page" is skipped entirely (its checksum
30
+ * contributes nothing), matching Go's `ChecksumReader`.
31
+ *
32
+ * For large databases this should later read page-by-page from a file rather
33
+ * than buffering the whole DB; provided as a buffer for Milestone 1.
34
+ */
35
+ export function checksumReader(data: Uint8Array, pageSize: number): bigint {
36
+ const lockPg = lockPgno(pageSize);
37
+ let chksum = 0n;
38
+ let offset = 0;
39
+ for (let pgno = 1; offset < data.length; pgno++, offset += pageSize) {
40
+ const page = data.subarray(offset, offset + pageSize);
41
+ if (pgno !== lockPg) {
42
+ chksum = ChecksumFlag | (chksum ^ checksumPage(pgno, page));
43
+ }
44
+ }
45
+ return chksum;
46
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * LTX format constants.
3
+ *
4
+ * Ground truth: superfly/ltx v0.5.2 (vendored by litestream). The byte layout
5
+ * here must match Go's `ltx` package exactly so files interoperate.
6
+ */
7
+
8
+ /** Magic is the first 4 bytes of every LTX file. */
9
+ export const Magic = 'LTX1';
10
+
11
+ /** Version is the current version of the LTX file format. */
12
+ export const Version = 3;
13
+
14
+ /** Size constants. */
15
+ export const HeaderSize = 100;
16
+ export const PageHeaderSize = 6;
17
+ export const TrailerSize = 16;
18
+
19
+ /** Checksum size & positions. */
20
+ export const ChecksumSize = 8;
21
+ export const TrailerChecksumOffset = TrailerSize - ChecksumSize;
22
+
23
+ /** ChecksumFlag ensures a checksum is non-zero. */
24
+ export const ChecksumFlag = 1n << 63n;
25
+
26
+ /** Entry byte offset of the PENDING_BYTE within a database. */
27
+ export const PENDING_BYTE = 0x40000000;
28
+
29
+ /** Header flags. */
30
+ export const HeaderFlagMask = 0x00000002;
31
+ export const HeaderFlagNoChecksum = 0x00000002;
32
+
33
+ /** Page header flags. */
34
+ /** PageHeaderFlagSize indicates a 4-byte size field follows the page header. */
35
+ export const PageHeaderFlagSize = 0x0001;
36
+
37
+ /** MaxPageSize is the maximum allowed SQLite page size. */
38
+ export const MaxPageSize = 65536;
39
+
40
+ /** SnapshotLevel is the LTX level reserved for full-database snapshots. */
41
+ export const SnapshotLevel = 9;
42
+
43
+ /** Error messages / codes. */
44
+ export const ErrInvalidFile = 'invalid LTX file';
45
+ export const ErrDecoderClosed = 'ltx decoder closed';
46
+ export const ErrEncoderClosed = 'ltx encoder closed';
47
+ export const ErrEncoderAborted = 'ltx encoder aborted';
48
+ export const ErrNoChecksum = 'no file checksum';
49
+ export const ErrInvalidChecksumFormat = 'invalid file checksum format';
50
+ export const ErrChecksumMismatch = 'file checksum mismatch';
51
+
52
+ /**
53
+ * LockPgno returns the page number at which the PENDING_BYTE exists.
54
+ * This page is never part of the LTX payload.
55
+ */
56
+ export function lockPgno(pageSize: number): number {
57
+ return Math.floor(PENDING_BYTE / pageSize) + 1;
58
+ }
59
+
60
+ /** IsValidPageSize returns true if sz is between 512 and 64K and a power of two. */
61
+ export function isValidPageSize(sz: number): boolean {
62
+ for (let i = 512; i <= MaxPageSize; i *= 2) {
63
+ if (sz === i) return true;
64
+ }
65
+ return false;
66
+ }
67
+
68
+ /** IsValidHeaderFlags returns true unless flags outside the valid mask are set. */
69
+ export function isValidHeaderFlags(flags: number): boolean {
70
+ return flags === (flags & HeaderFlagMask);
71
+ }