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