icechunk-js 0.3.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/dist/index.js ADDED
@@ -0,0 +1,3003 @@
1
+ // src/storage/storage.ts
2
+ var DefaultFetchClient = class {
3
+ fetch(url, init) {
4
+ return globalThis.fetch(url, init);
5
+ }
6
+ };
7
+ var NotFoundError = class extends Error {
8
+ constructor(path) {
9
+ super(`Object not found: ${path}`);
10
+ this.path = path;
11
+ this.name = "NotFoundError";
12
+ }
13
+ };
14
+ var StorageError = class extends Error {
15
+ constructor(message, cause) {
16
+ super(message);
17
+ this.cause = cause;
18
+ this.name = "StorageError";
19
+ }
20
+ };
21
+ var AbortError = class extends Error {
22
+ constructor(message = "Operation aborted") {
23
+ super(message);
24
+ this.name = "AbortError";
25
+ }
26
+ };
27
+
28
+ // src/format/constants.ts
29
+ var PATHS = {
30
+ /** Refs directory */
31
+ REFS: "refs",
32
+ /** Snapshots directory */
33
+ SNAPSHOTS: "snapshots",
34
+ /** Manifests directory */
35
+ MANIFESTS: "manifests",
36
+ /** Chunks directory */
37
+ CHUNKS: "chunks",
38
+ /** Transaction logs directory */
39
+ TRANSACTIONS: "transactions"
40
+ };
41
+ var REPO_INFO_PATH = "repo";
42
+ function getBranchRefDirPath(name) {
43
+ return `${PATHS.REFS}/branch.${name}/`;
44
+ }
45
+ function getTagRefDirPath(name) {
46
+ return `${PATHS.REFS}/tag.${name}/`;
47
+ }
48
+ var REF_FILE_NAME = "ref.json";
49
+ function getBranchRefPath(name) {
50
+ return `${PATHS.REFS}/branch.${name}/${REF_FILE_NAME}`;
51
+ }
52
+ function getTagRefPath(name) {
53
+ return `${PATHS.REFS}/tag.${name}/${REF_FILE_NAME}`;
54
+ }
55
+ function getSnapshotPath(id) {
56
+ return `${PATHS.SNAPSHOTS}/${id}`;
57
+ }
58
+ function getManifestPath(id) {
59
+ return `${PATHS.MANIFESTS}/${id}`;
60
+ }
61
+ function getChunkPath(id) {
62
+ return `${PATHS.CHUNKS}/${id}`;
63
+ }
64
+ function getTransactionLogPath(id) {
65
+ return `${PATHS.TRANSACTIONS}/${id}`;
66
+ }
67
+
68
+ // src/format/object-id.ts
69
+ var ENCODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
70
+ var DECODE_MAP = {};
71
+ for (let i = 0; i < ENCODE_ALPHABET.length; i++) {
72
+ const char = ENCODE_ALPHABET[i];
73
+ DECODE_MAP[char] = i;
74
+ DECODE_MAP[char.toLowerCase()] = i;
75
+ }
76
+ DECODE_MAP["I"] = DECODE_MAP["i"] = 1;
77
+ DECODE_MAP["L"] = DECODE_MAP["l"] = 1;
78
+ DECODE_MAP["O"] = DECODE_MAP["o"] = 0;
79
+ function encodeBase32(bytes) {
80
+ if (bytes.length === 0) return "";
81
+ let result = "";
82
+ let buffer = 0;
83
+ let bitsLeft = 0;
84
+ for (const byte of bytes) {
85
+ buffer = buffer << 8 | byte;
86
+ bitsLeft += 8;
87
+ while (bitsLeft >= 5) {
88
+ bitsLeft -= 5;
89
+ const index = buffer >> bitsLeft & 31;
90
+ result += ENCODE_ALPHABET[index];
91
+ }
92
+ }
93
+ if (bitsLeft > 0) {
94
+ const index = buffer << 5 - bitsLeft & 31;
95
+ result += ENCODE_ALPHABET[index];
96
+ }
97
+ return result;
98
+ }
99
+ function decodeBase32(str) {
100
+ if (str.length === 0) return new Uint8Array(0);
101
+ str = str.replace(/-/g, "");
102
+ const result = [];
103
+ let buffer = 0;
104
+ let bitsLeft = 0;
105
+ for (const char of str) {
106
+ const value = DECODE_MAP[char];
107
+ if (value === void 0) {
108
+ throw new Error(`Invalid Base32 Crockford character: ${char}`);
109
+ }
110
+ buffer = buffer << 5 | value;
111
+ bitsLeft += 5;
112
+ if (bitsLeft >= 8) {
113
+ bitsLeft -= 8;
114
+ result.push(buffer >> bitsLeft & 255);
115
+ }
116
+ }
117
+ return new Uint8Array(result);
118
+ }
119
+ function encodeObjectId12(id) {
120
+ if (id.length !== 12) {
121
+ throw new Error(`Expected 12 bytes, got ${id.length}`);
122
+ }
123
+ return encodeBase32(id);
124
+ }
125
+ function decodeObjectId12(str) {
126
+ const bytes = decodeBase32(str);
127
+ if (bytes.length !== 12) {
128
+ throw new Error(`Expected 12 bytes after decoding, got ${bytes.length}`);
129
+ }
130
+ return bytes;
131
+ }
132
+ function encodeObjectId8(id) {
133
+ if (id.length !== 8) {
134
+ throw new Error(`Expected 8 bytes, got ${id.length}`);
135
+ }
136
+ return encodeBase32(id);
137
+ }
138
+ function decodeObjectId8(str) {
139
+ const bytes = decodeBase32(str);
140
+ if (bytes.length !== 8) {
141
+ throw new Error(`Expected 8 bytes after decoding, got ${bytes.length}`);
142
+ }
143
+ return bytes;
144
+ }
145
+
146
+ // src/format/flatbuffers/repo-parser.ts
147
+ import { ByteBuffer } from "flatbuffers";
148
+
149
+ // src/format/flatbuffers/generated/metadata-item.ts
150
+ var MetadataItem = class _MetadataItem {
151
+ bb = null;
152
+ bb_pos = 0;
153
+ __init(i, bb) {
154
+ this.bb_pos = i;
155
+ this.bb = bb;
156
+ return this;
157
+ }
158
+ static getRootAsMetadataItem(bb, obj) {
159
+ return (obj || new _MetadataItem()).__init(
160
+ bb.readInt32(bb.position()) + bb.position(),
161
+ bb
162
+ );
163
+ }
164
+ name(optionalEncoding) {
165
+ const offset = this.bb.__offset(this.bb_pos, 4);
166
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
167
+ }
168
+ value(index) {
169
+ const offset = this.bb.__offset(this.bb_pos, 6);
170
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
171
+ }
172
+ valueLength() {
173
+ const offset = this.bb.__offset(this.bb_pos, 6);
174
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
175
+ }
176
+ valueArray() {
177
+ const offset = this.bb.__offset(this.bb_pos, 6);
178
+ return offset ? new Uint8Array(
179
+ this.bb.bytes().buffer,
180
+ this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset),
181
+ this.bb.__vector_len(this.bb_pos + offset)
182
+ ) : null;
183
+ }
184
+ };
185
+
186
+ // src/format/flatbuffers/generated/ref.ts
187
+ var Ref = class _Ref {
188
+ bb = null;
189
+ bb_pos = 0;
190
+ __init(i, bb) {
191
+ this.bb_pos = i;
192
+ this.bb = bb;
193
+ return this;
194
+ }
195
+ static getRootAsRef(bb, obj) {
196
+ return (obj || new _Ref()).__init(
197
+ bb.readInt32(bb.position()) + bb.position(),
198
+ bb
199
+ );
200
+ }
201
+ name(optionalEncoding) {
202
+ const offset = this.bb.__offset(this.bb_pos, 4);
203
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
204
+ }
205
+ snapshotIndex() {
206
+ const offset = this.bb.__offset(this.bb_pos, 6);
207
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
208
+ }
209
+ };
210
+
211
+ // src/format/flatbuffers/generated/repo-status.ts
212
+ var RepoStatus = class _RepoStatus {
213
+ bb = null;
214
+ bb_pos = 0;
215
+ __init(i, bb) {
216
+ this.bb_pos = i;
217
+ this.bb = bb;
218
+ return this;
219
+ }
220
+ static getRootAsRepoStatus(bb, obj) {
221
+ return (obj || new _RepoStatus()).__init(
222
+ bb.readInt32(bb.position()) + bb.position(),
223
+ bb
224
+ );
225
+ }
226
+ availability() {
227
+ const offset = this.bb.__offset(this.bb_pos, 4);
228
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : 0 /* Online */;
229
+ }
230
+ setAt() {
231
+ const offset = this.bb.__offset(this.bb_pos, 6);
232
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0");
233
+ }
234
+ limitedAvailabilityReason(optionalEncoding) {
235
+ const offset = this.bb.__offset(this.bb_pos, 8);
236
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
237
+ }
238
+ };
239
+
240
+ // src/format/flatbuffers/generated/object-id12.ts
241
+ var ObjectId12 = class {
242
+ bb = null;
243
+ bb_pos = 0;
244
+ __init(i, bb) {
245
+ this.bb_pos = i;
246
+ this.bb = bb;
247
+ return this;
248
+ }
249
+ bytes(index) {
250
+ return this.bb.readUint8(this.bb_pos + 0 + index);
251
+ }
252
+ static sizeOf() {
253
+ return 12;
254
+ }
255
+ };
256
+
257
+ // src/format/flatbuffers/generated/snapshot-info.ts
258
+ var SnapshotInfo = class _SnapshotInfo {
259
+ bb = null;
260
+ bb_pos = 0;
261
+ __init(i, bb) {
262
+ this.bb_pos = i;
263
+ this.bb = bb;
264
+ return this;
265
+ }
266
+ static getRootAsSnapshotInfo(bb, obj) {
267
+ return (obj || new _SnapshotInfo()).__init(
268
+ bb.readInt32(bb.position()) + bb.position(),
269
+ bb
270
+ );
271
+ }
272
+ id(obj) {
273
+ const offset = this.bb.__offset(this.bb_pos, 4);
274
+ return offset ? (obj || new ObjectId12()).__init(this.bb_pos + offset, this.bb) : null;
275
+ }
276
+ parentOffset() {
277
+ const offset = this.bb.__offset(this.bb_pos, 6);
278
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
279
+ }
280
+ flushedAt() {
281
+ const offset = this.bb.__offset(this.bb_pos, 8);
282
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0");
283
+ }
284
+ message(optionalEncoding) {
285
+ const offset = this.bb.__offset(this.bb_pos, 10);
286
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
287
+ }
288
+ metadata(index, obj) {
289
+ const offset = this.bb.__offset(this.bb_pos, 12);
290
+ return offset ? (obj || new MetadataItem()).__init(
291
+ this.bb.__indirect(
292
+ this.bb.__vector(this.bb_pos + offset) + index * 4
293
+ ),
294
+ this.bb
295
+ ) : null;
296
+ }
297
+ metadataLength() {
298
+ const offset = this.bb.__offset(this.bb_pos, 12);
299
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
300
+ }
301
+ };
302
+
303
+ // src/format/flatbuffers/generated/update.ts
304
+ var Update = class _Update {
305
+ bb = null;
306
+ bb_pos = 0;
307
+ __init(i, bb) {
308
+ this.bb_pos = i;
309
+ this.bb = bb;
310
+ return this;
311
+ }
312
+ static getRootAsUpdate(bb, obj) {
313
+ return (obj || new _Update()).__init(
314
+ bb.readInt32(bb.position()) + bb.position(),
315
+ bb
316
+ );
317
+ }
318
+ updateTypeType() {
319
+ const offset = this.bb.__offset(this.bb_pos, 4);
320
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : 0 /* NONE */;
321
+ }
322
+ updateType(obj) {
323
+ const offset = this.bb.__offset(this.bb_pos, 6);
324
+ return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
325
+ }
326
+ updatedAt() {
327
+ const offset = this.bb.__offset(this.bb_pos, 8);
328
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0");
329
+ }
330
+ backupPath(optionalEncoding) {
331
+ const offset = this.bb.__offset(this.bb_pos, 10);
332
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
333
+ }
334
+ };
335
+
336
+ // src/format/flatbuffers/generated/repo.ts
337
+ var Repo = class _Repo {
338
+ bb = null;
339
+ bb_pos = 0;
340
+ __init(i, bb) {
341
+ this.bb_pos = i;
342
+ this.bb = bb;
343
+ return this;
344
+ }
345
+ static getRootAsRepo(bb, obj) {
346
+ return (obj || new _Repo()).__init(
347
+ bb.readInt32(bb.position()) + bb.position(),
348
+ bb
349
+ );
350
+ }
351
+ specVersion() {
352
+ const offset = this.bb.__offset(this.bb_pos, 4);
353
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : 0;
354
+ }
355
+ tags(index, obj) {
356
+ const offset = this.bb.__offset(this.bb_pos, 6);
357
+ return offset ? (obj || new Ref()).__init(
358
+ this.bb.__indirect(
359
+ this.bb.__vector(this.bb_pos + offset) + index * 4
360
+ ),
361
+ this.bb
362
+ ) : null;
363
+ }
364
+ tagsLength() {
365
+ const offset = this.bb.__offset(this.bb_pos, 6);
366
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
367
+ }
368
+ branches(index, obj) {
369
+ const offset = this.bb.__offset(this.bb_pos, 8);
370
+ return offset ? (obj || new Ref()).__init(
371
+ this.bb.__indirect(
372
+ this.bb.__vector(this.bb_pos + offset) + index * 4
373
+ ),
374
+ this.bb
375
+ ) : null;
376
+ }
377
+ branchesLength() {
378
+ const offset = this.bb.__offset(this.bb_pos, 8);
379
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
380
+ }
381
+ deletedTags(index, optionalEncoding) {
382
+ const offset = this.bb.__offset(this.bb_pos, 10);
383
+ return offset ? this.bb.__string(
384
+ this.bb.__vector(this.bb_pos + offset) + index * 4,
385
+ optionalEncoding
386
+ ) : null;
387
+ }
388
+ deletedTagsLength() {
389
+ const offset = this.bb.__offset(this.bb_pos, 10);
390
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
391
+ }
392
+ snapshots(index, obj) {
393
+ const offset = this.bb.__offset(this.bb_pos, 12);
394
+ return offset ? (obj || new SnapshotInfo()).__init(
395
+ this.bb.__indirect(
396
+ this.bb.__vector(this.bb_pos + offset) + index * 4
397
+ ),
398
+ this.bb
399
+ ) : null;
400
+ }
401
+ snapshotsLength() {
402
+ const offset = this.bb.__offset(this.bb_pos, 12);
403
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
404
+ }
405
+ status(obj) {
406
+ const offset = this.bb.__offset(this.bb_pos, 14);
407
+ return offset ? (obj || new RepoStatus()).__init(
408
+ this.bb.__indirect(this.bb_pos + offset),
409
+ this.bb
410
+ ) : null;
411
+ }
412
+ metadata(index, obj) {
413
+ const offset = this.bb.__offset(this.bb_pos, 16);
414
+ return offset ? (obj || new MetadataItem()).__init(
415
+ this.bb.__indirect(
416
+ this.bb.__vector(this.bb_pos + offset) + index * 4
417
+ ),
418
+ this.bb
419
+ ) : null;
420
+ }
421
+ metadataLength() {
422
+ const offset = this.bb.__offset(this.bb_pos, 16);
423
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
424
+ }
425
+ latestUpdates(index, obj) {
426
+ const offset = this.bb.__offset(this.bb_pos, 18);
427
+ return offset ? (obj || new Update()).__init(
428
+ this.bb.__indirect(
429
+ this.bb.__vector(this.bb_pos + offset) + index * 4
430
+ ),
431
+ this.bb
432
+ ) : null;
433
+ }
434
+ latestUpdatesLength() {
435
+ const offset = this.bb.__offset(this.bb_pos, 18);
436
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
437
+ }
438
+ repoBeforeUpdates(optionalEncoding) {
439
+ const offset = this.bb.__offset(this.bb_pos, 20);
440
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
441
+ }
442
+ };
443
+
444
+ // src/format/flatbuffers/repo-parser.ts
445
+ import { decompress } from "fzstd";
446
+
447
+ // src/format/header.ts
448
+ var HEADER_SIZE = 39;
449
+ var MAGIC_BYTES = new Uint8Array([
450
+ 73,
451
+ 67,
452
+ 69,
453
+ // ICE
454
+ 240,
455
+ 159,
456
+ 167,
457
+ 138,
458
+ // 🧊 (U+1F9CA in UTF-8)
459
+ 67,
460
+ 72,
461
+ 85,
462
+ 78,
463
+ 75
464
+ // CHUNK
465
+ ]);
466
+ var SpecVersion = /* @__PURE__ */ ((SpecVersion3) => {
467
+ SpecVersion3[SpecVersion3["V1_0"] = 1] = "V1_0";
468
+ SpecVersion3[SpecVersion3["V2_0"] = 2] = "V2_0";
469
+ return SpecVersion3;
470
+ })(SpecVersion || {});
471
+ var FileType = /* @__PURE__ */ ((FileType2) => {
472
+ FileType2[FileType2["Snapshot"] = 1] = "Snapshot";
473
+ FileType2[FileType2["Manifest"] = 2] = "Manifest";
474
+ FileType2[FileType2["Attributes"] = 3] = "Attributes";
475
+ FileType2[FileType2["TransactionLog"] = 4] = "TransactionLog";
476
+ FileType2[FileType2["Chunk"] = 5] = "Chunk";
477
+ FileType2[FileType2["RepoInfo"] = 6] = "RepoInfo";
478
+ return FileType2;
479
+ })(FileType || {});
480
+ var CompressionAlgorithm = /* @__PURE__ */ ((CompressionAlgorithm2) => {
481
+ CompressionAlgorithm2[CompressionAlgorithm2["None"] = 0] = "None";
482
+ CompressionAlgorithm2[CompressionAlgorithm2["Zstd"] = 1] = "Zstd";
483
+ return CompressionAlgorithm2;
484
+ })(CompressionAlgorithm || {});
485
+ var HeaderParseError = class extends Error {
486
+ constructor(message) {
487
+ super(message);
488
+ this.name = "HeaderParseError";
489
+ }
490
+ };
491
+ function parseHeader(data) {
492
+ if (data.length < HEADER_SIZE) {
493
+ throw new HeaderParseError(
494
+ `Buffer too small: expected at least ${HEADER_SIZE} bytes, got ${data.length}`
495
+ );
496
+ }
497
+ const magic = data.slice(0, 12);
498
+ if (!compareMagic(magic, MAGIC_BYTES)) {
499
+ throw new HeaderParseError("Invalid magic bytes: not an icechunk file");
500
+ }
501
+ const implementationBytes = data.slice(12, 36);
502
+ const implementation = new TextDecoder().decode(implementationBytes).trimEnd();
503
+ const specVersionByte = data[36];
504
+ if (specVersionByte !== 1 /* V1_0 */ && specVersionByte !== 2 /* V2_0 */) {
505
+ throw new HeaderParseError(`Invalid spec version: ${specVersionByte}`);
506
+ }
507
+ const specVersion = specVersionByte;
508
+ const fileTypeByte = data[37];
509
+ if (fileTypeByte < 1 || fileTypeByte > 6) {
510
+ throw new HeaderParseError(`Invalid file type: ${fileTypeByte}`);
511
+ }
512
+ const fileType = fileTypeByte;
513
+ const compressionByte = data[38];
514
+ if (compressionByte !== 0 /* None */ && compressionByte !== 1 /* Zstd */) {
515
+ throw new HeaderParseError(
516
+ `Invalid compression algorithm: ${compressionByte}`
517
+ );
518
+ }
519
+ const compression = compressionByte;
520
+ return {
521
+ implementation,
522
+ specVersion,
523
+ fileType,
524
+ compression
525
+ };
526
+ }
527
+ function validateFileType(header, expectedType) {
528
+ if (header.fileType !== expectedType) {
529
+ const expected = FileType[expectedType];
530
+ const actual = FileType[header.fileType];
531
+ throw new HeaderParseError(
532
+ `Invalid file type: expected ${expected}, got ${actual}`
533
+ );
534
+ }
535
+ }
536
+ function getDataAfterHeader(data) {
537
+ return data.slice(HEADER_SIZE);
538
+ }
539
+ function compareMagic(a, b) {
540
+ if (a.length !== b.length) return false;
541
+ for (let i = 0; i < a.length; i++) {
542
+ if (a[i] !== b[i]) return false;
543
+ }
544
+ return true;
545
+ }
546
+
547
+ // src/format/flatbuffers/repo-parser.ts
548
+ var SUPPORTED_SPEC_VERSION = 2;
549
+ function parseRepo(data) {
550
+ if (data.length < HEADER_SIZE) {
551
+ throw new Error(
552
+ `Repo file too small: ${data.length} bytes, need at least ${HEADER_SIZE}`
553
+ );
554
+ }
555
+ const header = parseHeader(data);
556
+ validateFileType(header, 6 /* RepoInfo */);
557
+ let fbData = getDataAfterHeader(data);
558
+ if (header.compression === 1 /* Zstd */) {
559
+ fbData = decompress(fbData);
560
+ }
561
+ const bb = new ByteBuffer(fbData);
562
+ const repo = Repo.getRootAsRepo(bb);
563
+ const specVersion = repo.specVersion();
564
+ if (specVersion !== SUPPORTED_SPEC_VERSION) {
565
+ throw new Error(
566
+ `Unsupported repo spec version: ${specVersion}, expected ${SUPPORTED_SPEC_VERSION}`
567
+ );
568
+ }
569
+ const snapshotsLength = repo.snapshotsLength();
570
+ return { repo, specVersion, snapshotsLength };
571
+ }
572
+ function compareUtf8ByteOrder(aBytes, bBytes) {
573
+ const minLen = Math.min(aBytes.length, bBytes.length);
574
+ for (let i = 0; i < minLen; i++) {
575
+ if (aBytes[i] < bBytes[i]) return -1;
576
+ if (aBytes[i] > bBytes[i]) return 1;
577
+ }
578
+ return aBytes.length - bBytes.length;
579
+ }
580
+ function binarySearchRef(parsedRepo, accessor, length, name) {
581
+ const { snapshotsLength } = parsedRepo;
582
+ if (length === 0) return null;
583
+ const targetBytes = new TextEncoder().encode(name);
584
+ let low = 0;
585
+ let high = length - 1;
586
+ while (low <= high) {
587
+ const mid = low + high >>> 1;
588
+ const refTable = accessor(mid);
589
+ if (!refTable) {
590
+ throw new Error(`Corrupted repo file: null ref table at index ${mid}`);
591
+ }
592
+ const refName = refTable.name();
593
+ if (refName === null) {
594
+ throw new Error(`Corrupted repo file: null ref name at index ${mid}`);
595
+ }
596
+ const refNameBytes = new TextEncoder().encode(refName);
597
+ const cmp = compareUtf8ByteOrder(refNameBytes, targetBytes);
598
+ if (cmp < 0) {
599
+ low = mid + 1;
600
+ } else if (cmp > 0) {
601
+ high = mid - 1;
602
+ } else {
603
+ const snapshotIndex = refTable.snapshotIndex();
604
+ if (snapshotIndex >= snapshotsLength) {
605
+ throw new Error(
606
+ `Invalid snapshot index ${snapshotIndex} for ref '${name}', snapshots array has ${snapshotsLength} entries`
607
+ );
608
+ }
609
+ return getSnapshotIdByIndex(parsedRepo, snapshotIndex);
610
+ }
611
+ }
612
+ return null;
613
+ }
614
+ function getSnapshotIdByIndex(parsedRepo, index) {
615
+ const snapshotInfo = parsedRepo.repo.snapshots(index);
616
+ if (!snapshotInfo) {
617
+ throw new Error(`Corrupted repo file: null snapshot at index ${index}`);
618
+ }
619
+ const idObj = snapshotInfo.id();
620
+ if (!idObj) {
621
+ throw new Error(`Corrupted repo file: snapshot ${index} missing id`);
622
+ }
623
+ return idObj.bb.bytes().slice(idObj.bb_pos, idObj.bb_pos + 12);
624
+ }
625
+ function listRefs(accessor, length) {
626
+ const names = [];
627
+ for (let i = 0; i < length; i++) {
628
+ const refTable = accessor(i);
629
+ if (!refTable) {
630
+ throw new Error(`Corrupted repo file: null ref table at index ${i}`);
631
+ }
632
+ const name = refTable.name();
633
+ if (name === null) {
634
+ throw new Error(`Corrupted repo file: null ref name at index ${i}`);
635
+ }
636
+ names.push(name);
637
+ }
638
+ return names;
639
+ }
640
+ function resolveBranch(parsedRepo, name) {
641
+ const { repo } = parsedRepo;
642
+ return binarySearchRef(
643
+ parsedRepo,
644
+ (i) => repo.branches(i),
645
+ repo.branchesLength(),
646
+ name
647
+ );
648
+ }
649
+ function resolveTag(parsedRepo, name) {
650
+ const { repo } = parsedRepo;
651
+ return binarySearchRef(
652
+ parsedRepo,
653
+ (i) => repo.tags(i),
654
+ repo.tagsLength(),
655
+ name
656
+ );
657
+ }
658
+ function listBranchesFromRepo(parsedRepo) {
659
+ const { repo } = parsedRepo;
660
+ return listRefs((i) => repo.branches(i), repo.branchesLength());
661
+ }
662
+ function listTagsFromRepo(parsedRepo) {
663
+ const { repo } = parsedRepo;
664
+ return listRefs((i) => repo.tags(i), repo.tagsLength());
665
+ }
666
+
667
+ // src/reader/session.ts
668
+ import { decompress as decompress2 } from "fzstd";
669
+
670
+ // src/cache/lru.ts
671
+ var LRUCache = class {
672
+ cache;
673
+ maxSize;
674
+ constructor(maxSize) {
675
+ this.cache = /* @__PURE__ */ new Map();
676
+ this.maxSize = maxSize;
677
+ }
678
+ get(key) {
679
+ const value = this.cache.get(key);
680
+ if (value !== void 0) {
681
+ this.cache.delete(key);
682
+ this.cache.set(key, value);
683
+ }
684
+ return value;
685
+ }
686
+ set(key, value) {
687
+ if (this.maxSize <= 0) return;
688
+ if (this.cache.has(key)) {
689
+ this.cache.delete(key);
690
+ }
691
+ if (this.cache.size >= this.maxSize) {
692
+ const oldestKey = this.cache.keys().next().value;
693
+ if (oldestKey !== void 0) {
694
+ this.cache.delete(oldestKey);
695
+ }
696
+ }
697
+ this.cache.set(key, value);
698
+ }
699
+ has(key) {
700
+ return this.cache.has(key);
701
+ }
702
+ delete(key) {
703
+ return this.cache.delete(key);
704
+ }
705
+ clear() {
706
+ this.cache.clear();
707
+ }
708
+ get size() {
709
+ return this.cache.size;
710
+ }
711
+ };
712
+
713
+ // src/format/flatbuffers/types.ts
714
+ function asObjectId12(bytes) {
715
+ if (bytes.length !== 12) {
716
+ throw new Error(
717
+ `Invalid ObjectId12: expected 12 bytes, got ${bytes.length}`
718
+ );
719
+ }
720
+ return bytes;
721
+ }
722
+ function asObjectId8(bytes) {
723
+ if (bytes.length !== 8) {
724
+ throw new Error(`Invalid ObjectId8: expected 8 bytes, got ${bytes.length}`);
725
+ }
726
+ return bytes;
727
+ }
728
+
729
+ // src/format/flatbuffers/snapshot-parser.ts
730
+ import { ByteBuffer as ByteBuffer2 } from "flatbuffers";
731
+
732
+ // src/format/flatbuffers/generated/manifest-file-info.ts
733
+ var ManifestFileInfo = class {
734
+ bb = null;
735
+ bb_pos = 0;
736
+ __init(i, bb) {
737
+ this.bb_pos = i;
738
+ this.bb = bb;
739
+ return this;
740
+ }
741
+ id(obj) {
742
+ return (obj || new ObjectId12()).__init(this.bb_pos, this.bb);
743
+ }
744
+ sizeBytes() {
745
+ return this.bb.readUint64(this.bb_pos + 16);
746
+ }
747
+ numChunkRefs() {
748
+ return this.bb.readUint32(this.bb_pos + 24);
749
+ }
750
+ static sizeOf() {
751
+ return 32;
752
+ }
753
+ };
754
+
755
+ // src/format/flatbuffers/generated/dimension-name.ts
756
+ var DimensionName = class _DimensionName {
757
+ bb = null;
758
+ bb_pos = 0;
759
+ __init(i, bb) {
760
+ this.bb_pos = i;
761
+ this.bb = bb;
762
+ return this;
763
+ }
764
+ static getRootAsDimensionName(bb, obj) {
765
+ return (obj || new _DimensionName()).__init(
766
+ bb.readInt32(bb.position()) + bb.position(),
767
+ bb
768
+ );
769
+ }
770
+ name(optionalEncoding) {
771
+ const offset = this.bb.__offset(this.bb_pos, 4);
772
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
773
+ }
774
+ };
775
+
776
+ // src/format/flatbuffers/generated/dimension-shape.ts
777
+ var DimensionShape = class {
778
+ bb = null;
779
+ bb_pos = 0;
780
+ __init(i, bb) {
781
+ this.bb_pos = i;
782
+ this.bb = bb;
783
+ return this;
784
+ }
785
+ arrayLength() {
786
+ return this.bb.readUint64(this.bb_pos);
787
+ }
788
+ chunkLength() {
789
+ return this.bb.readUint64(this.bb_pos + 8);
790
+ }
791
+ static sizeOf() {
792
+ return 16;
793
+ }
794
+ };
795
+
796
+ // src/format/flatbuffers/generated/chunk-index-range.ts
797
+ var ChunkIndexRange = class {
798
+ bb = null;
799
+ bb_pos = 0;
800
+ __init(i, bb) {
801
+ this.bb_pos = i;
802
+ this.bb = bb;
803
+ return this;
804
+ }
805
+ from() {
806
+ return this.bb.readUint32(this.bb_pos);
807
+ }
808
+ to() {
809
+ return this.bb.readUint32(this.bb_pos + 4);
810
+ }
811
+ static sizeOf() {
812
+ return 8;
813
+ }
814
+ };
815
+
816
+ // src/format/flatbuffers/generated/manifest-ref.ts
817
+ var ManifestRef = class _ManifestRef {
818
+ bb = null;
819
+ bb_pos = 0;
820
+ __init(i, bb) {
821
+ this.bb_pos = i;
822
+ this.bb = bb;
823
+ return this;
824
+ }
825
+ static getRootAsManifestRef(bb, obj) {
826
+ return (obj || new _ManifestRef()).__init(
827
+ bb.readInt32(bb.position()) + bb.position(),
828
+ bb
829
+ );
830
+ }
831
+ objectId(obj) {
832
+ const offset = this.bb.__offset(this.bb_pos, 4);
833
+ return offset ? (obj || new ObjectId12()).__init(this.bb_pos + offset, this.bb) : null;
834
+ }
835
+ extents(index, obj) {
836
+ const offset = this.bb.__offset(this.bb_pos, 6);
837
+ return offset ? (obj || new ChunkIndexRange()).__init(
838
+ this.bb.__vector(this.bb_pos + offset) + index * 8,
839
+ this.bb
840
+ ) : null;
841
+ }
842
+ extentsLength() {
843
+ const offset = this.bb.__offset(this.bb_pos, 6);
844
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
845
+ }
846
+ };
847
+
848
+ // src/format/flatbuffers/generated/array-node-data.ts
849
+ var ArrayNodeData = class _ArrayNodeData {
850
+ bb = null;
851
+ bb_pos = 0;
852
+ __init(i, bb) {
853
+ this.bb_pos = i;
854
+ this.bb = bb;
855
+ return this;
856
+ }
857
+ static getRootAsArrayNodeData(bb, obj) {
858
+ return (obj || new _ArrayNodeData()).__init(
859
+ bb.readInt32(bb.position()) + bb.position(),
860
+ bb
861
+ );
862
+ }
863
+ shape(index, obj) {
864
+ const offset = this.bb.__offset(this.bb_pos, 4);
865
+ return offset ? (obj || new DimensionShape()).__init(
866
+ this.bb.__vector(this.bb_pos + offset) + index * 16,
867
+ this.bb
868
+ ) : null;
869
+ }
870
+ shapeLength() {
871
+ const offset = this.bb.__offset(this.bb_pos, 4);
872
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
873
+ }
874
+ dimensionNames(index, obj) {
875
+ const offset = this.bb.__offset(this.bb_pos, 6);
876
+ return offset ? (obj || new DimensionName()).__init(
877
+ this.bb.__indirect(
878
+ this.bb.__vector(this.bb_pos + offset) + index * 4
879
+ ),
880
+ this.bb
881
+ ) : null;
882
+ }
883
+ dimensionNamesLength() {
884
+ const offset = this.bb.__offset(this.bb_pos, 6);
885
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
886
+ }
887
+ manifests(index, obj) {
888
+ const offset = this.bb.__offset(this.bb_pos, 8);
889
+ return offset ? (obj || new ManifestRef()).__init(
890
+ this.bb.__indirect(
891
+ this.bb.__vector(this.bb_pos + offset) + index * 4
892
+ ),
893
+ this.bb
894
+ ) : null;
895
+ }
896
+ manifestsLength() {
897
+ const offset = this.bb.__offset(this.bb_pos, 8);
898
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
899
+ }
900
+ };
901
+
902
+ // src/format/flatbuffers/generated/object-id8.ts
903
+ var ObjectId8 = class {
904
+ bb = null;
905
+ bb_pos = 0;
906
+ __init(i, bb) {
907
+ this.bb_pos = i;
908
+ this.bb = bb;
909
+ return this;
910
+ }
911
+ bytes(index) {
912
+ return this.bb.readUint8(this.bb_pos + 0 + index);
913
+ }
914
+ static sizeOf() {
915
+ return 8;
916
+ }
917
+ };
918
+
919
+ // src/format/flatbuffers/generated/node-snapshot.ts
920
+ var NodeSnapshot = class _NodeSnapshot {
921
+ bb = null;
922
+ bb_pos = 0;
923
+ __init(i, bb) {
924
+ this.bb_pos = i;
925
+ this.bb = bb;
926
+ return this;
927
+ }
928
+ static getRootAsNodeSnapshot(bb, obj) {
929
+ return (obj || new _NodeSnapshot()).__init(
930
+ bb.readInt32(bb.position()) + bb.position(),
931
+ bb
932
+ );
933
+ }
934
+ id(obj) {
935
+ const offset = this.bb.__offset(this.bb_pos, 4);
936
+ return offset ? (obj || new ObjectId8()).__init(this.bb_pos + offset, this.bb) : null;
937
+ }
938
+ path(optionalEncoding) {
939
+ const offset = this.bb.__offset(this.bb_pos, 6);
940
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
941
+ }
942
+ userData(index) {
943
+ const offset = this.bb.__offset(this.bb_pos, 8);
944
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
945
+ }
946
+ userDataLength() {
947
+ const offset = this.bb.__offset(this.bb_pos, 8);
948
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
949
+ }
950
+ userDataArray() {
951
+ const offset = this.bb.__offset(this.bb_pos, 8);
952
+ return offset ? new Uint8Array(
953
+ this.bb.bytes().buffer,
954
+ this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset),
955
+ this.bb.__vector_len(this.bb_pos + offset)
956
+ ) : null;
957
+ }
958
+ nodeDataType() {
959
+ const offset = this.bb.__offset(this.bb_pos, 10);
960
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : 0 /* NONE */;
961
+ }
962
+ nodeData(obj) {
963
+ const offset = this.bb.__offset(this.bb_pos, 12);
964
+ return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
965
+ }
966
+ };
967
+
968
+ // src/format/flatbuffers/generated/snapshot.ts
969
+ var Snapshot = class _Snapshot {
970
+ bb = null;
971
+ bb_pos = 0;
972
+ __init(i, bb) {
973
+ this.bb_pos = i;
974
+ this.bb = bb;
975
+ return this;
976
+ }
977
+ static getRootAsSnapshot(bb, obj) {
978
+ return (obj || new _Snapshot()).__init(
979
+ bb.readInt32(bb.position()) + bb.position(),
980
+ bb
981
+ );
982
+ }
983
+ id(obj) {
984
+ const offset = this.bb.__offset(this.bb_pos, 4);
985
+ return offset ? (obj || new ObjectId12()).__init(this.bb_pos + offset, this.bb) : null;
986
+ }
987
+ parentId(obj) {
988
+ const offset = this.bb.__offset(this.bb_pos, 6);
989
+ return offset ? (obj || new ObjectId12()).__init(this.bb_pos + offset, this.bb) : null;
990
+ }
991
+ nodes(index, obj) {
992
+ const offset = this.bb.__offset(this.bb_pos, 8);
993
+ return offset ? (obj || new NodeSnapshot()).__init(
994
+ this.bb.__indirect(
995
+ this.bb.__vector(this.bb_pos + offset) + index * 4
996
+ ),
997
+ this.bb
998
+ ) : null;
999
+ }
1000
+ nodesLength() {
1001
+ const offset = this.bb.__offset(this.bb_pos, 8);
1002
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1003
+ }
1004
+ flushedAt() {
1005
+ const offset = this.bb.__offset(this.bb_pos, 10);
1006
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0");
1007
+ }
1008
+ message(optionalEncoding) {
1009
+ const offset = this.bb.__offset(this.bb_pos, 12);
1010
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
1011
+ }
1012
+ metadata(index, obj) {
1013
+ const offset = this.bb.__offset(this.bb_pos, 14);
1014
+ return offset ? (obj || new MetadataItem()).__init(
1015
+ this.bb.__indirect(
1016
+ this.bb.__vector(this.bb_pos + offset) + index * 4
1017
+ ),
1018
+ this.bb
1019
+ ) : null;
1020
+ }
1021
+ metadataLength() {
1022
+ const offset = this.bb.__offset(this.bb_pos, 14);
1023
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1024
+ }
1025
+ manifestFiles(index, obj) {
1026
+ const offset = this.bb.__offset(this.bb_pos, 16);
1027
+ return offset ? (obj || new ManifestFileInfo()).__init(
1028
+ this.bb.__vector(this.bb_pos + offset) + index * 32,
1029
+ this.bb
1030
+ ) : null;
1031
+ }
1032
+ manifestFilesLength() {
1033
+ const offset = this.bb.__offset(this.bb_pos, 16);
1034
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1035
+ }
1036
+ };
1037
+
1038
+ // src/format/flatbuffers/snapshot-parser.ts
1039
+ function readId12(bb, bbPos) {
1040
+ return bb.bytes().slice(bbPos, bbPos + 12);
1041
+ }
1042
+ function readId8(bb, bbPos) {
1043
+ return bb.bytes().slice(bbPos, bbPos + 8);
1044
+ }
1045
+ function parseSnapshot(data) {
1046
+ const bb = new ByteBuffer2(data);
1047
+ const fbsSnapshot = Snapshot.getRootAsSnapshot(bb);
1048
+ const idObj = fbsSnapshot.id();
1049
+ if (!idObj) throw new Error("Snapshot missing required id field");
1050
+ const id = asObjectId12(readId12(idObj.bb, idObj.bb_pos));
1051
+ const parentIdObj = fbsSnapshot.parentId();
1052
+ const parentId = parentIdObj ? asObjectId12(readId12(parentIdObj.bb, parentIdObj.bb_pos)) : null;
1053
+ const nodesLength = fbsSnapshot.nodesLength();
1054
+ const nodes = [];
1055
+ for (let i = 0; i < nodesLength; i++) {
1056
+ const fbsNode = fbsSnapshot.nodes(i);
1057
+ if (fbsNode) {
1058
+ nodes.push(parseNodeSnapshot(fbsNode));
1059
+ }
1060
+ }
1061
+ const flushedAt = fbsSnapshot.flushedAt();
1062
+ const message = fbsSnapshot.message() ?? "";
1063
+ const metadataLength = fbsSnapshot.metadataLength();
1064
+ const metadata = [];
1065
+ for (let i = 0; i < metadataLength; i++) {
1066
+ const fbsMeta = fbsSnapshot.metadata(i);
1067
+ if (fbsMeta) {
1068
+ const name = fbsMeta.name();
1069
+ const value = fbsMeta.valueArray();
1070
+ if (name && value) {
1071
+ metadata.push({ name, value: new Uint8Array(value) });
1072
+ }
1073
+ }
1074
+ }
1075
+ const manifestFilesLength = fbsSnapshot.manifestFilesLength();
1076
+ const manifestFiles = [];
1077
+ for (let i = 0; i < manifestFilesLength; i++) {
1078
+ const fbsMfi = fbsSnapshot.manifestFiles(i);
1079
+ if (fbsMfi) {
1080
+ const mfiIdObj = fbsMfi.id();
1081
+ if (!mfiIdObj) throw new Error("ManifestFileInfo missing id");
1082
+ manifestFiles.push({
1083
+ id: asObjectId12(readId12(mfiIdObj.bb, mfiIdObj.bb_pos)),
1084
+ sizeBytes: Number(fbsMfi.sizeBytes()),
1085
+ numChunkRefs: fbsMfi.numChunkRefs()
1086
+ });
1087
+ }
1088
+ }
1089
+ return {
1090
+ id,
1091
+ parentId,
1092
+ nodes,
1093
+ flushedAt,
1094
+ message,
1095
+ metadata,
1096
+ manifestFiles
1097
+ };
1098
+ }
1099
+ function parseNodeSnapshot(fbsNode) {
1100
+ const idObj = fbsNode.id();
1101
+ if (!idObj) throw new Error("NodeSnapshot missing required id field");
1102
+ const id = asObjectId8(readId8(idObj.bb, idObj.bb_pos));
1103
+ const path = fbsNode.path() ?? "";
1104
+ const userData = fbsNode.userDataArray() ?? new Uint8Array(0);
1105
+ const nodeDataType = fbsNode.nodeDataType();
1106
+ const nodeData = parseNodeData(fbsNode, nodeDataType);
1107
+ return { id, path, userData, nodeData };
1108
+ }
1109
+ function parseNodeData(fbsNode, unionType) {
1110
+ if (unionType === 0 /* NONE */ || unionType === 2 /* Group */) {
1111
+ return { type: "group" };
1112
+ }
1113
+ if (unionType === 1 /* Array */) {
1114
+ const arrayData = fbsNode.nodeData(new ArrayNodeData());
1115
+ if (!arrayData) {
1116
+ throw new Error("ArrayNodeData union type but no table");
1117
+ }
1118
+ return parseArrayNodeData(arrayData);
1119
+ }
1120
+ throw new Error(`Unknown node data union type: ${unionType}`);
1121
+ }
1122
+ function parseArrayNodeData(fbsArray) {
1123
+ const shapeLength = fbsArray.shapeLength();
1124
+ const shape = [];
1125
+ for (let i = 0; i < shapeLength; i++) {
1126
+ const fbsShape = fbsArray.shape(i);
1127
+ if (fbsShape) {
1128
+ shape.push({
1129
+ arrayLength: Number(fbsShape.arrayLength()),
1130
+ chunkLength: Number(fbsShape.chunkLength())
1131
+ });
1132
+ }
1133
+ }
1134
+ const dimNamesLength = fbsArray.dimensionNamesLength();
1135
+ const dimensionNames = [];
1136
+ for (let i = 0; i < dimNamesLength; i++) {
1137
+ const fbsDimName = fbsArray.dimensionNames(i);
1138
+ if (fbsDimName) {
1139
+ dimensionNames.push(fbsDimName.name());
1140
+ } else {
1141
+ dimensionNames.push(null);
1142
+ }
1143
+ }
1144
+ const manifestsLength = fbsArray.manifestsLength();
1145
+ const manifests = [];
1146
+ for (let i = 0; i < manifestsLength; i++) {
1147
+ const fbsManifest = fbsArray.manifests(i);
1148
+ if (fbsManifest) {
1149
+ manifests.push(parseManifestRef(fbsManifest));
1150
+ }
1151
+ }
1152
+ return {
1153
+ type: "array",
1154
+ shape,
1155
+ dimensionNames,
1156
+ manifests
1157
+ };
1158
+ }
1159
+ function parseManifestRef(fbsRef) {
1160
+ const objectIdObj = fbsRef.objectId();
1161
+ if (!objectIdObj) throw new Error("ManifestRef missing object_id");
1162
+ const objectId = asObjectId12(readId12(objectIdObj.bb, objectIdObj.bb_pos));
1163
+ const extentsLength = fbsRef.extentsLength();
1164
+ const extents = [];
1165
+ for (let i = 0; i < extentsLength; i++) {
1166
+ const fbsExtent = fbsRef.extents(i);
1167
+ if (fbsExtent) {
1168
+ extents.push({ from: fbsExtent.from(), to: fbsExtent.to() });
1169
+ }
1170
+ }
1171
+ return { objectId, extents };
1172
+ }
1173
+
1174
+ // src/format/flatbuffers/manifest-parser.ts
1175
+ import { ByteBuffer as ByteBuffer3 } from "flatbuffers";
1176
+
1177
+ // src/format/flatbuffers/generated/chunk-ref.ts
1178
+ var ChunkRef = class _ChunkRef {
1179
+ bb = null;
1180
+ bb_pos = 0;
1181
+ __init(i, bb) {
1182
+ this.bb_pos = i;
1183
+ this.bb = bb;
1184
+ return this;
1185
+ }
1186
+ static getRootAsChunkRef(bb, obj) {
1187
+ return (obj || new _ChunkRef()).__init(
1188
+ bb.readInt32(bb.position()) + bb.position(),
1189
+ bb
1190
+ );
1191
+ }
1192
+ index(index) {
1193
+ const offset = this.bb.__offset(this.bb_pos, 4);
1194
+ return offset ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
1195
+ }
1196
+ indexLength() {
1197
+ const offset = this.bb.__offset(this.bb_pos, 4);
1198
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1199
+ }
1200
+ indexArray() {
1201
+ const offset = this.bb.__offset(this.bb_pos, 4);
1202
+ return offset ? new Uint32Array(
1203
+ this.bb.bytes().buffer,
1204
+ this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset),
1205
+ this.bb.__vector_len(this.bb_pos + offset)
1206
+ ) : null;
1207
+ }
1208
+ inline(index) {
1209
+ const offset = this.bb.__offset(this.bb_pos, 6);
1210
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
1211
+ }
1212
+ inlineLength() {
1213
+ const offset = this.bb.__offset(this.bb_pos, 6);
1214
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1215
+ }
1216
+ inlineArray() {
1217
+ const offset = this.bb.__offset(this.bb_pos, 6);
1218
+ return offset ? new Uint8Array(
1219
+ this.bb.bytes().buffer,
1220
+ this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset),
1221
+ this.bb.__vector_len(this.bb_pos + offset)
1222
+ ) : null;
1223
+ }
1224
+ offset() {
1225
+ const offset = this.bb.__offset(this.bb_pos, 8);
1226
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0");
1227
+ }
1228
+ length() {
1229
+ const offset = this.bb.__offset(this.bb_pos, 10);
1230
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0");
1231
+ }
1232
+ chunkId(obj) {
1233
+ const offset = this.bb.__offset(this.bb_pos, 12);
1234
+ return offset ? (obj || new ObjectId12()).__init(this.bb_pos + offset, this.bb) : null;
1235
+ }
1236
+ location(optionalEncoding) {
1237
+ const offset = this.bb.__offset(this.bb_pos, 14);
1238
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
1239
+ }
1240
+ checksumEtag(optionalEncoding) {
1241
+ const offset = this.bb.__offset(this.bb_pos, 16);
1242
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
1243
+ }
1244
+ checksumLastModified() {
1245
+ const offset = this.bb.__offset(this.bb_pos, 18);
1246
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
1247
+ }
1248
+ };
1249
+
1250
+ // src/format/flatbuffers/generated/array-manifest.ts
1251
+ var ArrayManifest = class _ArrayManifest {
1252
+ bb = null;
1253
+ bb_pos = 0;
1254
+ __init(i, bb) {
1255
+ this.bb_pos = i;
1256
+ this.bb = bb;
1257
+ return this;
1258
+ }
1259
+ static getRootAsArrayManifest(bb, obj) {
1260
+ return (obj || new _ArrayManifest()).__init(
1261
+ bb.readInt32(bb.position()) + bb.position(),
1262
+ bb
1263
+ );
1264
+ }
1265
+ nodeId(obj) {
1266
+ const offset = this.bb.__offset(this.bb_pos, 4);
1267
+ return offset ? (obj || new ObjectId8()).__init(this.bb_pos + offset, this.bb) : null;
1268
+ }
1269
+ refs(index, obj) {
1270
+ const offset = this.bb.__offset(this.bb_pos, 6);
1271
+ return offset ? (obj || new ChunkRef()).__init(
1272
+ this.bb.__indirect(
1273
+ this.bb.__vector(this.bb_pos + offset) + index * 4
1274
+ ),
1275
+ this.bb
1276
+ ) : null;
1277
+ }
1278
+ refsLength() {
1279
+ const offset = this.bb.__offset(this.bb_pos, 6);
1280
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1281
+ }
1282
+ };
1283
+
1284
+ // src/format/flatbuffers/generated/manifest.ts
1285
+ var Manifest = class _Manifest {
1286
+ bb = null;
1287
+ bb_pos = 0;
1288
+ __init(i, bb) {
1289
+ this.bb_pos = i;
1290
+ this.bb = bb;
1291
+ return this;
1292
+ }
1293
+ static getRootAsManifest(bb, obj) {
1294
+ return (obj || new _Manifest()).__init(
1295
+ bb.readInt32(bb.position()) + bb.position(),
1296
+ bb
1297
+ );
1298
+ }
1299
+ id(obj) {
1300
+ const offset = this.bb.__offset(this.bb_pos, 4);
1301
+ return offset ? (obj || new ObjectId12()).__init(this.bb_pos + offset, this.bb) : null;
1302
+ }
1303
+ arrays(index, obj) {
1304
+ const offset = this.bb.__offset(this.bb_pos, 6);
1305
+ return offset ? (obj || new ArrayManifest()).__init(
1306
+ this.bb.__indirect(
1307
+ this.bb.__vector(this.bb_pos + offset) + index * 4
1308
+ ),
1309
+ this.bb
1310
+ ) : null;
1311
+ }
1312
+ arraysLength() {
1313
+ const offset = this.bb.__offset(this.bb_pos, 6);
1314
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1315
+ }
1316
+ };
1317
+
1318
+ // src/format/flatbuffers/manifest-parser.ts
1319
+ function parseManifest(data) {
1320
+ const bb = new ByteBuffer3(data);
1321
+ const fbsManifest = Manifest.getRootAsManifest(bb);
1322
+ const idObj = fbsManifest.id();
1323
+ if (!idObj) throw new Error("Manifest missing required id field");
1324
+ const id = asObjectId12(
1325
+ idObj.bb.bytes().slice(idObj.bb_pos, idObj.bb_pos + 12)
1326
+ );
1327
+ const arraysLength = fbsManifest.arraysLength();
1328
+ const arrays = [];
1329
+ for (let i = 0; i < arraysLength; i++) {
1330
+ const fbsArray = fbsManifest.arrays(i);
1331
+ if (fbsArray) {
1332
+ arrays.push(parseArrayManifest(fbsArray));
1333
+ }
1334
+ }
1335
+ return { id, arrays };
1336
+ }
1337
+ function parseArrayManifest(fbsArray) {
1338
+ const nodeIdObj = fbsArray.nodeId();
1339
+ if (!nodeIdObj)
1340
+ throw new Error("ArrayManifest missing required node_id field");
1341
+ const nodeId = asObjectId8(
1342
+ nodeIdObj.bb.bytes().slice(nodeIdObj.bb_pos, nodeIdObj.bb_pos + 8)
1343
+ );
1344
+ const refsLength = fbsArray.refsLength();
1345
+ const refs = [];
1346
+ for (let i = 0; i < refsLength; i++) {
1347
+ const fbsRef = fbsArray.refs(i);
1348
+ if (fbsRef) {
1349
+ refs.push(parseChunkRef(fbsRef));
1350
+ }
1351
+ }
1352
+ return { nodeId, refs };
1353
+ }
1354
+ function parseChunkRef(fbsRef) {
1355
+ const indexLength = fbsRef.indexLength();
1356
+ const index = [];
1357
+ for (let i = 0; i < indexLength; i++) {
1358
+ index.push(fbsRef.index(i));
1359
+ }
1360
+ const inlineData = fbsRef.inlineArray();
1361
+ const inline = inlineData ? new Uint8Array(inlineData) : null;
1362
+ const offset = Number(fbsRef.offset());
1363
+ const length = Number(fbsRef.length());
1364
+ const chunkIdObj = fbsRef.chunkId();
1365
+ const chunkId = chunkIdObj ? asObjectId12(
1366
+ chunkIdObj.bb.bytes().slice(chunkIdObj.bb_pos, chunkIdObj.bb_pos + 12)
1367
+ ) : null;
1368
+ const location = fbsRef.location();
1369
+ const checksumEtag = fbsRef.checksumEtag();
1370
+ const checksumLastModified = fbsRef.checksumLastModified();
1371
+ return {
1372
+ index,
1373
+ inline,
1374
+ offset,
1375
+ length,
1376
+ chunkId,
1377
+ location,
1378
+ checksumEtag,
1379
+ checksumLastModified
1380
+ };
1381
+ }
1382
+ function findChunkRef(manifest, nodeId, coords) {
1383
+ const arrayManifest = binarySearchArrayManifest(manifest.arrays, nodeId);
1384
+ if (!arrayManifest) return null;
1385
+ return binarySearchChunkRef(arrayManifest.refs, coords);
1386
+ }
1387
+ function binarySearchArrayManifest(arrays, nodeId) {
1388
+ let low = 0;
1389
+ let high = arrays.length - 1;
1390
+ while (low <= high) {
1391
+ const mid = Math.floor((low + high) / 2);
1392
+ const cmp = compareBytes(arrays[mid].nodeId, nodeId);
1393
+ if (cmp === 0) {
1394
+ return arrays[mid];
1395
+ } else if (cmp < 0) {
1396
+ low = mid + 1;
1397
+ } else {
1398
+ high = mid - 1;
1399
+ }
1400
+ }
1401
+ return null;
1402
+ }
1403
+ function compareBytes(a, b) {
1404
+ const minLen = Math.min(a.length, b.length);
1405
+ for (let i = 0; i < minLen; i++) {
1406
+ if (a[i] !== b[i]) return a[i] - b[i];
1407
+ }
1408
+ return a.length - b.length;
1409
+ }
1410
+ function compareCoords(a, b) {
1411
+ const minLen = Math.min(a.length, b.length);
1412
+ for (let i = 0; i < minLen; i++) {
1413
+ if (a[i] !== b[i]) return a[i] - b[i];
1414
+ }
1415
+ return a.length - b.length;
1416
+ }
1417
+ function binarySearchChunkRef(refs, coords) {
1418
+ let low = 0;
1419
+ let high = refs.length - 1;
1420
+ while (low <= high) {
1421
+ const mid = Math.floor((low + high) / 2);
1422
+ const cmp = compareCoords(refs[mid].index, coords);
1423
+ if (cmp === 0) {
1424
+ return refs[mid];
1425
+ } else if (cmp < 0) {
1426
+ low = mid + 1;
1427
+ } else {
1428
+ high = mid - 1;
1429
+ }
1430
+ }
1431
+ return null;
1432
+ }
1433
+ function getChunkPayload(ref) {
1434
+ if (ref.inline !== null) {
1435
+ return { type: "inline", data: ref.inline };
1436
+ }
1437
+ if (ref.chunkId !== null) {
1438
+ return {
1439
+ type: "native",
1440
+ chunkId: ref.chunkId,
1441
+ offset: ref.offset,
1442
+ length: ref.length
1443
+ };
1444
+ }
1445
+ if (ref.location !== null) {
1446
+ return {
1447
+ type: "virtual",
1448
+ location: ref.location,
1449
+ offset: ref.offset,
1450
+ length: ref.length,
1451
+ checksumEtag: ref.checksumEtag,
1452
+ checksumLastModified: ref.checksumLastModified
1453
+ };
1454
+ }
1455
+ throw new Error("Invalid ChunkRef: no inline, chunkId, or location");
1456
+ }
1457
+
1458
+ // src/format/flatbuffers/metadata.ts
1459
+ import { decode } from "@msgpack/msgpack";
1460
+ import * as flexbuffers from "flatbuffers/js/flexbuffers.js";
1461
+ function deserializeMetadata(items, specVersion) {
1462
+ const result = /* @__PURE__ */ Object.create(null);
1463
+ for (const item of items) {
1464
+ result[item.name] = specVersion === 1 /* V1_0 */ ? decode(item.value) : flexbuffers.toObject(
1465
+ item.value.buffer.slice(
1466
+ item.value.byteOffset,
1467
+ item.value.byteOffset + item.value.byteLength
1468
+ )
1469
+ );
1470
+ }
1471
+ return result;
1472
+ }
1473
+
1474
+ // src/format/flatbuffers/transaction-log-parser.ts
1475
+ import { ByteBuffer as ByteBuffer4 } from "flatbuffers";
1476
+
1477
+ // src/format/flatbuffers/generated/chunk-indices.ts
1478
+ var ChunkIndices = class _ChunkIndices {
1479
+ bb = null;
1480
+ bb_pos = 0;
1481
+ __init(i, bb) {
1482
+ this.bb_pos = i;
1483
+ this.bb = bb;
1484
+ return this;
1485
+ }
1486
+ static getRootAsChunkIndices(bb, obj) {
1487
+ return (obj || new _ChunkIndices()).__init(
1488
+ bb.readInt32(bb.position()) + bb.position(),
1489
+ bb
1490
+ );
1491
+ }
1492
+ coords(index) {
1493
+ const offset = this.bb.__offset(this.bb_pos, 4);
1494
+ return offset ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
1495
+ }
1496
+ coordsLength() {
1497
+ const offset = this.bb.__offset(this.bb_pos, 4);
1498
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1499
+ }
1500
+ coordsArray() {
1501
+ const offset = this.bb.__offset(this.bb_pos, 4);
1502
+ return offset ? new Uint32Array(
1503
+ this.bb.bytes().buffer,
1504
+ this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset),
1505
+ this.bb.__vector_len(this.bb_pos + offset)
1506
+ ) : null;
1507
+ }
1508
+ };
1509
+
1510
+ // src/format/flatbuffers/generated/array-updated-chunks.ts
1511
+ var ArrayUpdatedChunks = class _ArrayUpdatedChunks {
1512
+ bb = null;
1513
+ bb_pos = 0;
1514
+ __init(i, bb) {
1515
+ this.bb_pos = i;
1516
+ this.bb = bb;
1517
+ return this;
1518
+ }
1519
+ static getRootAsArrayUpdatedChunks(bb, obj) {
1520
+ return (obj || new _ArrayUpdatedChunks()).__init(
1521
+ bb.readInt32(bb.position()) + bb.position(),
1522
+ bb
1523
+ );
1524
+ }
1525
+ nodeId(obj) {
1526
+ const offset = this.bb.__offset(this.bb_pos, 4);
1527
+ return offset ? (obj || new ObjectId8()).__init(this.bb_pos + offset, this.bb) : null;
1528
+ }
1529
+ chunks(index, obj) {
1530
+ const offset = this.bb.__offset(this.bb_pos, 6);
1531
+ return offset ? (obj || new ChunkIndices()).__init(
1532
+ this.bb.__indirect(
1533
+ this.bb.__vector(this.bb_pos + offset) + index * 4
1534
+ ),
1535
+ this.bb
1536
+ ) : null;
1537
+ }
1538
+ chunksLength() {
1539
+ const offset = this.bb.__offset(this.bb_pos, 6);
1540
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1541
+ }
1542
+ };
1543
+
1544
+ // src/format/flatbuffers/generated/move-operation.ts
1545
+ var MoveOperation = class _MoveOperation {
1546
+ bb = null;
1547
+ bb_pos = 0;
1548
+ __init(i, bb) {
1549
+ this.bb_pos = i;
1550
+ this.bb = bb;
1551
+ return this;
1552
+ }
1553
+ static getRootAsMoveOperation(bb, obj) {
1554
+ return (obj || new _MoveOperation()).__init(
1555
+ bb.readInt32(bb.position()) + bb.position(),
1556
+ bb
1557
+ );
1558
+ }
1559
+ from(optionalEncoding) {
1560
+ const offset = this.bb.__offset(this.bb_pos, 4);
1561
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
1562
+ }
1563
+ to(optionalEncoding) {
1564
+ const offset = this.bb.__offset(this.bb_pos, 6);
1565
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
1566
+ }
1567
+ };
1568
+
1569
+ // src/format/flatbuffers/generated/transaction-log.ts
1570
+ var TransactionLog = class _TransactionLog {
1571
+ bb = null;
1572
+ bb_pos = 0;
1573
+ __init(i, bb) {
1574
+ this.bb_pos = i;
1575
+ this.bb = bb;
1576
+ return this;
1577
+ }
1578
+ static getRootAsTransactionLog(bb, obj) {
1579
+ return (obj || new _TransactionLog()).__init(
1580
+ bb.readInt32(bb.position()) + bb.position(),
1581
+ bb
1582
+ );
1583
+ }
1584
+ id(obj) {
1585
+ const offset = this.bb.__offset(this.bb_pos, 4);
1586
+ return offset ? (obj || new ObjectId12()).__init(this.bb_pos + offset, this.bb) : null;
1587
+ }
1588
+ newGroups(index, obj) {
1589
+ const offset = this.bb.__offset(this.bb_pos, 6);
1590
+ return offset ? (obj || new ObjectId8()).__init(
1591
+ this.bb.__vector(this.bb_pos + offset) + index * 8,
1592
+ this.bb
1593
+ ) : null;
1594
+ }
1595
+ newGroupsLength() {
1596
+ const offset = this.bb.__offset(this.bb_pos, 6);
1597
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1598
+ }
1599
+ newArrays(index, obj) {
1600
+ const offset = this.bb.__offset(this.bb_pos, 8);
1601
+ return offset ? (obj || new ObjectId8()).__init(
1602
+ this.bb.__vector(this.bb_pos + offset) + index * 8,
1603
+ this.bb
1604
+ ) : null;
1605
+ }
1606
+ newArraysLength() {
1607
+ const offset = this.bb.__offset(this.bb_pos, 8);
1608
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1609
+ }
1610
+ deletedGroups(index, obj) {
1611
+ const offset = this.bb.__offset(this.bb_pos, 10);
1612
+ return offset ? (obj || new ObjectId8()).__init(
1613
+ this.bb.__vector(this.bb_pos + offset) + index * 8,
1614
+ this.bb
1615
+ ) : null;
1616
+ }
1617
+ deletedGroupsLength() {
1618
+ const offset = this.bb.__offset(this.bb_pos, 10);
1619
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1620
+ }
1621
+ deletedArrays(index, obj) {
1622
+ const offset = this.bb.__offset(this.bb_pos, 12);
1623
+ return offset ? (obj || new ObjectId8()).__init(
1624
+ this.bb.__vector(this.bb_pos + offset) + index * 8,
1625
+ this.bb
1626
+ ) : null;
1627
+ }
1628
+ deletedArraysLength() {
1629
+ const offset = this.bb.__offset(this.bb_pos, 12);
1630
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1631
+ }
1632
+ updatedArrays(index, obj) {
1633
+ const offset = this.bb.__offset(this.bb_pos, 14);
1634
+ return offset ? (obj || new ObjectId8()).__init(
1635
+ this.bb.__vector(this.bb_pos + offset) + index * 8,
1636
+ this.bb
1637
+ ) : null;
1638
+ }
1639
+ updatedArraysLength() {
1640
+ const offset = this.bb.__offset(this.bb_pos, 14);
1641
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1642
+ }
1643
+ updatedGroups(index, obj) {
1644
+ const offset = this.bb.__offset(this.bb_pos, 16);
1645
+ return offset ? (obj || new ObjectId8()).__init(
1646
+ this.bb.__vector(this.bb_pos + offset) + index * 8,
1647
+ this.bb
1648
+ ) : null;
1649
+ }
1650
+ updatedGroupsLength() {
1651
+ const offset = this.bb.__offset(this.bb_pos, 16);
1652
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1653
+ }
1654
+ updatedChunks(index, obj) {
1655
+ const offset = this.bb.__offset(this.bb_pos, 18);
1656
+ return offset ? (obj || new ArrayUpdatedChunks()).__init(
1657
+ this.bb.__indirect(
1658
+ this.bb.__vector(this.bb_pos + offset) + index * 4
1659
+ ),
1660
+ this.bb
1661
+ ) : null;
1662
+ }
1663
+ updatedChunksLength() {
1664
+ const offset = this.bb.__offset(this.bb_pos, 18);
1665
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1666
+ }
1667
+ movedNodes(index, obj) {
1668
+ const offset = this.bb.__offset(this.bb_pos, 20);
1669
+ return offset ? (obj || new MoveOperation()).__init(
1670
+ this.bb.__indirect(
1671
+ this.bb.__vector(this.bb_pos + offset) + index * 4
1672
+ ),
1673
+ this.bb
1674
+ ) : null;
1675
+ }
1676
+ movedNodesLength() {
1677
+ const offset = this.bb.__offset(this.bb_pos, 20);
1678
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
1679
+ }
1680
+ };
1681
+
1682
+ // src/format/flatbuffers/transaction-log-parser.ts
1683
+ function readId122(bb, bbPos) {
1684
+ return bb.bytes().slice(bbPos, bbPos + 12);
1685
+ }
1686
+ function readId82(bb, bbPos) {
1687
+ return bb.bytes().slice(bbPos, bbPos + 8);
1688
+ }
1689
+ function readId8Vector(length, accessor) {
1690
+ const result = [];
1691
+ for (let i = 0; i < length; i++) {
1692
+ const obj = accessor(i);
1693
+ if (obj && obj.bb) {
1694
+ result.push(asObjectId8(readId82(obj.bb, obj.bb_pos)));
1695
+ }
1696
+ }
1697
+ return result;
1698
+ }
1699
+ function parseTransactionLog(data) {
1700
+ const bb = new ByteBuffer4(data);
1701
+ const fbs = TransactionLog.getRootAsTransactionLog(bb);
1702
+ const idObj = fbs.id();
1703
+ if (!idObj) throw new Error("TransactionLog missing required id field");
1704
+ const id = asObjectId12(readId122(idObj.bb, idObj.bb_pos));
1705
+ const newGroups = readId8Vector(
1706
+ fbs.newGroupsLength(),
1707
+ (i) => fbs.newGroups(i)
1708
+ );
1709
+ const newArrays = readId8Vector(
1710
+ fbs.newArraysLength(),
1711
+ (i) => fbs.newArrays(i)
1712
+ );
1713
+ const deletedGroups = readId8Vector(
1714
+ fbs.deletedGroupsLength(),
1715
+ (i) => fbs.deletedGroups(i)
1716
+ );
1717
+ const deletedArrays = readId8Vector(
1718
+ fbs.deletedArraysLength(),
1719
+ (i) => fbs.deletedArrays(i)
1720
+ );
1721
+ const updatedArrays = readId8Vector(
1722
+ fbs.updatedArraysLength(),
1723
+ (i) => fbs.updatedArrays(i)
1724
+ );
1725
+ const updatedGroups = readId8Vector(
1726
+ fbs.updatedGroupsLength(),
1727
+ (i) => fbs.updatedGroups(i)
1728
+ );
1729
+ const updatedChunks = [];
1730
+ for (let i = 0; i < fbs.updatedChunksLength(); i++) {
1731
+ const fbsChunk = fbs.updatedChunks(i);
1732
+ if (!fbsChunk) continue;
1733
+ const nodeIdObj = fbsChunk.nodeId();
1734
+ if (!nodeIdObj || !nodeIdObj.bb) continue;
1735
+ const nodeId = asObjectId8(readId82(nodeIdObj.bb, nodeIdObj.bb_pos));
1736
+ const chunks = [];
1737
+ for (let j = 0; j < fbsChunk.chunksLength(); j++) {
1738
+ const fbsIndices = fbsChunk.chunks(j);
1739
+ if (!fbsIndices) continue;
1740
+ const coords = [];
1741
+ for (let k = 0; k < fbsIndices.coordsLength(); k++) {
1742
+ const coord = fbsIndices.coords(k);
1743
+ if (coord !== null) coords.push(coord);
1744
+ }
1745
+ chunks.push({ coords });
1746
+ }
1747
+ updatedChunks.push({ nodeId, chunks });
1748
+ }
1749
+ const movedNodes = [];
1750
+ for (let i = 0; i < fbs.movedNodesLength(); i++) {
1751
+ const fbsMove = fbs.movedNodes(i);
1752
+ if (!fbsMove) continue;
1753
+ const from = fbsMove.from();
1754
+ const to = fbsMove.to();
1755
+ if (from !== null && to !== null) {
1756
+ movedNodes.push({ from, to });
1757
+ }
1758
+ }
1759
+ return {
1760
+ id,
1761
+ newGroups,
1762
+ newArrays,
1763
+ deletedGroups,
1764
+ deletedArrays,
1765
+ updatedArrays,
1766
+ updatedGroups,
1767
+ updatedChunks,
1768
+ movedNodes
1769
+ };
1770
+ }
1771
+
1772
+ // src/reader/session.ts
1773
+ var ReadSession = class _ReadSession {
1774
+ storage;
1775
+ snapshot;
1776
+ specVersion;
1777
+ manifestCache;
1778
+ constructor(storage, snapshot, specVersion, maxManifestCacheSize = 100) {
1779
+ this.storage = storage;
1780
+ this.snapshot = snapshot;
1781
+ this.specVersion = specVersion;
1782
+ this.manifestCache = new LRUCache(maxManifestCacheSize);
1783
+ }
1784
+ /**
1785
+ * Open a read session for a specific snapshot.
1786
+ *
1787
+ * @param storage - Storage backend
1788
+ * @param snapshotId - Snapshot ID (12 bytes)
1789
+ * @param options - Optional request options (signal for cancellation)
1790
+ * @returns ReadSession instance
1791
+ */
1792
+ static async open(storage, snapshotId, options) {
1793
+ const { snapshot, specVersion } = await _ReadSession.loadSnapshot(
1794
+ storage,
1795
+ snapshotId,
1796
+ options
1797
+ );
1798
+ return new _ReadSession(
1799
+ storage,
1800
+ snapshot,
1801
+ specVersion,
1802
+ options?.maxManifestCacheSize
1803
+ );
1804
+ }
1805
+ /** Load and parse a snapshot from storage */
1806
+ static async loadSnapshot(storage, snapshotId, options) {
1807
+ const path = getSnapshotPath(encodeObjectId12(snapshotId));
1808
+ const data = await storage.getObject(path, void 0, options);
1809
+ const header = parseHeader(data);
1810
+ validateFileType(header, 1 /* Snapshot */);
1811
+ let flatbufferData = getDataAfterHeader(data);
1812
+ if (header.compression === 1 /* Zstd */) {
1813
+ flatbufferData = decompress2(flatbufferData);
1814
+ }
1815
+ return {
1816
+ snapshot: parseSnapshot(flatbufferData),
1817
+ specVersion: header.specVersion
1818
+ };
1819
+ }
1820
+ /** Load and parse a manifest from storage */
1821
+ async loadManifest(manifestId, options) {
1822
+ const idStr = encodeObjectId12(manifestId);
1823
+ const cached = this.manifestCache.get(idStr);
1824
+ if (cached) return cached;
1825
+ const path = getManifestPath(idStr);
1826
+ const data = await this.storage.getObject(path, void 0, options);
1827
+ const header = parseHeader(data);
1828
+ validateFileType(header, 2 /* Manifest */);
1829
+ let flatbufferData = getDataAfterHeader(data);
1830
+ if (header.compression === 1 /* Zstd */) {
1831
+ flatbufferData = decompress2(flatbufferData);
1832
+ }
1833
+ const manifest = parseManifest(flatbufferData);
1834
+ this.manifestCache.set(idStr, manifest);
1835
+ return manifest;
1836
+ }
1837
+ /**
1838
+ * Get the snapshot ID.
1839
+ */
1840
+ getSnapshotId() {
1841
+ return this.snapshot.id;
1842
+ }
1843
+ /**
1844
+ * Get the spec version of the snapshot.
1845
+ */
1846
+ getSpecVersion() {
1847
+ return this.specVersion;
1848
+ }
1849
+ /**
1850
+ * Get the parent snapshot ID, or null for root snapshots.
1851
+ */
1852
+ getParentSnapshotId() {
1853
+ return this.snapshot.parentId;
1854
+ }
1855
+ /**
1856
+ * Get the commit message for this snapshot.
1857
+ */
1858
+ getMessage() {
1859
+ return this.snapshot.message;
1860
+ }
1861
+ /**
1862
+ * Get the timestamp when this snapshot was created.
1863
+ */
1864
+ getFlushedAt() {
1865
+ return new Date(Number(this.snapshot.flushedAt / 1000n));
1866
+ }
1867
+ /**
1868
+ * Get deserialized snapshot metadata.
1869
+ *
1870
+ * Decodes MessagePack (v1) or FlexBuffers (v2) metadata items
1871
+ * into a plain key-value object.
1872
+ */
1873
+ getSnapshotMetadata() {
1874
+ return deserializeMetadata(this.snapshot.metadata, this.specVersion);
1875
+ }
1876
+ /**
1877
+ * Load and parse the transaction log for this snapshot.
1878
+ *
1879
+ * Returns null if no transaction log exists (e.g., root snapshot).
1880
+ *
1881
+ * @param options - Optional request options (signal for cancellation)
1882
+ * @returns Parsed transaction log entry or null
1883
+ */
1884
+ async loadTransactionLog(options) {
1885
+ const path = getTransactionLogPath(encodeObjectId12(this.snapshot.id));
1886
+ let data;
1887
+ try {
1888
+ data = await this.storage.getObject(path, void 0, options);
1889
+ } catch (error) {
1890
+ if (error instanceof NotFoundError) return null;
1891
+ throw error;
1892
+ }
1893
+ const header = parseHeader(data);
1894
+ validateFileType(header, 4 /* TransactionLog */);
1895
+ let flatbufferData = getDataAfterHeader(data);
1896
+ if (header.compression === 1 /* Zstd */) {
1897
+ flatbufferData = decompress2(flatbufferData);
1898
+ }
1899
+ return parseTransactionLog(flatbufferData);
1900
+ }
1901
+ /**
1902
+ * Get a node by path.
1903
+ *
1904
+ * @param path - Absolute path (e.g., "/array" or "/group/nested")
1905
+ * @returns NodeSnapshot or null if not found
1906
+ */
1907
+ getNode(path) {
1908
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
1909
+ return this.binarySearchNode(normalizedPath);
1910
+ }
1911
+ /**
1912
+ * List all nodes in the snapshot.
1913
+ *
1914
+ * @returns Array of all nodes
1915
+ */
1916
+ listNodes() {
1917
+ return [...this.snapshot.nodes];
1918
+ }
1919
+ /**
1920
+ * List children of a group.
1921
+ *
1922
+ * @param parentPath - Path to the parent group (use "/" for root)
1923
+ * @returns Array of child nodes
1924
+ */
1925
+ listChildren(parentPath) {
1926
+ const normalizedParent = parentPath === "/" ? "" : parentPath;
1927
+ const prefix = normalizedParent + "/";
1928
+ return this.snapshot.nodes.filter((node) => {
1929
+ if (!node.path.startsWith(prefix)) return false;
1930
+ const rest = node.path.slice(prefix.length);
1931
+ return !rest.includes("/");
1932
+ });
1933
+ }
1934
+ /**
1935
+ * Get the Zarr metadata for a node.
1936
+ *
1937
+ * @param path - Path to the node
1938
+ * @returns Parsed JSON metadata or null if node not found
1939
+ */
1940
+ getMetadata(path) {
1941
+ const node = this.getNode(path);
1942
+ if (!node) return null;
1943
+ const json = new TextDecoder().decode(node.userData);
1944
+ return JSON.parse(json);
1945
+ }
1946
+ /**
1947
+ * Get raw user data (Zarr metadata bytes) for a node.
1948
+ *
1949
+ * @param path - Path to the node
1950
+ * @returns Raw metadata bytes or null if node not found
1951
+ */
1952
+ getRawMetadata(path) {
1953
+ const node = this.getNode(path);
1954
+ if (!node) return null;
1955
+ return node.userData;
1956
+ }
1957
+ /**
1958
+ * Read chunk data for an array.
1959
+ *
1960
+ * @param path - Path to the array
1961
+ * @param coords - Chunk coordinates (N-dimensional)
1962
+ * @param options - Optional request options (signal for cancellation)
1963
+ * @returns Chunk data bytes or null if not found
1964
+ */
1965
+ async getChunk(path, coords, options) {
1966
+ if (options?.signal?.aborted) return null;
1967
+ const node = this.getNode(path);
1968
+ if (!node || node.nodeData.type !== "array") {
1969
+ return null;
1970
+ }
1971
+ const arrayData = node.nodeData;
1972
+ try {
1973
+ for (const manifestRef of arrayData.manifests) {
1974
+ if (!this.coordsInExtents(coords, manifestRef.extents)) {
1975
+ continue;
1976
+ }
1977
+ const manifest = await this.loadManifest(manifestRef.objectId, options);
1978
+ const chunkRef = findChunkRef(manifest, node.id, coords);
1979
+ if (!chunkRef) continue;
1980
+ const payload = getChunkPayload(chunkRef);
1981
+ return this.fetchChunkPayload(payload, options);
1982
+ }
1983
+ } catch (error) {
1984
+ if (error instanceof AbortError) return null;
1985
+ throw error;
1986
+ }
1987
+ return null;
1988
+ }
1989
+ /**
1990
+ * Read a byte range of chunk data for an array.
1991
+ *
1992
+ * Like getChunk, but fetches only the requested byte range from storage
1993
+ * instead of the full chunk. Used by IcechunkStore.getRange to support
1994
+ * zarrita's sharded array reads efficiently.
1995
+ *
1996
+ * @param path - Path to the array
1997
+ * @param coords - Chunk coordinates (N-dimensional)
1998
+ * @param range - Byte range within the chunk data
1999
+ * @param options - Optional request options (signal for cancellation)
2000
+ * @returns Chunk data bytes or null if not found
2001
+ */
2002
+ async getChunkRange(path, coords, range, options) {
2003
+ if (options?.signal?.aborted) return null;
2004
+ const node = this.getNode(path);
2005
+ if (!node || node.nodeData.type !== "array") {
2006
+ return null;
2007
+ }
2008
+ const arrayData = node.nodeData;
2009
+ try {
2010
+ for (const manifestRef of arrayData.manifests) {
2011
+ if (!this.coordsInExtents(coords, manifestRef.extents)) {
2012
+ continue;
2013
+ }
2014
+ const manifest = await this.loadManifest(manifestRef.objectId, options);
2015
+ const chunkRef = findChunkRef(manifest, node.id, coords);
2016
+ if (!chunkRef) continue;
2017
+ const payload = getChunkPayload(chunkRef);
2018
+ return this.fetchChunkPayloadRange(payload, range, options);
2019
+ }
2020
+ } catch (error) {
2021
+ if (error instanceof AbortError) return null;
2022
+ throw error;
2023
+ }
2024
+ return null;
2025
+ }
2026
+ /** Check if coordinates fall within extent ranges */
2027
+ coordsInExtents(coords, extents) {
2028
+ if (coords.length !== extents.length) return false;
2029
+ for (let i = 0; i < coords.length; i++) {
2030
+ const { from, to } = extents[i];
2031
+ if (coords[i] < from || coords[i] >= to) {
2032
+ return false;
2033
+ }
2034
+ }
2035
+ return true;
2036
+ }
2037
+ /** Fetch chunk data based on payload type */
2038
+ async fetchChunkPayload(payload, options) {
2039
+ switch (payload.type) {
2040
+ case "inline":
2041
+ return payload.data;
2042
+ case "native": {
2043
+ const path = getChunkPath(encodeObjectId12(payload.chunkId));
2044
+ const range = {
2045
+ start: payload.offset,
2046
+ end: payload.offset + payload.length
2047
+ };
2048
+ const data = await this.storage.getObject(path, range, options);
2049
+ if (data.length === payload.length) return data;
2050
+ if (data.length >= range.end) {
2051
+ return data.slice(range.start, range.end);
2052
+ }
2053
+ throw new Error(
2054
+ `Storage returned ${data.length} bytes for ${path} range ${range.start}-${range.end - 1}; expected ${payload.length} bytes`
2055
+ );
2056
+ }
2057
+ case "virtual": {
2058
+ const httpUrl = translateToHttpUrl(
2059
+ payload.location,
2060
+ options?.azureAccount
2061
+ );
2062
+ const headers = {
2063
+ Range: `bytes=${payload.offset}-${payload.offset + payload.length - 1}`
2064
+ };
2065
+ if (options?.validateChecksums) {
2066
+ if (payload.checksumEtag) {
2067
+ headers["If-Match"] = payload.checksumEtag;
2068
+ }
2069
+ if (payload.checksumLastModified > 0) {
2070
+ headers["If-Unmodified-Since"] = new Date(
2071
+ payload.checksumLastModified * 1e3
2072
+ ).toUTCString();
2073
+ }
2074
+ }
2075
+ const fetchInit = {
2076
+ headers,
2077
+ signal: options?.signal
2078
+ };
2079
+ let response;
2080
+ try {
2081
+ const client = options?.fetchClient;
2082
+ response = client ? await client.fetch(httpUrl, fetchInit) : await fetch(httpUrl, fetchInit);
2083
+ } catch (error) {
2084
+ if (error instanceof Error && error.name === "AbortError") {
2085
+ throw new AbortError();
2086
+ }
2087
+ throw error;
2088
+ }
2089
+ if (response.status === 412) {
2090
+ throw new Error(
2091
+ `Virtual chunk at ${httpUrl} failed integrity check \u2014 data has been modified since snapshot was created`
2092
+ );
2093
+ }
2094
+ if (response.status !== 200 && response.status !== 206) {
2095
+ throw new Error(
2096
+ `Failed to fetch virtual chunk from ${httpUrl}: ${response.status} ${response.statusText}`
2097
+ );
2098
+ }
2099
+ const data = new Uint8Array(await response.arrayBuffer());
2100
+ if (response.status === 206) {
2101
+ if (data.length !== payload.length) {
2102
+ throw new Error(
2103
+ `Virtual range response size mismatch for ${httpUrl}: expected ${payload.length} bytes, got ${data.length}`
2104
+ );
2105
+ }
2106
+ return data;
2107
+ }
2108
+ const absoluteEnd = payload.offset + payload.length;
2109
+ if (data.length >= absoluteEnd) {
2110
+ return data.slice(payload.offset, absoluteEnd);
2111
+ }
2112
+ throw new Error(
2113
+ `Virtual range request not honored for ${httpUrl}: need at least ${absoluteEnd} bytes for fallback slicing, got ${data.length}`
2114
+ );
2115
+ }
2116
+ }
2117
+ }
2118
+ /** Fetch a byte range of chunk data based on payload type */
2119
+ async fetchChunkPayloadRange(payload, range, options) {
2120
+ let rangeStart;
2121
+ let rangeEnd;
2122
+ if ("suffixLength" in range) {
2123
+ rangeStart = payload.type === "inline" ? payload.data.length - range.suffixLength : payload.length - range.suffixLength;
2124
+ rangeEnd = payload.type === "inline" ? payload.data.length : payload.length;
2125
+ } else {
2126
+ rangeStart = range.offset;
2127
+ rangeEnd = range.offset + range.length;
2128
+ }
2129
+ switch (payload.type) {
2130
+ case "inline":
2131
+ return payload.data.slice(rangeStart, rangeEnd);
2132
+ case "native": {
2133
+ const path = getChunkPath(encodeObjectId12(payload.chunkId));
2134
+ const storageRange = {
2135
+ start: payload.offset + rangeStart,
2136
+ end: payload.offset + rangeEnd
2137
+ };
2138
+ const expectedSize = rangeEnd - rangeStart;
2139
+ const data = await this.storage.getObject(path, storageRange, options);
2140
+ if (data.length === expectedSize) return data;
2141
+ if (data.length >= storageRange.end) {
2142
+ return data.slice(storageRange.start, storageRange.end);
2143
+ }
2144
+ throw new Error(
2145
+ `Storage returned ${data.length} bytes for ${path} range ${storageRange.start}-${storageRange.end - 1}; expected ${expectedSize} bytes`
2146
+ );
2147
+ }
2148
+ case "virtual": {
2149
+ const absoluteStart = payload.offset + rangeStart;
2150
+ const absoluteEnd = payload.offset + rangeEnd;
2151
+ const httpUrl = translateToHttpUrl(
2152
+ payload.location,
2153
+ options?.azureAccount
2154
+ );
2155
+ const headers = {
2156
+ Range: `bytes=${absoluteStart}-${absoluteEnd - 1}`
2157
+ };
2158
+ if (options?.validateChecksums) {
2159
+ if (payload.checksumEtag) {
2160
+ headers["If-Match"] = payload.checksumEtag;
2161
+ }
2162
+ if (payload.checksumLastModified > 0) {
2163
+ headers["If-Unmodified-Since"] = new Date(
2164
+ payload.checksumLastModified * 1e3
2165
+ ).toUTCString();
2166
+ }
2167
+ }
2168
+ const fetchInit = {
2169
+ headers,
2170
+ signal: options?.signal
2171
+ };
2172
+ let response;
2173
+ try {
2174
+ const client = options?.fetchClient;
2175
+ response = client ? await client.fetch(httpUrl, fetchInit) : await fetch(httpUrl, fetchInit);
2176
+ } catch (error) {
2177
+ if (error instanceof Error && error.name === "AbortError") {
2178
+ throw new AbortError();
2179
+ }
2180
+ throw error;
2181
+ }
2182
+ if (response.status === 412) {
2183
+ throw new Error(
2184
+ `Virtual chunk at ${httpUrl} failed integrity check \u2014 data has been modified since snapshot was created`
2185
+ );
2186
+ }
2187
+ if (response.status !== 200 && response.status !== 206) {
2188
+ throw new Error(
2189
+ `Failed to fetch virtual chunk from ${httpUrl}: ${response.status} ${response.statusText}`
2190
+ );
2191
+ }
2192
+ const expectedSize = rangeEnd - rangeStart;
2193
+ const data = new Uint8Array(await response.arrayBuffer());
2194
+ if (response.status === 206) {
2195
+ if (data.length !== expectedSize) {
2196
+ throw new Error(
2197
+ `Virtual range response size mismatch for ${httpUrl}: expected ${expectedSize} bytes, got ${data.length}`
2198
+ );
2199
+ }
2200
+ return data;
2201
+ }
2202
+ if (data.length >= absoluteEnd) {
2203
+ return data.slice(absoluteStart, absoluteEnd);
2204
+ }
2205
+ throw new Error(
2206
+ `Virtual range request not honored for ${httpUrl}: need at least ${absoluteEnd} bytes for fallback slicing, got ${data.length}`
2207
+ );
2208
+ }
2209
+ }
2210
+ }
2211
+ /** Binary search for a node by path */
2212
+ binarySearchNode(path) {
2213
+ const nodes = this.snapshot.nodes;
2214
+ let low = 0;
2215
+ let high = nodes.length - 1;
2216
+ while (low <= high) {
2217
+ const mid = Math.floor((low + high) / 2);
2218
+ const cmp = compareUtf8Bytes(nodes[mid].path, path);
2219
+ if (cmp === 0) {
2220
+ return nodes[mid];
2221
+ } else if (cmp < 0) {
2222
+ low = mid + 1;
2223
+ } else {
2224
+ high = mid - 1;
2225
+ }
2226
+ }
2227
+ return null;
2228
+ }
2229
+ };
2230
+ var utf8Encoder = new TextEncoder();
2231
+ function compareUtf8Bytes(a, b) {
2232
+ const bytesA = utf8Encoder.encode(a);
2233
+ const bytesB = utf8Encoder.encode(b);
2234
+ const minLen = Math.min(bytesA.length, bytesB.length);
2235
+ for (let i = 0; i < minLen; i++) {
2236
+ if (bytesA[i] !== bytesB[i]) {
2237
+ return bytesA[i] - bytesB[i];
2238
+ }
2239
+ }
2240
+ return bytesA.length - bytesB.length;
2241
+ }
2242
+ function translateToHttpUrl(url, azureAccount) {
2243
+ if (url.startsWith("s3://")) {
2244
+ const rest = url.slice(5);
2245
+ const slashIndex = rest.indexOf("/");
2246
+ if (slashIndex === -1) {
2247
+ const bucket2 = rest;
2248
+ if (bucket2.includes(".")) {
2249
+ return `https://s3.amazonaws.com/${bucket2}/`;
2250
+ }
2251
+ return `https://${bucket2}.s3.amazonaws.com/`;
2252
+ }
2253
+ const bucket = rest.slice(0, slashIndex);
2254
+ const key = rest.slice(slashIndex + 1);
2255
+ if (bucket.includes(".")) {
2256
+ return `https://s3.amazonaws.com/${bucket}/${key}`;
2257
+ }
2258
+ return `https://${bucket}.s3.amazonaws.com/${key}`;
2259
+ }
2260
+ if (url.startsWith("gs://") || url.startsWith("gcs://")) {
2261
+ const prefixLen = url.startsWith("gs://") ? 5 : 6;
2262
+ const rest = url.slice(prefixLen);
2263
+ return `https://storage.googleapis.com/${rest}`;
2264
+ }
2265
+ if (url.startsWith("az://") || url.startsWith("azure://")) {
2266
+ if (!azureAccount) {
2267
+ throw new Error(
2268
+ `Cannot translate Azure URL "${url}": azureAccount option is required. az:// and azure:// URLs encode only the container name; pass azureAccount in store options to supply the storage account.`
2269
+ );
2270
+ }
2271
+ const prefixLen = url.startsWith("az://") ? 5 : 8;
2272
+ const rest = url.slice(prefixLen);
2273
+ const firstSlash = rest.indexOf("/");
2274
+ if (firstSlash === -1) {
2275
+ return `https://${azureAccount}.blob.core.windows.net/${rest}`;
2276
+ }
2277
+ const container = rest.slice(0, firstSlash);
2278
+ const path = rest.slice(firstSlash + 1);
2279
+ return `https://${azureAccount}.blob.core.windows.net/${container}/${path}`;
2280
+ }
2281
+ if (url.startsWith("abfs://")) {
2282
+ const rest = url.slice(7);
2283
+ const atIndex = rest.indexOf("@");
2284
+ if (atIndex !== -1) {
2285
+ const container = rest.slice(0, atIndex);
2286
+ const hostAndPath = rest.slice(atIndex + 1);
2287
+ const firstSlash = hostAndPath.indexOf("/");
2288
+ const host = firstSlash === -1 ? hostAndPath : hostAndPath.slice(0, firstSlash);
2289
+ const path = firstSlash === -1 ? "" : hostAndPath.slice(firstSlash + 1);
2290
+ const dotIndex = host.indexOf(".");
2291
+ const account = dotIndex === -1 ? host : host.slice(0, dotIndex);
2292
+ const suffix = path ? `${container}/${path}` : container;
2293
+ return `https://${account}.blob.core.windows.net/${suffix}`;
2294
+ }
2295
+ }
2296
+ return url;
2297
+ }
2298
+
2299
+ // src/reader/repository.ts
2300
+ var Repository = class _Repository {
2301
+ storage;
2302
+ repoInfo = null;
2303
+ repoInfoAttempted = false;
2304
+ constructor(storage) {
2305
+ this.storage = storage;
2306
+ }
2307
+ /**
2308
+ * Load and cache the v2 repo info file.
2309
+ *
2310
+ * Uses getObject() directly to avoid race conditions with exists().
2311
+ * - NotFoundError => v1 format (no repo file)
2312
+ * - Any other error => hard error (parse failure, etc.)
2313
+ *
2314
+ * @param options - Optional request options (signal for cancellation)
2315
+ * @returns ParsedRepo if v2 format, null if v1 format
2316
+ * @throws Error if repo file exists but fails to parse
2317
+ * @throws AbortError if the operation was aborted
2318
+ */
2319
+ async loadRepoInfo(options) {
2320
+ if (this.repoInfoAttempted) {
2321
+ return this.repoInfo;
2322
+ }
2323
+ this.repoInfoAttempted = true;
2324
+ try {
2325
+ const data = await this.storage.getObject(
2326
+ REPO_INFO_PATH,
2327
+ void 0,
2328
+ options
2329
+ );
2330
+ this.repoInfo = parseRepo(data);
2331
+ return this.repoInfo;
2332
+ } catch (error) {
2333
+ if (error instanceof AbortError) {
2334
+ this.repoInfoAttempted = false;
2335
+ throw error;
2336
+ }
2337
+ if (error instanceof NotFoundError) {
2338
+ return null;
2339
+ }
2340
+ throw new Error(
2341
+ `Failed to parse v2 repo file: ${error instanceof Error ? error.message : error}`
2342
+ );
2343
+ }
2344
+ }
2345
+ /**
2346
+ * Open an icechunk repository.
2347
+ *
2348
+ * - Try to load and parse repo info file (v2+ format)
2349
+ * - If NotFoundError, check for main branch (v1 format)
2350
+ * - Parse failures are hard errors (matching Rust behavior)
2351
+ *
2352
+ * @param options - Repository options including storage backend
2353
+ * @param requestOptions - Optional request options (signal for cancellation)
2354
+ * @returns A Repository instance
2355
+ */
2356
+ static async open(options, requestOptions) {
2357
+ const repo = new _Repository(options.storage);
2358
+ if (options.formatVersion === "v1") {
2359
+ repo.repoInfoAttempted = true;
2360
+ return repo;
2361
+ }
2362
+ const repoInfo = await repo.loadRepoInfo(requestOptions);
2363
+ if (repoInfo) {
2364
+ return repo;
2365
+ }
2366
+ if (options.formatVersion === "v2") {
2367
+ throw new Error("Repository info not found but v2 format was specified");
2368
+ }
2369
+ const mainBranchDir = getBranchRefDirPath("main");
2370
+ const mainExists = await repo.hasAnyRefFile(
2371
+ mainBranchDir,
2372
+ getBranchRefPath("main"),
2373
+ requestOptions
2374
+ );
2375
+ if (mainExists) {
2376
+ return repo;
2377
+ }
2378
+ throw new Error(
2379
+ "Not a valid icechunk repository: neither repo info file nor main branch found"
2380
+ );
2381
+ }
2382
+ /**
2383
+ * Check if any ref file exists in a directory.
2384
+ * Ref files are .json files that are not .deleted files.
2385
+ *
2386
+ * @param dirPrefix - Directory prefix to check
2387
+ * @param legacyPath - Optional legacy ref.json path to check if listing fails
2388
+ * @param options - Optional request options (signal for cancellation)
2389
+ */
2390
+ async hasAnyRefFile(dirPrefix, legacyPath, options) {
2391
+ try {
2392
+ for await (const path of this.storage.listPrefix(dirPrefix)) {
2393
+ if (path.endsWith(".json") && !path.endsWith(".deleted")) {
2394
+ return true;
2395
+ }
2396
+ }
2397
+ } catch (error) {
2398
+ if (error instanceof AbortError) {
2399
+ throw error;
2400
+ }
2401
+ if (legacyPath) {
2402
+ return await this.storage.exists(legacyPath, options);
2403
+ }
2404
+ }
2405
+ return false;
2406
+ }
2407
+ /**
2408
+ * Find the latest non-deleted ref file in a directory.
2409
+ * When storage supports listPrefix(), refs may use versioned filenames
2410
+ * (e.g., AAAAAAAA.json) for optimistic concurrency control. The latest
2411
+ * version has the highest filename. Deletion tombstones are checked.
2412
+ *
2413
+ * When listing is not supported (e.g., HTTP storage), only the legacy
2414
+ * ref.json path is checked (no tombstone check - assumes read-only).
2415
+ *
2416
+ * @param dirPrefix - Directory prefix to search
2417
+ * @param legacyPath - Optional legacy ref.json path to try if listing fails
2418
+ */
2419
+ async findLatestRefFile(dirPrefix, legacyPath) {
2420
+ const jsonFiles = [];
2421
+ const deletedFiles = /* @__PURE__ */ new Set();
2422
+ try {
2423
+ for await (const path of this.storage.listPrefix(dirPrefix)) {
2424
+ if (path.endsWith(".deleted")) {
2425
+ deletedFiles.add(path.slice(0, -".deleted".length));
2426
+ } else if (path.endsWith(".json")) {
2427
+ jsonFiles.push(path);
2428
+ }
2429
+ }
2430
+ } catch (error) {
2431
+ if (error instanceof AbortError) {
2432
+ throw error;
2433
+ }
2434
+ return legacyPath || null;
2435
+ }
2436
+ if (jsonFiles.length === 0) {
2437
+ return null;
2438
+ }
2439
+ jsonFiles.sort();
2440
+ for (let i = jsonFiles.length - 1; i >= 0; i--) {
2441
+ if (!deletedFiles.has(jsonFiles[i])) {
2442
+ return jsonFiles[i];
2443
+ }
2444
+ }
2445
+ return null;
2446
+ }
2447
+ /**
2448
+ * List all branches in the repository.
2449
+ *
2450
+ * Branches with deletion tombstones on their latest ref file are excluded.
2451
+ *
2452
+ * @returns Array of branch names
2453
+ */
2454
+ async listBranches() {
2455
+ const repoInfo = await this.loadRepoInfo();
2456
+ if (repoInfo) {
2457
+ return listBranchesFromRepo(repoInfo);
2458
+ }
2459
+ const branchFiles = /* @__PURE__ */ new Map();
2460
+ try {
2461
+ for await (const path of this.storage.listPrefix(
2462
+ `${PATHS.REFS}/branch.`
2463
+ )) {
2464
+ const jsonMatch = path.match(/^refs\/branch\.(.+)\/([^/]+\.json)$/);
2465
+ const deletedMatch = path.match(
2466
+ /^refs\/branch\.(.+)\/([^/]+\.json)\.deleted$/
2467
+ );
2468
+ if (deletedMatch) {
2469
+ const branchName = deletedMatch[1];
2470
+ const refFile = `refs/branch.${branchName}/${deletedMatch[2]}`;
2471
+ if (!branchFiles.has(branchName)) {
2472
+ branchFiles.set(branchName, {
2473
+ jsonFiles: [],
2474
+ deletedFiles: /* @__PURE__ */ new Set()
2475
+ });
2476
+ }
2477
+ branchFiles.get(branchName).deletedFiles.add(refFile);
2478
+ } else if (jsonMatch) {
2479
+ const branchName = jsonMatch[1];
2480
+ if (!branchFiles.has(branchName)) {
2481
+ branchFiles.set(branchName, {
2482
+ jsonFiles: [],
2483
+ deletedFiles: /* @__PURE__ */ new Set()
2484
+ });
2485
+ }
2486
+ branchFiles.get(branchName).jsonFiles.push(path);
2487
+ }
2488
+ }
2489
+ } catch {
2490
+ throw new Error("Cannot list branches: storage does not support listing");
2491
+ }
2492
+ const result = [];
2493
+ for (const [branchName, { jsonFiles, deletedFiles }] of branchFiles) {
2494
+ if (jsonFiles.length === 0) continue;
2495
+ jsonFiles.sort();
2496
+ const latestRef = jsonFiles[jsonFiles.length - 1];
2497
+ if (!deletedFiles.has(latestRef)) {
2498
+ result.push(branchName);
2499
+ }
2500
+ }
2501
+ return result;
2502
+ }
2503
+ /**
2504
+ * List all tags in the repository.
2505
+ *
2506
+ * Tags with deletion tombstones on their latest ref file are excluded.
2507
+ *
2508
+ * @returns Array of tag names
2509
+ */
2510
+ async listTags() {
2511
+ const repoInfo = await this.loadRepoInfo();
2512
+ if (repoInfo) {
2513
+ return listTagsFromRepo(repoInfo);
2514
+ }
2515
+ const tagFiles = /* @__PURE__ */ new Map();
2516
+ try {
2517
+ for await (const path of this.storage.listPrefix(`${PATHS.REFS}/tag.`)) {
2518
+ const jsonMatch = path.match(/^refs\/tag\.(.+)\/([^/]+\.json)$/);
2519
+ const deletedMatch = path.match(
2520
+ /^refs\/tag\.(.+)\/([^/]+\.json)\.deleted$/
2521
+ );
2522
+ if (deletedMatch) {
2523
+ const tagName = deletedMatch[1];
2524
+ const refFile = `refs/tag.${tagName}/${deletedMatch[2]}`;
2525
+ if (!tagFiles.has(tagName)) {
2526
+ tagFiles.set(tagName, { jsonFiles: [], deletedFiles: /* @__PURE__ */ new Set() });
2527
+ }
2528
+ tagFiles.get(tagName).deletedFiles.add(refFile);
2529
+ } else if (jsonMatch) {
2530
+ const tagName = jsonMatch[1];
2531
+ if (!tagFiles.has(tagName)) {
2532
+ tagFiles.set(tagName, { jsonFiles: [], deletedFiles: /* @__PURE__ */ new Set() });
2533
+ }
2534
+ tagFiles.get(tagName).jsonFiles.push(path);
2535
+ }
2536
+ }
2537
+ } catch {
2538
+ throw new Error("Cannot list tags: storage does not support listing");
2539
+ }
2540
+ const result = [];
2541
+ for (const [tagName, { jsonFiles, deletedFiles }] of tagFiles) {
2542
+ if (jsonFiles.length === 0) continue;
2543
+ jsonFiles.sort();
2544
+ const latestRef = jsonFiles[jsonFiles.length - 1];
2545
+ if (!deletedFiles.has(latestRef)) {
2546
+ result.push(tagName);
2547
+ }
2548
+ }
2549
+ return result;
2550
+ }
2551
+ /**
2552
+ * Checkout a branch to get a read session.
2553
+ *
2554
+ * @param name - Branch name
2555
+ * @param options - Optional request options (signal for cancellation)
2556
+ * @returns Read session at the branch's current snapshot
2557
+ */
2558
+ async checkoutBranch(name, options) {
2559
+ const repoInfo = await this.loadRepoInfo(options);
2560
+ if (repoInfo) {
2561
+ const snapshotId2 = resolveBranch(repoInfo, name);
2562
+ if (!snapshotId2) {
2563
+ throw new Error(`Branch not found: ${name}`);
2564
+ }
2565
+ return ReadSession.open(this.storage, snapshotId2, options);
2566
+ }
2567
+ const refDirPath = getBranchRefDirPath(name);
2568
+ const refPath = await this.findLatestRefFile(
2569
+ refDirPath,
2570
+ getBranchRefPath(name)
2571
+ );
2572
+ if (!refPath) {
2573
+ throw new Error(`Reference not found: ${refDirPath}`);
2574
+ }
2575
+ const snapshotId = await this.readSnapshotIdFromRef(refPath, options);
2576
+ return ReadSession.open(this.storage, snapshotId, options);
2577
+ }
2578
+ /**
2579
+ * Checkout a tag to get a read session.
2580
+ *
2581
+ * @param name - Tag name
2582
+ * @param options - Optional request options (signal for cancellation)
2583
+ * @returns Read session at the tag's snapshot
2584
+ */
2585
+ async checkoutTag(name, options) {
2586
+ const repoInfo = await this.loadRepoInfo(options);
2587
+ if (repoInfo) {
2588
+ const snapshotId2 = resolveTag(repoInfo, name);
2589
+ if (!snapshotId2) {
2590
+ throw new Error(`Tag not found: ${name}`);
2591
+ }
2592
+ return ReadSession.open(this.storage, snapshotId2, options);
2593
+ }
2594
+ const refDirPath = getTagRefDirPath(name);
2595
+ const legacyPath = getTagRefPath(name);
2596
+ const refPath = await this.findLatestRefFile(refDirPath, legacyPath);
2597
+ if (!refPath) {
2598
+ throw new Error(`Reference not found: ${refDirPath}`);
2599
+ }
2600
+ if (refPath === legacyPath && await this.storage.exists(`${refPath}.deleted`, options)) {
2601
+ throw new Error(`Tag not found: ${name}`);
2602
+ }
2603
+ const snapshotId = await this.readSnapshotIdFromRef(refPath, options);
2604
+ return ReadSession.open(this.storage, snapshotId, options);
2605
+ }
2606
+ /**
2607
+ * Checkout a specific snapshot by ID.
2608
+ *
2609
+ * @param snapshotId - Snapshot ID (12 bytes or Base32 string)
2610
+ * @param options - Optional request options (signal for cancellation)
2611
+ * @returns Read session at the specified snapshot
2612
+ */
2613
+ async checkoutSnapshot(snapshotId, options) {
2614
+ const id = typeof snapshotId === "string" ? decodeObjectId12(snapshotId) : snapshotId;
2615
+ return ReadSession.open(this.storage, id, options);
2616
+ }
2617
+ /**
2618
+ * Walk the snapshot history chain starting from the given session.
2619
+ *
2620
+ * Yields `{ id, message, flushedAt, metadata }` for each snapshot,
2621
+ * walking from the current snapshot back to the root.
2622
+ *
2623
+ * @param session - Read session to start from
2624
+ * @param options - Optional request options (signal for cancellation)
2625
+ */
2626
+ async *walkHistory(session, options) {
2627
+ let current = session;
2628
+ while (current) {
2629
+ yield {
2630
+ id: encodeObjectId12(current.getSnapshotId()),
2631
+ message: current.getMessage(),
2632
+ flushedAt: current.getFlushedAt(),
2633
+ metadata: current.getSnapshotMetadata()
2634
+ };
2635
+ const parentId = current.getParentSnapshotId();
2636
+ if (!parentId) break;
2637
+ current = await this.checkoutSnapshot(parentId, options);
2638
+ }
2639
+ }
2640
+ /**
2641
+ * Get the storage backend.
2642
+ */
2643
+ getStorage() {
2644
+ return this.storage;
2645
+ }
2646
+ /** Read and parse a ref file */
2647
+ async readRef(path, options) {
2648
+ const data = await this.storage.getObject(path, void 0, options);
2649
+ const json = new TextDecoder().decode(data);
2650
+ return JSON.parse(json);
2651
+ }
2652
+ /** Read snapshot ID from a ref file */
2653
+ async readSnapshotIdFromRef(path, options) {
2654
+ try {
2655
+ const ref = await this.readRef(path, options);
2656
+ return decodeObjectId12(ref.snapshot);
2657
+ } catch (error) {
2658
+ if (error instanceof NotFoundError) {
2659
+ throw new Error(`Reference not found: ${path}`);
2660
+ }
2661
+ throw error;
2662
+ }
2663
+ }
2664
+ };
2665
+
2666
+ // src/storage/http-storage.ts
2667
+ var HttpStorage = class {
2668
+ baseUrl;
2669
+ options;
2670
+ /**
2671
+ * Create an HTTP storage backend.
2672
+ *
2673
+ * @param baseUrl - Base URL for the repository (e.g., "https://example.com/repo")
2674
+ * @param options - Additional options
2675
+ */
2676
+ constructor(baseUrl, options = {}) {
2677
+ this.baseUrl = baseUrl.replace(/\/$/, "");
2678
+ this.options = options;
2679
+ }
2680
+ /** Build full URL for a path */
2681
+ getUrl(path) {
2682
+ const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
2683
+ return `${this.baseUrl}/${normalizedPath}`;
2684
+ }
2685
+ /** Build headers for a request */
2686
+ getHeaders(range) {
2687
+ const headers = { ...this.options.headers };
2688
+ if (range) {
2689
+ headers["Range"] = `bytes=${range.start}-${range.end - 1}`;
2690
+ }
2691
+ return headers;
2692
+ }
2693
+ async getObject(path, range, options) {
2694
+ if (options?.signal?.aborted) {
2695
+ throw new AbortError();
2696
+ }
2697
+ const url = this.getUrl(path);
2698
+ const headers = this.getHeaders(range);
2699
+ let response;
2700
+ try {
2701
+ response = await fetch(url, {
2702
+ method: "GET",
2703
+ headers,
2704
+ credentials: this.options.credentials,
2705
+ cache: this.options.cache,
2706
+ signal: options?.signal
2707
+ });
2708
+ } catch (error) {
2709
+ if (error instanceof Error && error.name === "AbortError") {
2710
+ throw new AbortError();
2711
+ }
2712
+ throw new StorageError(
2713
+ `Failed to fetch ${url}: ${error instanceof Error ? error.message : String(error)}`,
2714
+ error instanceof Error ? error : void 0
2715
+ );
2716
+ }
2717
+ if (response.status === 404) {
2718
+ throw new NotFoundError(path);
2719
+ }
2720
+ if (response.status !== 200 && response.status !== 206) {
2721
+ throw new StorageError(
2722
+ `HTTP ${response.status} ${response.statusText} for ${url}`
2723
+ );
2724
+ }
2725
+ const arrayBuffer = await response.arrayBuffer();
2726
+ return new Uint8Array(arrayBuffer);
2727
+ }
2728
+ async exists(path, options) {
2729
+ if (options?.signal?.aborted) {
2730
+ throw new AbortError();
2731
+ }
2732
+ const url = this.getUrl(path);
2733
+ try {
2734
+ const response = await fetch(url, {
2735
+ method: "HEAD",
2736
+ headers: this.options.headers,
2737
+ credentials: this.options.credentials,
2738
+ signal: options?.signal
2739
+ });
2740
+ return response.ok;
2741
+ } catch (error) {
2742
+ if (error instanceof Error && error.name === "AbortError") {
2743
+ throw new AbortError();
2744
+ }
2745
+ return false;
2746
+ }
2747
+ }
2748
+ async *listPrefix(_prefix) {
2749
+ throw new StorageError(
2750
+ "Listing not supported for HTTP storage. Use S3Storage for listing."
2751
+ );
2752
+ }
2753
+ };
2754
+
2755
+ // src/store.ts
2756
+ var IcechunkStore = class _IcechunkStore {
2757
+ /** The underlying read session. Exposed for advanced usage. */
2758
+ session;
2759
+ fetchClient;
2760
+ validateChecksums;
2761
+ azureAccount;
2762
+ basePath = "";
2763
+ constructor(session, fetchClient, validateChecksums, azureAccount) {
2764
+ if (!(session instanceof ReadSession)) {
2765
+ throw new Error(
2766
+ "IcechunkStore constructor is private. Use IcechunkStore.open() instead."
2767
+ );
2768
+ }
2769
+ this.session = session;
2770
+ this.fetchClient = fetchClient;
2771
+ this.validateChecksums = validateChecksums ?? false;
2772
+ this.azureAccount = azureAccount;
2773
+ }
2774
+ static async open(arg, options = {}) {
2775
+ if (arg instanceof ReadSession) {
2776
+ return new _IcechunkStore(
2777
+ arg,
2778
+ options.fetchClient,
2779
+ options.validateChecksums,
2780
+ options.azureAccount
2781
+ );
2782
+ }
2783
+ const storage = typeof arg === "string" ? new HttpStorage(arg) : arg;
2784
+ const requestOptions = options.signal ? { signal: options.signal } : void 0;
2785
+ const repo = await Repository.open(
2786
+ { storage, formatVersion: options.formatVersion },
2787
+ requestOptions
2788
+ );
2789
+ const sessionOptions = {
2790
+ ...requestOptions,
2791
+ maxManifestCacheSize: options.maxManifestCacheSize
2792
+ };
2793
+ let session;
2794
+ if (options.snapshot) {
2795
+ session = await repo.checkoutSnapshot(options.snapshot, sessionOptions);
2796
+ } else if (options.tag) {
2797
+ session = await repo.checkoutTag(options.tag, sessionOptions);
2798
+ } else {
2799
+ session = await repo.checkoutBranch(
2800
+ options.branch ?? "main",
2801
+ sessionOptions
2802
+ );
2803
+ }
2804
+ return new _IcechunkStore(
2805
+ session,
2806
+ options.fetchClient,
2807
+ options.validateChecksums,
2808
+ options.azureAccount
2809
+ );
2810
+ }
2811
+ /**
2812
+ * Get data for a zarr key.
2813
+ *
2814
+ * zarrita calls this method with keys like:
2815
+ * - "/zarr.json" - root metadata
2816
+ * - "/array/zarr.json" - array metadata
2817
+ * - "/array/c/0/1/2" - chunk at coords [0, 1, 2]
2818
+ *
2819
+ * @param key - Absolute path (must start with "/")
2820
+ * @param opts - Optional request options (supports AbortSignal for cancellation)
2821
+ * @returns Data bytes or undefined if not found
2822
+ */
2823
+ async get(key, opts) {
2824
+ if (opts?.signal?.aborted) return void 0;
2825
+ const parsed = parseZarrKey(key);
2826
+ const resolvedPath = this.resolvePath(parsed.path);
2827
+ try {
2828
+ if (parsed.type === "metadata") {
2829
+ const data = this.session.getRawMetadata(resolvedPath);
2830
+ return data ?? void 0;
2831
+ }
2832
+ const chunk = await this.session.getChunk(resolvedPath, parsed.coords, {
2833
+ signal: opts?.signal,
2834
+ ...this.fetchClient && { fetchClient: this.fetchClient },
2835
+ validateChecksums: this.validateChecksums,
2836
+ azureAccount: this.azureAccount
2837
+ });
2838
+ return chunk ?? void 0;
2839
+ } catch {
2840
+ return void 0;
2841
+ }
2842
+ }
2843
+ /**
2844
+ * Get partial data for a zarr key.
2845
+ *
2846
+ * Required by zarrita for sharded arrays. zarrita uses this to read the
2847
+ * shard index (via suffixLength) and extract individual inner chunks
2848
+ * (via offset/length) from shard data.
2849
+ *
2850
+ * @param key - Absolute path
2851
+ * @param range - Byte range to fetch
2852
+ * @param opts - Optional request options (supports AbortSignal for cancellation)
2853
+ * @returns Data bytes or undefined if not found
2854
+ */
2855
+ async getRange(key, range, opts) {
2856
+ if (opts?.signal?.aborted) return void 0;
2857
+ const parsed = parseZarrKey(key);
2858
+ const resolvedPath = this.resolvePath(parsed.path);
2859
+ try {
2860
+ if (parsed.type === "chunk") {
2861
+ const data2 = await this.session.getChunkRange(
2862
+ resolvedPath,
2863
+ parsed.coords,
2864
+ range,
2865
+ {
2866
+ signal: opts?.signal,
2867
+ ...this.fetchClient && { fetchClient: this.fetchClient },
2868
+ validateChecksums: this.validateChecksums,
2869
+ azureAccount: this.azureAccount
2870
+ }
2871
+ );
2872
+ return data2 ?? void 0;
2873
+ }
2874
+ const data = this.session.getRawMetadata(resolvedPath);
2875
+ if (!data) return void 0;
2876
+ if ("suffixLength" in range) {
2877
+ return data.slice(-range.suffixLength);
2878
+ }
2879
+ return data.slice(range.offset, range.offset + range.length);
2880
+ } catch {
2881
+ return void 0;
2882
+ }
2883
+ }
2884
+ /** Prepend basePath to a parsed path. */
2885
+ resolvePath(path) {
2886
+ if (!this.basePath) return path;
2887
+ if (path === "/") return `/${this.basePath}`;
2888
+ return `/${this.basePath}${path}`;
2889
+ }
2890
+ /**
2891
+ * Create a store scoped to a subpath.
2892
+ *
2893
+ * The returned store shares the same session (and manifest cache)
2894
+ * but prepends `path` to all key lookups. This matches zarrita's
2895
+ * `root(store).resolve(path)` pattern.
2896
+ *
2897
+ * @param path - Subpath to scope to (e.g., "group/array")
2898
+ * @returns A new IcechunkStore scoped to the subpath
2899
+ */
2900
+ resolve(path) {
2901
+ const scoped = new _IcechunkStore(
2902
+ this.session,
2903
+ this.fetchClient,
2904
+ this.validateChecksums,
2905
+ this.azureAccount
2906
+ );
2907
+ const cleanPath = path.replace(/^\/+|\/+$/g, "");
2908
+ scoped.basePath = this.basePath ? `${this.basePath}/${cleanPath}` : cleanPath;
2909
+ return scoped;
2910
+ }
2911
+ /**
2912
+ * List direct children of a group by name.
2913
+ *
2914
+ * @param parentPath - Path to the parent group (use "/" for root).
2915
+ * When omitted, uses the store's base path (or root).
2916
+ * @returns Array of child names (e.g., ["temperature", "precipitation"])
2917
+ */
2918
+ listChildren(parentPath) {
2919
+ let path;
2920
+ if (parentPath == null) {
2921
+ path = this.basePath ? `/${this.basePath}` : "/";
2922
+ } else if (this.basePath) {
2923
+ path = `/${this.basePath}/${parentPath.replace(/^\//, "")}`.replace(/\/+/g, "/").replace(/\/+$/, "") || "/";
2924
+ } else {
2925
+ path = (parentPath.startsWith("/") ? parentPath : `/${parentPath}`).replace(
2926
+ /\/+$/,
2927
+ ""
2928
+ ) || "/";
2929
+ }
2930
+ const nodes = this.session.listChildren(path);
2931
+ return nodes.map((node) => {
2932
+ const segments = node.path.split("/");
2933
+ return segments[segments.length - 1];
2934
+ });
2935
+ }
2936
+ /**
2937
+ * List all nodes in the snapshot.
2938
+ *
2939
+ * @returns Array of all nodes
2940
+ */
2941
+ listNodes() {
2942
+ return this.session.listNodes();
2943
+ }
2944
+ /**
2945
+ * Get a node by path.
2946
+ *
2947
+ * @param path - Absolute path (e.g., "/array" or "/group/nested")
2948
+ * @returns NodeSnapshot or null if not found
2949
+ */
2950
+ getNode(path) {
2951
+ const fullPath = (this.basePath ? `/${this.basePath}/${path.replace(/^\//, "")}`.replace(/\/+/g, "/") : path).replace(/\/+$/, "") || "/";
2952
+ return this.session.getNode(fullPath);
2953
+ }
2954
+ /**
2955
+ * Get parsed Zarr metadata for a node.
2956
+ *
2957
+ * @param path - Path to the node
2958
+ * @returns Parsed JSON metadata or null if node not found
2959
+ */
2960
+ getMetadata(path) {
2961
+ const fullPath = (this.basePath ? `/${this.basePath}/${path.replace(/^\//, "")}`.replace(/\/+/g, "/") : path).replace(/\/+$/, "") || "/";
2962
+ return this.session.getMetadata(fullPath);
2963
+ }
2964
+ };
2965
+ function parseZarrKey(key) {
2966
+ const path = key.slice(1);
2967
+ if (path === "zarr.json") {
2968
+ return { type: "metadata", path: "/" };
2969
+ }
2970
+ if (path.endsWith("/zarr.json")) {
2971
+ const nodePath = "/" + path.slice(0, -"/zarr.json".length);
2972
+ return { type: "metadata", path: nodePath };
2973
+ }
2974
+ const chunkMatch = path.match(/^(?:(.*)\/)?c(?:\/(.*))?$/);
2975
+ if (chunkMatch) {
2976
+ const arrayPath = chunkMatch[1] ? "/" + chunkMatch[1] : "/";
2977
+ const coordsStr = chunkMatch[2] ?? "";
2978
+ const coords = coordsStr ? coordsStr.split("/").map(Number) : [];
2979
+ return { type: "chunk", path: arrayPath, coords };
2980
+ }
2981
+ return { type: "metadata", path: "/" + path };
2982
+ }
2983
+ export {
2984
+ CompressionAlgorithm,
2985
+ DefaultFetchClient,
2986
+ FileType,
2987
+ HeaderParseError,
2988
+ HttpStorage,
2989
+ IcechunkStore,
2990
+ LRUCache,
2991
+ NotFoundError,
2992
+ ReadSession,
2993
+ Repository,
2994
+ SpecVersion,
2995
+ StorageError,
2996
+ decodeBase32,
2997
+ decodeObjectId12,
2998
+ decodeObjectId8,
2999
+ encodeBase32,
3000
+ encodeObjectId12,
3001
+ encodeObjectId8
3002
+ };
3003
+ //# sourceMappingURL=index.js.map