@vitessce/zarr 4.2.0 → 4.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -313,7 +313,7 @@ function resolveUri(url) {
313
313
  }
314
314
  return href;
315
315
  }
316
- function fetchRange(url, offset, length, opts = {}) {
316
+ function fetchRange$1(url, offset, length, opts = {}) {
317
317
  if (offset !== void 0 && length !== void 0) {
318
318
  opts = {
319
319
  ...opts,
@@ -335,7 +335,7 @@ function mergeInit(storeOverrides, requestOverrides) {
335
335
  }
336
336
  };
337
337
  }
338
- function assert$1(expression, msg = "") {
338
+ function assert$2(expression, msg = "") {
339
339
  if (!expression)
340
340
  throw new Error(msg);
341
341
  }
@@ -736,7 +736,7 @@ function getStrides(shape, order) {
736
736
  if (typeof order === "string") {
737
737
  order = order === "C" ? Array.from({ length: rank }, (_, i) => i) : Array.from({ length: rank }, (_, i) => rank - 1 - i);
738
738
  }
739
- assert(rank === order.length, "Order length must match the number of dimensions.");
739
+ assert$1(rank === order.length, "Order length must match the number of dimensions.");
740
740
  let step = 1;
741
741
  let stride = new Array(rank);
742
742
  for (let i = order.length - 1; i >= 0; i--) {
@@ -921,7 +921,7 @@ function rethrowUnless(error, ...errors) {
921
921
  throw error;
922
922
  }
923
923
  }
924
- function assert(expression, msg = "") {
924
+ function assert$1(expression, msg = "") {
925
925
  if (!expression) {
926
926
  throw new Error(msg);
927
927
  }
@@ -934,7 +934,7 @@ async function decompress(data, { format, signal }) {
934
934
  let bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
935
935
  response = new Response(bytes.slice().buffer);
936
936
  }
937
- assert(response.body, "Response does not contain body.");
937
+ assert$1(response.body, "Response does not contain body.");
938
938
  try {
939
939
  const decompressedResponse = new Response(response.body.pipeThrough(new DecompressionStream(format), { signal }));
940
940
  const buffer = await decompressedResponse.arrayBuffer();
@@ -1347,9 +1347,9 @@ class GzipCodec {
1347
1347
  }
1348
1348
  }
1349
1349
  function throwOnNanReplacer(_key, value) {
1350
- assert(!Number.isNaN(value), "JsonCodec allow_nan is false but NaN was encountered during encoding.");
1351
- assert(value !== Number.POSITIVE_INFINITY, "JsonCodec allow_nan is false but Infinity was encountered during encoding.");
1352
- assert(value !== Number.NEGATIVE_INFINITY, "JsonCodec allow_nan is false but -Infinity was encountered during encoding.");
1350
+ assert$1(!Number.isNaN(value), "JsonCodec allow_nan is false but NaN was encountered during encoding.");
1351
+ assert$1(value !== Number.POSITIVE_INFINITY, "JsonCodec allow_nan is false but Infinity was encountered during encoding.");
1352
+ assert$1(value !== Number.NEGATIVE_INFINITY, "JsonCodec allow_nan is false but -Infinity was encountered during encoding.");
1353
1353
  return value;
1354
1354
  }
1355
1355
  function sortKeysReplacer(_key, value) {
@@ -1390,9 +1390,9 @@ class JsonCodec {
1390
1390
  }
1391
1391
  encode(buf) {
1392
1392
  const { indent, encoding, ensure_ascii, check_circular, allow_nan, sort_keys } = this.#encoderConfig;
1393
- assert(encoding === "utf-8", "JsonCodec does not yet support non-utf-8 encoding.");
1393
+ assert$1(encoding === "utf-8", "JsonCodec does not yet support non-utf-8 encoding.");
1394
1394
  const replacerFunctions = [];
1395
- assert(check_circular, "JsonCodec does not yet support skipping the check for circular references during encoding.");
1395
+ assert$1(check_circular, "JsonCodec does not yet support skipping the check for circular references during encoding.");
1396
1396
  if (!allow_nan) {
1397
1397
  replacerFunctions.push(throwOnNanReplacer);
1398
1398
  }
@@ -1424,11 +1424,11 @@ class JsonCodec {
1424
1424
  }
1425
1425
  decode(bytes) {
1426
1426
  const { strict } = this.#decoderConfig;
1427
- assert(strict, "JsonCodec does not yet support non-strict decoding.");
1427
+ assert$1(strict, "JsonCodec does not yet support non-strict decoding.");
1428
1428
  const items = jsonDecodeObject(bytes);
1429
1429
  const shape = items.pop();
1430
1430
  items.pop();
1431
- assert(shape, "0D not implemented for JsonCodec.");
1431
+ assert$1(shape, "0D not implemented for JsonCodec.");
1432
1432
  const stride = getStrides(shape, "C");
1433
1433
  const data = items;
1434
1434
  return { data, shape, stride };
@@ -1478,7 +1478,7 @@ class ShuffleCodec {
1478
1478
  this.kind = "bytes_to_bytes";
1479
1479
  if (meta) {
1480
1480
  let sample = new (getCtr(meta.dataType))(0);
1481
- assert("BYTES_PER_ELEMENT" in sample, `Shuffle codec requires a fixed-size dtype, got "${meta.dataType}"`);
1481
+ assert$1("BYTES_PER_ELEMENT" in sample, `Shuffle codec requires a fixed-size dtype, got "${meta.dataType}"`);
1482
1482
  this.#BYTES_PER_ELEMENT = sample.BYTES_PER_ELEMENT;
1483
1483
  } else {
1484
1484
  this.#BYTES_PER_ELEMENT = configuration.elementsize ?? 4;
@@ -1492,7 +1492,7 @@ class ShuffleCodec {
1492
1492
  return shuffle(data, this.#BYTES_PER_ELEMENT);
1493
1493
  }
1494
1494
  decode(data) {
1495
- return unshuffle(data, this.#BYTES_PER_ELEMENT);
1495
+ return unshuffle$1(data, this.#BYTES_PER_ELEMENT);
1496
1496
  }
1497
1497
  }
1498
1498
  function shuffle(data, elementSize) {
@@ -1506,7 +1506,7 @@ function shuffle(data, elementSize) {
1506
1506
  }
1507
1507
  return result;
1508
1508
  }
1509
- function unshuffle(data, elementSize) {
1509
+ function unshuffle$1(data, elementSize) {
1510
1510
  let length = data.length;
1511
1511
  let nElements = Math.floor(length / elementSize);
1512
1512
  let result = new Uint8Array(length);
@@ -1579,12 +1579,12 @@ function convertArrayOrder(src, target) {
1579
1579
  }
1580
1580
  function getOrder(chunk) {
1581
1581
  let rank = chunk.shape.length;
1582
- assert(rank === chunk.stride.length, "Shape and stride must have the same length.");
1582
+ assert$1(rank === chunk.stride.length, "Shape and stride must have the same length.");
1583
1583
  return chunk.stride.map((s, i) => ({ stride: s, index: i })).sort((a, b) => b.stride - a.stride).map((entry) => entry.index);
1584
1584
  }
1585
1585
  function matchesOrder(chunk, target) {
1586
1586
  let source = getOrder(chunk);
1587
- assert(source.length === target.length, "Orders must match");
1587
+ assert$1(source.length === target.length, "Orders must match");
1588
1588
  return source.every((dim, i) => dim === target[i]);
1589
1589
  }
1590
1590
  class TransposeCodec {
@@ -1605,7 +1605,7 @@ class TransposeCodec {
1605
1605
  order = value;
1606
1606
  let seen = new Array(rank);
1607
1607
  order.forEach((x) => {
1608
- assert(!seen[x], `Invalid permutation: ${JSON.stringify(value)}`);
1608
+ assert$1(!seen[x], `Invalid permutation: ${JSON.stringify(value)}`);
1609
1609
  seen[x] = true;
1610
1610
  });
1611
1611
  }
@@ -1846,7 +1846,7 @@ class Location {
1846
1846
  function root$1(store) {
1847
1847
  return new Location(store ?? /* @__PURE__ */ new Map());
1848
1848
  }
1849
- class Group extends Location {
1849
+ let Group$1 = class Group extends Location {
1850
1850
  constructor(store, path, metadata) {
1851
1851
  super(store, path);
1852
1852
  this.kind = "group";
@@ -1856,7 +1856,7 @@ class Group extends Location {
1856
1856
  get attrs() {
1857
1857
  return this.#metadata.attributes;
1858
1858
  }
1859
- }
1859
+ };
1860
1860
  function getArrayOrder(codecs) {
1861
1861
  const maybeTransposeCodec = codecs.find((c) => c.name === "transpose");
1862
1862
  return maybeTransposeCodec?.configuration?.order ?? "C";
@@ -2139,7 +2139,7 @@ async function openGroupV2(location, attrs, signal) {
2139
2139
  throw new NotFoundError("v2 group", { path });
2140
2140
  }
2141
2141
  VERSION_COUNTER.increment(location.store, "v2");
2142
- return new Group(location.store, location.path, v2ToV3GroupMetadata(jsonDecodeObject(meta), attrs));
2142
+ return new Group$1(location.store, location.path, v2ToV3GroupMetadata(jsonDecodeObject(meta), attrs));
2143
2143
  }
2144
2144
  async function _openV3(location, signal) {
2145
2145
  let { store, path } = location.resolve("zarr.json");
@@ -2151,7 +2151,7 @@ async function _openV3(location, signal) {
2151
2151
  if (metaDoc.node_type === "array") {
2152
2152
  metaDoc.fill_value = ensureCorrectScalar(metaDoc);
2153
2153
  }
2154
- return metaDoc.node_type === "array" ? maybeExtend(new Array$1(store, location.path, metaDoc)) : new Group(store, location.path, metaDoc);
2154
+ return metaDoc.node_type === "array" ? maybeExtend(new Array$1(store, location.path, metaDoc)) : new Group$1(store, location.path, metaDoc);
2155
2155
  }
2156
2156
  async function openV3(location, options = {}) {
2157
2157
  let loc = "store" in location ? location : new Location(location);
@@ -2161,7 +2161,7 @@ async function openV3(location, options = {}) {
2161
2161
  return node;
2162
2162
  if (options.kind === "array" && node instanceof Array$1)
2163
2163
  return node;
2164
- if (options.kind === "group" && node instanceof Group)
2164
+ if (options.kind === "group" && node instanceof Group$1)
2165
2165
  return node;
2166
2166
  let kind = node instanceof Array$1 ? "array" : "group";
2167
2167
  throw new NotFoundError(`${options.kind} at ${loc.path}`, {
@@ -2184,6 +2184,140 @@ open.v3 = openV3;
2184
2184
  function extendStore(store, ...extensions) {
2185
2185
  return applyExtensions(store, extensions);
2186
2186
  }
2187
+ function assertRangeCapable(store) {
2188
+ if (!store.getRange) {
2189
+ throw new UnsupportedError("`zarr.withRangeCoalescing` requires a store with getRange");
2190
+ }
2191
+ }
2192
+ function mergeSignals(signals) {
2193
+ let present = [];
2194
+ for (let s of signals)
2195
+ if (s)
2196
+ present.push(s);
2197
+ if (present.length === 0)
2198
+ return void 0;
2199
+ if (present.length === 1)
2200
+ return present[0];
2201
+ return AbortSignal.any(present);
2202
+ }
2203
+ const DEFAULT_COALESCE_SIZE = 32768;
2204
+ function groupRequests(sorted, coalesceSize) {
2205
+ if (sorted.length === 0)
2206
+ return [];
2207
+ let groups = [];
2208
+ let current = [sorted[0]];
2209
+ let groupStart = sorted[0].offset;
2210
+ let groupEnd = sorted[0].offset + sorted[0].length;
2211
+ for (let i = 1; i < sorted.length; i++) {
2212
+ let req = sorted[i];
2213
+ let reqEnd = req.offset + req.length;
2214
+ if (req.offset <= groupEnd + coalesceSize) {
2215
+ current.push(req);
2216
+ groupEnd = Math.max(groupEnd, reqEnd);
2217
+ } else {
2218
+ groups.push({
2219
+ offset: groupStart,
2220
+ length: groupEnd - groupStart,
2221
+ requests: current
2222
+ });
2223
+ current = [req];
2224
+ groupStart = req.offset;
2225
+ groupEnd = reqEnd;
2226
+ }
2227
+ }
2228
+ groups.push({
2229
+ offset: groupStart,
2230
+ length: groupEnd - groupStart,
2231
+ requests: current
2232
+ });
2233
+ return groups;
2234
+ }
2235
+ function emitFlush(onFlush, report) {
2236
+ if (!onFlush)
2237
+ return;
2238
+ try {
2239
+ onFlush(report);
2240
+ } catch (err) {
2241
+ console.warn("withRangeCoalescing: onFlush threw, swallowing:", err);
2242
+ }
2243
+ }
2244
+ const withRangeCoalescing = defineStoreExtension((_store, opts = {}) => {
2245
+ assertRangeCapable(_store);
2246
+ let store = _store;
2247
+ let boundGetRange = store.getRange.bind(store);
2248
+ let coalesceSize = opts.coalesceSize ?? DEFAULT_COALESCE_SIZE;
2249
+ let onFlush = opts.onFlush;
2250
+ let pending = /* @__PURE__ */ new Map();
2251
+ let scheduled = false;
2252
+ async function flush() {
2253
+ let work = new Map(pending);
2254
+ pending.clear();
2255
+ scheduled = false;
2256
+ let pathPromises = [];
2257
+ for (let [path, requests] of work) {
2258
+ requests.sort((a, b) => a.offset - b.offset);
2259
+ let groups = groupRequests(requests, coalesceSize);
2260
+ emitFlush(onFlush, {
2261
+ path,
2262
+ groupCount: groups.length,
2263
+ requestCount: requests.length,
2264
+ bytesFetched: groups.reduce((sum, g) => sum + g.length, 0)
2265
+ });
2266
+ pathPromises.push(fetchGroups(path, groups));
2267
+ }
2268
+ await Promise.all(pathPromises);
2269
+ }
2270
+ async function fetchGroups(path, groups) {
2271
+ await Promise.all(groups.map(async (group) => {
2272
+ let signal = mergeSignals(group.requests.map((r) => r.signal));
2273
+ try {
2274
+ let data = await boundGetRange(path, { offset: group.offset, length: group.length }, { signal });
2275
+ if (data && data.length < group.length) {
2276
+ throw new Error(`Short read: expected ${group.length} bytes but received ${data.length}`);
2277
+ }
2278
+ for (let req of group.requests) {
2279
+ if (!data) {
2280
+ req.resolve(void 0);
2281
+ continue;
2282
+ }
2283
+ let start = req.offset - group.offset;
2284
+ let slice2 = data.slice(start, start + req.length);
2285
+ req.resolve(slice2);
2286
+ }
2287
+ } catch (err) {
2288
+ for (let req of group.requests) {
2289
+ req.reject(err);
2290
+ }
2291
+ }
2292
+ }));
2293
+ }
2294
+ return {
2295
+ getRange(key, range2, options) {
2296
+ if ("suffixLength" in range2) {
2297
+ return boundGetRange(key, range2, options);
2298
+ }
2299
+ let { offset, length } = range2;
2300
+ return new Promise((resolve2, reject) => {
2301
+ let reqs = pending.get(key);
2302
+ if (!reqs) {
2303
+ reqs = [];
2304
+ pending.set(key, reqs);
2305
+ }
2306
+ reqs.push({
2307
+ offset,
2308
+ length,
2309
+ signal: options?.signal,
2310
+ resolve: resolve2,
2311
+ reject
2312
+ });
2313
+ if (!scheduled) {
2314
+ scheduled = true;
2315
+ queueMicrotask(() => flush());
2316
+ }
2317
+ });
2318
+ }
2319
+ };
2320
+ });
2187
2321
  function* range$2(start, stop, step = 1) {
2188
2322
  if (stop === void 0) {
2189
2323
  stop = start;
@@ -3140,7 +3274,7 @@ class HTTPRangeReader {
3140
3274
  ...this.#overrides,
3141
3275
  method: "HEAD"
3142
3276
  });
3143
- assert$1(req.ok, `failed http request ${this.url}, status: ${req.status}: ${req.statusText}`);
3277
+ assert$2(req.ok, `failed http request ${this.url}, status: ${req.status}: ${req.statusText}`);
3144
3278
  this.length = Number(req.headers.get("content-length"));
3145
3279
  if (Number.isNaN(this.length)) {
3146
3280
  throw Error("could not get length");
@@ -3152,8 +3286,8 @@ class HTTPRangeReader {
3152
3286
  if (size === 0) {
3153
3287
  return new Uint8Array(0);
3154
3288
  }
3155
- const req = await fetchRange(this.url, offset, size, this.#overrides);
3156
- assert$1(req.ok, `failed http request ${this.url}, status: ${req.status} offset: ${offset} size: ${size}: ${req.statusText}`);
3289
+ const req = await fetchRange$1(this.url, offset, size, this.#overrides);
3290
+ assert$2(req.ok, `failed http request ${this.url}, status: ${req.status} offset: ${offset} size: ${size}: ${req.statusText}`);
3157
3291
  return new Uint8Array(await req.arrayBuffer());
3158
3292
  }
3159
3293
  }
@@ -3390,9 +3524,9 @@ function* range$1({ stop, start = 0, step = 1 }) {
3390
3524
  }
3391
3525
  }
3392
3526
  (() => {
3393
- var table = new Uint8Array(128);
3527
+ var table2 = new Uint8Array(128);
3394
3528
  for (var i = 0; i < 64; i++) {
3395
- table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;
3529
+ table2[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;
3396
3530
  }
3397
3531
  return (base64) => {
3398
3532
  var n = base64.length;
@@ -3401,8 +3535,8 @@ function* range$1({ stop, start = 0, step = 1 }) {
3401
3535
  (n - (base64[n - 1] == "=") - (base64[n - 2] == "=")) * 3 / 4 | 0
3402
3536
  );
3403
3537
  for (var i2 = 0, j = 0; i2 < n; ) {
3404
- var c0 = table[base64.charCodeAt(i2++)], c1 = table[base64.charCodeAt(i2++)];
3405
- var c2 = table[base64.charCodeAt(i2++)], c3 = table[base64.charCodeAt(i2++)];
3538
+ var c0 = table2[base64.charCodeAt(i2++)], c1 = table2[base64.charCodeAt(i2++)];
3539
+ var c2 = table2[base64.charCodeAt(i2++)], c3 = table2[base64.charCodeAt(i2++)];
3406
3540
  bytes[j++] = c0 << 2 | c1 >> 4;
3407
3541
  bytes[j++] = c1 << 4 | c2 >> 2;
3408
3542
  bytes[j++] = c2 << 6 | c3;
@@ -3412,9 +3546,9 @@ function* range$1({ stop, start = 0, step = 1 }) {
3412
3546
  })();
3413
3547
  new TextEncoder();
3414
3548
  const toBinary = typeof Uint8Array.fromBase64 === "function" ? (s) => Uint8Array.fromBase64(s) : (() => {
3415
- let table = new Uint8Array(128);
3549
+ let table2 = new Uint8Array(128);
3416
3550
  for (let i = 0; i < 64; i++) {
3417
- table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;
3551
+ table2[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;
3418
3552
  }
3419
3553
  return (base64) => {
3420
3554
  const n = base64.length;
@@ -3423,10 +3557,10 @@ const toBinary = typeof Uint8Array.fromBase64 === "function" ? (s) => Uint8Array
3423
3557
  (n - (base64[n - 1] === "=") - (base64[n - 2] === "=")) * 3 / 4 | 0
3424
3558
  );
3425
3559
  for (let i = 0, j = 0; i < n; ) {
3426
- const c0 = table[base64.charCodeAt(i++)];
3427
- const c1 = table[base64.charCodeAt(i++)];
3428
- const c2 = table[base64.charCodeAt(i++)];
3429
- const c3 = table[base64.charCodeAt(i++)];
3560
+ const c0 = table2[base64.charCodeAt(i++)];
3561
+ const c1 = table2[base64.charCodeAt(i++)];
3562
+ const c2 = table2[base64.charCodeAt(i++)];
3563
+ const c3 = table2[base64.charCodeAt(i++)];
3430
3564
  bytes[j++] = c0 << 2 | c1 >> 4;
3431
3565
  bytes[j++] = c1 << 4 | c2 >> 2;
3432
3566
  bytes[j++] = c2 << 6 | c3;
@@ -3527,215 +3661,3999 @@ const _ReferenceStore = class _ReferenceStore {
3527
3661
  _inner = new WeakMap();
3528
3662
  _ReferenceStore.resolveUri = resolveUri;
3529
3663
  let ReferenceStore = _ReferenceStore;
3530
- const withGetRange = defineStoreExtension((innerStore) => ({
3531
- async getRange(...args) {
3532
- const [key, range2, opts] = args;
3533
- if (typeof innerStore.getRange === "function") {
3534
- return innerStore.getRange(key, range2, opts);
3535
- }
3536
- const arr = await innerStore.get(key, opts);
3537
- if (!arr)
3538
- return void 0;
3539
- const { buffer } = arr;
3540
- if ("suffixLength" in range2) {
3541
- const { suffixLength } = range2;
3542
- return new Uint8Array(buffer, buffer.byteLength - suffixLength, suffixLength);
3543
- }
3544
- if ("offset" in range2 && "length" in range2) {
3545
- const { offset, length } = range2;
3546
- return new Uint8Array(buffer, offset, length);
3664
+ async function fetchRange(source, offset, length) {
3665
+ const result = await source.getRange("/", { offset, length });
3666
+ if (!result)
3667
+ throw new Error(`fetchRange: no data at offset=${offset} length=${length}`);
3668
+ const copy = new Uint8Array(result.byteLength);
3669
+ copy.set(result);
3670
+ return copy.buffer;
3671
+ }
3672
+ const fileSizes = /* @__PURE__ */ new WeakMap();
3673
+ function setFileSize(source, size) {
3674
+ fileSizes.set(source, size);
3675
+ }
3676
+ function fetchRangeWithReadAhead(source, offset, length, readAhead) {
3677
+ const size = fileSizes.get(source);
3678
+ let want = length;
3679
+ if (size !== void 0 && readAhead > length) {
3680
+ want = Math.max(length, Math.min(readAhead, size - offset));
3681
+ }
3682
+ return fetchRange(source, offset, want);
3683
+ }
3684
+ function _unpack_struct_from(structure, buf, offset = 0) {
3685
+ const output = /* @__PURE__ */ new Map();
3686
+ for (const [key, fmt] of structure.entries()) {
3687
+ let value = struct.unpack_from("<" + fmt, buf, offset);
3688
+ offset += struct.calcsize(fmt);
3689
+ if (value.length === 1) {
3690
+ value = value[0];
3691
+ }
3692
+ output.set(key, value);
3693
+ }
3694
+ return output;
3695
+ }
3696
+ function _structure_size(structure) {
3697
+ const fmt = "<" + Array.from(structure.values()).join("");
3698
+ return struct.calcsize(fmt);
3699
+ }
3700
+ function _padded_size(size, padding_multiple = 8) {
3701
+ return Math.ceil(size / padding_multiple) * padding_multiple;
3702
+ }
3703
+ const dtype_to_format = {
3704
+ u: "Uint",
3705
+ i: "Int",
3706
+ f: "Float"
3707
+ };
3708
+ function dtype_getter(dtype_str) {
3709
+ const big_endian = struct._is_big_endian(dtype_str);
3710
+ let getter;
3711
+ let nbytes;
3712
+ if (/S/.test(dtype_str)) {
3713
+ getter = "getString";
3714
+ nbytes = parseInt((dtype_str.match(/S(\d*)/) || [])[1] || "1", 10) | 0;
3715
+ } else {
3716
+ const m = dtype_str.match(/[<>=!@]?(i|u|f)(\d*)/);
3717
+ if (!m)
3718
+ throw new Error("Invalid dtype: " + dtype_str);
3719
+ const fstr = m[1];
3720
+ const bytestr = m[2];
3721
+ nbytes = parseInt(bytestr || "4", 10);
3722
+ const nbits = nbytes * 8;
3723
+ getter = "get" + dtype_to_format[fstr] + nbits.toFixed();
3724
+ }
3725
+ return [getter, big_endian, nbytes];
3726
+ }
3727
+ function isBigEndian() {
3728
+ const array = new Uint8Array(4);
3729
+ const view = new Uint32Array(array.buffer);
3730
+ return !((view[0] = 1) & array[0]);
3731
+ }
3732
+ function decodeFloat16(low, high) {
3733
+ const sign = (high & 128) >> 7;
3734
+ const exponent = (high & 124) >> 2;
3735
+ const fraction = ((high & 3) << 8) + low;
3736
+ let magnitude;
3737
+ if (exponent === 31) {
3738
+ magnitude = fraction === 0 ? Infinity : NaN;
3739
+ } else if (exponent === 0) {
3740
+ magnitude = 2 ** -14 * (fraction / 1024);
3741
+ } else {
3742
+ magnitude = 2 ** (exponent - 15) * (1 + fraction / 1024);
3743
+ }
3744
+ return sign ? -magnitude : magnitude;
3745
+ }
3746
+ class DataView64 extends DataView {
3747
+ getFloat16(byteOffset, littleEndian) {
3748
+ const bytes = [this.getUint8(byteOffset), this.getUint8(byteOffset + 1)];
3749
+ if (!littleEndian)
3750
+ bytes.reverse();
3751
+ return decodeFloat16(bytes[0], bytes[1]);
3752
+ }
3753
+ getUint64(byteOffset, littleEndian) {
3754
+ const left = BigInt(this.getUint32(byteOffset, littleEndian));
3755
+ const right = BigInt(this.getUint32(byteOffset + 4, littleEndian));
3756
+ const combined = littleEndian ? left + (right << 32n) : (left << 32n) + right;
3757
+ return Number(combined);
3758
+ }
3759
+ getInt64(byteOffset, littleEndian) {
3760
+ let low, high;
3761
+ if (littleEndian) {
3762
+ low = this.getUint32(byteOffset, true);
3763
+ high = this.getInt32(byteOffset + 4, true);
3764
+ } else {
3765
+ high = this.getInt32(byteOffset, false);
3766
+ low = this.getUint32(byteOffset + 4, false);
3547
3767
  }
3548
- throw new Error("Invalid rangeQuery value.");
3768
+ const combined = BigInt(low) + (BigInt(high) << 32n);
3769
+ return Number(combined);
3549
3770
  }
3550
- }));
3551
- async function relaxedFetch(...args) {
3552
- const response = await fetch(...args);
3553
- if (response.status === 403) {
3554
- return new Response(null, { status: 404 });
3771
+ getString(byteOffset, _littleEndian, length) {
3772
+ const str_buffer = this.buffer.slice(byteOffset, byteOffset + length);
3773
+ return new TextDecoder().decode(str_buffer);
3555
3774
  }
3556
- return response;
3557
- }
3558
- const CHUNK_GC_TIME = 3e4;
3559
- const UNDEFINED_SENTINEL = null;
3560
- const UNCACHED_READ = "vitessceUncachedRead";
3561
- function splitReadOptions(opts) {
3562
- if (!opts || !opts[UNCACHED_READ]) {
3563
- return [false, opts];
3775
+ getVLENStruct(byteOffset, littleEndian, _length) {
3776
+ const item_size = this.getUint32(byteOffset, littleEndian);
3777
+ const collection_address = this.getUint64(byteOffset + 4, littleEndian);
3778
+ const object_index = this.getUint32(byteOffset + 12, littleEndian);
3779
+ return [item_size, collection_address, object_index];
3564
3780
  }
3565
- const rest = { ...opts };
3566
- delete rest[UNCACHED_READ];
3567
- return [true, rest];
3568
3781
  }
3569
- function makeCacheFetch(queryClient) {
3570
- if (queryClient) {
3571
- return async (cacheKey, fn) => {
3572
- const result = await queryClient.fetchQuery({
3573
- queryKey: cacheKey,
3574
- queryFn: async () => await fn() ?? UNDEFINED_SENTINEL,
3575
- staleTime: Infinity,
3576
- gcTime: CHUNK_GC_TIME
3577
- });
3578
- return result === UNDEFINED_SENTINEL ? void 0 : result;
3782
+ class Struct {
3783
+ big_endian;
3784
+ getters;
3785
+ byte_lengths;
3786
+ fmt_size_regex;
3787
+ constructor() {
3788
+ this.big_endian = isBigEndian();
3789
+ this.getters = {
3790
+ s: "getUint8",
3791
+ b: "getInt8",
3792
+ B: "getUint8",
3793
+ h: "getInt16",
3794
+ H: "getUint16",
3795
+ i: "getInt32",
3796
+ I: "getUint32",
3797
+ l: "getInt32",
3798
+ L: "getUint32",
3799
+ q: "getInt64",
3800
+ Q: "getUint64",
3801
+ e: "getFloat16",
3802
+ f: "getFloat32",
3803
+ d: "getFloat64"
3579
3804
  };
3580
- }
3581
- const inflight = /* @__PURE__ */ new Map();
3582
- return (cacheKey, fn) => {
3583
- const key = JSON.stringify(cacheKey);
3584
- let promise = inflight.get(key);
3585
- if (!promise) {
3586
- promise = Promise.resolve(fn()).finally(() => {
3587
- inflight.delete(key);
3588
- });
3589
- inflight.set(key, promise);
3805
+ this.byte_lengths = {
3806
+ s: 1,
3807
+ b: 1,
3808
+ B: 1,
3809
+ h: 2,
3810
+ H: 2,
3811
+ i: 4,
3812
+ I: 4,
3813
+ l: 4,
3814
+ L: 4,
3815
+ q: 8,
3816
+ Q: 8,
3817
+ e: 2,
3818
+ f: 4,
3819
+ d: 8
3820
+ };
3821
+ const all_formats = Object.keys(this.byte_lengths).join("");
3822
+ this.fmt_size_regex = "(\\d*)([" + all_formats + "])";
3823
+ }
3824
+ calcsize(fmt) {
3825
+ let size = 0;
3826
+ const regex2 = new RegExp(this.fmt_size_regex, "g");
3827
+ let match;
3828
+ while ((match = regex2.exec(fmt)) !== null) {
3829
+ const n = parseInt(match[1] || "1", 10);
3830
+ const f = match[2];
3831
+ size += n * this.byte_lengths[f];
3832
+ }
3833
+ return size;
3834
+ }
3835
+ _is_big_endian(fmt) {
3836
+ if (/^</.test(fmt))
3837
+ return false;
3838
+ if (/^(!|>)/.test(fmt))
3839
+ return true;
3840
+ return this.big_endian;
3841
+ }
3842
+ unpack_from(fmt, buffer, offset) {
3843
+ offset = Number(offset || 0);
3844
+ const view = new DataView64(buffer, 0);
3845
+ const output = [];
3846
+ const big_endian = this._is_big_endian(fmt);
3847
+ const regex2 = new RegExp(this.fmt_size_regex, "g");
3848
+ let match;
3849
+ while ((match = regex2.exec(fmt)) !== null) {
3850
+ const n = parseInt(match[1] || "1", 10);
3851
+ const f = match[2];
3852
+ const getter = this.getters[f];
3853
+ const size = this.byte_lengths[f];
3854
+ if (f === "s") {
3855
+ output.push(new TextDecoder().decode(buffer.slice(offset, offset + n)));
3856
+ offset += n;
3857
+ } else {
3858
+ for (let i = 0; i < n; i++) {
3859
+ output.push(view[getter](offset, !big_endian));
3860
+ offset += size;
3861
+ }
3862
+ }
3590
3863
  }
3591
- return promise;
3592
- };
3864
+ return output;
3865
+ }
3593
3866
  }
3594
- const withQueryClientCache = defineStoreExtension((innerStore, extOpts) => {
3595
- const { cacheKeyPrefix, queryClient } = extOpts;
3596
- const cacheFetch = makeCacheFetch(queryClient);
3597
- return {
3598
- async get(...args) {
3599
- const [key, opts] = args;
3600
- const [uncached, rest] = splitReadOptions(opts);
3601
- if (uncached) {
3602
- return innerStore.get(key, rest);
3603
- }
3604
- return cacheFetch(["zarrStore", cacheKeyPrefix, key], () => innerStore.get(key, rest));
3605
- },
3606
- async getRange(...args) {
3607
- const [key, range2, opts] = args;
3608
- const [uncached, rest] = splitReadOptions(opts);
3609
- if (typeof innerStore.getRange !== "function") {
3610
- throw new Error("innerStore does not implement getRange");
3611
- }
3612
- if (uncached) {
3613
- return innerStore.getRange(key, range2, rest);
3867
+ const struct = new Struct();
3868
+ function bitSize(integer) {
3869
+ return integer.toString(2).length;
3870
+ }
3871
+ function _unpack_integer(nbytes, fh, offset = 0, littleEndian = true) {
3872
+ const bytes = new Uint8Array(fh.slice(offset, offset + nbytes));
3873
+ if (!littleEndian)
3874
+ bytes.reverse();
3875
+ return bytes.reduce((acc, val, idx) => acc + (val << idx * 8), 0);
3876
+ }
3877
+ function assert(thing) {
3878
+ if (!thing) {
3879
+ throw new Error("Assertion failed");
3880
+ }
3881
+ }
3882
+ const DATATYPE_MSG = /* @__PURE__ */ new Map([
3883
+ ["class_and_version", "B"],
3884
+ ["class_bit_field_0", "B"],
3885
+ ["class_bit_field_1", "B"],
3886
+ ["class_bit_field_2", "B"],
3887
+ ["size", "I"]
3888
+ ]);
3889
+ const DATATYPE_MSG_SIZE = _structure_size(DATATYPE_MSG);
3890
+ const DATATYPE_FIXED_POINT = 0;
3891
+ const DATATYPE_FLOATING_POINT = 1;
3892
+ const DATATYPE_TIME = 2;
3893
+ const DATATYPE_STRING = 3;
3894
+ const DATATYPE_BITFIELD = 4;
3895
+ const DATATYPE_OPAQUE = 5;
3896
+ const DATATYPE_COMPOUND = 6;
3897
+ const DATATYPE_REFERENCE = 7;
3898
+ const DATATYPE_ENUMERATED$1 = 8;
3899
+ const DATATYPE_VARIABLE_LENGTH = 9;
3900
+ class DatatypeMessage {
3901
+ buf;
3902
+ offset;
3903
+ dtype;
3904
+ constructor(buf, offset) {
3905
+ this.buf = buf;
3906
+ this.offset = offset;
3907
+ this.dtype = this.determine_dtype();
3908
+ }
3909
+ determine_dtype() {
3910
+ const datatype_msg = _unpack_struct_from(DATATYPE_MSG, this.buf, this.offset);
3911
+ this.offset += DATATYPE_MSG_SIZE;
3912
+ const datatype_class = datatype_msg.get("class_and_version") & 15;
3913
+ if (datatype_class === DATATYPE_FIXED_POINT) {
3914
+ return this._determine_dtype_fixed_point(datatype_msg);
3915
+ } else if (datatype_class === DATATYPE_FLOATING_POINT) {
3916
+ return this._determine_dtype_floating_point(datatype_msg);
3917
+ } else if (datatype_class === DATATYPE_TIME) {
3918
+ throw new Error("Time datatype class not supported.");
3919
+ } else if (datatype_class === DATATYPE_STRING) {
3920
+ return this._determine_dtype_string(datatype_msg);
3921
+ } else if (datatype_class === DATATYPE_BITFIELD) {
3922
+ throw new Error("Bitfield datatype class not supported.");
3923
+ } else if (datatype_class === DATATYPE_OPAQUE) {
3924
+ throw new Error("Opaque datatype class not supported.");
3925
+ } else if (datatype_class === DATATYPE_COMPOUND) {
3926
+ return this._determine_dtype_compound(datatype_msg);
3927
+ } else if (datatype_class === DATATYPE_REFERENCE) {
3928
+ return ["REFERENCE", datatype_msg.get("size")];
3929
+ } else if (datatype_class === DATATYPE_ENUMERATED$1) {
3930
+ return this.determine_dtype();
3931
+ } else if (datatype_class === DATATYPE_VARIABLE_LENGTH) {
3932
+ const vlen_type = this._determine_dtype_vlen(datatype_msg);
3933
+ if (vlen_type[0] === "VLEN_SEQUENCE") {
3934
+ const base_type = this.determine_dtype();
3935
+ return ["VLEN_SEQUENCE", base_type];
3936
+ }
3937
+ return vlen_type;
3938
+ } else {
3939
+ throw new Error("Invalid datatype class " + datatype_class);
3940
+ }
3941
+ }
3942
+ _determine_dtype_fixed_point(datatype_msg) {
3943
+ const length_in_bytes = datatype_msg.get("size");
3944
+ if (![1, 2, 4, 8].includes(length_in_bytes)) {
3945
+ throw new Error("Unsupported datatype size");
3946
+ }
3947
+ const signed = datatype_msg.get("class_bit_field_0") & 8;
3948
+ const dtype_char = signed > 0 ? "i" : "u";
3949
+ const byte_order = datatype_msg.get("class_bit_field_0") & 1;
3950
+ const byte_order_char = byte_order === 0 ? "<" : ">";
3951
+ this.offset += 4;
3952
+ return byte_order_char + dtype_char + length_in_bytes.toFixed();
3953
+ }
3954
+ _determine_dtype_floating_point(datatype_msg) {
3955
+ const length_in_bytes = datatype_msg.get("size");
3956
+ if (![1, 2, 4, 8].includes(length_in_bytes)) {
3957
+ throw new Error("Unsupported datatype size");
3958
+ }
3959
+ const byte_order = datatype_msg.get("class_bit_field_0") & 1;
3960
+ const byte_order_char = byte_order === 0 ? "<" : ">";
3961
+ this.offset += 12;
3962
+ return byte_order_char + "f" + length_in_bytes.toFixed();
3963
+ }
3964
+ _determine_dtype_string(datatype_msg) {
3965
+ return "S" + datatype_msg.get("size").toFixed();
3966
+ }
3967
+ _determine_dtype_compound(datatype_msg) {
3968
+ const version = datatype_msg.get("class_and_version") >> 4 & 15;
3969
+ const num_members = datatype_msg.get("class_bit_field_0") | datatype_msg.get("class_bit_field_1") << 8;
3970
+ const total_size = datatype_msg.get("size");
3971
+ try {
3972
+ const members = [];
3973
+ const view = new DataView(this.buf);
3974
+ for (let i = 0; i < num_members; i++) {
3975
+ let nameEnd = this.offset;
3976
+ while (nameEnd < this.buf.byteLength && view.getUint8(nameEnd) !== 0) {
3977
+ nameEnd++;
3978
+ }
3979
+ const nameBytes = new Uint8Array(this.buf, this.offset, nameEnd - this.offset);
3980
+ const name = new TextDecoder().decode(nameBytes);
3981
+ let memberOffset;
3982
+ if (version === 1) {
3983
+ const nameLenWithNull = nameEnd - this.offset + 1;
3984
+ const paddedLen = Math.ceil(nameLenWithNull / 8) * 8;
3985
+ this.offset += paddedLen;
3986
+ memberOffset = view.getUint32(this.offset, true);
3987
+ this.offset += 4;
3988
+ this.offset += 28;
3989
+ } else if (version === 2) {
3990
+ this.offset = nameEnd + 1;
3991
+ memberOffset = view.getUint32(this.offset, true);
3992
+ this.offset += 4;
3993
+ } else {
3994
+ this.offset = nameEnd + 1;
3995
+ const offsetBytes = Math.max(1, Math.ceil(Math.ceil(Math.log2(total_size + 1)) / 8));
3996
+ memberOffset = 0;
3997
+ for (let j = 0; j < offsetBytes; j++) {
3998
+ memberOffset |= view.getUint8(this.offset + j) << j * 8;
3999
+ }
4000
+ this.offset += offsetBytes;
4001
+ }
4002
+ const nestedMsg = new DatatypeMessage(this.buf, this.offset);
4003
+ this.offset = nestedMsg.offset;
4004
+ members.push({ name, dtype: nestedMsg.dtype, offset: memberOffset });
3614
4005
  }
3615
- return cacheFetch(["zarrStore", cacheKeyPrefix, key, range2], () => {
3616
- if (typeof innerStore.getRange !== "function") {
3617
- throw new Error("innerStore does not implement getRange");
4006
+ return ["COMPOUND", members, total_size];
4007
+ } catch {
4008
+ return ["COMPOUND", [], total_size];
4009
+ }
4010
+ }
4011
+ _determine_dtype_vlen(datatype_msg) {
4012
+ const vlen_type = datatype_msg.get("class_bit_field_0") & 1;
4013
+ if (vlen_type !== 1) {
4014
+ return ["VLEN_SEQUENCE", 0, 0];
4015
+ }
4016
+ const padding_type = datatype_msg.get("class_bit_field_0") >> 4;
4017
+ const character_set = datatype_msg.get("class_bit_field_1") & 1;
4018
+ return ["VLEN_STRING", padding_type, character_set];
4019
+ }
4020
+ }
4021
+ const B_LINK_NODE_V1 = /* @__PURE__ */ new Map([
4022
+ ["signature", "4s"],
4023
+ ["node_type", "B"],
4024
+ ["node_level", "B"],
4025
+ ["entries_used", "H"],
4026
+ ["left_sibling", "Q"],
4027
+ ["right_sibling", "Q"]
4028
+ ]);
4029
+ const B_LINK_NODE_V1_SIZE = _structure_size(B_LINK_NODE_V1);
4030
+ const V1_NODE_READ_AHEAD_ENTRIES = 64;
4031
+ async function _readV1Node(source, offset, node_level, entrySize, trailingSize) {
4032
+ const buf = await fetchRangeWithReadAhead(source, offset, B_LINK_NODE_V1_SIZE, B_LINK_NODE_V1_SIZE + V1_NODE_READ_AHEAD_ENTRIES * entrySize + trailingSize);
4033
+ const node = _unpack_struct_from(B_LINK_NODE_V1, buf, 0);
4034
+ if (node_level != null && node.get("node_level") !== node_level) {
4035
+ throw new Error("node level does not match");
4036
+ }
4037
+ const dataSize = node.get("entries_used") * entrySize + trailingSize;
4038
+ const dataEnd = B_LINK_NODE_V1_SIZE + dataSize;
4039
+ const data = dataEnd <= buf.byteLength ? buf.slice(B_LINK_NODE_V1_SIZE, dataEnd) : await fetchRange(source, offset + B_LINK_NODE_V1_SIZE, dataSize);
4040
+ return [node, data];
4041
+ }
4042
+ class BTreeV1Groups {
4043
+ all_nodes;
4044
+ depth;
4045
+ constructor(all_nodes, depth) {
4046
+ this.all_nodes = all_nodes;
4047
+ this.depth = depth;
4048
+ }
4049
+ static async create(source, offset) {
4050
+ const all_nodes = /* @__PURE__ */ new Map();
4051
+ async function readNode(off, node_level2) {
4052
+ const [header, dataBuf] = await _readV1Node(source, off, node_level2, 16, 8);
4053
+ const entries_used = header.get("entries_used");
4054
+ let localOff = 0;
4055
+ const keys2 = [];
4056
+ const addresses = [];
4057
+ for (let i = 0; i < entries_used; i++) {
4058
+ keys2.push(struct.unpack_from("<Q", dataBuf, localOff)[0]);
4059
+ localOff += 8;
4060
+ addresses.push(struct.unpack_from("<Q", dataBuf, localOff)[0]);
4061
+ localOff += 8;
4062
+ }
4063
+ keys2.push(struct.unpack_from("<Q", dataBuf, localOff)[0]);
4064
+ return { header, keys: keys2, addresses };
4065
+ }
4066
+ const root2 = await readNode(offset, null);
4067
+ const depth = root2.header.get("node_level");
4068
+ addNode(all_nodes, root2, depth);
4069
+ let node_level = depth;
4070
+ while (node_level > 0) {
4071
+ const parents = all_nodes.get(node_level) || [];
4072
+ const childAddrs = parents.flatMap((parent) => parent.addresses);
4073
+ const children = await Promise.all(childAddrs.map((child_addr) => readNode(child_addr, node_level - 1)));
4074
+ for (const child of children)
4075
+ addNode(all_nodes, child, node_level - 1);
4076
+ node_level--;
4077
+ }
4078
+ return new BTreeV1Groups(all_nodes, depth);
4079
+ }
4080
+ symbol_table_addresses() {
4081
+ const all_address = [];
4082
+ const root_nodes = this.all_nodes.get(0) || [];
4083
+ for (const node of root_nodes) {
4084
+ all_address.push(...node.addresses);
4085
+ }
4086
+ return all_address;
4087
+ }
4088
+ }
4089
+ class BTreeV1RawDataChunks {
4090
+ all_nodes;
4091
+ depth;
4092
+ dims;
4093
+ constructor(all_nodes, depth, dims) {
4094
+ this.all_nodes = all_nodes;
4095
+ this.depth = depth;
4096
+ this.dims = dims;
4097
+ }
4098
+ static async create(source, offset, dims) {
4099
+ const all_nodes = /* @__PURE__ */ new Map();
4100
+ async function readNode(off, node_level2) {
4101
+ const fmt = "<" + dims.toFixed() + "Q";
4102
+ const fmt_size = struct.calcsize(fmt);
4103
+ const entrySize = 8 + fmt_size + 8;
4104
+ const [header, dataBuf] = await _readV1Node(source, off, node_level2, entrySize, 0);
4105
+ const entries_used = header.get("entries_used");
4106
+ let localOff = 0;
4107
+ const keys2 = [];
4108
+ const addresses = [];
4109
+ for (let i = 0; i < entries_used; i++) {
4110
+ const [chunk_size, filter_mask] = struct.unpack_from("<II", dataBuf, localOff);
4111
+ localOff += 8;
4112
+ const chunk_offset = struct.unpack_from(fmt, dataBuf, localOff);
4113
+ localOff += fmt_size;
4114
+ const chunk_address = struct.unpack_from("<Q", dataBuf, localOff)[0];
4115
+ localOff += 8;
4116
+ keys2.push({ chunk_size, filter_mask, chunk_offset });
4117
+ addresses.push(chunk_address);
4118
+ }
4119
+ return { header, keys: keys2, addresses };
4120
+ }
4121
+ const root2 = await readNode(offset, null);
4122
+ const depth = root2.header.get("node_level");
4123
+ addNode(all_nodes, root2, depth);
4124
+ let node_level = depth;
4125
+ while (node_level > 0) {
4126
+ const parents = all_nodes.get(node_level) || [];
4127
+ const childAddrs = parents.flatMap((parent) => parent.addresses);
4128
+ const children = await Promise.all(childAddrs.map((child_addr) => readNode(child_addr, node_level - 1)));
4129
+ for (const child of children)
4130
+ addNode(all_nodes, child, node_level - 1);
4131
+ node_level--;
4132
+ }
4133
+ return new BTreeV1RawDataChunks(all_nodes, depth, dims);
4134
+ }
4135
+ }
4136
+ const B_TREE_HEADER_V2 = /* @__PURE__ */ new Map([
4137
+ ["signature", "4s"],
4138
+ ["version", "B"],
4139
+ ["node_type", "B"],
4140
+ ["node_size", "I"],
4141
+ ["record_size", "H"],
4142
+ ["depth", "H"],
4143
+ ["split_percent", "B"],
4144
+ ["merge_percent", "B"],
4145
+ ["root_address", "Q"],
4146
+ ["root_nrecords", "H"],
4147
+ ["total_nrecords", "Q"]
4148
+ ]);
4149
+ const B_LINK_NODE_V2 = /* @__PURE__ */ new Map([
4150
+ ["signature", "4s"],
4151
+ ["version", "B"],
4152
+ ["node_type", "B"]
4153
+ ]);
4154
+ const B_LINK_NODE_V2_SIZE = _structure_size(B_LINK_NODE_V2);
4155
+ function _required_bytes(integer) {
4156
+ return Math.ceil(bitSize(integer) / 8);
4157
+ }
4158
+ function _int_format(bytelength) {
4159
+ return ["<B", "<H", "<I", "<Q"][bytelength - 1];
4160
+ }
4161
+ function _nrecords_max(node_size, record_size, addr_size) {
4162
+ return Math.floor((node_size - 10 - addr_size) / (record_size + addr_size));
4163
+ }
4164
+ function _calculate_address_formats(header) {
4165
+ const node_size = header.get("node_size");
4166
+ const record_size = header.get("record_size");
4167
+ let nrecords_max = 0;
4168
+ let ntotalrecords_max = 0;
4169
+ const address_formats = /* @__PURE__ */ new Map();
4170
+ const max_depth = header.get("depth");
4171
+ for (let node_level = 0; node_level <= max_depth; node_level++) {
4172
+ let offset_fmt = "";
4173
+ let num1_fmt = "";
4174
+ let num2_fmt = "";
4175
+ let offset_size, num1_size, num2_size;
4176
+ if (node_level === 0) {
4177
+ offset_size = 0;
4178
+ num1_size = 0;
4179
+ num2_size = 0;
4180
+ } else if (node_level === 1) {
4181
+ offset_size = 8;
4182
+ offset_fmt = "<Q";
4183
+ num1_size = _required_bytes(nrecords_max);
4184
+ num1_fmt = _int_format(num1_size);
4185
+ num2_size = 0;
4186
+ } else {
4187
+ offset_size = 8;
4188
+ offset_fmt = "<Q";
4189
+ num1_size = _required_bytes(nrecords_max);
4190
+ num1_fmt = _int_format(num1_size);
4191
+ num2_size = _required_bytes(ntotalrecords_max);
4192
+ num2_fmt = _int_format(num2_size);
4193
+ }
4194
+ address_formats.set(node_level, [
4195
+ offset_size,
4196
+ num1_size,
4197
+ num2_size,
4198
+ offset_fmt,
4199
+ num1_fmt,
4200
+ num2_fmt
4201
+ ]);
4202
+ if (node_level < max_depth) {
4203
+ const addr_size = offset_size + num1_size + num2_size;
4204
+ nrecords_max = _nrecords_max(node_size, record_size, addr_size);
4205
+ if (ntotalrecords_max > 0) {
4206
+ ntotalrecords_max *= nrecords_max;
4207
+ } else {
4208
+ ntotalrecords_max = nrecords_max;
4209
+ }
4210
+ }
4211
+ }
4212
+ return address_formats;
4213
+ }
4214
+ async function _readBTreeV2(source, offset, parseRecord) {
4215
+ const headerSize = _structure_size(B_TREE_HEADER_V2);
4216
+ const hBuf = await fetchRange(source, offset, headerSize);
4217
+ const header = _unpack_struct_from(B_TREE_HEADER_V2, hBuf, 0);
4218
+ const address_formats = _calculate_address_formats(header);
4219
+ const depth = header.get("depth");
4220
+ const record_size = header.get("record_size");
4221
+ const all_nodes = /* @__PURE__ */ new Map();
4222
+ async function readNode(address, node_level2) {
4223
+ const [off, nrecords] = address;
4224
+ const addr_fmts = address_formats.get(node_level2);
4225
+ const [offset_size, num1_size, num2_size] = addr_fmts;
4226
+ const addr_entry_size = offset_size + num1_size + num2_size;
4227
+ const maxBytes = B_LINK_NODE_V2_SIZE + nrecords * record_size + (node_level2 !== 0 ? (nrecords + 1) * addr_entry_size : 0) + 4;
4228
+ const nodeBuf = await fetchRange(source, off, maxBytes);
4229
+ const node = _unpack_struct_from(B_LINK_NODE_V2, nodeBuf, 0);
4230
+ node.set("node_level", node_level2);
4231
+ let localOff = B_LINK_NODE_V2_SIZE;
4232
+ const keys2 = [];
4233
+ for (let i = 0; i < nrecords; i++) {
4234
+ keys2.push(parseRecord(nodeBuf, localOff, record_size));
4235
+ localOff += record_size;
4236
+ }
4237
+ const addresses = [];
4238
+ if (node_level2 !== 0) {
4239
+ const [os, n1s, n2s, offset_fmt, num1_fmt, num2_fmt] = addr_fmts;
4240
+ for (let j = 0; j <= nrecords; j++) {
4241
+ const address_offset = struct.unpack_from(offset_fmt, nodeBuf, localOff)[0];
4242
+ localOff += os;
4243
+ const num1 = struct.unpack_from(num1_fmt, nodeBuf, localOff)[0];
4244
+ localOff += n1s;
4245
+ let num2 = num1;
4246
+ if (n2s > 0) {
4247
+ num2 = struct.unpack_from(num2_fmt, nodeBuf, localOff)[0];
4248
+ localOff += n2s;
3618
4249
  }
3619
- return innerStore.getRange(key, range2, rest);
3620
- });
4250
+ addresses.push([address_offset, num1, num2]);
4251
+ }
3621
4252
  }
3622
- };
3623
- });
3624
- function transformEntriesForZipFileStore(entries) {
3625
- const topLevelZarrDirectories = new Set(Object.keys(entries).map((k) => k.split("/")[0]).filter((firstPathItem) => firstPathItem?.endsWith(".zarr")));
3626
- if (topLevelZarrDirectories.size === 0) {
3627
- return entries;
4253
+ return { header: node, keys: keys2, addresses };
3628
4254
  }
3629
- if (topLevelZarrDirectories.size > 1) {
3630
- throw Error("expected exactly one top-level .zarr directory");
4255
+ const rootAddr = [
4256
+ header.get("root_address"),
4257
+ header.get("root_nrecords"),
4258
+ header.get("total_nrecords")
4259
+ ];
4260
+ const root2 = await readNode(rootAddr, depth);
4261
+ addNode(all_nodes, root2, depth);
4262
+ let node_level = depth;
4263
+ while (node_level > 0) {
4264
+ const parents = all_nodes.get(node_level) || [];
4265
+ const childAddrs = parents.flatMap((parent) => parent.addresses);
4266
+ const children = await Promise.all(childAddrs.map((child_addr) => readNode(child_addr, node_level - 1)));
4267
+ for (const child of children)
4268
+ addNode(all_nodes, child, node_level - 1);
4269
+ node_level--;
4270
+ }
4271
+ return { all_nodes, header };
4272
+ }
4273
+ class BTreeV2GroupNames {
4274
+ all_nodes;
4275
+ header;
4276
+ constructor(all_nodes, header) {
4277
+ this.all_nodes = all_nodes;
4278
+ this.header = header;
4279
+ }
4280
+ static async create(source, offset) {
4281
+ const { all_nodes, header } = await _readBTreeV2(source, offset, (buf, off) => {
4282
+ const namehash = struct.unpack_from("<I", buf, off)[0];
4283
+ return /* @__PURE__ */ new Map([
4284
+ ["namehash", namehash],
4285
+ ["heapid", buf.slice(off + 4, off + 4 + 7)]
4286
+ ]);
4287
+ });
4288
+ return new BTreeV2GroupNames(all_nodes, header);
3631
4289
  }
3632
- const topLevelZarrDirectory = Array.from(topLevelZarrDirectories)[0];
3633
- const newEntries = Object.fromEntries(Object.entries(entries).map(([k, v]) => {
3634
- let newKey = k;
3635
- if (k.split("/")[0] === topLevelZarrDirectory) {
3636
- newKey = k.substring(topLevelZarrDirectory.length + 1);
4290
+ *iter_records() {
4291
+ for (const nodelist of this.all_nodes.values()) {
4292
+ for (const node of nodelist) {
4293
+ for (const key of node.keys) {
4294
+ yield key;
4295
+ }
4296
+ }
3637
4297
  }
3638
- return [newKey, v];
3639
- }));
3640
- return newEntries;
3641
- }
3642
- function applyStoreExtensions(store, url, queryClient) {
3643
- return extendStore(
3644
- store,
3645
- withGetRange,
3646
- // Wrap remote stores in a read-through cache, so that concurrent reads of the
3647
- // same chunk (e.g. multiple embedding dims within one chunk column-block) share
3648
- // one request instead of downloading it once per reader.
3649
- (s) => withQueryClientCache(s, { cacheKeyPrefix: url, queryClient })
3650
- );
4298
+ }
3651
4299
  }
3652
- function zarrOpenRoot(url, fileType, opts) {
3653
- let store;
3654
- if (fileType && fileType.endsWith(".zip")) {
3655
- store = ZipFileStore.fromUrl(url, {
3656
- overrides: opts?.requestInit,
3657
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3658
- // @ts-ignore
3659
- transformEntries: transformEntriesForZipFileStore
4300
+ class BTreeV2GroupOrders {
4301
+ all_nodes;
4302
+ header;
4303
+ constructor(all_nodes, header) {
4304
+ this.all_nodes = all_nodes;
4305
+ this.header = header;
4306
+ }
4307
+ static async create(source, offset) {
4308
+ const { all_nodes, header } = await _readBTreeV2(source, offset, (buf, off) => {
4309
+ const creationorder = struct.unpack_from("<Q", buf, off)[0];
4310
+ return /* @__PURE__ */ new Map([
4311
+ ["creationorder", creationorder],
4312
+ ["heapid", buf.slice(off + 8, off + 8 + 7)]
4313
+ ]);
3660
4314
  });
3661
- } else if (fileType && fileType.endsWith(".h5ad")) {
3662
- if (!opts?.refSpecUrl) {
3663
- throw new Error("refSpecUrl is required for H5AD files");
3664
- }
3665
- const referenceSpecPromise = fetch(opts.refSpecUrl).then((res) => res.json()).then((referenceSpec) => Object.fromEntries(
3666
- // We want ReferenceStore.fromSpec to use our `target` URL option regardless
3667
- // of what target URL(s) are specified in the reference spec JSON.
3668
- // Reference: https://github.com/manzt/zarrita.js/pull/155
3669
- Object.entries(referenceSpec).map(([key, entry]) => {
3670
- if (Array.isArray(entry) && entry.length >= 1) {
3671
- entry[0] = null;
4315
+ return new BTreeV2GroupOrders(all_nodes, header);
4316
+ }
4317
+ *iter_records() {
4318
+ for (const nodelist of this.all_nodes.values()) {
4319
+ for (const node of nodelist) {
4320
+ for (const key of node.keys) {
4321
+ yield key;
3672
4322
  }
3673
- return [key, entry];
3674
- })
3675
- ));
3676
- store = ReferenceStore.fromSpec(referenceSpecPromise, { target: url, overrides: opts?.requestInit });
3677
- } else {
3678
- store = new FetchStore(url, { overrides: opts?.requestInit, fetch: relaxedFetch });
4323
+ }
4324
+ }
3679
4325
  }
3680
- const extendedStore = applyStoreExtensions(store, url, opts?.queryClient);
3681
- return root$1(extendedStore);
3682
4326
  }
3683
- function flattenOmeAttrs(rootAttrs) {
3684
- if (rootAttrs && typeof rootAttrs.ome === "object" && rootAttrs.ome !== null) {
3685
- return { ...rootAttrs.ome, ...rootAttrs };
4327
+ function addNode(all_nodes, node, node_level) {
4328
+ const level = node.header?.get?.("node_level") ?? node_level;
4329
+ if (all_nodes.has(level)) {
4330
+ all_nodes.get(level).push(node);
4331
+ } else {
4332
+ all_nodes.set(level, [node]);
3686
4333
  }
3687
- return rootAttrs;
3688
4334
  }
3689
- class VitessceError extends Error {
3690
- constructor(message) {
3691
- super(message);
3692
- this.name = "VitessceError";
3693
- }
4335
+ const FILTER_DEFLATE = 1;
4336
+ const FILTER_SHUFFLE = 2;
4337
+ const FILTER_FLETCHER32 = 3;
4338
+ async function inflate(data) {
4339
+ const stream = new Blob([data]).stream().pipeThrough(new DecompressionStream("deflate"));
4340
+ return new Uint8Array(await new Response(stream).arrayBuffer());
3694
4341
  }
3695
- class DataLoaderError extends VitessceError {
3696
- constructor(message) {
3697
- super(message);
3698
- this.name = "DataLoaderError";
4342
+ function unshuffle(data, elementSize) {
4343
+ if (elementSize <= 1)
4344
+ return data;
4345
+ const count = Math.floor(data.length / elementSize);
4346
+ const out = new Uint8Array(data.length);
4347
+ for (let b = 0; b < elementSize; b++) {
4348
+ const src = b * count;
4349
+ for (let i = 0; i < count; i++) {
4350
+ out[i * elementSize + b] = data[src + i];
4351
+ }
3699
4352
  }
4353
+ out.set(data.subarray(count * elementSize), count * elementSize);
4354
+ return out;
3700
4355
  }
3701
- class ZarrNodeNotFoundError extends DataLoaderError {
3702
- constructor(message) {
3703
- super(message);
3704
- this.name = "ZarrNodeNotFoundError";
4356
+ async function decodeChunk(data, pipeline, filterMask = 0) {
4357
+ if (!pipeline)
4358
+ return data;
4359
+ let out = data;
4360
+ for (let i = pipeline.length - 1; i >= 0; i--) {
4361
+ if (filterMask & 1 << i)
4362
+ continue;
4363
+ const filter = pipeline[i];
4364
+ const id = filter.get("filter_id");
4365
+ const clientData = filter.get("client_data") ?? [];
4366
+ if (id === FILTER_DEFLATE) {
4367
+ out = await inflate(out);
4368
+ } else if (id === FILTER_SHUFFLE) {
4369
+ out = unshuffle(out, clientData[0] ?? 1);
4370
+ } else if (id === FILTER_FLETCHER32) {
4371
+ out = out.subarray(0, out.length - 4);
4372
+ } else {
4373
+ throw new Error(`Unsupported HDF5 filter id ${id} for chunk decoding`);
4374
+ }
3705
4375
  }
4376
+ return out;
3706
4377
  }
3707
- class MatrixTooLargeError extends DataLoaderError {
3708
- constructor(message) {
3709
- super(message);
3710
- this.name = "MatrixTooLargeError";
4378
+ const isValidMaxSize = (value) => typeof value === "number" && value > 0 && (Number.isInteger(value) || value === Infinity);
4379
+ const hasExpiry = (item) => item.expiry !== void 0 && !Number.isNaN(item.expiry);
4380
+ const MODE_KEYS = 0;
4381
+ const MODE_VALUES = 1;
4382
+ const MODE_ENTRIES = 2;
4383
+ const MODE_ITEMS = 3;
4384
+ const INVALID_MAX_SIZE_MESSAGE = "`maxSize` must be a whole number greater than 0 or `Infinity`";
4385
+ class QuickLRU extends Map {
4386
+ #cache = /* @__PURE__ */ new Map();
4387
+ #oldCache = /* @__PURE__ */ new Map();
4388
+ #maxSize;
4389
+ #maxAge;
4390
+ #onEviction;
4391
+ constructor(options = {}) {
4392
+ super();
4393
+ if (!isValidMaxSize(options.maxSize)) {
4394
+ throw new TypeError(INVALID_MAX_SIZE_MESSAGE);
4395
+ }
4396
+ if (typeof options.maxAge === "number" && !(options.maxAge > 0)) {
4397
+ throw new TypeError("`maxAge` must be a number greater than 0");
4398
+ }
4399
+ this.#maxSize = options.maxSize;
4400
+ this.#maxAge = typeof options.maxAge === "number" ? options.maxAge : Infinity;
4401
+ this.#onEviction = options.onEviction;
3711
4402
  }
3712
- }
3713
- class ZarrDataSource {
3714
- /**
3715
- * @param {DataSourceParams & { refSpecUrl?: string }} params The parameters object.
3716
- */
3717
- constructor({ url, requestInit: requestInit2, refSpecUrl, store, fileType, queryClient }) {
3718
- log.info("Using a Zarr-based data source. 403 and 404 HTTP responses for Zarr metadata files (.zattrs, .zarray, .zgroup, zarr.json) are to be expected and do not necessarily indicate errors.");
3719
- this.queryClient = queryClient;
3720
- if (store) {
3721
- const extendedStore = applyStoreExtensions(store, url, queryClient);
3722
- this.storeRoot = root$1(extendedStore);
3723
- } else if (url) {
3724
- this.storeRoot = zarrOpenRoot(url, fileType, { requestInit: requestInit2, refSpecUrl, queryClient });
3725
- } else {
3726
- throw new Error("Either a store or a URL must be provided to the ZarrDataSource constructor.");
4403
+ #emitEvictions(cache) {
4404
+ if (typeof this.#onEviction !== "function") {
4405
+ return;
4406
+ }
4407
+ const evictions = [...cache].filter(([key]) => !this.#cache.has(key) && !this.#oldCache.has(key));
4408
+ for (const [key, item] of evictions) {
4409
+ this.#onEviction(key, item.value);
3727
4410
  }
3728
- this.nodeCache = /* @__PURE__ */ new Map();
3729
4411
  }
3730
- /**
3731
- * Open the zarr node (array or group) at a path relative to the store root,
3732
- * memoized per path. A rejected open is dropped again, so a later call
3733
- * retries instead of re-awaiting a dead promise.
3734
- * @param {string} path The node path relative to the store root.
3735
- * @returns {Promise<any>} The zarrita Array or Group.
3736
- */
3737
- openNode(path) {
3738
- const key = path.startsWith("/") ? path : `/${path}`;
4412
+ #deleteIfExpired(key, item) {
4413
+ if (hasExpiry(item) && item.expiry <= Date.now()) {
4414
+ const deleted = this.delete(key);
4415
+ if (deleted && typeof this.#onEviction === "function") {
4416
+ this.#onEviction(key, item.value);
4417
+ }
4418
+ return deleted;
4419
+ }
4420
+ return false;
4421
+ }
4422
+ // Returns the value, or `undefined` once the item has been removed as expired.
4423
+ #getItemValue(key, item) {
4424
+ return this.#deleteIfExpired(key, item) === false ? item.value : void 0;
4425
+ }
4426
+ #set(key, item) {
4427
+ this.#cache.set(key, item);
4428
+ if (this.#cache.size < this.#maxSize) {
4429
+ return;
4430
+ }
4431
+ const oldCache = this.#oldCache;
4432
+ this.#oldCache = this.#cache;
4433
+ this.#cache = /* @__PURE__ */ new Map();
4434
+ this.#emitEvictions(oldCache);
4435
+ }
4436
+ #moveToRecent(key, item) {
4437
+ this.#oldCache.delete(key);
4438
+ this.#set(key, item);
4439
+ }
4440
+ // The current item for `key`, or `undefined` if it is gone or has expired. The recent cache wins, since an old cache copy of a key that is in both is stale. Not a generator, since this runs once per item during iteration.
4441
+ #liveItem(key) {
4442
+ const item = this.#cache.get(key) ?? this.#oldCache.get(key);
4443
+ if (item !== void 0 && this.#deleteIfExpired(key, item) === false) {
4444
+ return item;
4445
+ }
4446
+ }
4447
+ // The current item for `key`, promoted to the recent cache when it was in the old one, or `undefined` when the key is missing or has expired. Only for the methods that refresh recency, since promoting is what separates them from `peek()`. One lookup per cache, since where the item is found decides the promotion. Not a generator, since this runs once per lookup.
4448
+ #getLiveItem(key) {
4449
+ let item = this.#cache.get(key);
4450
+ if (item === void 0) {
4451
+ item = this.#oldCache.get(key);
4452
+ if (item === void 0 || this.#deleteIfExpired(key, item)) {
4453
+ return;
4454
+ }
4455
+ this.#moveToRecent(key, item);
4456
+ } else if (this.#deleteIfExpired(key, item)) {
4457
+ return;
4458
+ }
4459
+ return item;
4460
+ }
4461
+ // The old cache keys that are not also in the recent cache, since an old copy of such a key is stale. A plain loop, since this runs once per item during iteration.
4462
+ #olderKeys() {
4463
+ const keys2 = [];
4464
+ for (const key of this.#oldCache.keys()) {
4465
+ if (!this.#cache.has(key)) {
4466
+ keys2.push(key);
4467
+ }
4468
+ }
4469
+ return keys2;
4470
+ }
4471
+ *#walk(mode, descending) {
4472
+ const keys2 = [...this.#olderKeys(), ...this.#cache.keys()];
4473
+ if (descending) {
4474
+ keys2.reverse();
4475
+ }
4476
+ for (const key of keys2) {
4477
+ const item = this.#liveItem(key);
4478
+ if (item === void 0) {
4479
+ continue;
4480
+ }
4481
+ if (mode === MODE_KEYS) {
4482
+ yield key;
4483
+ } else if (mode === MODE_VALUES) {
4484
+ yield item.value;
4485
+ } else if (mode === MODE_ITEMS) {
4486
+ yield [key, item];
4487
+ } else {
4488
+ yield [key, item.value];
4489
+ }
4490
+ }
4491
+ }
4492
+ // For tests. Public on purpose, so the test suite can see where an item lives.
4493
+ // eslint-disable-next-line unicorn/prefer-private-class-fields
4494
+ get __oldCache() {
4495
+ return this.#oldCache;
4496
+ }
4497
+ get(key) {
4498
+ const item = this.#getLiveItem(key);
4499
+ return item === void 0 ? void 0 : item.value;
4500
+ }
4501
+ getOrInsert(key, value) {
4502
+ const item = this.#getLiveItem(key);
4503
+ if (item === void 0) {
4504
+ this.set(key, value);
4505
+ return value;
4506
+ }
4507
+ return item.value;
4508
+ }
4509
+ getOrInsertComputed(key, callback) {
4510
+ const item = this.#getLiveItem(key);
4511
+ if (item === void 0) {
4512
+ const value = callback(key);
4513
+ this.set(key, value);
4514
+ return value;
4515
+ }
4516
+ return item.value;
4517
+ }
4518
+ set(key, value, { maxAge = this.#maxAge } = {}) {
4519
+ const expiry = typeof maxAge === "number" && maxAge !== Infinity ? Date.now() + maxAge : void 0;
4520
+ this.#set(key, { value, expiry });
4521
+ return this;
4522
+ }
4523
+ has(key) {
4524
+ const item = this.#cache.get(key) ?? this.#oldCache.get(key);
4525
+ return item !== void 0 && !this.#deleteIfExpired(key, item);
4526
+ }
4527
+ peek(key) {
4528
+ const item = this.#cache.get(key) ?? this.#oldCache.get(key);
4529
+ return item === void 0 ? void 0 : this.#getItemValue(key, item);
4530
+ }
4531
+ expiresIn(key) {
4532
+ const item = this.#cache.get(key) ?? this.#oldCache.get(key);
4533
+ if (item) {
4534
+ return hasExpiry(item) ? item.expiry - Date.now() : Infinity;
4535
+ }
4536
+ }
4537
+ delete(key) {
4538
+ const deleted = this.#cache.delete(key);
4539
+ return this.#oldCache.delete(key) || deleted;
4540
+ }
4541
+ clear() {
4542
+ this.#cache.clear();
4543
+ this.#oldCache.clear();
4544
+ }
4545
+ resize(newSize) {
4546
+ if (!isValidMaxSize(newSize)) {
4547
+ throw new TypeError(INVALID_MAX_SIZE_MESSAGE);
4548
+ }
4549
+ const items = [...this.#walk(MODE_ITEMS)];
4550
+ const removeCount = items.length - newSize;
4551
+ if (removeCount < 0) {
4552
+ this.#cache = new Map(items);
4553
+ this.#oldCache = /* @__PURE__ */ new Map();
4554
+ } else {
4555
+ this.#oldCache = new Map(items.slice(removeCount));
4556
+ this.#cache = /* @__PURE__ */ new Map();
4557
+ }
4558
+ this.#maxSize = newSize;
4559
+ if (removeCount > 0) {
4560
+ this.#emitEvictions(items.slice(0, removeCount));
4561
+ }
4562
+ }
4563
+ evict(count = 1) {
4564
+ const requested = Number(count);
4565
+ if (!requested || requested <= 0) {
4566
+ return;
4567
+ }
4568
+ const live = [...this.#walk(MODE_ITEMS)];
4569
+ const evictCount = Math.min(Math.trunc(requested), Math.max(live.length - 1, 0));
4570
+ const evicted = [];
4571
+ for (const [key] of live.slice(0, evictCount)) {
4572
+ const item = this.#cache.get(key) ?? this.#oldCache.get(key);
4573
+ if (item !== void 0 && this.delete(key)) {
4574
+ evicted.push([key, item]);
4575
+ }
4576
+ }
4577
+ this.#emitEvictions(evicted);
4578
+ }
4579
+ keys() {
4580
+ return this.#walk(MODE_KEYS);
4581
+ }
4582
+ values() {
4583
+ return this.#walk(MODE_VALUES);
4584
+ }
4585
+ [Symbol.iterator]() {
4586
+ return this.entriesAscending();
4587
+ }
4588
+ entriesDescending() {
4589
+ return this.#walk(MODE_ENTRIES, true);
4590
+ }
4591
+ entriesAscending() {
4592
+ return this.#walk(MODE_ENTRIES);
4593
+ }
4594
+ get size() {
4595
+ const recentSize = this.#cache.size;
4596
+ const olderSize = this.#oldCache.size;
4597
+ if (recentSize === 0 || olderSize === 0) {
4598
+ return Math.min(recentSize + olderSize, this.#maxSize);
4599
+ }
4600
+ let walked = this.#cache;
4601
+ let checked = this.#oldCache;
4602
+ if (olderSize < recentSize) {
4603
+ walked = this.#oldCache;
4604
+ checked = this.#cache;
4605
+ }
4606
+ let duplicates = 0;
4607
+ for (const key of walked.keys()) {
4608
+ if (checked.has(key)) {
4609
+ duplicates++;
4610
+ }
4611
+ }
4612
+ return Math.min(recentSize + olderSize - duplicates, this.#maxSize);
4613
+ }
4614
+ get maxSize() {
4615
+ return this.#maxSize;
4616
+ }
4617
+ get maxAge() {
4618
+ return this.#maxAge;
4619
+ }
4620
+ entries() {
4621
+ return this.entriesAscending();
4622
+ }
4623
+ forEach(callbackFunction, thisArgument = this) {
4624
+ for (const [key, value] of this.entriesAscending()) {
4625
+ callbackFunction.call(thisArgument, value, key, this);
4626
+ }
4627
+ }
4628
+ get [Symbol.toStringTag]() {
4629
+ return "QuickLRU";
4630
+ }
4631
+ toString() {
4632
+ return `QuickLRU(${this.size}/${this.maxSize})`;
4633
+ }
4634
+ [Symbol.for("nodejs.util.inspect.custom")]() {
4635
+ return this.toString();
4636
+ }
4637
+ }
4638
+ const FORMAT_SIGNATURE = struct.unpack_from("8s", new Uint8Array([137, 72, 68, 70, 13, 10, 26, 10]).buffer)[0];
4639
+ const UNDEFINED_ADDRESS = struct.unpack_from("<Q", new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]).buffer)[0];
4640
+ const SUPERBLOCK_V0 = /* @__PURE__ */ new Map([
4641
+ ["format_signature", "8s"],
4642
+ ["superblock_version", "B"],
4643
+ ["free_storage_version", "B"],
4644
+ ["root_group_version", "B"],
4645
+ ["reserved_0", "B"],
4646
+ ["shared_header_version", "B"],
4647
+ ["offset_size", "B"],
4648
+ ["length_size", "B"],
4649
+ ["reserved_1", "B"],
4650
+ ["group_leaf_node_k", "H"],
4651
+ ["group_internal_node_k", "H"],
4652
+ ["file_consistency_flags", "L"],
4653
+ ["base_address_lower", "Q"],
4654
+ ["free_space_address", "Q"],
4655
+ ["end_of_file_address", "Q"],
4656
+ ["driver_information_address", "Q"]
4657
+ ]);
4658
+ const SUPERBLOCK_V0_SIZE = _structure_size(SUPERBLOCK_V0);
4659
+ const SUPERBLOCK_V2_V3 = /* @__PURE__ */ new Map([
4660
+ ["format_signature", "8s"],
4661
+ ["superblock_version", "B"],
4662
+ ["offset_size", "B"],
4663
+ ["length_size", "B"],
4664
+ ["file_consistency_flags", "B"],
4665
+ ["base_address", "Q"],
4666
+ ["superblock_extension_address", "Q"],
4667
+ ["end_of_file_address", "Q"],
4668
+ ["root_group_address", "Q"],
4669
+ ["superblock_checksum", "I"]
4670
+ ]);
4671
+ const SUPERBLOCK_V2_V3_SIZE = _structure_size(SUPERBLOCK_V2_V3);
4672
+ const SYMBOL_TABLE_ENTRY = /* @__PURE__ */ new Map([
4673
+ ["link_name_offset", "Q"],
4674
+ ["object_header_address", "Q"],
4675
+ ["cache_type", "I"],
4676
+ ["reserved", "I"],
4677
+ ["scratch", "16s"]
4678
+ ]);
4679
+ const SYMBOL_TABLE_ENTRY_SIZE = _structure_size(SYMBOL_TABLE_ENTRY);
4680
+ const SYMBOL_TABLE_NODE = /* @__PURE__ */ new Map([
4681
+ ["signature", "4s"],
4682
+ ["version", "B"],
4683
+ ["reserved_0", "B"],
4684
+ ["symbols", "H"]
4685
+ ]);
4686
+ const SYMBOL_TABLE_NODE_SIZE = _structure_size(SYMBOL_TABLE_NODE);
4687
+ const LOCAL_HEAP = /* @__PURE__ */ new Map([
4688
+ ["signature", "4s"],
4689
+ ["version", "B"],
4690
+ ["reserved", "3s"],
4691
+ ["data_segment_size", "Q"],
4692
+ ["offset_to_free_list", "Q"],
4693
+ ["address_of_data_segment", "Q"]
4694
+ ]);
4695
+ const GLOBAL_HEAP_HEADER = /* @__PURE__ */ new Map([
4696
+ ["signature", "4s"],
4697
+ ["version", "B"],
4698
+ ["reserved", "3s"],
4699
+ ["collection_size", "Q"]
4700
+ ]);
4701
+ const GLOBAL_HEAP_HEADER_SIZE = _structure_size(GLOBAL_HEAP_HEADER);
4702
+ const GLOBAL_HEAP_OBJECT = /* @__PURE__ */ new Map([
4703
+ ["object_index", "H"],
4704
+ ["reference_count", "H"],
4705
+ ["reserved", "I"],
4706
+ ["object_size", "Q"]
4707
+ ]);
4708
+ const GLOBAL_HEAP_OBJECT_SIZE = _structure_size(GLOBAL_HEAP_OBJECT);
4709
+ const FRACTAL_HEAP_HEADER = /* @__PURE__ */ new Map([
4710
+ ["signature", "4s"],
4711
+ ["version", "B"],
4712
+ ["object_index_size", "H"],
4713
+ ["filter_info_size", "H"],
4714
+ ["flags", "B"],
4715
+ ["max_managed_object_size", "I"],
4716
+ ["next_huge_object_index", "Q"],
4717
+ ["btree_address_huge_objects", "Q"],
4718
+ ["managed_freespace_size", "Q"],
4719
+ ["freespace_manager_address", "Q"],
4720
+ ["managed_space_size", "Q"],
4721
+ ["managed_alloc_size", "Q"],
4722
+ ["next_directblock_iterator_address", "Q"],
4723
+ ["managed_object_count", "Q"],
4724
+ ["huge_objects_total_size", "Q"],
4725
+ ["huge_object_count", "Q"],
4726
+ ["tiny_objects_total_size", "Q"],
4727
+ ["tiny_object_count", "Q"],
4728
+ ["table_width", "H"],
4729
+ ["starting_block_size", "Q"],
4730
+ ["maximum_direct_block_size", "Q"],
4731
+ ["log2_maximum_heap_size", "H"],
4732
+ ["indirect_starting_rows_count", "H"],
4733
+ ["root_block_address", "Q"],
4734
+ ["indirect_current_rows_count", "H"]
4735
+ ]);
4736
+ const LOCAL_HEAP_READ_AHEAD = 1024;
4737
+ const GLOBAL_HEAP_READ_AHEAD = 4096;
4738
+ class SuperBlock {
4739
+ version;
4740
+ _contents;
4741
+ _end_of_sblock;
4742
+ _root_symbol_table = null;
4743
+ _source;
4744
+ constructor(source, contents, version, end_of_sblock) {
4745
+ this._source = source;
4746
+ this._contents = contents;
4747
+ this.version = version;
4748
+ this._end_of_sblock = end_of_sblock;
4749
+ }
4750
+ static async create(source, offset) {
4751
+ const needed = Math.max(SUPERBLOCK_V0_SIZE, SUPERBLOCK_V2_V3_SIZE);
4752
+ const buf = await fetchRange(source, offset, needed);
4753
+ const version_hint = struct.unpack_from("<B", buf, 8)[0];
4754
+ let contents;
4755
+ let end_of_sblock;
4756
+ if (version_hint === 0) {
4757
+ contents = _unpack_struct_from(SUPERBLOCK_V0, buf, 0);
4758
+ end_of_sblock = offset + SUPERBLOCK_V0_SIZE;
4759
+ } else if (version_hint === 2 || version_hint === 3) {
4760
+ contents = _unpack_struct_from(SUPERBLOCK_V2_V3, buf, 0);
4761
+ end_of_sblock = offset + SUPERBLOCK_V2_V3_SIZE;
4762
+ } else {
4763
+ throw new Error("unsupported superblock version: " + version_hint);
4764
+ }
4765
+ if (contents.get("format_signature") !== FORMAT_SIGNATURE) {
4766
+ throw new Error("Incorrect file signature: " + contents.get("format_signature"));
4767
+ }
4768
+ if (contents.get("offset_size") !== 8 || contents.get("length_size") !== 8) {
4769
+ throw new Error("File uses non-64-bit addressing");
4770
+ }
4771
+ const version = contents.get("superblock_version");
4772
+ return new SuperBlock(source, contents, version, end_of_sblock);
4773
+ }
4774
+ /** Absolute end-of-file address (i.e. the file size), as recorded in the superblock. */
4775
+ get end_of_file() {
4776
+ const base = this.version === 0 ? this._contents.get("base_address_lower") : this._contents.get("base_address");
4777
+ return base + this._contents.get("end_of_file_address");
4778
+ }
4779
+ async getOffsetToDataobjects() {
4780
+ if (this.version === 0) {
4781
+ const sym_table = await SymbolTable.create(this._source, this._end_of_sblock, true);
4782
+ this._root_symbol_table = sym_table;
4783
+ return sym_table.group_offset;
4784
+ } else if (this.version === 2 || this.version === 3) {
4785
+ return this._contents.get("root_group_address");
4786
+ } else {
4787
+ throw new Error("Not implemented version = " + this.version);
4788
+ }
4789
+ }
4790
+ }
4791
+ class Heap {
4792
+ data;
4793
+ _contents;
4794
+ constructor(contents, data) {
4795
+ this._contents = contents;
4796
+ this.data = data;
4797
+ }
4798
+ static async create(source, offset) {
4799
+ const headerSize = _structure_size(LOCAL_HEAP);
4800
+ const hBuf = await fetchRangeWithReadAhead(source, offset, headerSize, LOCAL_HEAP_READ_AHEAD);
4801
+ const local_heap = _unpack_struct_from(LOCAL_HEAP, hBuf, 0);
4802
+ assert(local_heap.get("signature") === "HEAP");
4803
+ assert(local_heap.get("version") === 0);
4804
+ const data_offset = local_heap.get("address_of_data_segment");
4805
+ const seg_size = local_heap.get("data_segment_size");
4806
+ const rel = data_offset - offset;
4807
+ const heap_data = rel >= 0 && rel + seg_size <= hBuf.byteLength ? hBuf.slice(rel, rel + seg_size) : await fetchRange(source, data_offset, seg_size);
4808
+ local_heap.set("heap_data", heap_data);
4809
+ return new Heap(local_heap, heap_data);
4810
+ }
4811
+ get_object_name(offset) {
4812
+ const end = new Uint8Array(this.data).indexOf(0, offset);
4813
+ const name_size = end - offset;
4814
+ return struct.unpack_from("<" + name_size.toFixed() + "s", this.data, offset)[0];
4815
+ }
4816
+ }
4817
+ class SymbolTable {
4818
+ entries;
4819
+ group_offset;
4820
+ _contents;
4821
+ constructor(contents, entries, group_offset) {
4822
+ this._contents = contents;
4823
+ this.entries = entries;
4824
+ this.group_offset = group_offset;
4825
+ }
4826
+ static async create(source, offset, root2 = false) {
4827
+ let node;
4828
+ let readOffset = offset;
4829
+ let nodeBuf = null;
4830
+ if (root2) {
4831
+ node = /* @__PURE__ */ new Map([["symbols", 1]]);
4832
+ } else {
4833
+ nodeBuf = await fetchRangeWithReadAhead(source, offset, SYMBOL_TABLE_NODE_SIZE, SYMBOL_TABLE_NODE_SIZE + 32 * SYMBOL_TABLE_ENTRY_SIZE);
4834
+ node = _unpack_struct_from(SYMBOL_TABLE_NODE, nodeBuf, 0);
4835
+ if (node.get("signature") !== "SNOD")
4836
+ throw new Error("incorrect node type");
4837
+ readOffset = offset + SYMBOL_TABLE_NODE_SIZE;
4838
+ }
4839
+ const n_symbols = node.get("symbols");
4840
+ const entryBytes = n_symbols * SYMBOL_TABLE_ENTRY_SIZE;
4841
+ const entryBuf = nodeBuf && SYMBOL_TABLE_NODE_SIZE + entryBytes <= nodeBuf.byteLength ? nodeBuf.slice(SYMBOL_TABLE_NODE_SIZE, SYMBOL_TABLE_NODE_SIZE + entryBytes) : await fetchRange(source, readOffset, entryBytes);
4842
+ const entries = [];
4843
+ let localOff = 0;
4844
+ for (let i = 0; i < n_symbols; i++) {
4845
+ entries.push(_unpack_struct_from(SYMBOL_TABLE_ENTRY, entryBuf, localOff));
4846
+ localOff += SYMBOL_TABLE_ENTRY_SIZE;
4847
+ }
4848
+ let group_offset;
4849
+ if (root2) {
4850
+ group_offset = entries[0].get("object_header_address");
4851
+ }
4852
+ return new SymbolTable(node, entries, group_offset);
4853
+ }
4854
+ assign_name(heap) {
4855
+ for (const entry of this.entries) {
4856
+ const offset = entry.get("link_name_offset");
4857
+ entry.set("link_name", heap.get_object_name(offset));
4858
+ }
4859
+ }
4860
+ get_links(heap) {
4861
+ const links = {};
4862
+ for (const e of this.entries) {
4863
+ const cache_type = e.get("cache_type");
4864
+ const link_name = e.get("link_name");
4865
+ if (cache_type === 0 || cache_type === 1) {
4866
+ links[link_name] = e.get("object_header_address");
4867
+ } else if (cache_type === 2) {
4868
+ const scratch = e.get("scratch");
4869
+ const buf = new ArrayBuffer(4);
4870
+ const bufView = new Uint8Array(buf);
4871
+ for (let i = 0; i < 4; i++) {
4872
+ bufView[i] = scratch.charCodeAt(i);
4873
+ }
4874
+ const off = struct.unpack_from("<I", buf, 0)[0];
4875
+ links[link_name] = heap.get_object_name(off);
4876
+ }
4877
+ }
4878
+ return links;
4879
+ }
4880
+ }
4881
+ class GlobalHeap {
4882
+ heap_data;
4883
+ _header;
4884
+ _objects = null;
4885
+ constructor(header, heap_data) {
4886
+ this._header = header;
4887
+ this.heap_data = heap_data;
4888
+ }
4889
+ static async create(source, offset) {
4890
+ const hBuf = await fetchRangeWithReadAhead(source, offset, GLOBAL_HEAP_HEADER_SIZE, GLOBAL_HEAP_READ_AHEAD);
4891
+ const header = _unpack_struct_from(GLOBAL_HEAP_HEADER, hBuf, 0);
4892
+ const heap_data_size = header.get("collection_size") - GLOBAL_HEAP_HEADER_SIZE;
4893
+ const heap_data = GLOBAL_HEAP_HEADER_SIZE + heap_data_size <= hBuf.byteLength ? hBuf.slice(GLOBAL_HEAP_HEADER_SIZE, GLOBAL_HEAP_HEADER_SIZE + heap_data_size) : await fetchRange(source, offset + GLOBAL_HEAP_HEADER_SIZE, heap_data_size);
4894
+ return new GlobalHeap(header, heap_data);
4895
+ }
4896
+ get objects() {
4897
+ if (this._objects === null) {
4898
+ this._objects = /* @__PURE__ */ new Map();
4899
+ let offset = 0;
4900
+ while (offset <= this.heap_data.byteLength - GLOBAL_HEAP_OBJECT_SIZE) {
4901
+ const info = _unpack_struct_from(GLOBAL_HEAP_OBJECT, this.heap_data, offset);
4902
+ if (info.get("object_index") === 0)
4903
+ break;
4904
+ offset += GLOBAL_HEAP_OBJECT_SIZE;
4905
+ const obj_data = this.heap_data.slice(offset, offset + info.get("object_size"));
4906
+ this._objects.set(info.get("object_index"), obj_data);
4907
+ offset += _padded_size(info.get("object_size"));
4908
+ }
4909
+ }
4910
+ return this._objects;
4911
+ }
4912
+ }
4913
+ class FractalHeap {
4914
+ header;
4915
+ nobjects;
4916
+ managed;
4917
+ _managed_object_offset_size;
4918
+ _managed_object_length_size;
4919
+ _max_direct_nrows;
4920
+ _indirect_nrows_sub;
4921
+ direct_block_header;
4922
+ direct_block_header_size;
4923
+ indirect_block_header;
4924
+ indirect_block_header_size;
4925
+ constructor(header, managed, direct_block_header, direct_block_header_size, indirect_block_header, indirect_block_header_size, managed_object_offset_size, managed_object_length_size, max_direct_nrows, indirect_nrows_sub) {
4926
+ this.header = header;
4927
+ this.nobjects = header.get("managed_object_count") + header.get("huge_object_count") + header.get("tiny_object_count");
4928
+ this.managed = managed;
4929
+ this.direct_block_header = direct_block_header;
4930
+ this.direct_block_header_size = direct_block_header_size;
4931
+ this.indirect_block_header = indirect_block_header;
4932
+ this.indirect_block_header_size = indirect_block_header_size;
4933
+ this._managed_object_offset_size = managed_object_offset_size;
4934
+ this._managed_object_length_size = managed_object_length_size;
4935
+ this._max_direct_nrows = max_direct_nrows;
4936
+ this._indirect_nrows_sub = indirect_nrows_sub;
4937
+ }
4938
+ static async create(source, offset) {
4939
+ const headerSize = _structure_size(FRACTAL_HEAP_HEADER);
4940
+ const hBuf = await fetchRange(source, offset, headerSize);
4941
+ const header = _unpack_struct_from(FRACTAL_HEAP_HEADER, hBuf, 0);
4942
+ assert(header.get("signature") === "FRHP");
4943
+ assert(header.get("version") === 0);
4944
+ if (header.get("filter_info_size") > 0) {
4945
+ throw new Error("Filter info size not supported on FractalHeap");
4946
+ }
4947
+ if (header.get("btree_address_huge_objects") === UNDEFINED_ADDRESS) {
4948
+ header.set("btree_address_huge_objects", null);
4949
+ } else {
4950
+ throw new Error("Huge objects not implemented in FractalHeap");
4951
+ }
4952
+ if (header.get("root_block_address") === UNDEFINED_ADDRESS) {
4953
+ header.set("root_block_address", null);
4954
+ }
4955
+ const nbits = header.get("log2_maximum_heap_size");
4956
+ const block_offset_size = FractalHeap._min_size_nbits(nbits);
4957
+ const h = /* @__PURE__ */ new Map([
4958
+ ["signature", "4s"],
4959
+ ["version", "B"],
4960
+ ["heap_header_adddress", "Q"],
4961
+ ["block_offset", `${block_offset_size}B`]
4962
+ ]);
4963
+ const indirect_block_header = new Map(h);
4964
+ const indirect_block_header_size = _structure_size(h);
4965
+ if ((header.get("flags") & 2) === 2) {
4966
+ h.set("checksum", "I");
4967
+ }
4968
+ const direct_block_header = h;
4969
+ const direct_block_header_size = _structure_size(h);
4970
+ const maximum_dblock_size = header.get("maximum_direct_block_size");
4971
+ const managed_object_offset_size = FractalHeap._min_size_nbits(nbits);
4972
+ const value = Math.min(maximum_dblock_size, header.get("max_managed_object_size"));
4973
+ const managed_object_length_size = FractalHeap._min_size_integer(value);
4974
+ const start_block_size = header.get("starting_block_size");
4975
+ const table_width = header.get("table_width");
4976
+ if (!(start_block_size > 0)) {
4977
+ throw new Error("Starting block size == 0 not implemented");
4978
+ }
4979
+ const log2_maximum_dblock_size = Math.floor(Math.log2(maximum_dblock_size));
4980
+ assert(1n << BigInt(log2_maximum_dblock_size) === BigInt(maximum_dblock_size));
4981
+ const log2_start_block_size = Math.floor(Math.log2(start_block_size));
4982
+ assert(1n << BigInt(log2_start_block_size) === BigInt(start_block_size));
4983
+ const max_direct_nrows = log2_maximum_dblock_size - log2_start_block_size + 2;
4984
+ const log2_table_width = Math.floor(Math.log2(table_width));
4985
+ assert(1 << log2_table_width === table_width);
4986
+ const indirect_nrows_sub = log2_table_width + log2_start_block_size - 1;
4987
+ const managedParts = [];
4988
+ const root_address = header.get("root_block_address");
4989
+ let nrows = 0;
4990
+ if (root_address != null) {
4991
+ nrows = header.get("indirect_current_rows_count");
4992
+ }
4993
+ const ctx = {
4994
+ source,
4995
+ header,
4996
+ direct_block_header,
4997
+ direct_block_header_size,
4998
+ indirect_block_header,
4999
+ indirect_block_header_size,
5000
+ max_direct_nrows,
5001
+ indirect_nrows_sub,
5002
+ table_width
5003
+ };
5004
+ if (nrows > 0) {
5005
+ managedParts.push(...await FractalHeap._read_indirect_block(ctx, root_address, nrows));
5006
+ } else if (root_address != null) {
5007
+ const data = await FractalHeap._read_direct_block(ctx, root_address, start_block_size);
5008
+ managedParts.push(data);
5009
+ }
5010
+ const data_size = managedParts.reduce((p, c) => p + c.byteLength, 0);
5011
+ const combined = new Uint8Array(data_size);
5012
+ let moffset = 0;
5013
+ for (const m of managedParts) {
5014
+ combined.set(new Uint8Array(m), moffset);
5015
+ moffset += m.byteLength;
5016
+ }
5017
+ return new FractalHeap(header, combined.buffer, direct_block_header, direct_block_header_size, indirect_block_header, indirect_block_header_size, managed_object_offset_size, managed_object_length_size, max_direct_nrows, indirect_nrows_sub);
5018
+ }
5019
+ get_data(heapid) {
5020
+ const firstbyte = struct.unpack_from("<B", heapid, 0)[0];
5021
+ const idtype = firstbyte >> 4 & 3;
5022
+ const version = firstbyte >> 6;
5023
+ let data_offset = 1;
5024
+ if (idtype === 0) {
5025
+ assert(version === 0);
5026
+ let nbytes = this._managed_object_offset_size;
5027
+ const offset = _unpack_integer(nbytes, heapid, data_offset);
5028
+ data_offset += nbytes;
5029
+ nbytes = this._managed_object_length_size;
5030
+ const size = _unpack_integer(nbytes, heapid, data_offset);
5031
+ return this.managed.slice(offset, offset + size);
5032
+ } else if (idtype === 1) {
5033
+ throw new Error("tiny objectID not supported in FractalHeap");
5034
+ } else if (idtype === 2) {
5035
+ throw new Error("huge objectID not supported in FractalHeap");
5036
+ } else {
5037
+ throw new Error("unknown objectID type in FractalHeap");
5038
+ }
5039
+ }
5040
+ static _min_size_integer(integer) {
5041
+ return FractalHeap._min_size_nbits(bitSize(integer));
5042
+ }
5043
+ static _min_size_nbits(nbits) {
5044
+ return Math.ceil(nbits / 8);
5045
+ }
5046
+ static async _read_direct_block(ctx, offset, block_size) {
5047
+ const data = await fetchRange(ctx.source, offset, block_size);
5048
+ const header = _unpack_struct_from(ctx.direct_block_header, data, 0);
5049
+ assert(header.get("signature") === "FHDB");
5050
+ return data;
5051
+ }
5052
+ /**
5053
+ * Read all direct blocks reachable from an indirect block (in heap order).
5054
+ * Blocks are fetched concurrently.
5055
+ */
5056
+ static async _read_indirect_block(ctx, offset, nrows) {
5057
+ const ibHdrBuf = await fetchRange(ctx.source, offset, ctx.indirect_block_header_size);
5058
+ const header = _unpack_struct_from(ctx.indirect_block_header, ibHdrBuf, 0);
5059
+ let readOff = offset + ctx.indirect_block_header_size;
5060
+ assert(header.get("signature") === "FHIB");
5061
+ const block_offset_bytes = header.get("block_offset");
5062
+ const block_offset = block_offset_bytes.reduce((p, c, i) => p + (c << i * 8), 0);
5063
+ header.set("block_offset", block_offset);
5064
+ const [ndirect, nindirect] = FractalHeap._indirect_info(ctx, nrows);
5065
+ const addrBytes = (ndirect + nindirect) * 8;
5066
+ const addrBuf = await fetchRange(ctx.source, readOff, addrBytes);
5067
+ let addrOff = 0;
5068
+ const direct_blocks = [];
5069
+ for (let i = 0; i < ndirect; i++) {
5070
+ const address = struct.unpack_from("<Q", addrBuf, addrOff)[0];
5071
+ addrOff += 8;
5072
+ if (address === UNDEFINED_ADDRESS)
5073
+ break;
5074
+ const block_size = FractalHeap._calc_block_size(ctx, i);
5075
+ direct_blocks.push([address, block_size]);
5076
+ }
5077
+ const indirect_blocks = [];
5078
+ for (let i = ndirect; i < ndirect + nindirect; i++) {
5079
+ const address = struct.unpack_from("<Q", addrBuf, addrOff)[0];
5080
+ addrOff += 8;
5081
+ if (address === UNDEFINED_ADDRESS)
5082
+ break;
5083
+ const block_size = FractalHeap._calc_block_size(ctx, i);
5084
+ const nr = FractalHeap._iblock_nrows_from_block_size(ctx, block_size);
5085
+ indirect_blocks.push([address, nr]);
5086
+ }
5087
+ const [direct, indirect] = await Promise.all([
5088
+ Promise.all(direct_blocks.map(([address, block_size]) => FractalHeap._read_direct_block(ctx, address, block_size))),
5089
+ Promise.all(indirect_blocks.map(([address, nr]) => FractalHeap._read_indirect_block(ctx, address, nr)))
5090
+ ]);
5091
+ return [...direct, ...indirect.flat()];
5092
+ }
5093
+ static _calc_block_size(ctx, iblock) {
5094
+ const row = Math.floor(iblock / ctx.table_width);
5095
+ return 2 ** Math.max(row - 1, 0) * ctx.header.get("starting_block_size");
5096
+ }
5097
+ static _iblock_nrows_from_block_size(ctx, block_size) {
5098
+ const log2_block_size = Math.floor(Math.log2(block_size));
5099
+ assert(2 ** log2_block_size === block_size);
5100
+ return log2_block_size - ctx.indirect_nrows_sub;
5101
+ }
5102
+ static _indirect_info(ctx, nrows) {
5103
+ const table_width = ctx.table_width;
5104
+ const nobjects = nrows * table_width;
5105
+ const ndirect_max = ctx.max_direct_nrows * table_width;
5106
+ let ndirect, nindirect;
5107
+ if (nrows <= ndirect_max) {
5108
+ ndirect = nobjects;
5109
+ nindirect = 0;
5110
+ } else {
5111
+ ndirect = ndirect_max;
5112
+ nindirect = nobjects - ndirect_max;
5113
+ }
5114
+ return [ndirect, nindirect];
5115
+ }
5116
+ }
5117
+ const DATASPACE_MSG_TYPE = 1;
5118
+ const LINK_INFO_MSG_TYPE = 2;
5119
+ const DATATYPE_MSG_TYPE = 3;
5120
+ const FILLVALUE_MSG_TYPE = 5;
5121
+ const LINK_MSG_TYPE = 6;
5122
+ const DATA_STORAGE_MSG_TYPE = 8;
5123
+ const DATA_STORAGE_FILTER_PIPELINE_MSG_TYPE = 11;
5124
+ const ATTRIBUTE_MSG_TYPE$1 = 12;
5125
+ const OBJECT_CONTINUATION_MSG_TYPE = 16;
5126
+ const SYMBOL_TABLE_MSG_TYPE = 17;
5127
+ const ATTRIBUTE_INFO_MSG_TYPE = 21;
5128
+ const OBJECT_HEADER_V1 = /* @__PURE__ */ new Map([
5129
+ ["version", "B"],
5130
+ ["reserved", "B"],
5131
+ ["total_header_messages", "H"],
5132
+ ["object_reference_count", "I"],
5133
+ ["object_header_size", "I"],
5134
+ ["padding", "I"]
5135
+ ]);
5136
+ const OBJECT_HEADER_V1_SIZE = _structure_size(OBJECT_HEADER_V1);
5137
+ const OBJECT_HEADER_V2 = /* @__PURE__ */ new Map([
5138
+ ["signature", "4s"],
5139
+ ["version", "B"],
5140
+ ["flags", "B"]
5141
+ ]);
5142
+ const OBJECT_HEADER_V2_SIZE = _structure_size(OBJECT_HEADER_V2);
5143
+ const HEADER_MSG_INFO_V1 = /* @__PURE__ */ new Map([
5144
+ ["type", "H"],
5145
+ ["size", "H"],
5146
+ ["flags", "B"],
5147
+ ["reserved", "3s"]
5148
+ ]);
5149
+ const HEADER_MSG_INFO_V1_SIZE = _structure_size(HEADER_MSG_INFO_V1);
5150
+ const HEADER_MSG_INFO_V2 = /* @__PURE__ */ new Map([
5151
+ ["type", "B"],
5152
+ ["size", "H"],
5153
+ ["flags", "B"]
5154
+ ]);
5155
+ const HEADER_MSG_INFO_V2_SIZE = _structure_size(HEADER_MSG_INFO_V2);
5156
+ const SYMBOL_TABLE_MSG = /* @__PURE__ */ new Map([
5157
+ ["btree_address", "Q"],
5158
+ ["heap_address", "Q"]
5159
+ ]);
5160
+ const ATTR_MSG_HEADER_V1 = /* @__PURE__ */ new Map([
5161
+ ["version", "B"],
5162
+ ["reserved", "B"],
5163
+ ["name_size", "H"],
5164
+ ["datatype_size", "H"],
5165
+ ["dataspace_size", "H"]
5166
+ ]);
5167
+ const ATTR_MSG_HEADER_V1_SIZE = _structure_size(ATTR_MSG_HEADER_V1);
5168
+ const ATTR_MSG_HEADER_V3 = /* @__PURE__ */ new Map([
5169
+ ["version", "B"],
5170
+ ["flags", "B"],
5171
+ ["name_size", "H"],
5172
+ ["datatype_size", "H"],
5173
+ ["dataspace_size", "H"],
5174
+ ["character_set_encoding", "B"]
5175
+ ]);
5176
+ const ATTR_MSG_HEADER_V3_SIZE = _structure_size(ATTR_MSG_HEADER_V3);
5177
+ const DATASPACE_MSG_HEADER_V1 = /* @__PURE__ */ new Map([
5178
+ ["version", "B"],
5179
+ ["dimensionality", "B"],
5180
+ ["flags", "B"],
5181
+ ["reserved_0", "B"],
5182
+ ["reserved_1", "I"]
5183
+ ]);
5184
+ const DATASPACE_MSG_HEADER_V1_SIZE = _structure_size(DATASPACE_MSG_HEADER_V1);
5185
+ const DATASPACE_MSG_HEADER_V2 = /* @__PURE__ */ new Map([
5186
+ ["version", "B"],
5187
+ ["dimensionality", "B"],
5188
+ ["flags", "B"],
5189
+ ["type", "B"]
5190
+ ]);
5191
+ const DATASPACE_MSG_HEADER_V2_SIZE = _structure_size(DATASPACE_MSG_HEADER_V2);
5192
+ const FILLVAL_MSG_V1V2 = /* @__PURE__ */ new Map([
5193
+ ["version", "B"],
5194
+ ["space_allocation_time", "B"],
5195
+ ["fillvalue_write_time", "B"],
5196
+ ["fillvalue_defined", "B"]
5197
+ ]);
5198
+ const FILLVAL_MSG_V1V2_SIZE = _structure_size(FILLVAL_MSG_V1V2);
5199
+ const FILLVAL_MSG_V3 = /* @__PURE__ */ new Map([
5200
+ ["version", "B"],
5201
+ ["flags", "B"]
5202
+ ]);
5203
+ const FILLVAL_MSG_V3_SIZE = _structure_size(FILLVAL_MSG_V3);
5204
+ const FILTER_PIPELINE_DESCR_V1 = /* @__PURE__ */ new Map([
5205
+ ["filter_id", "H"],
5206
+ ["name_length", "H"],
5207
+ ["flags", "H"],
5208
+ ["client_data_values", "H"]
5209
+ ]);
5210
+ const FILTER_PIPELINE_DESCR_V1_SIZE = _structure_size(FILTER_PIPELINE_DESCR_V1);
5211
+ const GLOBAL_HEAP_ID = /* @__PURE__ */ new Map([
5212
+ ["collection_address", "Q"],
5213
+ ["object_index", "I"]
5214
+ ]);
5215
+ _structure_size(GLOBAL_HEAP_ID);
5216
+ const LINK_INFO_MSG1 = /* @__PURE__ */ new Map([
5217
+ ["heap_address", "Q"],
5218
+ ["name_btree_address", "Q"]
5219
+ ]);
5220
+ const LINK_INFO_MSG2 = /* @__PURE__ */ new Map([
5221
+ ["heap_address", "Q"],
5222
+ ["name_btree_address", "Q"],
5223
+ ["order_btree_address", "Q"]
5224
+ ]);
5225
+ const OBJECT_HEADER_READ_AHEAD = 1024;
5226
+ const GLOBAL_HEAP_CACHE_SIZE = 256;
5227
+ async function sliceOrFetch(source, prefix, prefixOffset, absOffset, size) {
5228
+ const start = absOffset - prefixOffset;
5229
+ if (start >= 0 && start + size <= prefix.byteLength) {
5230
+ return prefix.slice(start, start + size);
5231
+ }
5232
+ return fetchRange(source, absOffset, size);
5233
+ }
5234
+ class DataObjects {
5235
+ buf;
5236
+ bufStart;
5237
+ msgs;
5238
+ msg_data;
5239
+ offset;
5240
+ _global_heaps;
5241
+ _header;
5242
+ _filter_pipeline;
5243
+ _chunk_params_set;
5244
+ _chunks;
5245
+ _chunk_dims;
5246
+ _chunk_address;
5247
+ _source;
5248
+ constructor(source, buf, bufStart, msgs, msg_data, offset, header) {
5249
+ this._source = source;
5250
+ this.buf = buf;
5251
+ this.bufStart = bufStart;
5252
+ this.msgs = msgs;
5253
+ this.msg_data = msg_data;
5254
+ this.offset = offset;
5255
+ this._global_heaps = new QuickLRU({ maxSize: GLOBAL_HEAP_CACHE_SIZE });
5256
+ this._header = header;
5257
+ this._filter_pipeline = null;
5258
+ this._chunk_params_set = false;
5259
+ this._chunks = null;
5260
+ this._chunk_dims = null;
5261
+ this._chunk_address = null;
5262
+ }
5263
+ static async create(source, offset) {
5264
+ const prefix = await fetchRangeWithReadAhead(source, offset, 1, OBJECT_HEADER_READ_AHEAD);
5265
+ const versionHint = struct.unpack_from("<B", prefix, 0)[0];
5266
+ let result;
5267
+ if (versionHint === 1) {
5268
+ result = await DataObjects._parseV1(source, offset, prefix);
5269
+ } else if (versionHint === "O".charCodeAt(0)) {
5270
+ result = await DataObjects._parseV2(source, offset, prefix);
5271
+ } else {
5272
+ throw new Error(`Unknown Data Object Header version hint: ${versionHint}`);
5273
+ }
5274
+ return new DataObjects(source, result.buf, result.bufStart, result.msgs, result.msg_data, offset, result.header);
5275
+ }
5276
+ // ────────── V1 parsing ──────────
5277
+ static async _parseV1(source, offset, prefix) {
5278
+ const headerBuf = prefix.byteLength >= OBJECT_HEADER_V1_SIZE ? prefix : await fetchRange(source, offset, OBJECT_HEADER_V1_SIZE);
5279
+ const header = _unpack_struct_from(OBJECT_HEADER_V1, headerBuf, 0);
5280
+ assert(header.get("version") === 1);
5281
+ const total_header_messages = header.get("total_header_messages");
5282
+ const first_block_size = header.get("object_header_size");
5283
+ const first_block_offset = offset + OBJECT_HEADER_V1_SIZE;
5284
+ const allBlocks = [];
5285
+ const blockQueue = [
5286
+ { absOffset: first_block_offset, size: first_block_size }
5287
+ ];
5288
+ while (blockQueue.length > 0) {
5289
+ const wave = blockQueue.splice(0, blockQueue.length);
5290
+ const datas = await Promise.all(wave.map(({ absOffset, size }) => sliceOrFetch(source, prefix, offset, absOffset, size)));
5291
+ for (let w = 0; w < wave.length; w++) {
5292
+ const { absOffset, size } = wave[w];
5293
+ const data = datas[w];
5294
+ allBlocks.push({ absOffset, size, data });
5295
+ let local_offset2 = 0;
5296
+ while (local_offset2 + HEADER_MSG_INFO_V1_SIZE <= size) {
5297
+ const msg = _unpack_struct_from(HEADER_MSG_INFO_V1, data, local_offset2);
5298
+ const msg_type = msg.get("type");
5299
+ const msg_size = msg.get("size");
5300
+ const offset_in_block = local_offset2 + HEADER_MSG_INFO_V1_SIZE;
5301
+ if (msg_type === OBJECT_CONTINUATION_MSG_TYPE) {
5302
+ const [fh_off, cont_size] = struct.unpack_from("<QQ", data, offset_in_block);
5303
+ blockQueue.push({ absOffset: fh_off, size: cont_size });
5304
+ }
5305
+ if (msg_type === 0 && msg_size === 0)
5306
+ break;
5307
+ local_offset2 += HEADER_MSG_INFO_V1_SIZE + msg_size;
5308
+ }
5309
+ }
5310
+ }
5311
+ let bufStart = offset;
5312
+ let maxEnd = first_block_offset + first_block_size;
5313
+ for (const b of allBlocks) {
5314
+ bufStart = Math.min(bufStart, b.absOffset);
5315
+ maxEnd = Math.max(maxEnd, b.absOffset + b.size);
5316
+ }
5317
+ const combined = new Uint8Array(maxEnd - bufStart);
5318
+ combined.set(new Uint8Array(headerBuf, 0, OBJECT_HEADER_V1_SIZE), offset - bufStart);
5319
+ for (const b of allBlocks) {
5320
+ combined.set(new Uint8Array(b.data), b.absOffset - bufStart);
5321
+ }
5322
+ const buf = combined.buffer;
5323
+ const msgs = new Array(total_header_messages);
5324
+ let object_header_blocks = [[first_block_offset, first_block_size]];
5325
+ for (let bi = 1; bi < allBlocks.length; bi++) {
5326
+ object_header_blocks.push([allBlocks[bi].absOffset, allBlocks[bi].size]);
5327
+ }
5328
+ let current_block = 0;
5329
+ let block_offset = object_header_blocks[0][0];
5330
+ let block_size = object_header_blocks[0][1];
5331
+ let local_offset = 0;
5332
+ for (let i = 0; i < total_header_messages; i++) {
5333
+ if (local_offset >= block_size) {
5334
+ current_block++;
5335
+ if (current_block >= object_header_blocks.length)
5336
+ break;
5337
+ [block_offset, block_size] = object_header_blocks[current_block];
5338
+ local_offset = 0;
5339
+ }
5340
+ const absPos = block_offset - bufStart + local_offset;
5341
+ const msg = _unpack_struct_from(HEADER_MSG_INFO_V1, buf, absPos);
5342
+ const offset_to_message = block_offset + local_offset + HEADER_MSG_INFO_V1_SIZE;
5343
+ msg.set("offset_to_message", offset_to_message);
5344
+ const msg_size = msg.get("size");
5345
+ local_offset += HEADER_MSG_INFO_V1_SIZE + msg_size;
5346
+ msgs[i] = msg;
5347
+ }
5348
+ const msg_data = buf.slice(first_block_offset - bufStart, first_block_offset - bufStart + first_block_size);
5349
+ return { buf, bufStart, msgs: msgs.filter(Boolean), msg_data, header };
5350
+ }
5351
+ // ────────── V2 parsing ──────────
5352
+ static async _parseV2(source, offset, prefix) {
5353
+ const peekBuf = prefix.byteLength >= 64 ? prefix : await fetchRange(source, offset, 64);
5354
+ const peekSize = peekBuf.byteLength;
5355
+ const { header, creation_order_size, block_offset: first_block_offset } = DataObjects._parseV2Header(peekBuf, 0, offset);
5356
+ const first_block_size = header.get("size_of_chunk_0");
5357
+ const allBlocks = [];
5358
+ const blockQueue = [
5359
+ { absOffset: first_block_offset, size: first_block_size }
5360
+ ];
5361
+ while (blockQueue.length > 0) {
5362
+ const wave = blockQueue.splice(0, blockQueue.length);
5363
+ const datas = await Promise.all(wave.map(({ absOffset, size }) => sliceOrFetch(source, peekBuf, offset, absOffset, size)));
5364
+ for (let w = 0; w < wave.length; w++) {
5365
+ const { absOffset, size } = wave[w];
5366
+ const data = datas[w];
5367
+ allBlocks.push({ absOffset, size, data });
5368
+ let local_offset2 = 0;
5369
+ while (local_offset2 + HEADER_MSG_INFO_V2_SIZE <= size) {
5370
+ const relOff = local_offset2;
5371
+ const msg_type = struct.unpack_from("<B", data, relOff)[0];
5372
+ const msg_size = struct.unpack_from("<H", data, relOff + 1)[0];
5373
+ const offset_in_data = relOff + HEADER_MSG_INFO_V2_SIZE + creation_order_size;
5374
+ if (msg_type === OBJECT_CONTINUATION_MSG_TYPE) {
5375
+ const [fh_off, cont_size] = struct.unpack_from("<QQ", data, offset_in_data);
5376
+ blockQueue.push({ absOffset: fh_off + 4, size: cont_size - 4 });
5377
+ }
5378
+ if (msg_type === 0 && msg_size === 0)
5379
+ break;
5380
+ local_offset2 += HEADER_MSG_INFO_V2_SIZE + msg_size + creation_order_size;
5381
+ if (local_offset2 >= size - HEADER_MSG_INFO_V2_SIZE)
5382
+ break;
5383
+ }
5384
+ }
5385
+ }
5386
+ const bufStart = offset;
5387
+ let maxEnd = first_block_offset + first_block_size;
5388
+ for (const b of allBlocks) {
5389
+ maxEnd = Math.max(maxEnd, b.absOffset + b.size);
5390
+ }
5391
+ const combined = new Uint8Array(maxEnd - bufStart);
5392
+ const copySize = Math.min(peekSize, combined.length);
5393
+ combined.set(new Uint8Array(peekBuf).subarray(0, copySize), 0);
5394
+ for (const b of allBlocks) {
5395
+ combined.set(new Uint8Array(b.data), b.absOffset - bufStart);
5396
+ }
5397
+ const buf = combined.buffer;
5398
+ const msgs = [];
5399
+ const object_header_blocks = [];
5400
+ for (const b of allBlocks) {
5401
+ object_header_blocks.push([b.absOffset, b.size]);
5402
+ }
5403
+ let current_block = 0;
5404
+ let block_offset = object_header_blocks[0][0];
5405
+ let block_size = object_header_blocks[0][1];
5406
+ let local_offset = 0;
5407
+ while (true) {
5408
+ if (local_offset >= block_size - HEADER_MSG_INFO_V2_SIZE) {
5409
+ current_block++;
5410
+ if (current_block >= object_header_blocks.length)
5411
+ break;
5412
+ [block_offset, block_size] = object_header_blocks[current_block];
5413
+ local_offset = 0;
5414
+ }
5415
+ const absPos = block_offset - bufStart + local_offset;
5416
+ const msg = _unpack_struct_from(HEADER_MSG_INFO_V2, buf, absPos);
5417
+ const offset_to_message = block_offset + local_offset + HEADER_MSG_INFO_V2_SIZE + creation_order_size;
5418
+ msg.set("offset_to_message", offset_to_message);
5419
+ const msg_size = msg.get("size");
5420
+ local_offset += HEADER_MSG_INFO_V2_SIZE + msg_size + creation_order_size;
5421
+ msgs.push(msg);
5422
+ if (local_offset >= block_size - HEADER_MSG_INFO_V2_SIZE) {
5423
+ current_block++;
5424
+ if (current_block >= object_header_blocks.length)
5425
+ break;
5426
+ [block_offset, block_size] = object_header_blocks[current_block];
5427
+ local_offset = 0;
5428
+ }
5429
+ }
5430
+ const msg_data = buf.slice(first_block_offset - bufStart, first_block_offset - bufStart + first_block_size);
5431
+ return { buf, bufStart, msgs, msg_data, header };
5432
+ }
5433
+ static _parseV2Header(buf, localOffset, absBase) {
5434
+ const header = _unpack_struct_from(OBJECT_HEADER_V2, buf, localOffset);
5435
+ assert(header.get("version") === 2);
5436
+ localOffset += OBJECT_HEADER_V2_SIZE;
5437
+ const flags = header.get("flags");
5438
+ const creation_order_size = flags & 4 ? 2 : 0;
5439
+ assert((flags & 16) === 0);
5440
+ if (flags & 32) {
5441
+ localOffset += 16;
5442
+ }
5443
+ const chunk_fmt = ["<B", "<H", "<I", "<Q"][flags & 3];
5444
+ header.set("size_of_chunk_0", struct.unpack_from(chunk_fmt, buf, localOffset)[0]);
5445
+ localOffset += struct.calcsize(chunk_fmt);
5446
+ const block_offset = absBase + localOffset;
5447
+ return { header, creation_order_size, block_offset };
5448
+ }
5449
+ // ────────── Core methods ──────────
5450
+ find_msg_type(msg_type) {
5451
+ return this.msgs.filter((m) => m.get("type") === msg_type);
5452
+ }
5453
+ get is_dataset() {
5454
+ return this.find_msg_type(DATASPACE_MSG_TYPE).length > 0;
5455
+ }
5456
+ get dtype() {
5457
+ const msg = this.find_msg_type(DATATYPE_MSG_TYPE)[0];
5458
+ const msg_offset = msg.get("offset_to_message");
5459
+ const relOffset = msg_offset - this.bufStart;
5460
+ return new DatatypeMessage(this.buf, relOffset).dtype;
5461
+ }
5462
+ get shape() {
5463
+ const msg = this.find_msg_type(DATASPACE_MSG_TYPE)[0];
5464
+ const msg_offset = msg.get("offset_to_message");
5465
+ const relOffset = msg_offset - this.bufStart;
5466
+ return this._determine_data_shape(this.buf, relOffset);
5467
+ }
5468
+ get chunks() {
5469
+ this._get_chunk_params();
5470
+ return this._chunks;
5471
+ }
5472
+ get filter_pipeline() {
5473
+ if (this._filter_pipeline !== null) {
5474
+ return this._filter_pipeline;
5475
+ }
5476
+ const filter_msgs = this.find_msg_type(DATA_STORAGE_FILTER_PIPELINE_MSG_TYPE);
5477
+ if (!filter_msgs.length) {
5478
+ this._filter_pipeline = null;
5479
+ return null;
5480
+ }
5481
+ const absOffset = filter_msgs[0].get("offset_to_message");
5482
+ let offset = absOffset - this.bufStart;
5483
+ const buf = this.buf;
5484
+ const [version, nfilters] = struct.unpack_from("<BB", buf, offset);
5485
+ offset += struct.calcsize("<BB");
5486
+ const filters = [];
5487
+ if (version === 1) {
5488
+ offset += struct.calcsize("<HI");
5489
+ for (let _ = 0; _ < nfilters; _++) {
5490
+ const filter_info = _unpack_struct_from(FILTER_PIPELINE_DESCR_V1, buf, offset);
5491
+ offset += FILTER_PIPELINE_DESCR_V1_SIZE;
5492
+ const padded_name_length = _padded_size(filter_info.get("name_length"), 8);
5493
+ const fmt = "<" + padded_name_length.toFixed() + "s";
5494
+ const filter_name = struct.unpack_from(fmt, buf, offset)[0];
5495
+ filter_info.set("filter_name", filter_name);
5496
+ offset += padded_name_length;
5497
+ const client_data_values = filter_info.get("client_data_values");
5498
+ const client_data_fmt = "<" + client_data_values.toFixed() + "I";
5499
+ const client_data = struct.unpack_from(client_data_fmt, buf, offset);
5500
+ filter_info.set("client_data", client_data);
5501
+ offset += 4 * client_data_values;
5502
+ if (client_data_values % 2) {
5503
+ offset += 4;
5504
+ }
5505
+ filters.push(filter_info);
5506
+ }
5507
+ } else if (version === 2) {
5508
+ for (let nf = 0; nf < nfilters; nf++) {
5509
+ const filter_info = /* @__PURE__ */ new Map();
5510
+ const filter_id = struct.unpack_from("<H", buf, offset)[0];
5511
+ offset += 2;
5512
+ filter_info.set("filter_id", filter_id);
5513
+ let name_length = 0;
5514
+ if (filter_id > 255) {
5515
+ name_length = struct.unpack_from("<H", buf, offset)[0];
5516
+ offset += 2;
5517
+ }
5518
+ const flags_val = struct.unpack_from("<H", buf, offset)[0];
5519
+ offset += 2;
5520
+ filter_info.set("optional", (flags_val & 1) > 0);
5521
+ const num_client_values = struct.unpack_from("<H", buf, offset)[0];
5522
+ offset += 2;
5523
+ if (name_length > 0) {
5524
+ const name = struct.unpack_from(`${name_length}s`, buf, offset)[0];
5525
+ filter_info.set("name", name);
5526
+ offset += name_length;
5527
+ }
5528
+ const client_values = struct.unpack_from(`<${num_client_values}i`, buf, offset);
5529
+ offset += 4 * num_client_values;
5530
+ filter_info.set("client_data", client_values);
5531
+ filter_info.set("client_data_values", num_client_values);
5532
+ filters.push(filter_info);
5533
+ }
5534
+ } else {
5535
+ throw new Error(`Filter pipeline version ${version} not supported`);
5536
+ }
5537
+ this._filter_pipeline = filters;
5538
+ return this._filter_pipeline;
5539
+ }
5540
+ get fillvalue() {
5541
+ const msg = this.find_msg_type(FILLVALUE_MSG_TYPE)[0];
5542
+ if (!msg)
5543
+ return 0;
5544
+ let absOffset = msg.get("offset_to_message");
5545
+ let offset = absOffset - this.bufStart;
5546
+ const buf = this.buf;
5547
+ const version = struct.unpack_from("<B", buf, offset)[0];
5548
+ let info;
5549
+ let is_defined;
5550
+ if (version === 1 || version === 2) {
5551
+ info = _unpack_struct_from(FILLVAL_MSG_V1V2, buf, offset);
5552
+ offset += FILLVAL_MSG_V1V2_SIZE;
5553
+ is_defined = info.get("fillvalue_defined") !== 0;
5554
+ } else if (version === 3) {
5555
+ info = _unpack_struct_from(FILLVAL_MSG_V3, buf, offset);
5556
+ offset += FILLVAL_MSG_V3_SIZE;
5557
+ is_defined = (info.get("flags") & 32) !== 0;
5558
+ } else {
5559
+ throw new Error(`Unknown fillvalue message version: ${version}`);
5560
+ }
5561
+ let size = 0;
5562
+ if (is_defined) {
5563
+ size = struct.unpack_from("<I", buf, offset)[0];
5564
+ offset += 4;
5565
+ }
5566
+ if (size) {
5567
+ const dtype = this.dtype;
5568
+ if (typeof dtype === "string") {
5569
+ const [getter, big_endian, itemSize] = dtype_getter(dtype);
5570
+ const view = new DataView64(buf, 0);
5571
+ return view[getter](offset, !big_endian, itemSize);
5572
+ }
5573
+ }
5574
+ return 0;
5575
+ }
5576
+ _get_data_message_properties(msg_offset) {
5577
+ const buf = this.buf;
5578
+ const [version, arg1, arg2] = struct.unpack_from("<BBB", buf, msg_offset);
5579
+ let dims;
5580
+ let layout_class;
5581
+ let property_offset;
5582
+ if (version === 1 || version === 2) {
5583
+ dims = arg1;
5584
+ layout_class = arg2;
5585
+ property_offset = msg_offset + struct.calcsize("<BBB") + struct.calcsize("<BI");
5586
+ } else if (version === 3 || version === 4) {
5587
+ layout_class = arg1;
5588
+ dims = 0;
5589
+ property_offset = msg_offset + struct.calcsize("<BB");
5590
+ } else {
5591
+ throw new Error(`Unknown data storage message version: ${version}`);
5592
+ }
5593
+ return { version, dims, layout_class, property_offset };
5594
+ }
5595
+ _get_chunk_params() {
5596
+ if (this._chunk_params_set)
5597
+ return;
5598
+ this._chunk_params_set = true;
5599
+ const msg = this.find_msg_type(DATA_STORAGE_MSG_TYPE)[0];
5600
+ if (!msg)
5601
+ return;
5602
+ const absOffset = msg.get("offset_to_message");
5603
+ const relOffset = absOffset - this.bufStart;
5604
+ const { version, dims: msgDims, layout_class, property_offset } = this._get_data_message_properties(relOffset);
5605
+ if (layout_class !== 2)
5606
+ return;
5607
+ const buf = this.buf;
5608
+ let address;
5609
+ let dims;
5610
+ let data_offset;
5611
+ if (version === 1 || version === 2) {
5612
+ address = struct.unpack_from("<Q", buf, property_offset)[0];
5613
+ data_offset = property_offset + struct.calcsize("<Q");
5614
+ dims = msgDims;
5615
+ } else if (version === 3) {
5616
+ [dims, address] = struct.unpack_from("<BQ", buf, property_offset);
5617
+ data_offset = property_offset + struct.calcsize("<BQ");
5618
+ } else {
5619
+ return;
5620
+ }
5621
+ const fmt = "<" + (dims - 1).toFixed() + "I";
5622
+ const chunk_shape = struct.unpack_from(fmt, buf, data_offset);
5623
+ this._chunks = chunk_shape;
5624
+ this._chunk_dims = dims;
5625
+ this._chunk_address = address;
5626
+ }
5627
+ // ────────── Data shape helper ──────────
5628
+ _determine_data_shape(buf, offset) {
5629
+ const version = struct.unpack_from("<B", buf, offset)[0];
5630
+ let header;
5631
+ if (version === 1) {
5632
+ header = _unpack_struct_from(DATASPACE_MSG_HEADER_V1, buf, offset);
5633
+ assert(header.get("version") === 1);
5634
+ offset += DATASPACE_MSG_HEADER_V1_SIZE;
5635
+ } else if (version === 2) {
5636
+ header = _unpack_struct_from(DATASPACE_MSG_HEADER_V2, buf, offset);
5637
+ assert(header.get("version") === 2);
5638
+ offset += DATASPACE_MSG_HEADER_V2_SIZE;
5639
+ } else {
5640
+ throw new Error(`Unknown dataspace message version: ${version}`);
5641
+ }
5642
+ const ndims = header.get("dimensionality");
5643
+ if (ndims === 0)
5644
+ return [];
5645
+ const dim_sizes = struct.unpack_from("<" + ndims.toFixed() + "Q", buf, offset);
5646
+ return dim_sizes;
5647
+ }
5648
+ // ────────── Async: get_links ──────────
5649
+ async get_links() {
5650
+ const links = {};
5651
+ for (const msg of this.msgs) {
5652
+ const msg_type = msg.get("type");
5653
+ if (msg_type === SYMBOL_TABLE_MSG_TYPE) {
5654
+ const newLinks = await this._iter_links_from_symbol_tables(msg);
5655
+ Object.assign(links, newLinks);
5656
+ } else if (msg_type === LINK_MSG_TYPE) {
5657
+ const absOffset = msg.get("offset_to_message");
5658
+ const relOffset = absOffset - this.bufStart;
5659
+ const [, [name, address]] = this._decode_link_msg(this.buf, relOffset);
5660
+ links[name] = address;
5661
+ } else if (msg_type === LINK_INFO_MSG_TYPE) {
5662
+ const newLinks = await this._iter_link_from_link_info_msg(msg);
5663
+ Object.assign(links, newLinks);
5664
+ }
5665
+ }
5666
+ return links;
5667
+ }
5668
+ async _iter_links_from_symbol_tables(sym_tbl_msg) {
5669
+ assert(sym_tbl_msg.get("size") === 16);
5670
+ const absOffset = sym_tbl_msg.get("offset_to_message");
5671
+ const relOffset = absOffset - this.bufStart;
5672
+ const data = _unpack_struct_from(SYMBOL_TABLE_MSG, this.buf, relOffset);
5673
+ return this._iter_links_btree_v1(data.get("btree_address"), data.get("heap_address"));
5674
+ }
5675
+ async _iter_links_btree_v1(btree_address, heap_address) {
5676
+ const [btree, heap] = await Promise.all([
5677
+ BTreeV1Groups.create(this._source, btree_address),
5678
+ Heap.create(this._source, heap_address)
5679
+ ]);
5680
+ const tables = await Promise.all(btree.symbol_table_addresses().map((address) => SymbolTable.create(this._source, address)));
5681
+ const links = {};
5682
+ for (const table2 of tables) {
5683
+ table2.assign_name(heap);
5684
+ Object.assign(links, table2.get_links(heap));
5685
+ }
5686
+ return links;
5687
+ }
5688
+ async _iter_link_from_link_info_msg(info_msg) {
5689
+ const absOffset = info_msg.get("offset_to_message");
5690
+ const relOffset = absOffset - this.bufStart;
5691
+ const data = this._decode_link_info_msg(this.buf, relOffset);
5692
+ const heap_address = data.get("heap_address") ?? null;
5693
+ const name_btree_address = data.get("name_btree_address") ?? null;
5694
+ const order_btree_address = data.get("order_btree_address") ?? null;
5695
+ if (name_btree_address !== null) {
5696
+ return this._iter_links_btree_v2(name_btree_address, order_btree_address, heap_address);
5697
+ }
5698
+ return {};
5699
+ }
5700
+ async _iter_links_btree_v2(name_btree_address, order_btree_address, heap_address) {
5701
+ const ordered = order_btree_address !== null;
5702
+ const [heap, btree] = await Promise.all([
5703
+ FractalHeap.create(this._source, heap_address),
5704
+ ordered ? BTreeV2GroupOrders.create(this._source, order_btree_address) : BTreeV2GroupNames.create(this._source, name_btree_address)
5705
+ ]);
5706
+ const items = /* @__PURE__ */ new Map();
5707
+ for (const record of btree.iter_records()) {
5708
+ const data = heap.get_data(record.get("heapid"));
5709
+ const [creationorder, item] = this._decode_link_msg(data, 0);
5710
+ const key = ordered ? creationorder : item[0];
5711
+ items.set(key, item);
5712
+ }
5713
+ const sorted_keys = Array.from(items.keys()).sort();
5714
+ const links = {};
5715
+ for (const key of sorted_keys) {
5716
+ const [name, address] = items.get(key);
5717
+ links[name] = address;
5718
+ }
5719
+ return links;
5720
+ }
5721
+ _decode_link_msg(data, offset) {
5722
+ const [version, flags] = struct.unpack_from("<BB", data, offset);
5723
+ offset += 2;
5724
+ assert(version === 1);
5725
+ const size_of_length_of_link_name = 2 ** (flags & 3);
5726
+ const link_type_field_present = (flags & 1 << 3) > 0;
5727
+ const link_name_character_set_field_present = (flags & 1 << 4) > 0;
5728
+ const ordered = (flags & 1 << 2) > 0;
5729
+ let link_type = 0;
5730
+ if (link_type_field_present) {
5731
+ link_type = struct.unpack_from("<B", data, offset)[0];
5732
+ offset += 1;
5733
+ }
5734
+ assert([0, 1].includes(link_type));
5735
+ let creationorder;
5736
+ if (ordered) {
5737
+ creationorder = struct.unpack_from("<Q", data, offset)[0];
5738
+ offset += 8;
5739
+ }
5740
+ let link_name_character_set = 0;
5741
+ if (link_name_character_set_field_present) {
5742
+ link_name_character_set = struct.unpack_from("<B", data, offset)[0];
5743
+ offset += 1;
5744
+ }
5745
+ const encoding = link_name_character_set === 0 ? "ascii" : "utf-8";
5746
+ const name_size_fmt = ["<B", "<H", "<I", "<Q"][flags & 3];
5747
+ const name_size = struct.unpack_from(name_size_fmt, data, offset)[0];
5748
+ offset += size_of_length_of_link_name;
5749
+ const name = new TextDecoder(encoding).decode(data.slice(offset, offset + name_size));
5750
+ offset += name_size;
5751
+ let address;
5752
+ if (link_type === 0) {
5753
+ address = struct.unpack_from("<Q", data, offset)[0];
5754
+ } else if (link_type === 1) {
5755
+ const length_of_soft_link_value = struct.unpack_from("<H", data, offset)[0];
5756
+ offset += 2;
5757
+ address = new TextDecoder(encoding).decode(data.slice(offset, offset + length_of_soft_link_value));
5758
+ }
5759
+ return [creationorder, [name, address]];
5760
+ }
5761
+ _decode_link_info_msg(data, offset) {
5762
+ const [version, flags] = struct.unpack_from("<BB", data, offset);
5763
+ assert(version === 0);
5764
+ offset += 2;
5765
+ if ((flags & 1) > 0) {
5766
+ offset += 8;
5767
+ }
5768
+ const fmt = (flags & 2) > 0 ? LINK_INFO_MSG2 : LINK_INFO_MSG1;
5769
+ const link_info = _unpack_struct_from(fmt, data, offset);
5770
+ const output = /* @__PURE__ */ new Map();
5771
+ for (const [k, v] of link_info.entries()) {
5772
+ output.set(k, v === UNDEFINED_ADDRESS ? null : v);
5773
+ }
5774
+ if (!output.has("order_btree_address")) {
5775
+ output.set("order_btree_address", null);
5776
+ }
5777
+ return output;
5778
+ }
5779
+ // ────────── Async: get_attributes ──────────
5780
+ async get_attributes() {
5781
+ const attrs = {};
5782
+ const attr_msgs = this.find_msg_type(ATTRIBUTE_MSG_TYPE$1);
5783
+ for (const msg of attr_msgs) {
5784
+ const absOffset = msg.get("offset_to_message");
5785
+ const relOffset = absOffset - this.bufStart;
5786
+ try {
5787
+ const [name, value] = await this._unpack_attribute(relOffset);
5788
+ attrs[name] = value;
5789
+ } catch {
5790
+ }
5791
+ }
5792
+ const attr_info_msgs = this.find_msg_type(ATTRIBUTE_INFO_MSG_TYPE);
5793
+ for (const info_msg of attr_info_msgs) {
5794
+ try {
5795
+ const newAttrs = await this._read_dense_attributes(info_msg);
5796
+ Object.assign(attrs, newAttrs);
5797
+ } catch {
5798
+ }
5799
+ }
5800
+ return attrs;
5801
+ }
5802
+ async _read_dense_attributes(info_msg) {
5803
+ const absOffset = info_msg.get("offset_to_message");
5804
+ let offset = absOffset - this.bufStart;
5805
+ const buf = this.buf;
5806
+ const [version, flags] = struct.unpack_from("<BB", buf, offset);
5807
+ if (version !== 0)
5808
+ return {};
5809
+ offset += 2;
5810
+ if (flags & 1)
5811
+ offset += 2;
5812
+ const [fractal_heap_address, name_btree_address] = struct.unpack_from("<QQ", buf, offset);
5813
+ offset += 16;
5814
+ let order_btree_address = null;
5815
+ if (flags & 2) {
5816
+ order_btree_address = struct.unpack_from("<Q", buf, offset)[0];
5817
+ offset += 8;
5818
+ }
5819
+ if (fractal_heap_address === UNDEFINED_ADDRESS || name_btree_address === UNDEFINED_ADDRESS) {
5820
+ return {};
5821
+ }
5822
+ const ordered = order_btree_address !== null && order_btree_address !== UNDEFINED_ADDRESS;
5823
+ const [heap, btree] = await Promise.all([
5824
+ FractalHeap.create(this._source, fractal_heap_address),
5825
+ ordered ? BTreeV2GroupOrders.create(this._source, order_btree_address) : BTreeV2GroupNames.create(this._source, name_btree_address)
5826
+ ]);
5827
+ const attrs = {};
5828
+ for (const record of btree.iter_records()) {
5829
+ try {
5830
+ const attr_data = heap.get_data(record.get("heapid"));
5831
+ const [name, value] = await this._unpack_attribute_from_buf(attr_data, 0);
5832
+ attrs[name] = value;
5833
+ } catch {
5834
+ }
5835
+ }
5836
+ return attrs;
5837
+ }
5838
+ async _unpack_attribute(relOffset) {
5839
+ return this._unpack_attribute_from_buf(this.buf, relOffset);
5840
+ }
5841
+ async _unpack_attribute_from_buf(buf, offset) {
5842
+ const version = struct.unpack_from("<B", buf, offset)[0];
5843
+ let attr_map;
5844
+ let padding_multiple;
5845
+ if (version === 1) {
5846
+ attr_map = _unpack_struct_from(ATTR_MSG_HEADER_V1, buf, offset);
5847
+ assert(attr_map.get("version") === 1);
5848
+ offset += ATTR_MSG_HEADER_V1_SIZE;
5849
+ padding_multiple = 8;
5850
+ } else if (version === 3) {
5851
+ attr_map = _unpack_struct_from(ATTR_MSG_HEADER_V3, buf, offset);
5852
+ assert(attr_map.get("version") === 3);
5853
+ offset += ATTR_MSG_HEADER_V3_SIZE;
5854
+ padding_multiple = 1;
5855
+ } else {
5856
+ throw new Error(`Unsupported attribute message version: ${version}`);
5857
+ }
5858
+ const name_size = attr_map.get("name_size");
5859
+ let name = struct.unpack_from("<" + name_size.toFixed() + "s", buf, offset)[0];
5860
+ name = name.replace(/\x00$/, "");
5861
+ offset += _padded_size(name_size, padding_multiple);
5862
+ let dtype;
5863
+ try {
5864
+ dtype = new DatatypeMessage(buf, offset).dtype;
5865
+ } catch {
5866
+ console.warn(`Attribute '${name}' type not implemented, set to null.`);
5867
+ return [name, null];
5868
+ }
5869
+ const datatype_size = attr_map.get("datatype_size");
5870
+ offset += _padded_size(datatype_size, padding_multiple);
5871
+ const shape = this._determine_data_shape(buf, offset);
5872
+ const items = shape.reduce((a, b) => a * b, 1);
5873
+ const dataspace_size = attr_map.get("dataspace_size");
5874
+ offset += _padded_size(dataspace_size, padding_multiple);
5875
+ let value = await this._attr_value(dtype, buf, items, offset);
5876
+ if (shape.length === 0) {
5877
+ value = value[0];
5878
+ }
5879
+ return [name, value];
5880
+ }
5881
+ async _attr_value(dtype, buf, count, offset) {
5882
+ const value = new Array(count);
5883
+ if (Array.isArray(dtype)) {
5884
+ const dtype_class = dtype[0];
5885
+ for (let i = 0; i < count; i++) {
5886
+ if (dtype_class === "VLEN_STRING") {
5887
+ const character_set = dtype[2];
5888
+ const [, vlen_data] = await this._vlen_size_and_data(buf, offset);
5889
+ const encoding = character_set === 0 ? "ascii" : "utf-8";
5890
+ value[i] = new TextDecoder(encoding).decode(vlen_data);
5891
+ offset += 16;
5892
+ } else if (dtype_class === "REFERENCE") {
5893
+ const address = struct.unpack_from("<Q", buf, offset);
5894
+ value[i] = address;
5895
+ offset += 8;
5896
+ } else if (dtype_class === "VLEN_SEQUENCE") {
5897
+ const base_dtype = dtype[1];
5898
+ const [vlen, vlen_data] = await this._vlen_size_and_data(buf, offset);
5899
+ value[i] = await this._attr_value(base_dtype, vlen_data, vlen, 0);
5900
+ offset += 16;
5901
+ } else if (dtype_class === "COMPOUND") {
5902
+ const total_size = dtype[2];
5903
+ value[i] = buf.slice(offset, offset + total_size);
5904
+ offset += total_size;
5905
+ } else {
5906
+ throw new Error("NotImplementedError: unsupported dtype class " + dtype_class);
5907
+ }
5908
+ }
5909
+ } else {
5910
+ const [getter, big_endian, size] = dtype_getter(dtype);
5911
+ const view = new DataView64(buf, 0);
5912
+ for (let i = 0; i < count; i++) {
5913
+ value[i] = view[getter](offset, !big_endian, size);
5914
+ offset += size;
5915
+ }
5916
+ }
5917
+ return value;
5918
+ }
5919
+ async _vlen_size_and_data(buf, offset) {
5920
+ const vlen_size = struct.unpack_from("<I", buf, offset)[0];
5921
+ const gheap_id = _unpack_struct_from(GLOBAL_HEAP_ID, buf, offset + 4);
5922
+ const gheap_address = gheap_id.get("collection_address");
5923
+ assert(gheap_address < Number.MAX_SAFE_INTEGER);
5924
+ const gheap = await this._get_global_heap(gheap_address);
5925
+ const vlen_data = gheap.objects.get(gheap_id.get("object_index"));
5926
+ if (!vlen_data) {
5927
+ throw new Error(`Global heap object not found at index ${gheap_id.get("object_index")}`);
5928
+ }
5929
+ return [vlen_size, vlen_data];
5930
+ }
5931
+ _get_global_heap(address) {
5932
+ let gheap = this._global_heaps.get(address);
5933
+ if (!gheap) {
5934
+ const promise = GlobalHeap.create(this._source, address);
5935
+ promise.catch(() => {
5936
+ if (this._global_heaps.peek(address) === promise)
5937
+ this._global_heaps.delete(address);
5938
+ });
5939
+ this._global_heaps.set(address, promise);
5940
+ gheap = promise;
5941
+ }
5942
+ return gheap;
5943
+ }
5944
+ /**
5945
+ * Decode `count` variable-length strings from consecutive 16-byte global heap references
5946
+ * (uint32 length, uint64 collection address, uint32 object index) starting at `offset`.
5947
+ * All referenced global heap collections are fetched concurrently.
5948
+ * Null / missing references decode to "".
5949
+ */
5950
+ async _read_vlen_strings(buf, offset, count, decoder) {
5951
+ const view = new DataView(buf);
5952
+ const refs = new Array(count);
5953
+ const addresses = /* @__PURE__ */ new Set();
5954
+ for (let i = 0; i < count; i++) {
5955
+ const o = offset + i * 16;
5956
+ const size = view.getUint32(o, true);
5957
+ const address = Number(view.getBigUint64(o + 4, true));
5958
+ const index = view.getUint32(o + 12, true);
5959
+ refs[i] = { size, address, index };
5960
+ if (size > 0 && address !== 0 && address < Number.MAX_SAFE_INTEGER) {
5961
+ addresses.add(address);
5962
+ }
5963
+ }
5964
+ const heaps = /* @__PURE__ */ new Map();
5965
+ await Promise.all(Array.from(addresses, async (address) => {
5966
+ heaps.set(address, await this._get_global_heap(address));
5967
+ }));
5968
+ return refs.map(({ address, index }) => {
5969
+ const data = heaps.get(address)?.objects.get(index);
5970
+ return data ? decoder.decode(data) : "";
5971
+ });
5972
+ }
5973
+ // ────────── Async: get_data ──────────
5974
+ async get_data() {
5975
+ const msg = this.find_msg_type(DATA_STORAGE_MSG_TYPE)[0];
5976
+ if (!msg)
5977
+ return [];
5978
+ const absOffset = msg.get("offset_to_message");
5979
+ const relOffset = absOffset - this.bufStart;
5980
+ const { layout_class, property_offset } = this._get_data_message_properties(relOffset);
5981
+ if (layout_class === 0) {
5982
+ throw new Error("Compact storage of DataObject not implemented");
5983
+ } else if (layout_class === 1) {
5984
+ return this._get_contiguous_data(property_offset);
5985
+ } else if (layout_class === 2) {
5986
+ return this._get_chunked_data(relOffset);
5987
+ }
5988
+ return [];
5989
+ }
5990
+ async _get_contiguous_data(property_offset) {
5991
+ const buf = this.buf;
5992
+ const data_offset = struct.unpack_from("<Q", buf, property_offset)[0];
5993
+ const shape = this.shape;
5994
+ const fullsize = shape.reduce((a, b) => a * b, 1);
5995
+ if (data_offset === UNDEFINED_ADDRESS) {
5996
+ return new Array(fullsize);
5997
+ }
5998
+ const dtype = this.dtype;
5999
+ if (!Array.isArray(dtype)) {
6000
+ if (/[<>=!@|]?(i|u|f|S)(\d*)/.test(dtype)) {
6001
+ const [item_getter, item_is_big_endian, item_size] = dtype_getter(dtype);
6002
+ const dataBuf = await fetchRange(this._source, data_offset, fullsize * item_size);
6003
+ const view = new DataView64(dataBuf, 0);
6004
+ const output = new Array(fullsize);
6005
+ for (let i = 0; i < fullsize; i++) {
6006
+ output[i] = view[item_getter](i * item_size, !item_is_big_endian, item_size);
6007
+ }
6008
+ return output;
6009
+ } else {
6010
+ throw new Error("Not implemented - no proper dtype defined: " + dtype);
6011
+ }
6012
+ } else {
6013
+ const dtype_class = dtype[0];
6014
+ if (dtype_class === "REFERENCE") {
6015
+ const size = dtype[1];
6016
+ if (size !== 8) {
6017
+ throw new Error("Unsupported Reference type size: " + size);
6018
+ }
6019
+ const dataBuf = await fetchRange(this._source, data_offset, fullsize * 8);
6020
+ return [dataBuf];
6021
+ } else if (dtype_class === "VLEN_STRING") {
6022
+ const character_set = dtype[2];
6023
+ const encoding = character_set === 0 ? "ascii" : "utf-8";
6024
+ const decoder = new TextDecoder(encoding);
6025
+ const refBuf = await fetchRange(this._source, data_offset, fullsize * 16);
6026
+ return this._read_vlen_strings(refBuf, 0, fullsize, decoder);
6027
+ } else if (dtype_class === "COMPOUND") {
6028
+ const total_size = dtype[2];
6029
+ const dataBuf = await fetchRange(this._source, data_offset, fullsize * total_size);
6030
+ const output = new Array(fullsize);
6031
+ for (let i = 0; i < fullsize; i++) {
6032
+ output[i] = dataBuf.slice(i * total_size, (i + 1) * total_size);
6033
+ }
6034
+ return output;
6035
+ } else {
6036
+ throw new Error("Not implemented datatype class: " + dtype_class);
6037
+ }
6038
+ }
6039
+ }
6040
+ async _get_chunked_data(_msg_offset) {
6041
+ this._get_chunk_params();
6042
+ if (this._chunk_address === null || this._chunk_address === UNDEFINED_ADDRESS) {
6043
+ return [];
6044
+ }
6045
+ const dtype = this.dtype;
6046
+ if (!Array.isArray(dtype) || dtype[0] !== "VLEN_STRING") {
6047
+ return [];
6048
+ }
6049
+ const character_set = dtype[2];
6050
+ const encoding = character_set === 0 ? "ascii" : "utf-8";
6051
+ const decoder = new TextDecoder(encoding);
6052
+ const shape = this.shape;
6053
+ const chunkShape = this._chunks;
6054
+ const ndim = shape.length;
6055
+ const total = shape.reduce((a, b) => a * b, 1);
6056
+ const output = new Array(total).fill("");
6057
+ const pipeline = this.filter_pipeline;
6058
+ const chunk_btree = await BTreeV1RawDataChunks.create(this._source, this._chunk_address, this._chunk_dims);
6059
+ const leafNodes = chunk_btree.all_nodes.get(0) ?? [];
6060
+ const chunks = [];
6061
+ for (const node of leafNodes) {
6062
+ for (let ik = 0; ik < node.keys.length; ik++) {
6063
+ const key = node.keys[ik];
6064
+ chunks.push({
6065
+ address: node.addresses[ik],
6066
+ size: key.chunk_size,
6067
+ filterMask: key.filter_mask,
6068
+ start: key.chunk_offset.slice(0, ndim)
6069
+ });
6070
+ }
6071
+ }
6072
+ const chunkItems = chunkShape.reduce((a, b) => a * b, 1);
6073
+ const strides = new Array(ndim).fill(1);
6074
+ const chunkStrides = new Array(ndim).fill(1);
6075
+ for (let d = ndim - 2; d >= 0; d--) {
6076
+ strides[d] = strides[d + 1] * shape[d + 1];
6077
+ chunkStrides[d] = chunkStrides[d + 1] * chunkShape[d + 1];
6078
+ }
6079
+ await Promise.all(chunks.map(async ({ address, size, filterMask, start }) => {
6080
+ const raw = new Uint8Array(await fetchRange(this._source, address, size));
6081
+ const decoded = await decodeChunk(raw, pipeline, filterMask);
6082
+ const nItems = Math.min(chunkItems, Math.floor(decoded.byteLength / 16));
6083
+ const buf = decoded.buffer.slice(decoded.byteOffset, decoded.byteOffset + nItems * 16);
6084
+ const strings = await this._read_vlen_strings(buf, 0, nItems, decoder);
6085
+ for (let i = 0; i < nItems; i++) {
6086
+ let flat2 = 0;
6087
+ let inBounds = true;
6088
+ for (let d = 0; d < ndim; d++) {
6089
+ const coord = start[d] + Math.floor(i / chunkStrides[d]) % chunkShape[d];
6090
+ if (coord >= shape[d]) {
6091
+ inBounds = false;
6092
+ break;
6093
+ }
6094
+ flat2 += coord * strides[d];
6095
+ }
6096
+ if (inBounds)
6097
+ output[flat2] = strings[i];
6098
+ }
6099
+ }));
6100
+ return output;
6101
+ }
6102
+ }
6103
+ class Group2 {
6104
+ parent;
6105
+ file;
6106
+ name;
6107
+ _links;
6108
+ _dataobjects;
6109
+ _attrs = null;
6110
+ _keys = null;
6111
+ constructor(name, dataobjects, links, parent) {
6112
+ if (parent == null) {
6113
+ this.parent = this;
6114
+ this.file = this;
6115
+ } else {
6116
+ this.parent = parent;
6117
+ this.file = parent instanceof File ? parent : parent.file;
6118
+ }
6119
+ this.name = name;
6120
+ this._links = links;
6121
+ this._dataobjects = dataobjects;
6122
+ }
6123
+ get keys() {
6124
+ if (this._keys == null) {
6125
+ this._keys = Object.keys(this._links);
6126
+ }
6127
+ return this._keys.slice();
6128
+ }
6129
+ async get(y) {
6130
+ let path = normpath(y);
6131
+ if (path === "/")
6132
+ return this.file;
6133
+ if (path === ".")
6134
+ return this;
6135
+ if (/^\//.test(path))
6136
+ return this.file.get(path.slice(1));
6137
+ let next_obj;
6138
+ let additional_obj;
6139
+ if (posix_dirname(path) !== "") {
6140
+ [next_obj, additional_obj] = path.split(/\/(.*)/);
6141
+ } else {
6142
+ next_obj = path;
6143
+ additional_obj = ".";
6144
+ }
6145
+ if (!(next_obj in this._links)) {
6146
+ throw new Error(next_obj + " not found in group");
6147
+ }
6148
+ const obj_name = normpath(this.name + "/" + next_obj);
6149
+ const link_target = this._links[next_obj];
6150
+ if (typeof link_target === "string") {
6151
+ try {
6152
+ return await this.get(link_target);
6153
+ } catch {
6154
+ throw new Error("Broken soft link: " + link_target);
6155
+ }
6156
+ }
6157
+ const source = this.file._source;
6158
+ const dataobjs = await DataObjects.create(source, link_target);
6159
+ if (dataobjs.is_dataset) {
6160
+ if (additional_obj !== ".") {
6161
+ throw new Error(obj_name + " is a dataset, not a group");
6162
+ }
6163
+ return new Dataset(obj_name, dataobjs, this);
6164
+ } else {
6165
+ const links = await dataobjs.get_links();
6166
+ const new_group = new Group2(obj_name, dataobjs, links, this);
6167
+ return new_group.get(additional_obj);
6168
+ }
6169
+ }
6170
+ async get_attrs() {
6171
+ if (this._attrs == null) {
6172
+ this._attrs = await this._dataobjects.get_attributes();
6173
+ }
6174
+ return this._attrs;
6175
+ }
6176
+ }
6177
+ class File extends Group2 {
6178
+ _source;
6179
+ filename;
6180
+ mode = "r";
6181
+ userblock_size = 0;
6182
+ constructor(source, dataobjects, links, filename) {
6183
+ super("/", dataobjects, links);
6184
+ this.parent = this;
6185
+ this.file = this;
6186
+ this._source = source;
6187
+ this.filename = filename;
6188
+ }
6189
+ static async create(source, filename) {
6190
+ const superblock = await SuperBlock.create(source, 0);
6191
+ setFileSize(source, superblock.end_of_file);
6192
+ const offset = await superblock.getOffsetToDataobjects();
6193
+ const dataobjects = await DataObjects.create(source, offset);
6194
+ const links = await dataobjects.get_links();
6195
+ return new File(source, dataobjects, links, filename || "");
6196
+ }
6197
+ }
6198
+ class Dataset {
6199
+ parent;
6200
+ file;
6201
+ name;
6202
+ _dataobjects;
6203
+ constructor(name, dataobjects, parent) {
6204
+ this.parent = parent;
6205
+ this.file = parent instanceof File ? parent : parent.file;
6206
+ this.name = name;
6207
+ this._dataobjects = dataobjects;
6208
+ }
6209
+ get shape() {
6210
+ return this._dataobjects.shape;
6211
+ }
6212
+ async get_attrs() {
6213
+ return this._dataobjects.get_attributes();
6214
+ }
6215
+ get dtype() {
6216
+ return this._dataobjects.dtype;
6217
+ }
6218
+ get fillvalue() {
6219
+ return this._dataobjects.fillvalue;
6220
+ }
6221
+ async get_data() {
6222
+ return this._dataobjects.get_data();
6223
+ }
6224
+ }
6225
+ function posix_dirname(p) {
6226
+ const sep = "/";
6227
+ const i = p.lastIndexOf(sep) + 1;
6228
+ let head = p.slice(0, i);
6229
+ if (head && !/^\/+$/.test(head)) {
6230
+ head = head.replace(/\/$/, "");
6231
+ }
6232
+ return head;
6233
+ }
6234
+ function normpath(path) {
6235
+ return path.replace(/\/(\/)+/g, "/");
6236
+ }
6237
+ function jsonStringifySorted(obj) {
6238
+ return JSON.stringify(obj, (_key, value) => {
6239
+ if (value && typeof value === "object" && !Array.isArray(value)) {
6240
+ const sorted = {};
6241
+ for (const k of Object.keys(value).sort()) {
6242
+ sorted[k] = value[k];
6243
+ }
6244
+ return sorted;
6245
+ }
6246
+ return value;
6247
+ });
6248
+ }
6249
+ function inlineBytes(data) {
6250
+ let binary = "";
6251
+ let asciiSafe = true;
6252
+ for (let i = 0; i < data.length; i++) {
6253
+ if (data[i] >= 128)
6254
+ asciiSafe = false;
6255
+ binary += String.fromCharCode(data[i]);
6256
+ }
6257
+ return asciiSafe ? binary : "base64:" + btoa(binary);
6258
+ }
6259
+ function decodeInline(entry) {
6260
+ if (entry.startsWith("base64:")) {
6261
+ const binary = atob(entry.slice("base64:".length));
6262
+ return Uint8Array.from(binary, (c) => c.charCodeAt(0));
6263
+ }
6264
+ return new TextEncoder().encode(entry);
6265
+ }
6266
+ function encodeVlenUtf8(strings) {
6267
+ const encoder = new TextEncoder();
6268
+ const encoded = strings.map((s) => encoder.encode(s));
6269
+ const totalSize = 4 + encoded.reduce((acc, b) => acc + 4 + b.length, 0);
6270
+ const out = new Uint8Array(totalSize);
6271
+ const view = new DataView(out.buffer);
6272
+ view.setUint32(0, strings.length, true);
6273
+ let pos = 4;
6274
+ for (const b of encoded) {
6275
+ view.setUint32(pos, b.length, true);
6276
+ pos += 4;
6277
+ out.set(b, pos);
6278
+ pos += b.length;
6279
+ }
6280
+ return out;
6281
+ }
6282
+ const V3_DATA_TYPES = {
6283
+ b1: "bool",
6284
+ i1: "int8",
6285
+ u1: "uint8",
6286
+ i2: "int16",
6287
+ u2: "uint16",
6288
+ i4: "int32",
6289
+ u4: "uint32",
6290
+ i8: "int64",
6291
+ u8: "uint64",
6292
+ f2: "float16",
6293
+ f4: "float32",
6294
+ f8: "float64"
6295
+ };
6296
+ const BLOSC_SHUFFLE = ["noshuffle", "shuffle", "bitshuffle"];
6297
+ const V2_CHUNK_KEY = /^\d+(\.\d+)*$/;
6298
+ function v2CodecToV3(codec, itemSize) {
6299
+ const { id, ...configuration } = codec;
6300
+ if (id === "blosc") {
6301
+ return {
6302
+ name: "blosc",
6303
+ configuration: {
6304
+ cname: configuration.cname,
6305
+ clevel: configuration.clevel,
6306
+ shuffle: BLOSC_SHUFFLE[configuration.shuffle] ?? "noshuffle",
6307
+ typesize: itemSize,
6308
+ blocksize: configuration.blocksize ?? 0
6309
+ }
6310
+ };
6311
+ }
6312
+ if (id === "zstd") {
6313
+ return { name: "zstd", configuration: { level: configuration.level, checksum: false } };
6314
+ }
6315
+ return { name: `numcodecs.${id}`, configuration };
6316
+ }
6317
+ function decodeStringChunk(entry, meta) {
6318
+ if (typeof entry !== "string") {
6319
+ throw new Error("String chunks must be inlined");
6320
+ }
6321
+ const bytes = decodeInline(entry);
6322
+ if (meta.dtype === "|O") {
6323
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
6324
+ return parsed.slice(0, -2).map((v) => v === null || v === void 0 ? "" : String(v));
6325
+ }
6326
+ const itemSize = parseInt(meta.dtype.slice(2), 10);
6327
+ const decoder = new TextDecoder();
6328
+ const strings = [];
6329
+ for (let i = 0; i + itemSize <= bytes.length; i += itemSize) {
6330
+ let end = i + itemSize;
6331
+ while (end > i && bytes[end - 1] === 0)
6332
+ end--;
6333
+ strings.push(decoder.decode(bytes.subarray(i, end)));
6334
+ }
6335
+ return strings;
6336
+ }
6337
+ function refSpecV2ToV3(spec) {
6338
+ const v2Refs = spec.refs;
6339
+ const refs = {};
6340
+ const parseJson = (key) => {
6341
+ const value = v2Refs[key];
6342
+ return typeof value === "string" ? JSON.parse(value) : void 0;
6343
+ };
6344
+ const chunkKeysByNode = /* @__PURE__ */ new Map();
6345
+ for (const key of Object.keys(v2Refs)) {
6346
+ const idx = key.lastIndexOf("/");
6347
+ const nodePath = idx === -1 ? "" : key.slice(0, idx);
6348
+ const name = key.slice(idx + 1);
6349
+ if (V2_CHUNK_KEY.test(name)) {
6350
+ if (!chunkKeysByNode.has(nodePath))
6351
+ chunkKeysByNode.set(nodePath, []);
6352
+ chunkKeysByNode.get(nodePath).push(name);
6353
+ }
6354
+ }
6355
+ for (const key of Object.keys(v2Refs)) {
6356
+ const isGroup = key === ".zgroup" || key.endsWith("/.zgroup");
6357
+ const isArray2 = key === ".zarray" || key.endsWith("/.zarray");
6358
+ if (!isGroup && !isArray2)
6359
+ continue;
6360
+ const nodePath = key.slice(0, -".zgroup".length).replace(/\/$/, "");
6361
+ const prefix = nodePath ? `${nodePath}/` : "";
6362
+ const attributes = parseJson(`${prefix}.zattrs`) ?? {};
6363
+ if (isGroup) {
6364
+ refs[`${prefix}zarr.json`] = jsonStringifySorted({
6365
+ zarr_format: 3,
6366
+ node_type: "group",
6367
+ attributes
6368
+ });
6369
+ continue;
6370
+ }
6371
+ const meta = parseJson(key);
6372
+ const { _ARRAY_DIMENSIONS: dims, ...arrayAttributes } = attributes;
6373
+ const chunkNames = chunkKeysByNode.get(nodePath) ?? [];
6374
+ const isJson2 = meta.dtype === "|O" && (meta.filters ?? []).some((f) => f.id === "json2");
6375
+ const isFixedString = /^\|S\d+$/.test(meta.dtype);
6376
+ if (meta.dtype === "|O" && !isJson2) {
6377
+ continue;
6378
+ }
6379
+ const v3Meta = {
6380
+ zarr_format: 3,
6381
+ node_type: "array",
6382
+ shape: meta.shape,
6383
+ chunk_key_encoding: { name: "default", configuration: { separator: "/" } },
6384
+ attributes: arrayAttributes
6385
+ };
6386
+ if (Array.isArray(dims) && dims.length === meta.shape.length) {
6387
+ v3Meta.dimension_names = dims;
6388
+ }
6389
+ const toV3ChunkKey = (name) => meta.shape.length === 0 ? `${prefix}c` : `${prefix}c/${name.split(".").join("/")}`;
6390
+ if (isJson2 || isFixedString) {
6391
+ v3Meta.data_type = "string";
6392
+ v3Meta.chunk_grid = { name: "regular", configuration: { chunk_shape: meta.shape } };
6393
+ v3Meta.codecs = [{ name: "vlen-utf8" }];
6394
+ v3Meta.fill_value = "";
6395
+ for (const name of chunkNames) {
6396
+ const strings = decodeStringChunk(v2Refs[`${prefix}${name}`], meta);
6397
+ refs[toV3ChunkKey(name)] = inlineBytes(encodeVlenUtf8(strings));
6398
+ }
6399
+ refs[`${prefix}zarr.json`] = jsonStringifySorted(v3Meta);
6400
+ continue;
6401
+ }
6402
+ const match = meta.dtype.match(/^([<>|])([a-z]\d+)$/);
6403
+ const dataType = match ? V3_DATA_TYPES[match[2]] : void 0;
6404
+ if (!dataType) {
6405
+ continue;
6406
+ }
6407
+ const itemSize = parseInt(match[2].slice(1), 10);
6408
+ const codecs = [
6409
+ itemSize > 1 ? { name: "bytes", configuration: { endian: match[1] === ">" ? "big" : "little" } } : { name: "bytes" }
6410
+ ];
6411
+ for (const filter of meta.filters ?? []) {
6412
+ codecs.push(v2CodecToV3(filter, itemSize));
6413
+ }
6414
+ if (meta.compressor) {
6415
+ codecs.push(v2CodecToV3(meta.compressor, itemSize));
6416
+ }
6417
+ v3Meta.data_type = dataType;
6418
+ v3Meta.chunk_grid = { name: "regular", configuration: { chunk_shape: meta.chunks } };
6419
+ v3Meta.codecs = codecs;
6420
+ v3Meta.fill_value = meta.fill_value ?? (dataType === "bool" ? false : 0);
6421
+ refs[`${prefix}zarr.json`] = jsonStringifySorted(v3Meta);
6422
+ for (const name of chunkNames) {
6423
+ refs[toV3ChunkKey(name)] = v2Refs[`${prefix}${name}`];
6424
+ }
6425
+ }
6426
+ return { version: 1, refs };
6427
+ }
6428
+ const HIDDEN_ATTRS = /* @__PURE__ */ new Set([
6429
+ "REFERENCE_LIST",
6430
+ "CLASS",
6431
+ "DIMENSION_LIST",
6432
+ "NAME",
6433
+ "_Netcdf4Dimid",
6434
+ "_Netcdf4Coordinates",
6435
+ "_nc3_strict",
6436
+ "_NCProperties"
6437
+ ]);
6438
+ function jsfiveDtypeToZarr(dtype) {
6439
+ if (Array.isArray(dtype)) {
6440
+ const dtypeClass = dtype[0];
6441
+ if (dtypeClass === "VLEN_STRING")
6442
+ return "|O";
6443
+ if (dtypeClass === "VLEN_SEQUENCE")
6444
+ return "|O";
6445
+ if (dtypeClass === "REFERENCE")
6446
+ return "|O";
6447
+ return "|O";
6448
+ }
6449
+ if (/^S\d+/.test(dtype)) {
6450
+ return "|" + dtype;
6451
+ }
6452
+ const match = dtype.match(/^([<>|])([iufS])(\d+)$/);
6453
+ if (!match)
6454
+ return dtype;
6455
+ const [, endian, typeChar, sizeStr] = match;
6456
+ const size = parseInt(sizeStr, 10);
6457
+ if ((typeChar === "i" || typeChar === "u") && size === 1) {
6458
+ return `|${typeChar}${size}`;
6459
+ }
6460
+ return dtype;
6461
+ }
6462
+ function decodeFilterPipeline(filterPipeline) {
6463
+ const zarrFilters = [];
6464
+ let compressor = null;
6465
+ if (!filterPipeline) {
6466
+ return { compressor, zarrFilters: null };
6467
+ }
6468
+ for (const filterInfo of filterPipeline) {
6469
+ const filterId = filterInfo.get("filter_id");
6470
+ const clientData = filterInfo.get("client_data");
6471
+ if (filterId === 1) {
6472
+ compressor = {
6473
+ id: "zlib",
6474
+ level: clientData?.[0] ?? 4
6475
+ };
6476
+ } else if (filterId === 2) {
6477
+ zarrFilters.push({
6478
+ id: "shuffle",
6479
+ elementsize: clientData?.[0] ?? 4
6480
+ });
6481
+ } else if (filterId === 32001) {
6482
+ const blosccnames = [
6483
+ "blosclz",
6484
+ "lz4",
6485
+ "lz4hc",
6486
+ "snappy",
6487
+ "zlib",
6488
+ "zstd"
6489
+ ];
6490
+ const cd = clientData || [];
6491
+ compressor = {
6492
+ id: "blosc",
6493
+ cname: blosccnames[cd[4]] || "lz4",
6494
+ clevel: cd[3] || 5,
6495
+ shuffle: cd[5] || 0,
6496
+ blocksize: cd[2] || 0
6497
+ };
6498
+ } else if (filterId === 32015) {
6499
+ compressor = {
6500
+ id: "zstd",
6501
+ level: clientData?.[0] ?? 3
6502
+ };
6503
+ } else ;
6504
+ }
6505
+ return {
6506
+ compressor,
6507
+ zarrFilters: zarrFilters.length > 0 ? zarrFilters : null
6508
+ };
6509
+ }
6510
+ function encodeFillValue(fillValue, dtype) {
6511
+ if (fillValue === null || fillValue === void 0) {
6512
+ return null;
6513
+ }
6514
+ if (typeof fillValue === "number") {
6515
+ if (Number.isNaN(fillValue))
6516
+ return "NaN";
6517
+ if (fillValue === Infinity)
6518
+ return "Infinity";
6519
+ if (fillValue === -Infinity)
6520
+ return "-Infinity";
6521
+ if (dtype.match(/[iu]\d/)) {
6522
+ return Math.round(fillValue);
6523
+ }
6524
+ return fillValue;
6525
+ }
6526
+ if (typeof fillValue === "bigint") {
6527
+ return Number(fillValue);
6528
+ }
6529
+ if (typeof fillValue === "string") {
6530
+ return fillValue;
6531
+ }
6532
+ return 0;
6533
+ }
6534
+ function encodeScalar(value, dtype) {
6535
+ if (value === null || value === void 0)
6536
+ return void 0;
6537
+ const strMatch = dtype.match(/^\|S(\d+)$/);
6538
+ if (strMatch) {
6539
+ const out2 = new Uint8Array(parseInt(strMatch[1], 10));
6540
+ out2.set(new TextEncoder().encode(String(value)).subarray(0, out2.length));
6541
+ return out2;
6542
+ }
6543
+ const match = dtype.match(/^([<>|])([iuf])(\d+)$/);
6544
+ if (!match)
6545
+ return void 0;
6546
+ const [, endian, kind, sizeStr] = match;
6547
+ const size = parseInt(sizeStr, 10);
6548
+ const littleEndian = endian !== ">";
6549
+ const out = new Uint8Array(size);
6550
+ const view = new DataView(out.buffer);
6551
+ const num = Number(value);
6552
+ if (kind === "f") {
6553
+ if (size === 4)
6554
+ view.setFloat32(0, num, littleEndian);
6555
+ else if (size === 8)
6556
+ view.setFloat64(0, num, littleEndian);
6557
+ else
6558
+ return void 0;
6559
+ } else if (size === 1) {
6560
+ if (kind === "i")
6561
+ view.setInt8(0, num);
6562
+ else
6563
+ view.setUint8(0, num);
6564
+ } else if (size === 2) {
6565
+ if (kind === "i")
6566
+ view.setInt16(0, num, littleEndian);
6567
+ else
6568
+ view.setUint16(0, num, littleEndian);
6569
+ } else if (size === 4) {
6570
+ if (kind === "i")
6571
+ view.setInt32(0, num, littleEndian);
6572
+ else
6573
+ view.setUint32(0, num, littleEndian);
6574
+ } else if (size === 8) {
6575
+ const big = BigInt(typeof value === "bigint" ? value : Math.round(num));
6576
+ if (kind === "i")
6577
+ view.setBigInt64(0, big, littleEndian);
6578
+ else
6579
+ view.setBigUint64(0, big, littleEndian);
6580
+ } else {
6581
+ return void 0;
6582
+ }
6583
+ return out;
6584
+ }
6585
+ function encodeJson2(strings, shape) {
6586
+ const parts = [...strings, "|O", shape];
6587
+ return JSON.stringify(parts);
6588
+ }
6589
+ const JSON2_FILTER = {
6590
+ allow_nan: true,
6591
+ check_circular: true,
6592
+ encoding: "utf-8",
6593
+ ensure_ascii: true,
6594
+ id: "json2",
6595
+ indent: null,
6596
+ separators: [",", ":"],
6597
+ skipkeys: false,
6598
+ sort_keys: true,
6599
+ strict: true
6600
+ };
6601
+ function serializeZarrayMeta(meta) {
6602
+ let json = jsonStringifySorted(meta);
6603
+ if (/[<>]f\d/.test(meta.dtype) && typeof meta.fill_value === "number" && Number.isFinite(meta.fill_value) && meta.fill_value === Math.round(meta.fill_value)) {
6604
+ const intStr = String(Math.round(meta.fill_value));
6605
+ json = json.replace(`"fill_value":${intStr}`, `"fill_value":${intStr}.0`);
6606
+ }
6607
+ return json;
6608
+ }
6609
+ function getStorageInfo(dataobjects) {
6610
+ const DATA_STORAGE_MSG_TYPE2 = 8;
6611
+ const msg = dataobjects.find_msg_type(DATA_STORAGE_MSG_TYPE2)[0];
6612
+ if (!msg)
6613
+ return { layoutClass: -1 };
6614
+ const relOffset = msg.get("offset_to_message") - dataobjects.bufStart;
6615
+ const props = dataobjects._get_data_message_properties(relOffset);
6616
+ const { version, dims, layout_class: layoutClass, property_offset } = props;
6617
+ if (layoutClass === 1) {
6618
+ const localBuf = dataobjects.buf;
6619
+ const dataOffset = struct.unpack_from("<Q", localBuf, property_offset)[0];
6620
+ if (dataOffset === UNDEFINED_ADDRESS || dataOffset >= Number.MAX_SAFE_INTEGER * 0.99) {
6621
+ return { layoutClass: 1 };
6622
+ }
6623
+ let size;
6624
+ if (version === 3 || version === 4) {
6625
+ size = struct.unpack_from("<Q", localBuf, property_offset + 8)[0];
6626
+ } else {
6627
+ const shape = dataobjects.shape;
6628
+ const dtype = dataobjects.dtype;
6629
+ let itemSize = 0;
6630
+ if (typeof dtype === "string") {
6631
+ const m = dtype.match(/\d+$/);
6632
+ itemSize = m ? parseInt(m[0], 10) : 1;
6633
+ } else {
6634
+ itemSize = 8;
6635
+ }
6636
+ size = shape.reduce((a, b) => a * b, 1) * itemSize;
6637
+ }
6638
+ return { layoutClass: 1, contiguousOffset: dataOffset, contiguousSize: size };
6639
+ } else if (layoutClass === 2) {
6640
+ dataobjects._get_chunk_params();
6641
+ const chunkAddress = dataobjects._chunk_address;
6642
+ const chunkDims = dataobjects._chunk_dims;
6643
+ const chunkShape = dataobjects._chunks;
6644
+ if (chunkAddress == null || chunkAddress === UNDEFINED_ADDRESS) {
6645
+ return { layoutClass: 2 };
6646
+ }
6647
+ return {
6648
+ layoutClass: 2,
6649
+ chunkAddress,
6650
+ chunkDims,
6651
+ chunkShape
6652
+ };
6653
+ }
6654
+ return { layoutClass };
6655
+ }
6656
+ async function getChunkLocations(source, btreeAddress, chunkDims, dataShape, chunkShape) {
6657
+ const btree = await BTreeV1RawDataChunks.create(source, btreeAddress, chunkDims);
6658
+ const results = [];
6659
+ const leafNodes = btree.all_nodes.get(0);
6660
+ if (!leafNodes)
6661
+ return results;
6662
+ for (const node of leafNodes) {
6663
+ const nodeKeys = node.keys;
6664
+ const nodeAddresses = node.addresses;
6665
+ const nkeys = nodeKeys.length;
6666
+ for (let ik = 0; ik < nkeys; ik++) {
6667
+ const nodeKey = nodeKeys[ik];
6668
+ const addr = nodeAddresses[ik];
6669
+ const chunkOffset = nodeKey.chunk_offset;
6670
+ const chunkSize = nodeKey.chunk_size;
6671
+ const chunkIndex = chunkOffset.slice(0, -1).map((co, d) => Math.floor(co / chunkShape[d]));
6672
+ while (chunkIndex.length < dataShape.length) {
6673
+ chunkIndex.push(0);
6674
+ }
6675
+ while (chunkIndex.length > dataShape.length) {
6676
+ chunkIndex.pop();
6677
+ }
6678
+ results.push({
6679
+ chunkIndex,
6680
+ offset: addr,
6681
+ size: chunkSize
6682
+ });
6683
+ }
6684
+ }
6685
+ return results;
6686
+ }
6687
+ const ATTRIBUTE_MSG_TYPE = 12;
6688
+ const DATATYPE_ENUMERATED = 8;
6689
+ function getAttrDatatypeClasses(dataobjects) {
6690
+ const result = /* @__PURE__ */ new Map();
6691
+ const attrMsgs = dataobjects.find_msg_type(ATTRIBUTE_MSG_TYPE);
6692
+ const fh = dataobjects.buf;
6693
+ const bufStart = dataobjects.bufStart;
6694
+ for (const msg of attrMsgs) {
6695
+ let offset = msg.get("offset_to_message") - bufStart;
6696
+ const version = struct.unpack_from("<B", fh, offset)[0];
6697
+ let nameSize;
6698
+ let paddingMultiple;
6699
+ if (version === 1) {
6700
+ nameSize = struct.unpack_from("<H", fh, offset + 2)[0];
6701
+ paddingMultiple = 8;
6702
+ offset += 8;
6703
+ } else if (version === 3) {
6704
+ nameSize = struct.unpack_from("<H", fh, offset + 2)[0];
6705
+ paddingMultiple = 1;
6706
+ offset += 9;
6707
+ } else {
6708
+ continue;
6709
+ }
6710
+ const nameBytes = struct.unpack_from("<" + nameSize.toFixed() + "s", fh, offset)[0];
6711
+ const name = nameBytes.replace(/\x00$/, "");
6712
+ const paddedNameSize = paddingMultiple > 1 ? Math.ceil(nameSize / paddingMultiple) * paddingMultiple : nameSize;
6713
+ offset += paddedNameSize;
6714
+ const classAndVersion = struct.unpack_from("<B", fh, offset)[0];
6715
+ const datatypeClass = classAndVersion & 15;
6716
+ result.set(name, datatypeClass);
6717
+ }
6718
+ return result;
6719
+ }
6720
+ function isVlenString(rawDtype) {
6721
+ return Array.isArray(rawDtype) && rawDtype[0] === "VLEN_STRING";
6722
+ }
6723
+ class SingleHdf5ToZarr {
6724
+ source;
6725
+ h5File = null;
6726
+ url;
6727
+ inlineThreshold;
6728
+ zarrFormat;
6729
+ /**
6730
+ * @param source - An AsyncReadable instance for reading the HDF5 file.
6731
+ * @param options - Configuration options.
6732
+ */
6733
+ constructor(source, options = {}) {
6734
+ this.source = source;
6735
+ this.url = options.url ?? null;
6736
+ this.inlineThreshold = options.inlineThreshold ?? 300;
6737
+ this.zarrFormat = options.zarrFormat ?? 2;
6738
+ }
6739
+ /**
6740
+ * Open (and cache) the HDF5 file: reads the superblock and the root group's links.
6741
+ */
6742
+ open() {
6743
+ if (!this.h5File) {
6744
+ this.h5File = File.create(this.source);
6745
+ this.h5File.catch(() => {
6746
+ this.h5File = null;
6747
+ });
6748
+ }
6749
+ return this.h5File;
6750
+ }
6751
+ /**
6752
+ * Translate the HDF5 file content into a Zarr reference spec.
6753
+ * Independent groups and datasets are processed concurrently.
6754
+ */
6755
+ async translate() {
6756
+ const h5File = await this.open();
6757
+ const refs = await this.translateTree(h5File, true);
6758
+ const refSpec = { version: 1, refs };
6759
+ return this.zarrFormat === 3 ? refSpecV2ToV3(refSpec) : refSpec;
6760
+ }
6761
+ /**
6762
+ * Translate the metadata (groups, arrays, attributes) of the whole hierarchy,
6763
+ * without any chunk references. Only HDF5 metadata is read; no data chunks or
6764
+ * variable-length string heaps are touched.
6765
+ */
6766
+ async translateMetadata() {
6767
+ const h5File = await this.open();
6768
+ const refs = await this.translateTree(h5File, false);
6769
+ const refSpec = { version: 1, refs };
6770
+ return this.zarrFormat === 3 ? refSpecV2ToV3(refSpec) : refSpec;
6771
+ }
6772
+ /**
6773
+ * Translate a single HDF5 group or dataset into Zarr v2 references
6774
+ * (keys are relative to the hierarchy root, e.g. "obs/.zattrs" or "X/data/0").
6775
+ *
6776
+ * @param path Path of the node within the hierarchy ("" for the root).
6777
+ * @param obj The HDF5 group or dataset at that path.
6778
+ * @param options.chunks Whether to include chunk references (and inline data).
6779
+ */
6780
+ async translateNode(path, obj, options = {}) {
6781
+ const refs = {};
6782
+ if (obj instanceof Dataset) {
6783
+ await this.processDataset(refs, path, obj, options.chunks ?? true);
6784
+ } else {
6785
+ await this.processGroup(refs, path, obj);
6786
+ }
6787
+ return refs;
6788
+ }
6789
+ /**
6790
+ * Translate a node and all of its descendants. Children are processed
6791
+ * concurrently, but the returned refs are in depth-first order
6792
+ * (the same order a sequential walk would produce).
6793
+ */
6794
+ async translateTree(root2, chunks) {
6795
+ const parts = [];
6796
+ const visit = async (path, obj) => {
6797
+ const own = this.translateNode(path, obj, { chunks });
6798
+ if (!(obj instanceof Group2))
6799
+ return [await own];
6800
+ const children = await Promise.all(obj.keys.map(async (key) => {
6801
+ const childPath = path ? `${path}/${key}` : key;
6802
+ let child;
6803
+ try {
6804
+ child = await obj.get(key);
6805
+ } catch {
6806
+ return [];
6807
+ }
6808
+ if (!child)
6809
+ return [];
6810
+ return visit(childPath, child);
6811
+ }));
6812
+ return [await own, ...children.flat()];
6813
+ };
6814
+ parts.push(...await visit("", root2));
6815
+ return Object.assign({}, ...parts);
6816
+ }
6817
+ /**
6818
+ * Process an HDF5 group into Zarr group metadata.
6819
+ */
6820
+ async processGroup(refs, path, group) {
6821
+ const prefix = path ? `${path}/` : "";
6822
+ refs[`${prefix}.zgroup`] = jsonStringifySorted({
6823
+ zarr_format: 2
6824
+ });
6825
+ await this.transferAttrs(refs, group, path);
6826
+ }
6827
+ /**
6828
+ * Process an HDF5 dataset into Zarr array metadata and (optionally) chunk references.
6829
+ */
6830
+ async processDataset(refs, path, dataset, includeChunks) {
6831
+ const dataobjects = dataset._dataobjects;
6832
+ const shape = dataobjects.shape;
6833
+ if (!shape || shape.length === 0) {
6834
+ await this.processScalarDataset(refs, path, dataset, dataobjects, includeChunks);
6835
+ return;
6836
+ }
6837
+ const rawDtype = dataobjects.dtype;
6838
+ const isVlen = Array.isArray(rawDtype) && (rawDtype[0] === "VLEN_STRING" || rawDtype[0] === "VLEN_SEQUENCE");
6839
+ const isFixedString = typeof rawDtype === "string" && /^S\d+/.test(rawDtype);
6840
+ const isCompound = Array.isArray(rawDtype) && rawDtype[0] === "COMPOUND";
6841
+ if (isCompound) {
6842
+ return;
6843
+ }
6844
+ const dtype = jsfiveDtypeToZarr(rawDtype);
6845
+ const chunks = dataobjects.chunks || [...shape];
6846
+ const filterPipeline = dataobjects.filter_pipeline;
6847
+ const { compressor, zarrFilters } = decodeFilterPipeline(filterPipeline);
6848
+ let fillValue = null;
6849
+ if (dtype.startsWith("|S")) {
6850
+ fillValue = "";
6851
+ } else if (dtype === "|O") {
6852
+ fillValue = null;
6853
+ } else if (/[<>|]f\d/.test(dtype)) {
6854
+ fillValue = 0;
6855
+ } else {
6856
+ fillValue = 0;
6857
+ }
6858
+ fillValue = encodeFillValue(fillValue, dtype);
6859
+ const zarrMeta = {
6860
+ zarr_format: 2,
6861
+ shape: [...shape],
6862
+ chunks: [...chunks],
6863
+ dtype,
6864
+ compressor,
6865
+ fill_value: fillValue,
6866
+ order: "C",
6867
+ filters: zarrFilters
6868
+ };
6869
+ if (isVlenString(rawDtype)) {
6870
+ zarrMeta.dtype = "|O";
6871
+ zarrMeta.fill_value = null;
6872
+ zarrMeta.filters = [JSON2_FILTER];
6873
+ zarrMeta.compressor = null;
6874
+ }
6875
+ refs[`${path}/.zarray`] = serializeZarrayMeta(zarrMeta);
6876
+ await this.transferAttrs(refs, dataset, path);
6877
+ const dims = this.getArrayDims(dataset, path, shape);
6878
+ const existingAttrsKey = `${path}/.zattrs`;
6879
+ const existingAttrs = refs[existingAttrsKey] ? JSON.parse(refs[existingAttrsKey]) : {};
6880
+ existingAttrs["_ARRAY_DIMENSIONS"] = dims;
6881
+ refs[existingAttrsKey] = jsonStringifySorted(existingAttrs);
6882
+ if (!includeChunks)
6883
+ return;
6884
+ if (isVlen) {
6885
+ await this.inlineVlenData(refs, path, dataset, shape, chunks);
6886
+ } else if (isFixedString) {
6887
+ await this.inlineFixedStringData(refs, path, dataset, shape, chunks, rawDtype);
6888
+ } else {
6889
+ await this.processChunkReferences(refs, path, dataobjects, shape, chunks, dtype);
6890
+ }
6891
+ }
6892
+ /**
6893
+ * Process a scalar dataset (shape=[]).
6894
+ */
6895
+ async processScalarDataset(refs, path, dataset, dataobjects, includeChunks) {
6896
+ const rawDtype = dataobjects.dtype;
6897
+ const isVlen = Array.isArray(rawDtype) && (rawDtype[0] === "VLEN_STRING" || rawDtype[0] === "VLEN_SEQUENCE");
6898
+ const dtype = jsfiveDtypeToZarr(rawDtype);
6899
+ let fillValue = null;
6900
+ if (dtype === "|O")
6901
+ fillValue = null;
6902
+ else if (/[<>|]f\d/.test(dtype))
6903
+ fillValue = 0;
6904
+ else
6905
+ fillValue = 0;
6906
+ fillValue = encodeFillValue(fillValue, dtype);
6907
+ const zarrMeta = {
6908
+ zarr_format: 2,
6909
+ shape: [],
6910
+ chunks: [],
6911
+ dtype,
6912
+ compressor: null,
6913
+ fill_value: fillValue,
6914
+ order: "C",
6915
+ filters: null
6916
+ };
6917
+ if (isVlen) {
6918
+ zarrMeta.dtype = "|O";
6919
+ zarrMeta.fill_value = null;
6920
+ zarrMeta.filters = [JSON2_FILTER];
6921
+ }
6922
+ refs[`${path}/.zarray`] = serializeZarrayMeta(zarrMeta);
6923
+ await this.transferAttrs(refs, dataset, path);
6924
+ const existingAttrsKey = `${path}/.zattrs`;
6925
+ const existingAttrs = refs[existingAttrsKey] ? JSON.parse(refs[existingAttrsKey]) : {};
6926
+ existingAttrs["_ARRAY_DIMENSIONS"] = [];
6927
+ refs[existingAttrsKey] = jsonStringifySorted(existingAttrs);
6928
+ if (!includeChunks)
6929
+ return;
6930
+ if (isVlen) {
6931
+ try {
6932
+ const data = await dataobjects.get_data();
6933
+ const strings = Array.isArray(data) ? data.map(String) : [String(data)];
6934
+ refs[`${path}/0`] = encodeJson2(strings, []);
6935
+ } catch {
6936
+ }
6937
+ } else {
6938
+ try {
6939
+ const data = await dataobjects.get_data();
6940
+ const value = Array.isArray(data) ? data[0] : data;
6941
+ const bytes = encodeScalar(value, dtype);
6942
+ if (bytes) {
6943
+ refs[`${path}/0`] = inlineBytes(bytes);
6944
+ }
6945
+ } catch {
6946
+ }
6947
+ }
6948
+ }
6949
+ /**
6950
+ * Inline vlen string data using json2 codec encoding.
6951
+ */
6952
+ async inlineVlenData(refs, path, dataset, shape, chunks) {
6953
+ try {
6954
+ const data = await dataset._dataobjects.get_data();
6955
+ if (data === null || data === void 0)
6956
+ return;
6957
+ const strings = Array.isArray(data) ? data.map(String) : [String(data)];
6958
+ const key = `${path}/${chunks.map(() => "0").join(".")}`;
6959
+ refs[key] = encodeJson2(strings, shape);
6960
+ const zarrMeta = JSON.parse(refs[`${path}/.zarray`]);
6961
+ zarrMeta.dtype = "|O";
6962
+ zarrMeta.fill_value = null;
6963
+ zarrMeta.filters = [JSON2_FILTER];
6964
+ zarrMeta.compressor = null;
6965
+ refs[`${path}/.zarray`] = serializeZarrayMeta(zarrMeta);
6966
+ } catch {
6967
+ }
6968
+ }
6969
+ /**
6970
+ * Inline fixed-length string data.
6971
+ */
6972
+ async inlineFixedStringData(refs, path, dataset, shape, chunks, rawDtype) {
6973
+ try {
6974
+ const data = await dataset._dataobjects.get_data();
6975
+ if (data === null || data === void 0)
6976
+ return;
6977
+ const strings = Array.isArray(data) ? data.map(String) : [String(data)];
6978
+ const key = `${path}/${chunks.map(() => "0").join(".")}`;
6979
+ const sizeMatch = rawDtype.match(/S(\d+)/);
6980
+ const strSize = sizeMatch ? parseInt(sizeMatch[1], 10) : 1;
6981
+ const totalSize = strings.length * strSize;
6982
+ const buf = new Uint8Array(totalSize);
6983
+ const encoder = new TextEncoder();
6984
+ for (let i = 0; i < strings.length; i++) {
6985
+ const encoded = encoder.encode(strings[i]);
6986
+ buf.set(encoded.subarray(0, strSize), i * strSize);
6987
+ }
6988
+ refs[key] = inlineBytes(buf);
6989
+ } catch {
6990
+ }
6991
+ }
6992
+ /**
6993
+ * Process chunk references for non-string datasets.
6994
+ * Uses file byte offset references for chunked and contiguous data.
6995
+ */
6996
+ async processChunkReferences(refs, path, dataobjects, shape, chunks, dtype) {
6997
+ const storageInfo = getStorageInfo(dataobjects);
6998
+ if (storageInfo.layoutClass === 1 && storageInfo.contiguousOffset !== void 0) {
6999
+ const key = `${path}/${shape.map(() => "0").join(".")}`;
7000
+ const offset = storageInfo.contiguousOffset;
7001
+ const size = storageInfo.contiguousSize;
7002
+ if (size <= this.inlineThreshold) {
7003
+ const ab = await fetchRange(this.source, offset, size);
7004
+ refs[key] = inlineBytes(new Uint8Array(ab));
7005
+ } else {
7006
+ refs[key] = [this.url, offset, size];
7007
+ }
7008
+ } else if (storageInfo.layoutClass === 2 && storageInfo.chunkAddress !== void 0) {
7009
+ const filterPipeline = dataobjects.filter_pipeline;
7010
+ const hasFilters = filterPipeline && filterPipeline.length > 0;
7011
+ let itemSize = 1;
7012
+ const sizeMatch = dtype.match(/\d+$/);
7013
+ if (sizeMatch)
7014
+ itemSize = parseInt(sizeMatch[0], 10);
7015
+ const chunkElements = chunks.reduce((a, b) => a * b, 1);
7016
+ const uncompressedChunkBytes = chunkElements * itemSize;
7017
+ let hasF32 = false;
7018
+ if (filterPipeline) {
7019
+ for (const f of filterPipeline) {
7020
+ if (f.get("filter_id") === 3) {
7021
+ hasF32 = true;
7022
+ break;
7023
+ }
7024
+ }
7025
+ }
7026
+ const chunkLocations = await getChunkLocations(this.source, storageInfo.chunkAddress, storageInfo.chunkDims, shape, storageInfo.chunkShape);
7027
+ const entries = await Promise.all(chunkLocations.map(async (loc) => {
7028
+ const key = `${path}/${loc.chunkIndex.join(".")}`;
7029
+ let size = hasFilters ? loc.size : uncompressedChunkBytes;
7030
+ if (hasF32) {
7031
+ size -= 4;
7032
+ }
7033
+ if (size <= this.inlineThreshold) {
7034
+ const ab = await fetchRange(this.source, loc.offset, size);
7035
+ return [key, inlineBytes(new Uint8Array(ab))];
7036
+ }
7037
+ return [key, [this.url, loc.offset, size]];
7038
+ }));
7039
+ for (const [key, value] of entries)
7040
+ refs[key] = value;
7041
+ } else if (storageInfo.layoutClass === 1) ;
7042
+ }
7043
+ /**
7044
+ * Get dimension names for a dataset.
7045
+ */
7046
+ getArrayDims(dataset, path, shape) {
7047
+ if (!shape || shape.length === 0)
7048
+ return [];
7049
+ const rank = shape.length;
7050
+ const dims = [];
7051
+ for (let i = 0; i < rank; i++) {
7052
+ dims.push(`phony_dim_${i}`);
7053
+ }
7054
+ return dims;
7055
+ }
7056
+ /**
7057
+ * Transfer attributes from an HDF5 object to the Zarr .zattrs.
7058
+ */
7059
+ async transferAttrs(refs, h5obj, path) {
7060
+ const attrs = {};
7061
+ let rawAttrs;
7062
+ try {
7063
+ rawAttrs = await h5obj.get_attrs();
7064
+ if (!rawAttrs || typeof rawAttrs !== "object")
7065
+ return;
7066
+ } catch {
7067
+ return;
7068
+ }
7069
+ let enumAttrs = /* @__PURE__ */ new Map();
7070
+ try {
7071
+ const dataobjects = h5obj._dataobjects;
7072
+ if (dataobjects) {
7073
+ enumAttrs = getAttrDatatypeClasses(dataobjects);
7074
+ }
7075
+ } catch {
7076
+ }
7077
+ for (const [name, value] of Object.entries(rawAttrs)) {
7078
+ if (HIDDEN_ATTRS.has(name))
7079
+ continue;
7080
+ if (name === "_FillValue")
7081
+ continue;
7082
+ let v = value;
7083
+ if (v === null || v === void 0) {
7084
+ v = "";
7085
+ }
7086
+ if (v === "DIMENSION_SCALE")
7087
+ continue;
7088
+ if (enumAttrs.get(name) === DATATYPE_ENUMERATED) {
7089
+ if (v === 0)
7090
+ v = false;
7091
+ else if (v === 1)
7092
+ v = true;
7093
+ }
7094
+ if (ArrayBuffer.isView(v) && !(v instanceof DataView)) {
7095
+ v = Array.from(v);
7096
+ }
7097
+ if (Array.isArray(v) && v.length === 1) {
7098
+ v = v[0];
7099
+ }
7100
+ attrs[name] = v;
7101
+ }
7102
+ if (Object.keys(attrs).length > 0) {
7103
+ const key = path ? `${path}/.zattrs` : ".zattrs";
7104
+ refs[key] = jsonStringifySorted(attrs);
7105
+ }
7106
+ }
7107
+ }
7108
+ function refSpecToConsolidatedMetadataV3(refSpec) {
7109
+ const rootValue = refSpec.refs["zarr.json"];
7110
+ if (typeof rootValue !== "string") {
7111
+ throw new Error("Reference spec does not contain a v3 root zarr.json");
7112
+ }
7113
+ const root2 = JSON.parse(rootValue);
7114
+ const metadata = {};
7115
+ for (const [key, value] of Object.entries(refSpec.refs)) {
7116
+ if (key.endsWith("/zarr.json") && typeof value === "string") {
7117
+ metadata[key.slice(0, -"/zarr.json".length)] = JSON.parse(value);
7118
+ }
7119
+ }
7120
+ return {
7121
+ ...root2,
7122
+ consolidated_metadata: {
7123
+ kind: "inline",
7124
+ must_understand: false,
7125
+ metadata
7126
+ }
7127
+ };
7128
+ }
7129
+ let table = new Uint8Array(128);
7130
+ for (let i = 0; i < 64; i++) {
7131
+ table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;
7132
+ }
7133
+ function to_binary(base64) {
7134
+ const n = base64.length;
7135
+ const bytes = new Uint8Array(
7136
+ // @ts-ignore
7137
+ (n - (base64[n - 1] === "=") - (base64[n - 2] === "=")) * 3 / 4 | 0
7138
+ );
7139
+ for (let i = 0, j = 0; i < n; ) {
7140
+ const c0 = table[base64.charCodeAt(i++)];
7141
+ const c1 = table[base64.charCodeAt(i++)];
7142
+ const c2 = table[base64.charCodeAt(i++)];
7143
+ const c3 = table[base64.charCodeAt(i++)];
7144
+ bytes[j++] = c0 << 2 | c1 >> 4;
7145
+ bytes[j++] = c1 << 4 | c2 >> 2;
7146
+ bytes[j++] = c2 << 6 | c3;
7147
+ }
7148
+ return bytes;
7149
+ }
7150
+ function evictOnReject(cache, key, promise) {
7151
+ promise.catch(() => {
7152
+ if (cache.peek(key) === promise)
7153
+ cache.delete(key);
7154
+ });
7155
+ }
7156
+ class HdfStore {
7157
+ #source;
7158
+ #converter;
7159
+ /** The root group; kept outside the LRU caches so it is never evicted. */
7160
+ #root;
7161
+ #nodes;
7162
+ #nodeRefs;
7163
+ #consolidated = null;
7164
+ constructor(source, converter, file, options) {
7165
+ this.#source = source;
7166
+ this.#converter = converter;
7167
+ this.#root = Promise.resolve(file);
7168
+ this.#nodes = new QuickLRU({ maxSize: options.maxCachedNodes ?? 1e3 });
7169
+ this.#nodeRefs = new QuickLRU({ maxSize: options.maxCachedRefs ?? 500 });
7170
+ }
7171
+ /**
7172
+ * @param {AsyncReadable} hdfSource Assumed to be a zarrita Store,
7173
+ * with the HDF5 file located at the root key "/". In other words,
7174
+ * hdfSource.getRange("/", { offset, length }) should return the
7175
+ * corresponding byte range from the HDF5 file.
7176
+ * @returns {Promise<HdfStore>} An HdfStore instance which exposes the HDF5
7177
+ * file as a Zarr v3 hierarchy.
7178
+ * @param {HdfStoreOptions} options Sizes of the in-memory LRU caches.
7179
+ */
7180
+ static async fromStore(hdfSource, options = {}) {
7181
+ const converter = new SingleHdf5ToZarr(hdfSource, { url: null, zarrFormat: 2 });
7182
+ const file = await converter.open();
7183
+ return new HdfStore(hdfSource, converter, file, options);
7184
+ }
7185
+ async get(key, opts) {
7186
+ const path = key.replace(/^\/+/, "");
7187
+ const parts = path === "" ? [] : path.split("/");
7188
+ if (parts[parts.length - 1] === "zarr.json") {
7189
+ const nodePath2 = parts.slice(0, -1).join("/");
7190
+ const refs2 = await this.#getNodeRefs(nodePath2, false);
7191
+ return this.#resolveRef(refs2?.[path], opts);
7192
+ }
7193
+ let nodePath = "";
7194
+ for (const part of parts) {
7195
+ const node = await this.#resolveNode(nodePath);
7196
+ if (!node)
7197
+ return void 0;
7198
+ if (node instanceof Dataset)
7199
+ break;
7200
+ nodePath = nodePath ? `${nodePath}/${part}` : part;
7201
+ }
7202
+ const chunkKey = path.slice(nodePath.length + 1);
7203
+ if (nodePath === path || !(chunkKey === "c" || chunkKey.startsWith("c/")) || !(await this.#resolveNode(nodePath) instanceof Dataset)) {
7204
+ return void 0;
7205
+ }
7206
+ const refs = await this.#getNodeRefs(nodePath, true);
7207
+ return this.#resolveRef(refs?.[path], opts);
7208
+ }
7209
+ /**
7210
+ * @returns The root zarr.json document with inline consolidated metadata
7211
+ * (zarr-python format) describing every group and array in the hierarchy.
7212
+ * Reads the metadata of every node in the file (but no chunk data); nodes
7213
+ * already opened through this store are not read again.
7214
+ */
7215
+ getConsolidatedMetadata() {
7216
+ if (!this.#consolidated) {
7217
+ this.#consolidated = this.#collectMetadata("").then((parts) => refSpecToConsolidatedMetadataV3({ refs: Object.assign({}, ...parts) }));
7218
+ this.#consolidated.catch(() => {
7219
+ this.#consolidated = null;
7220
+ });
7221
+ }
7222
+ return this.#consolidated;
7223
+ }
7224
+ /**
7225
+ * Metadata refs for a node and all of its descendants, in depth-first order.
7226
+ * Sibling subtrees are visited concurrently.
7227
+ */
7228
+ async #collectMetadata(path) {
7229
+ const [node, own] = await Promise.all([
7230
+ this.#resolveNode(path),
7231
+ this.#getNodeRefs(path, false)
7232
+ ]);
7233
+ if (!(node instanceof Group2))
7234
+ return [own];
7235
+ const children = await Promise.all(node.keys.map((key) => this.#collectMetadata(path ? `${path}/${key}` : key)));
7236
+ return [own, ...children.flat()];
7237
+ }
7238
+ /**
7239
+ * Resolve the HDF5 group or dataset at a hierarchy path (cached).
7240
+ * Returns null if there is no such node.
7241
+ */
7242
+ #resolveNode(path) {
7243
+ if (path === "")
7244
+ return this.#root;
7245
+ let node = this.#nodes.get(path);
7246
+ if (!node) {
7247
+ const idx = path.lastIndexOf("/");
7248
+ const parentPath = idx === -1 ? "" : path.slice(0, idx);
7249
+ const name = path.slice(idx + 1);
7250
+ node = this.#resolveNode(parentPath).then(async (parent) => {
7251
+ if (!(parent instanceof Group2) || !(name in parent._links))
7252
+ return null;
7253
+ try {
7254
+ return await parent.get(name);
7255
+ } catch {
7256
+ return null;
7257
+ }
7258
+ });
7259
+ evictOnReject(this.#nodes, path, node);
7260
+ this.#nodes.set(path, node);
7261
+ }
7262
+ return node;
7263
+ }
7264
+ /**
7265
+ * Zarr v3 references for a single node (cached). Metadata-only refs contain
7266
+ * just the node's zarr.json; with `chunks`, its chunk references too.
7267
+ */
7268
+ #getNodeRefs(path, chunks) {
7269
+ const cacheKey = `${chunks ? "c" : "m"}:${path}`;
7270
+ let refs = this.#nodeRefs.get(cacheKey);
7271
+ if (!refs) {
7272
+ refs = (async () => {
7273
+ const node = await this.#resolveNode(path);
7274
+ if (!node)
7275
+ return {};
7276
+ const v2Refs = await this.#converter.translateNode(path, node, { chunks });
7277
+ return refSpecV2ToV3({ refs: v2Refs }).refs;
7278
+ })();
7279
+ evictOnReject(this.#nodeRefs, cacheKey, refs);
7280
+ this.#nodeRefs.set(cacheKey, refs);
7281
+ }
7282
+ return refs;
7283
+ }
7284
+ async #resolveRef(ref, opts) {
7285
+ if (ref === void 0)
7286
+ return void 0;
7287
+ if (typeof ref === "string") {
7288
+ return ref.startsWith("base64:") ? to_binary(ref.slice("base64:".length)) : new TextEncoder().encode(ref);
7289
+ }
7290
+ const [, offset, length] = ref;
7291
+ return this.#source.getRange("/", { offset, length }, opts);
7292
+ }
7293
+ }
7294
+ const withGetRange = defineStoreExtension((innerStore) => ({
7295
+ async getRange(...args) {
7296
+ const [key, range2, opts] = args;
7297
+ if (typeof innerStore.getRange === "function") {
7298
+ return innerStore.getRange(key, range2, opts);
7299
+ }
7300
+ const arr = await innerStore.get(key, opts);
7301
+ if (!arr)
7302
+ return void 0;
7303
+ const { buffer } = arr;
7304
+ if ("suffixLength" in range2) {
7305
+ const { suffixLength } = range2;
7306
+ return new Uint8Array(buffer, buffer.byteLength - suffixLength, suffixLength);
7307
+ }
7308
+ if ("offset" in range2 && "length" in range2) {
7309
+ const { offset, length } = range2;
7310
+ return new Uint8Array(buffer, offset, length);
7311
+ }
7312
+ throw new Error("Invalid rangeQuery value.");
7313
+ }
7314
+ }));
7315
+ function isAbortError(error) {
7316
+ return error?.name === "AbortError";
7317
+ }
7318
+ function raceAbortSignal(promise, signal) {
7319
+ if (!signal)
7320
+ return promise;
7321
+ if (signal.aborted)
7322
+ return Promise.reject(signal.reason);
7323
+ return new Promise((resolve2, reject) => {
7324
+ const onAbort = () => reject(signal.reason);
7325
+ signal.addEventListener("abort", onAbort, { once: true });
7326
+ promise.then((value) => {
7327
+ signal.removeEventListener("abort", onAbort);
7328
+ resolve2(value);
7329
+ }, (error) => {
7330
+ signal.removeEventListener("abort", onAbort);
7331
+ reject(error);
7332
+ });
7333
+ });
7334
+ }
7335
+ function createSharedAbort(onAbort) {
7336
+ const controller = new AbortController();
7337
+ let activeCallers = 0;
7338
+ const cleanups = [];
7339
+ function attach(callerSignal) {
7340
+ if (controller.signal.aborted)
7341
+ return;
7342
+ activeCallers += 1;
7343
+ if (!callerSignal)
7344
+ return;
7345
+ const onCallerAbort = () => {
7346
+ activeCallers -= 1;
7347
+ if (activeCallers === 0) {
7348
+ controller.abort(callerSignal.reason);
7349
+ onAbort?.();
7350
+ }
7351
+ };
7352
+ if (callerSignal.aborted) {
7353
+ onCallerAbort();
7354
+ return;
7355
+ }
7356
+ callerSignal.addEventListener("abort", onCallerAbort, { once: true });
7357
+ cleanups.push(() => callerSignal.removeEventListener("abort", onCallerAbort));
7358
+ }
7359
+ function release() {
7360
+ cleanups.forEach((cleanup) => cleanup());
7361
+ cleanups.length = 0;
7362
+ }
7363
+ return { signal: controller.signal, attach, release };
7364
+ }
7365
+ async function relaxedFetch(...args) {
7366
+ const response = await fetch(...args);
7367
+ if (response.status === 403) {
7368
+ return new Response(null, { status: 404 });
7369
+ }
7370
+ return response;
7371
+ }
7372
+ const CHUNK_GC_TIME = 3e4;
7373
+ const UNDEFINED_SENTINEL = null;
7374
+ const MAX_ABORT_RETRIES = 2;
7375
+ const UNCACHED_READ = "vitessceUncachedRead";
7376
+ function splitReadOptions(opts) {
7377
+ if (!opts || !opts[UNCACHED_READ]) {
7378
+ return [false, opts];
7379
+ }
7380
+ const rest = { ...opts };
7381
+ delete rest[UNCACHED_READ];
7382
+ return [true, rest];
7383
+ }
7384
+ function makeCacheFetch(queryClient) {
7385
+ const inflight = /* @__PURE__ */ new Map();
7386
+ function read(cacheKey, fn) {
7387
+ if (!queryClient) {
7388
+ return (signal) => Promise.resolve(fn(signal));
7389
+ }
7390
+ return async (signal) => {
7391
+ const result = await queryClient.fetchQuery({
7392
+ queryKey: cacheKey,
7393
+ queryFn: async () => await fn(signal) ?? UNDEFINED_SENTINEL,
7394
+ staleTime: Infinity,
7395
+ gcTime: CHUNK_GC_TIME
7396
+ });
7397
+ return result === UNDEFINED_SENTINEL ? void 0 : result;
7398
+ };
7399
+ }
7400
+ function readShared(cacheKey, fn, signal) {
7401
+ const key = JSON.stringify(cacheKey);
7402
+ let entry = inflight.get(key);
7403
+ if (!entry) {
7404
+ const forget = () => {
7405
+ if (inflight.get(key) === entry)
7406
+ inflight.delete(key);
7407
+ };
7408
+ const shared = createSharedAbort(forget);
7409
+ const newEntry = {
7410
+ shared,
7411
+ promise: read(cacheKey, fn)(shared.signal).finally(() => {
7412
+ shared.release();
7413
+ forget();
7414
+ })
7415
+ };
7416
+ entry = newEntry;
7417
+ inflight.set(key, newEntry);
7418
+ }
7419
+ entry.shared.attach(signal);
7420
+ return raceAbortSignal(entry.promise, signal);
7421
+ }
7422
+ return async (cacheKey, fn, signal) => {
7423
+ for (let attempt = 0; ; attempt++) {
7424
+ try {
7425
+ return await readShared(cacheKey, fn, signal);
7426
+ } catch (error) {
7427
+ if (signal?.aborted || !isAbortError(error) || attempt >= MAX_ABORT_RETRIES) {
7428
+ throw error;
7429
+ }
7430
+ }
7431
+ }
7432
+ };
7433
+ }
7434
+ function splitSignal(opts) {
7435
+ const { signal, ...init } = opts ?? {};
7436
+ return [signal ?? void 0, init];
7437
+ }
7438
+ const withQueryClientCache = defineStoreExtension((innerStore, extOpts) => {
7439
+ const { cacheKeyPrefix, queryClient } = extOpts;
7440
+ const cacheFetch = makeCacheFetch(queryClient);
7441
+ return {
7442
+ async get(...args) {
7443
+ const [key, opts] = args;
7444
+ const [uncached, rest] = splitReadOptions(opts);
7445
+ if (uncached) {
7446
+ return innerStore.get(key, rest);
7447
+ }
7448
+ const [signal, init] = splitSignal(rest);
7449
+ return cacheFetch(["zarrStore", cacheKeyPrefix, key], (sharedSignal) => innerStore.get(key, { ...init, signal: sharedSignal }), signal);
7450
+ },
7451
+ async getRange(...args) {
7452
+ const [key, range2, opts] = args;
7453
+ const [uncached, rest] = splitReadOptions(opts);
7454
+ if (typeof innerStore.getRange !== "function") {
7455
+ throw new Error("innerStore does not implement getRange");
7456
+ }
7457
+ if (uncached) {
7458
+ return innerStore.getRange(key, range2, rest);
7459
+ }
7460
+ const [signal, init] = splitSignal(rest);
7461
+ return cacheFetch(["zarrStore", cacheKeyPrefix, key, range2], (sharedSignal) => {
7462
+ if (typeof innerStore.getRange !== "function") {
7463
+ throw new Error("innerStore does not implement getRange");
7464
+ }
7465
+ return innerStore.getRange(key, range2, { ...init, signal: sharedSignal });
7466
+ }, signal);
7467
+ }
7468
+ };
7469
+ });
7470
+ function transformEntriesForZipFileStore(entries) {
7471
+ const topLevelZarrDirectories = new Set(Object.keys(entries).map((k) => k.split("/")[0]).filter((firstPathItem) => firstPathItem?.endsWith(".zarr")));
7472
+ if (topLevelZarrDirectories.size === 0) {
7473
+ return entries;
7474
+ }
7475
+ if (topLevelZarrDirectories.size > 1) {
7476
+ throw Error("expected exactly one top-level .zarr directory");
7477
+ }
7478
+ const topLevelZarrDirectory = Array.from(topLevelZarrDirectories)[0];
7479
+ const newEntries = Object.fromEntries(Object.entries(entries).map(([k, v]) => {
7480
+ let newKey = k;
7481
+ if (k.split("/")[0] === topLevelZarrDirectory) {
7482
+ newKey = k.substring(topLevelZarrDirectory.length + 1);
7483
+ }
7484
+ return [newKey, v];
7485
+ }));
7486
+ return newEntries;
7487
+ }
7488
+ function applyStoreExtensions(store, url, queryClient) {
7489
+ return extendStore(
7490
+ store,
7491
+ // Ensure getRange is implemented (required by withRangeCoalescing).
7492
+ withGetRange,
7493
+ // Concurrent getRange calls for the same key (e.g. sharded chunks)
7494
+ // within a single microtask are merged into fewer, larger range requests.
7495
+ (s) => withRangeCoalescing(s),
7496
+ // Wrap remote stores in a read-through cache, so that concurrent reads of the
7497
+ // same chunk (e.g. multiple embedding dims within one chunk column-block) share
7498
+ // one request instead of downloading it once per reader.
7499
+ (s) => withQueryClientCache(s, { cacheKeyPrefix: url, queryClient })
7500
+ );
7501
+ }
7502
+ function createLazyStore(storePromise) {
7503
+ const innerStorePromise = storePromise.then((innerStore) => withGetRange(innerStore));
7504
+ return {
7505
+ async get(...args) {
7506
+ const innerStore = await innerStorePromise;
7507
+ return innerStore.get(...args);
7508
+ },
7509
+ async getRange(...args) {
7510
+ const innerStore = await innerStorePromise;
7511
+ if (typeof innerStore.getRange !== "function") {
7512
+ throw new Error("innerStore does not implement getRange");
7513
+ }
7514
+ return innerStore.getRange(...args);
7515
+ }
7516
+ };
7517
+ }
7518
+ function createSingleFileStore(url, requestInit2) {
7519
+ async function fetchBytes(range2, opts) {
7520
+ const headers = new Headers(requestInit2?.headers);
7521
+ new Headers(opts?.headers).forEach((value, name) => headers.set(name, value));
7522
+ if (range2) {
7523
+ headers.set("Range", "suffixLength" in range2 ? `bytes=-${range2.suffixLength}` : `bytes=${range2.offset}-${range2.offset + range2.length - 1}`);
7524
+ }
7525
+ const response = await fetch(url, { ...requestInit2, ...opts, headers });
7526
+ if (response.status === 404 || response.status === 403) {
7527
+ return void 0;
7528
+ }
7529
+ if (!response.ok) {
7530
+ throw new Error(`Unexpected response status ${response.status} ${response.statusText} for ${url}`);
7531
+ }
7532
+ return new Uint8Array(await response.arrayBuffer());
7533
+ }
7534
+ return {
7535
+ async get(_key, opts) {
7536
+ return fetchBytes(null, opts);
7537
+ },
7538
+ async getRange(_key, range2, opts) {
7539
+ return fetchBytes(range2, opts);
7540
+ }
7541
+ };
7542
+ }
7543
+ function createReferenceStore(url, refSpecUrl, requestInit2) {
7544
+ const referenceSpecPromise = fetch(refSpecUrl).then((res) => res.json()).then((referenceSpec) => {
7545
+ const isVersion1 = referenceSpec.version === 1 && typeof referenceSpec.refs === "object";
7546
+ const refs = isVersion1 ? referenceSpec.refs : referenceSpec;
7547
+ const newRefs = Object.fromEntries(Object.entries(refs).map(([key, entry]) => {
7548
+ if (Array.isArray(entry) && entry.length >= 1) {
7549
+ return [key, [url, ...entry.slice(1)]];
7550
+ }
7551
+ return [key, entry];
7552
+ }));
7553
+ return isVersion1 ? { ...referenceSpec, refs: newRefs } : newRefs;
7554
+ });
7555
+ return ReferenceStore.fromSpec(referenceSpecPromise, { overrides: requestInit2 });
7556
+ }
7557
+ function zarrOpenRoot(url, fileType, opts) {
7558
+ let store;
7559
+ if (fileType && fileType.endsWith(".zip")) {
7560
+ store = ZipFileStore.fromUrl(url, {
7561
+ overrides: opts?.requestInit,
7562
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
7563
+ // @ts-ignore
7564
+ transformEntries: transformEntriesForZipFileStore
7565
+ });
7566
+ } else if (fileType && fileType.endsWith(".h5ad")) {
7567
+ if (opts?.refSpecUrl) {
7568
+ store = createLazyStore(createReferenceStore(url, opts.refSpecUrl, opts.requestInit));
7569
+ } else {
7570
+ const hdfSource = withRangeCoalescing(createSingleFileStore(url, opts?.requestInit));
7571
+ store = createLazyStore(HdfStore.fromStore(hdfSource));
7572
+ }
7573
+ } else {
7574
+ store = new FetchStore(url, { overrides: opts?.requestInit, fetch: relaxedFetch });
7575
+ }
7576
+ const extendedStore = applyStoreExtensions(store, url, opts?.queryClient);
7577
+ return root$1(extendedStore);
7578
+ }
7579
+ function flattenOmeAttrs(rootAttrs) {
7580
+ if (rootAttrs && typeof rootAttrs.ome === "object" && rootAttrs.ome !== null) {
7581
+ return { ...rootAttrs.ome, ...rootAttrs };
7582
+ }
7583
+ return rootAttrs;
7584
+ }
7585
+ const BYTES_PER_ELEMENT = {
7586
+ bool: 1,
7587
+ int8: 1,
7588
+ uint8: 1,
7589
+ int16: 2,
7590
+ uint16: 2,
7591
+ int32: 4,
7592
+ uint32: 4,
7593
+ float16: 2,
7594
+ float32: 4,
7595
+ int64: 8,
7596
+ uint64: 8,
7597
+ float64: 8
7598
+ };
7599
+ function getBytesPerElement(dtype) {
7600
+ const name = String(dtype).toLowerCase();
7601
+ if (name in BYTES_PER_ELEMENT) {
7602
+ return BYTES_PER_ELEMENT[name];
7603
+ }
7604
+ const [, bytes] = name.match(/^[<>|=][biuf](\d+)$/) ?? [];
7605
+ return bytes ? Number(bytes) : 8;
7606
+ }
7607
+ class VitessceError extends Error {
7608
+ constructor(message) {
7609
+ super(message);
7610
+ this.name = "VitessceError";
7611
+ }
7612
+ }
7613
+ class DataLoaderError extends VitessceError {
7614
+ constructor(message) {
7615
+ super(message);
7616
+ this.name = "DataLoaderError";
7617
+ }
7618
+ }
7619
+ class ZarrNodeNotFoundError extends DataLoaderError {
7620
+ constructor(message) {
7621
+ super(message);
7622
+ this.name = "ZarrNodeNotFoundError";
7623
+ }
7624
+ }
7625
+ class MatrixTooLargeError extends DataLoaderError {
7626
+ constructor(message) {
7627
+ super(message);
7628
+ this.name = "MatrixTooLargeError";
7629
+ }
7630
+ }
7631
+ class ZarrDataSource {
7632
+ /**
7633
+ * @param {DataSourceParams & { refSpecUrl?: string }} params The parameters object.
7634
+ */
7635
+ constructor({ url, requestInit: requestInit2, refSpecUrl, store, fileType, queryClient }) {
7636
+ log.info("Using a Zarr-based data source. 403 and 404 HTTP responses for Zarr metadata files (.zattrs, .zarray, .zgroup, zarr.json) are to be expected and do not necessarily indicate errors.");
7637
+ this.queryClient = queryClient;
7638
+ if (store) {
7639
+ const extendedStore = applyStoreExtensions(store, url, queryClient);
7640
+ this.storeRoot = root$1(extendedStore);
7641
+ } else if (url) {
7642
+ this.storeRoot = zarrOpenRoot(url, fileType, { requestInit: requestInit2, refSpecUrl, queryClient });
7643
+ } else {
7644
+ throw new Error("Either a store or a URL must be provided to the ZarrDataSource constructor.");
7645
+ }
7646
+ this.nodeCache = /* @__PURE__ */ new Map();
7647
+ }
7648
+ /**
7649
+ * Open the zarr node (array or group) at a path relative to the store root,
7650
+ * memoized per path. A rejected open is dropped again, so a later call
7651
+ * retries instead of re-awaiting a dead promise.
7652
+ * @param {string} path The node path relative to the store root.
7653
+ * @returns {Promise<any>} The zarrita Array or Group.
7654
+ */
7655
+ openNode(path) {
7656
+ const key = path.startsWith("/") ? path : `/${path}`;
3739
7657
  if (!this.nodeCache.has(key)) {
3740
7658
  const promise = open(this.storeRoot.resolve(path)).catch((err) => {
3741
7659
  this.nodeCache.delete(key);
@@ -3860,22 +7778,6 @@ function bigInt64ToNumberArray(data) {
3860
7778
  }
3861
7779
  return data;
3862
7780
  }
3863
- const BYTES_PER_ELEMENT = {
3864
- bool: 1,
3865
- int8: 1,
3866
- uint8: 1,
3867
- int16: 2,
3868
- uint16: 2,
3869
- int32: 4,
3870
- uint32: 4,
3871
- float32: 4,
3872
- int64: 8,
3873
- uint64: 8,
3874
- float64: 8
3875
- };
3876
- function getBytesPerElement(dtype) {
3877
- return BYTES_PER_ELEMENT[dtype] ?? 8;
3878
- }
3879
7781
  function createLimiter(concurrency) {
3880
7782
  let active = 0;
3881
7783
  const queue = [];
@@ -16112,7 +20014,7 @@ const anndataZarrSchema = z.object({
16112
20014
  sampleEdges: annDataSampleEdges
16113
20015
  }).partial();
16114
20016
  anndataZarrSchema.extend({
16115
- refSpecUrl: z.string()
20017
+ refSpecUrl: z.string().optional()
16116
20018
  });
16117
20019
  z.object({
16118
20020
  // TODO: should `image` be a special schema