rida-format 0.0.0-stage → 2.0.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.
package/src/index.js ADDED
@@ -0,0 +1,360 @@
1
+ import { createDecipheriv, createHash } from "node:crypto";
2
+ import { open, readFile } from "node:fs/promises";
3
+ import { basename, dirname, extname, join, parse } from "node:path";
4
+ import { createRequire } from "node:module";
5
+ import { inflateRawSync } from "node:zlib";
6
+
7
+ const require = createRequire(import.meta.url);
8
+ const lzma = require("lzma-native");
9
+
10
+ export const version = "2.0.0";
11
+ export const MERGE_GAP_LIMIT = 660;
12
+ const INDEX_MAGIC = Buffer.from("RIDAIDX1");
13
+ const CATALOG_MAGIC = Buffer.from("RDACAT01");
14
+
15
+ export class RidaError extends Error {
16
+ constructor(message, options) { super(message, options); this.name = "RidaError"; }
17
+ }
18
+
19
+ function need(condition, message) {
20
+ if (!condition) throw new RidaError(message);
21
+ }
22
+
23
+ function readVarint(bytes, start) {
24
+ let value = 0n;
25
+ let shift = 0n;
26
+ let pos = start;
27
+ while (pos < bytes.length && shift <= 63n) {
28
+ const byte = bytes[pos++];
29
+ value |= BigInt(byte & 0x7f) << shift;
30
+ if (!(byte & 0x80)) {
31
+ need(value <= BigInt(Number.MAX_SAFE_INTEGER), "RIDA catalog offset is too large for this Node.js runtime");
32
+ return [Number(value), pos];
33
+ }
34
+ shift += 7n;
35
+ }
36
+ throw new RidaError("Invalid variable-length value in RIDA catalog");
37
+ }
38
+
39
+ function parseIndex(raw) {
40
+ need(raw.length >= 72, "RIDA index is incomplete");
41
+ need(raw.subarray(0, 8).equals(INDEX_MAGIC), "Unsupported or invalid RIDA index");
42
+ const versionNo = raw.readUInt32BE(8);
43
+ const catalogLength = raw.readUInt32BE(12);
44
+ const rawCatalogLength = raw.readUInt32BE(16);
45
+ const recordCount = raw.readUInt32BE(20);
46
+ const dataLengthBig = raw.readBigUInt64BE(24);
47
+ need(versionNo === 1, `Unsupported RIDA index version: ${versionNo}`);
48
+ need(dataLengthBig <= BigInt(Number.MAX_SAFE_INTEGER), "RIDA data file is too large for this Node.js runtime");
49
+ const codecNo = raw.readUInt32BE(32);
50
+ need(codecNo === 1 || codecNo === 2, "RIDA index has an unknown value codec");
51
+ const catalog = raw.subarray(72);
52
+ need(catalog.length === catalogLength, "RIDA catalog is incomplete");
53
+ return {
54
+ info: {
55
+ version: 3,
56
+ indexVersion: versionNo,
57
+ recordCount,
58
+ dataLength: Number(dataLengthBig),
59
+ valueCodec: codecNo === 1 ? "deflate-per-field" : "plain",
60
+ encrypted: Boolean(raw.readUInt32BE(36) & 1),
61
+ digest: Buffer.from(raw.subarray(40, 72)),
62
+ catalogLength,
63
+ rawCatalogLength,
64
+ },
65
+ catalog,
66
+ };
67
+ }
68
+
69
+ async function parseCatalog(compressed, info) {
70
+ let raw;
71
+ try { raw = await lzma.decompress(compressed); }
72
+ catch (cause) { throw new RidaError("RIDA catalog cannot be decompressed", { cause }); }
73
+ raw = Buffer.from(raw);
74
+ need(raw.length === info.rawCatalogLength, "RIDA catalog length does not match its index");
75
+ need(raw.length >= 44 && raw.subarray(0, 8).equals(CATALOG_MAGIC), "Unsupported or invalid RIDA catalog");
76
+ need(raw.readUInt32BE(8) === 1, "Unsupported RIDA catalog version");
77
+ const modeCode = raw.readUInt32BE(12);
78
+ need(modeCode === 1 || modeCode === 2, "RIDA catalog has an invalid index mode");
79
+ const recordCountBig = raw.readBigUInt64BE(16);
80
+ need(recordCountBig === BigInt(info.recordCount), "RIDA record count does not match its catalog");
81
+ const fieldCount = raw.readUInt32BE(24);
82
+ const schemaLength = raw.readUInt32BE(28);
83
+ const idsLength = raw.readUInt32BE(32);
84
+ const rowsLengthBig = raw.readBigUInt64BE(36);
85
+ need(rowsLengthBig <= BigInt(Number.MAX_SAFE_INTEGER), "RIDA catalog is too large for this Node.js runtime");
86
+ const rowsLength = Number(rowsLengthBig);
87
+ const expected = 44 + schemaLength + idsLength + (info.recordCount + 1) * 8 + rowsLength;
88
+ need(raw.length === expected, "RIDA catalog layout is invalid");
89
+ const schemaEnd = 44 + schemaLength;
90
+ let fields;
91
+ let ids;
92
+ try {
93
+ fields = JSON.parse(raw.subarray(44, schemaEnd).toString("utf8"));
94
+ ids = idsLength ? JSON.parse(raw.subarray(schemaEnd, schemaEnd + idsLength).toString("utf8")) : [];
95
+ } catch (cause) { throw new RidaError("RIDA catalog JSON is invalid", { cause }); }
96
+ need(Array.isArray(fields) && fields.length === fieldCount && fields.every((x) => typeof x === "string") && new Set(fields).size === fields.length, "RIDA field dictionary is invalid");
97
+ need(Array.isArray(ids) && (ids.length === 0 || ids.length === info.recordCount) && ids.every((x) => typeof x === "string") && new Set(ids).size === ids.length, "RIDA record-ID dictionary is invalid");
98
+ const offsetsStart = schemaEnd + idsLength;
99
+ const rowDataStart = offsetsStart + (info.recordCount + 1) * 8;
100
+ const rowOffsets = [];
101
+ for (let n = 0; n <= info.recordCount; n++) {
102
+ const value = raw.readBigUInt64BE(offsetsStart + n * 8);
103
+ need(value <= BigInt(rowsLength), "RIDA row offset is out of bounds");
104
+ rowOffsets.push(Number(value));
105
+ }
106
+ need(rowOffsets[0] === 0 && rowOffsets.at(-1) === rowsLength, "RIDA row offsets are incomplete");
107
+ for (let n = 1; n < rowOffsets.length; n++) need(rowOffsets[n] >= rowOffsets[n - 1], "RIDA row offsets are not ordered");
108
+ return { raw, fields, fieldIds: new Map(fields.map((name, i) => [name, i])), ids, idToRecord: ids.length ? new Map(ids.map((id, i) => [id, i])) : null, mode: modeCode === 1 ? "dense" : "sparse", recordCount: info.recordCount, rowOffsets, rowDataStart };
109
+ }
110
+
111
+ function getRecordNumber(catalog, recordId) {
112
+ const id = String(recordId);
113
+ if (catalog.idToRecord) {
114
+ const n = catalog.idToRecord.get(id);
115
+ if (n === undefined) throw new RangeError(`Unknown RIDA record ID: ${id}`);
116
+ return n;
117
+ }
118
+ if (!/^[1-9]\d*$/.test(id)) throw new RangeError(`Unknown RIDA record ID: ${id}`);
119
+ const n = Number(id) - 1;
120
+ if (!Number.isSafeInteger(n) || n < 0 || n >= catalog.recordCount) throw new RangeError(`Unknown RIDA record ID: ${id}`);
121
+ return n;
122
+ }
123
+
124
+ function locate(catalog, recordId, wantedNames) {
125
+ const rowNo = getRecordNumber(catalog, recordId);
126
+ const start = catalog.rowOffsets[rowNo];
127
+ const end = catalog.rowOffsets[rowNo + 1];
128
+ const row = catalog.raw.subarray(catalog.rowDataStart + start, catalog.rowDataStart + end);
129
+ let [dataOffset, pos] = readVarint(row, 0);
130
+ const wanted = new Map();
131
+ for (const name of new Set(wantedNames)) {
132
+ const id = catalog.fieldIds.get(name);
133
+ if (id === undefined) throw new RangeError(`Unknown RIDA field: ${name}`);
134
+ wanted.set(id, name);
135
+ }
136
+ const found = new Map();
137
+ if (catalog.mode === "dense") {
138
+ for (let fieldId = 0, valueOffset = dataOffset; fieldId < catalog.fields.length; fieldId++) {
139
+ let length; [length, pos] = readVarint(row, pos);
140
+ if (length) {
141
+ const name = wanted.get(fieldId);
142
+ if (name !== undefined) found.set(name, [valueOffset, length]);
143
+ valueOffset += length;
144
+ }
145
+ }
146
+ return found;
147
+ }
148
+ let count; [count, pos] = readVarint(row, pos);
149
+ let fieldId = 0;
150
+ for (let i = 0; i < count; i++) {
151
+ let delta; [delta, pos] = readVarint(row, pos);
152
+ let length; [length, pos] = readVarint(row, pos);
153
+ need(!(i > 0 && delta === 0) && length > 0, "RIDA sparse row is invalid");
154
+ fieldId += delta;
155
+ need(fieldId < catalog.fields.length, "RIDA sparse field ID is out of range");
156
+ const name = wanted.get(fieldId);
157
+ if (name !== undefined) found.set(name, [dataOffset, length]);
158
+ dataOffset += length;
159
+ }
160
+ return found;
161
+ }
162
+
163
+ function normalizeKey(key) {
164
+ if (key == null) return null;
165
+ if (Buffer.isBuffer(key) || key instanceof Uint8Array) {
166
+ const result = Buffer.from(key);
167
+ need(result.length === 32, "RIDA encryption key must be exactly 32 bytes");
168
+ return result;
169
+ }
170
+ const text = String(key).trim();
171
+ let result;
172
+ try { result = Buffer.from(text, "base64"); } catch { result = Buffer.alloc(0); }
173
+ if (result.length !== 32) result = Buffer.from(text, "hex");
174
+ need(result.length === 32, "RIDA key must be 32 bytes or its base64/hex text form");
175
+ return result;
176
+ }
177
+
178
+ function decodeValue(bytes, info, key) {
179
+ let raw = bytes;
180
+ if (info.encrypted) {
181
+ need(key, "This RIDA file is encrypted; provide its private key");
182
+ need(raw.length >= 28, "Encrypted RIDA value is incomplete");
183
+ const decipher = createDecipheriv("aes-256-gcm", key, raw.subarray(0, 12));
184
+ decipher.setAuthTag(raw.subarray(raw.length - 16));
185
+ try { raw = Buffer.concat([decipher.update(raw.subarray(12, -16)), decipher.final()]); }
186
+ catch (cause) { throw new RidaError("RIDA field value could not be decrypted", { cause }); }
187
+ }
188
+ if (info.valueCodec === "deflate-per-field") {
189
+ try { raw = inflateRawSync(raw); }
190
+ catch (cause) { throw new RidaError("RIDA field value cannot be decompressed", { cause }); }
191
+ }
192
+ try { return JSON.parse(raw.toString("utf8")); }
193
+ catch (cause) { throw new RidaError("RIDA field value is not valid JSON", { cause }); }
194
+ }
195
+
196
+ function companionPath(dataPath, suffix) {
197
+ const parsed = parse(dataPath);
198
+ const stem = extname(dataPath) ? basename(dataPath, extname(dataPath)) : parsed.base;
199
+ const clean = stem.endsWith("Data") ? stem.slice(0, -4) : stem;
200
+ return join(dirname(dataPath), `${clean}${suffix}`);
201
+ }
202
+
203
+ function remoteIndexUrl(dataUrl) {
204
+ const url = new URL(dataUrl);
205
+ const file = basename(url.pathname);
206
+ const extension = extname(file);
207
+ let stem = extension ? file.slice(0, -extension.length) : file;
208
+ if (stem.endsWith("Data")) stem = stem.slice(0, -4);
209
+ url.pathname = `${dirname(url.pathname)}/${stem}Index.rida`.replaceAll("\\", "/");
210
+ return url.toString();
211
+ }
212
+
213
+ async function bytesFrom(location) {
214
+ if (location instanceof Uint8Array) return Buffer.from(location);
215
+ if (location instanceof URL && location.protocol === "file:") return readFile(location);
216
+ if (typeof location === "string" && /^https?:\/\//i.test(location)) {
217
+ const response = await fetch(location);
218
+ if (!response.ok) throw new RidaError(`Could not fetch ${location}: HTTP ${response.status}`);
219
+ return Buffer.from(await response.arrayBuffer());
220
+ }
221
+ return readFile(location);
222
+ }
223
+
224
+ export class RidaReader {
225
+ static async open(data, { index, map, key } = {}) {
226
+ const dataIsUrl = typeof data === "string" && /^https?:\/\//i.test(data);
227
+ let indexLocation = index;
228
+ if (!indexLocation) {
229
+ if (dataIsUrl) indexLocation = remoteIndexUrl(data);
230
+ else indexLocation = companionPath(String(data), "Index.rida");
231
+ }
232
+ const [indexBytes, mapBytes] = await Promise.all([bytesFrom(indexLocation), map ? bytesFrom(map) : (dataIsUrl ? Promise.resolve(null) : readFile(companionPath(String(data), "Map.json")).catch(() => null))]);
233
+ const { info, catalog: compressed } = parseIndex(indexBytes);
234
+ const catalog = await parseCatalog(compressed, info);
235
+ const normalizedKey = normalizeKey(key);
236
+ need(!info.encrypted || normalizedKey, "This RIDA file is encrypted; provide its private key");
237
+ let mapping = null;
238
+ if (mapBytes) { try { mapping = JSON.parse(mapBytes.toString("utf8")); } catch { throw new RidaError("RIDA map JSON is invalid"); } }
239
+ let handle = null;
240
+ if (!dataIsUrl) {
241
+ handle = await open(data instanceof URL ? data : String(data), "r");
242
+ const stat = await handle.stat();
243
+ need(stat.size === info.dataLength, "RIDA data file does not match its index");
244
+ }
245
+ return new RidaReader(data, handle, info, catalog, mapping, normalizedKey);
246
+ }
247
+
248
+ constructor(data, handle, info, catalog, mapping, key) {
249
+ this.data = data; this.handle = handle; this.info = info; this.catalog = catalog; this.map = mapping; this.key = key;
250
+ }
251
+
252
+ async _range(offset, length) {
253
+ need(Number.isSafeInteger(offset) && Number.isSafeInteger(length) && offset >= 0 && length > 0 && offset + length <= this.info.dataLength, "Requested RIDA byte range is invalid");
254
+ if (this.handle) {
255
+ const result = Buffer.alloc(length);
256
+ const { bytesRead } = await this.handle.read(result, 0, length, offset);
257
+ need(bytesRead === length, "RIDA data range is incomplete");
258
+ return result;
259
+ }
260
+ const response = await fetch(this.data, { headers: { Range: `bytes=${offset}-${offset + length - 1}` } });
261
+ need(response.status === 206, `RIDA host must support HTTP byte ranges (received ${response.status})`);
262
+ const result = Buffer.from(await response.arrayBuffer());
263
+ need(result.length === length, `RIDA range returned ${result.length} bytes; expected ${length}`);
264
+ return result;
265
+ }
266
+
267
+ get fields() { return [...this.catalog.fields]; }
268
+ get recordCount() { return this.info.recordCount; }
269
+ get valueCodec() { return this.info.valueCodec; }
270
+ get mode() { return this.catalog.mode; }
271
+
272
+ recordsUnder(prefix) {
273
+ const start = `${String(prefix).replace(/\/$/, "")}/`;
274
+ return this.catalog.ids.filter((id) => id.startsWith(start));
275
+ }
276
+
277
+ resolve(...names) {
278
+ const wanted = names.map((name) => String(name).trim().toLocaleLowerCase()).filter(Boolean);
279
+ const paths = this.map?.paths;
280
+ if (!wanted.length || !paths || typeof paths !== "object") return null;
281
+ let found = null;
282
+ for (const [prefix, folderName] of Object.entries(paths)) {
283
+ const chain = [];
284
+ const parts = prefix.split("/");
285
+ for (let i = 1; i <= parts.length; i++) {
286
+ const key = parts.slice(0, i).join("/");
287
+ if (typeof paths[key] === "string") chain.push(paths[key].toLocaleLowerCase());
288
+ }
289
+ const last = wanted.at(-1);
290
+ const lastMatch = folderName.toLocaleLowerCase();
291
+ if (!(lastMatch === last || lastMatch.endsWith(last) || lastMatch.includes(last))) continue;
292
+ if (wanted.every((name) => chain.some((part) => part.includes(name))) && (!found || prefix.length > found.length)) found = prefix;
293
+ }
294
+ return found;
295
+ }
296
+
297
+ _resolveId(recordId) {
298
+ const text = String(recordId).replace(/\/$/, "");
299
+ if (!this.map || !text || this.catalog.idToRecord?.has(text)) return recordId;
300
+ const parts = text.split("/");
301
+ if (parts.length > 1 && /^\d+$/.test(parts.at(-1))) {
302
+ const prefix = this.resolve(...parts.slice(0, -1));
303
+ if (prefix) {
304
+ const candidate = `${prefix}/${parts.at(-1)}`;
305
+ if (this.catalog.idToRecord?.has(candidate)) return candidate;
306
+ const descendant = this.recordsUnder(prefix).find((id) => id.split("/").at(-1) === parts.at(-1));
307
+ if (descendant) return descendant;
308
+ return candidate;
309
+ }
310
+ }
311
+ const prefix = this.resolve(...parts);
312
+ if (prefix) return this.recordsUnder(prefix)[0] ?? recordId;
313
+ return recordId;
314
+ }
315
+
316
+ async get(recordId, field) {
317
+ recordId = this._resolveId(recordId);
318
+ const pointer = locate(this.catalog, recordId, [field]).get(field);
319
+ if (!pointer) throw new RangeError(`Field ${field} is absent from record ${recordId}`);
320
+ return decodeValue(await this._range(...pointer), this.info, this.key);
321
+ }
322
+
323
+ async getMany(recordId, fields) {
324
+ recordId = this._resolveId(recordId);
325
+ const pointers = locate(this.catalog, recordId, fields);
326
+ const sorted = [...pointers.entries()].sort((a, b) => a[1][0] - b[1][0]);
327
+ const groups = [];
328
+ for (const entry of sorted) {
329
+ const [offset, length] = entry[1];
330
+ const last = groups.at(-1);
331
+ if (last && offset - last.end <= MERGE_GAP_LIMIT) {
332
+ last.end = Math.max(last.end, offset + length);
333
+ last.entries.push(entry);
334
+ } else groups.push({ start: offset, end: offset + length, entries: [entry] });
335
+ }
336
+ const out = {};
337
+ for (const group of groups) {
338
+ const block = await this._range(group.start, group.end - group.start);
339
+ for (const [name, [offset, length]] of group.entries) {
340
+ out[name] = decodeValue(block.subarray(offset - group.start, offset - group.start + length), this.info, this.key);
341
+ }
342
+ }
343
+ return out;
344
+ }
345
+
346
+ async getRecord(recordId) { return this.getMany(this._resolveId(recordId), this.catalog.fields); }
347
+
348
+ async verifyData() {
349
+ const hash = createHash("sha256");
350
+ const chunkSize = 1024 * 1024;
351
+ for (let offset = 0; offset < this.info.dataLength; offset += chunkSize) {
352
+ hash.update(await this._range(offset, Math.min(chunkSize, this.info.dataLength - offset)));
353
+ }
354
+ return this.info.digest.equals(Buffer.alloc(32)) || hash.digest().equals(this.info.digest);
355
+ }
356
+
357
+ async close() { await this.handle?.close(); this.handle = null; }
358
+ }
359
+
360
+ export { decodeValue, parseIndex, parseCatalog };