@query-farm/vgi 0.43.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +5 -2
  2. package/dist/arrow/impl-arrowjs/index.d.ts +1 -1
  3. package/dist/arrow/impl-arrowjs/ipc.d.ts +6 -0
  4. package/dist/arrow/impl-flechette/build.d.ts +2 -2
  5. package/dist/arrow/impl-flechette/canonical.d.ts +1 -1
  6. package/dist/arrow/impl-flechette/index.d.ts +1 -1
  7. package/dist/arrow/impl-flechette/ipc.d.ts +6 -0
  8. package/dist/arrow/index.d.ts +1 -1
  9. package/dist/attach-ticket.d.ts +18 -7
  10. package/dist/catalog/contents-codec.d.ts +7 -0
  11. package/dist/catalog/contents-digest.d.ts +2 -1
  12. package/dist/catalog/interface.d.ts +3 -0
  13. package/dist/catalog/publication-envelope.d.ts +1 -0
  14. package/dist/catalog/publication.d.ts +142 -0
  15. package/dist/catalog/s3-publication.d.ts +38 -0
  16. package/dist/client-entry.js +349 -114
  17. package/dist/client-entry.js.map +16 -14
  18. package/dist/codec/asd.d.ts +7 -1
  19. package/dist/codec/conform.d.ts +51 -0
  20. package/dist/errors.d.ts +5 -1
  21. package/dist/generated/vgi-client.d.ts +6 -14
  22. package/dist/generated/vgi-protocol-schemas.d.ts +2 -0
  23. package/dist/generated/vgi-protocol-types.d.ts +26 -3
  24. package/dist/generated/vgi-service.d.ts +3 -3
  25. package/dist/index.core.d.ts +1 -1
  26. package/dist/index.d.ts +4 -0
  27. package/dist/index.js +955 -118
  28. package/dist/index.js.map +33 -28
  29. package/dist/protocol/dispatch.d.ts +1 -1
  30. package/dist/protocol/handlers/catalog/contents.d.ts +4 -4
  31. package/dist/protocol/handlers/shared.d.ts +2 -1
  32. package/dist/protocol/serializers/shared.d.ts +2 -1
  33. package/dist/rpc-server.d.ts +2 -2
  34. package/dist/serve-entry.js +867 -165
  35. package/dist/serve-entry.js.map +26 -22
  36. package/dist/worker-cf-entry.js +825 -114
  37. package/dist/worker-cf-entry.js.map +31 -27
  38. package/package.json +3 -3
  39. package/src/arrow/impl-arrowjs/index.ts +1 -0
  40. package/src/arrow/impl-arrowjs/ipc.ts +23 -0
  41. package/src/arrow/impl-flechette/build.ts +4 -2
  42. package/src/arrow/impl-flechette/canonical.ts +7 -2
  43. package/src/arrow/impl-flechette/index.ts +1 -0
  44. package/src/arrow/impl-flechette/ipc.ts +19 -0
  45. package/src/arrow/index.ts +1 -1
  46. package/src/attach-ticket.ts +41 -13
  47. package/src/catalog/composite.ts +2 -1
  48. package/src/catalog/contents-codec.ts +77 -0
  49. package/src/catalog/contents-digest.ts +20 -17
  50. package/src/catalog/interface.ts +8 -4
  51. package/src/catalog/publication-envelope.ts +62 -0
  52. package/src/catalog/publication.ts +290 -0
  53. package/src/catalog/read-only.ts +8 -8
  54. package/src/catalog/s3-publication.ts +81 -0
  55. package/src/client/client.ts +15 -24
  56. package/src/codec/asd.ts +45 -3
  57. package/src/codec/conform.ts +194 -0
  58. package/src/errors.ts +27 -7
  59. package/src/functions/registry.ts +3 -2
  60. package/src/generated/vgi-client.ts +7 -16
  61. package/src/generated/vgi-protocol-schemas.ts +13 -6
  62. package/src/generated/vgi-protocol-types.ts +39 -5
  63. package/src/generated/vgi-service.ts +4 -3
  64. package/src/http/fetch.ts +1 -1
  65. package/src/index.core.ts +3 -1
  66. package/src/index.ts +5 -0
  67. package/src/protocol/dispatch.ts +1 -1
  68. package/src/protocol/handlers/catalog/admin.ts +7 -4
  69. package/src/protocol/handlers/catalog/contents.ts +50 -35
  70. package/src/protocol/handlers/shared.ts +8 -2
  71. package/src/protocol/serializers/bind.ts +3 -1
  72. package/src/protocol/serializers/shared.ts +5 -2
  73. package/src/rpc-server.ts +7 -7
@@ -1,5 +1,28 @@
1
1
  // @bun
2
2
  var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ function __accessProp(key) {
7
+ return this[key];
8
+ }
9
+ var __toCommonJS = (from) => {
10
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
11
+ if (entry)
12
+ return entry;
13
+ entry = __defProp({}, "__esModule", { value: true });
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (var key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(entry, key))
17
+ __defProp(entry, key, {
18
+ get: __accessProp.bind(from, key),
19
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
+ });
21
+ }
22
+ __moduleCache.set(from, entry);
23
+ return entry;
24
+ };
25
+ var __moduleCache;
3
26
  var __returnValue = (v) => v;
4
27
  function __exportSetter(name, newValue) {
5
28
  this[name] = __returnValue.bind(null, newValue);
@@ -26,6 +49,11 @@ var __esm = (fn, res, err) => () => {
26
49
  };
27
50
 
28
51
  // src/functions/storage-cf-do.ts
52
+ var exports_storage_cf_do = {};
53
+ __export(exports_storage_cf_do, {
54
+ FunctionStorageCfDo: () => FunctionStorageCfDo
55
+ });
56
+
29
57
  class FunctionStorageCfDo {
30
58
  _baseUrl;
31
59
  _token;
@@ -471,7 +499,7 @@ function resolveStorageFromEnv() {
471
499
  return new FunctionStorageSqlite;
472
500
  }
473
501
  if (backend === "cloudflare-do") {
474
- init_storage_cf_do();
502
+ const { FunctionStorageCfDo } = (init_storage_cf_do(), __toCommonJS(exports_storage_cf_do));
475
503
  return FunctionStorageCfDo.fromEnv();
476
504
  }
477
505
  throw new Error(`Unknown VGI_WORKER_SHARED_STORAGE backend: '${backend}'. Supported: 'memory', 'sqlite', 'cloudflare-do'.`);
@@ -512,6 +540,82 @@ var init_storage = __esm(() => {
512
540
  });
513
541
  });
514
542
 
543
+ // src/arrow/impl-arrowjs/index.ts
544
+ var exports_impl_arrowjs = {};
545
+ __export(exports_impl_arrowjs, {
546
+ DateUnit: () => DateUnit,
547
+ IntervalUnit: () => IntervalUnit,
548
+ TimeUnit: () => TimeUnit,
549
+ UnionMode: () => UnionMode,
550
+ adoptArrowJsShape: () => adoptArrowJsShape,
551
+ backend: () => backend,
552
+ batchFromColumns: () => batchFromColumns,
553
+ batchFromRows: () => batchFromRows,
554
+ batchToScalarDict: () => batchToScalarDict,
555
+ batchToSecretDict: () => batchToSecretDict,
556
+ binary: () => binary,
557
+ bool: () => bool,
558
+ buildStatisticsBatch: () => buildStatisticsBatch,
559
+ columnFromArray: () => columnFromArray,
560
+ date: () => date,
561
+ dateDay: () => dateDay,
562
+ dateMillisecond: () => dateMillisecond,
563
+ decimal: () => decimal,
564
+ decimal128: () => decimal128,
565
+ decimal256: () => decimal256,
566
+ decodeDictValue: () => decodeDictValue,
567
+ denseUnion: () => denseUnion,
568
+ deserializeBatch: () => deserializeBatch,
569
+ deserializeBatches: () => deserializeBatches,
570
+ deserializeSchema: () => deserializeSchema,
571
+ dictionary: () => dictionary,
572
+ duration: () => duration,
573
+ emptyBatch: () => emptyBatch,
574
+ field: () => field,
575
+ filterBatch: () => filterBatch,
576
+ fixedSizeBinary: () => fixedSizeBinary,
577
+ fixedSizeList: () => fixedSizeList,
578
+ float16: () => float16,
579
+ float32: () => float32,
580
+ float64: () => float64,
581
+ int: () => int,
582
+ int16: () => int16,
583
+ int32: () => int32,
584
+ int64: () => int64,
585
+ int8: () => int8,
586
+ interval: () => interval,
587
+ iterRows: () => iterRows,
588
+ largeBinary: () => largeBinary,
589
+ largeUtf8: () => largeUtf8,
590
+ list: () => list,
591
+ map: () => map,
592
+ nullType: () => nullType,
593
+ projectBatch: () => projectBatch,
594
+ projectSchema: () => projectSchema,
595
+ readCanonicalValue: () => readCanonicalValue,
596
+ safeNumber: () => safeNumber,
597
+ schema: () => schema,
598
+ serializeBatch: () => serializeBatch,
599
+ serializeBatches: () => serializeBatches,
600
+ serializeCollectionRows: () => serializeCollectionRows,
601
+ serializeSchema: () => serializeSchema,
602
+ sparseUnion: () => sparseUnion,
603
+ struct: () => struct,
604
+ time: () => time,
605
+ timeMicrosecond: () => timeMicrosecond,
606
+ timeMillisecond: () => timeMillisecond,
607
+ timeNanosecond: () => timeNanosecond,
608
+ timeSecond: () => timeSecond,
609
+ timestamp: () => timestamp,
610
+ uint16: () => uint16,
611
+ uint32: () => uint32,
612
+ uint64: () => uint64,
613
+ uint8: () => uint8,
614
+ union: () => union,
615
+ utf8: () => utf8,
616
+ withBatchMetadata: () => withBatchMetadata
617
+ });
618
+
515
619
  // src/serve-entry.ts
516
620
  import {
517
621
  irohForwardedHeaderIdentityProvider,
@@ -551,6 +655,21 @@ var TypeId = {
551
655
  LargeUtf8: 20,
552
656
  Dictionary: -1
553
657
  };
658
+ function isInt(t) {
659
+ return t.typeId === TypeId.Int;
660
+ }
661
+ function isFloat(t) {
662
+ return t.typeId === TypeId.Float;
663
+ }
664
+ function isBinary(t) {
665
+ return t.typeId === TypeId.Binary || t.typeId === TypeId.LargeBinary;
666
+ }
667
+ function isUtf8(t) {
668
+ return t.typeId === TypeId.Utf8 || t.typeId === TypeId.LargeUtf8;
669
+ }
670
+ function isBool(t) {
671
+ return t.typeId === TypeId.Bool;
672
+ }
554
673
  function isDecimal(t) {
555
674
  return t.typeId === TypeId.Decimal;
556
675
  }
@@ -563,6 +682,9 @@ function isStruct(t) {
563
682
  function isMap(t) {
564
683
  return t.typeId === TypeId.Map;
565
684
  }
685
+ function isDictionary(t) {
686
+ return t.typeId === TypeId.Dictionary;
687
+ }
566
688
  function typeSignature(t) {
567
689
  if (t == null)
568
690
  return "null";
@@ -599,79 +721,6 @@ function typeSignature(t) {
599
721
  return Array.isArray(a.children) ? `${t.typeId}<${kids()}>` : String(t.typeId);
600
722
  }
601
723
  }
602
- // src/arrow/impl-arrowjs/index.ts
603
- var exports_impl_arrowjs = {};
604
- __export(exports_impl_arrowjs, {
605
- DateUnit: () => DateUnit,
606
- IntervalUnit: () => IntervalUnit,
607
- TimeUnit: () => TimeUnit,
608
- UnionMode: () => UnionMode,
609
- adoptArrowJsShape: () => adoptArrowJsShape,
610
- backend: () => backend,
611
- batchFromColumns: () => batchFromColumns,
612
- batchFromRows: () => batchFromRows,
613
- batchToScalarDict: () => batchToScalarDict,
614
- batchToSecretDict: () => batchToSecretDict,
615
- binary: () => binary,
616
- bool: () => bool,
617
- buildStatisticsBatch: () => buildStatisticsBatch,
618
- columnFromArray: () => columnFromArray,
619
- date: () => date,
620
- dateDay: () => dateDay,
621
- dateMillisecond: () => dateMillisecond,
622
- decimal: () => decimal,
623
- decimal128: () => decimal128,
624
- decimal256: () => decimal256,
625
- decodeDictValue: () => decodeDictValue,
626
- denseUnion: () => denseUnion,
627
- deserializeBatch: () => deserializeBatch,
628
- deserializeSchema: () => deserializeSchema,
629
- dictionary: () => dictionary,
630
- duration: () => duration,
631
- emptyBatch: () => emptyBatch,
632
- field: () => field,
633
- filterBatch: () => filterBatch,
634
- fixedSizeBinary: () => fixedSizeBinary,
635
- fixedSizeList: () => fixedSizeList,
636
- float16: () => float16,
637
- float32: () => float32,
638
- float64: () => float64,
639
- int: () => int,
640
- int16: () => int16,
641
- int32: () => int32,
642
- int64: () => int64,
643
- int8: () => int8,
644
- interval: () => interval,
645
- iterRows: () => iterRows,
646
- largeBinary: () => largeBinary,
647
- largeUtf8: () => largeUtf8,
648
- list: () => list,
649
- map: () => map,
650
- nullType: () => nullType,
651
- projectBatch: () => projectBatch,
652
- projectSchema: () => projectSchema,
653
- readCanonicalValue: () => readCanonicalValue,
654
- safeNumber: () => safeNumber,
655
- schema: () => schema,
656
- serializeBatch: () => serializeBatch,
657
- serializeSchema: () => serializeSchema,
658
- sparseUnion: () => sparseUnion,
659
- struct: () => struct,
660
- time: () => time,
661
- timeMicrosecond: () => timeMicrosecond,
662
- timeMillisecond: () => timeMillisecond,
663
- timeNanosecond: () => timeNanosecond,
664
- timeSecond: () => timeSecond,
665
- timestamp: () => timestamp,
666
- uint16: () => uint16,
667
- uint32: () => uint32,
668
- uint64: () => uint64,
669
- uint8: () => uint8,
670
- union: () => union,
671
- utf8: () => utf8,
672
- withBatchMetadata: () => withBatchMetadata
673
- });
674
-
675
724
  // src/arrow/impl-arrowjs/schema.ts
676
725
  import {
677
726
  Schema as A_Schema,
@@ -2231,6 +2280,24 @@ function deserializeBatch(bytes) {
2231
2280
  }
2232
2281
  return batches[0];
2233
2282
  }
2283
+ function deserializeBatches(bytes) {
2284
+ return [...RecordBatchReader.from(bytes)];
2285
+ }
2286
+ function serializeBatches(batches, schema) {
2287
+ const writer = new RecordBatchStreamWriter;
2288
+ writer.reset(undefined, schema);
2289
+ for (const batch of batches)
2290
+ writer._writeRecordBatch(batch);
2291
+ writer.close();
2292
+ return writer.toUint8Array(true);
2293
+ }
2294
+ function serializeCollectionRows(schema, rows, maxBatchRows) {
2295
+ const batch = batchFromRows(rows, schema);
2296
+ const batches = [];
2297
+ for (let offset = 0;offset < batch.numRows; offset += maxBatchRows)
2298
+ batches.push(batch.slice(offset, offset + maxBatchRows));
2299
+ return serializeBatches(batches, schema);
2300
+ }
2234
2301
  // src/arrow/impl-arrowjs/statistics.ts
2235
2302
  import {
2236
2303
  Field as Field3,
@@ -2638,6 +2705,118 @@ function deserializeArguments(bytes) {
2638
2705
  }
2639
2706
  return new Arguments(positional, named, sch);
2640
2707
  }
2708
+ // src/codec/conform.ts
2709
+ var OPTIONAL_ITEM_FIELDS = new Set(["argument_names"]);
2710
+ function children(type) {
2711
+ return type.children ?? [];
2712
+ }
2713
+ function mapValueType(type) {
2714
+ const entries = children(type)[0].type;
2715
+ return children(entries)[1].type;
2716
+ }
2717
+ function mapPairs(raw) {
2718
+ if (Array.isArray(raw))
2719
+ return raw.map((e) => Array.isArray(e) ? [e[0], e[1]] : [e?.key, e?.value]);
2720
+ if (raw instanceof Map)
2721
+ return Array.from(raw.entries());
2722
+ if (typeof raw[Symbol.iterator] === "function")
2723
+ return Array.from(raw);
2724
+ return Object.entries(raw);
2725
+ }
2726
+ function zeroValue(type) {
2727
+ if (isDictionary(type))
2728
+ return zeroValue(type.dictionary);
2729
+ if (isUtf8(type))
2730
+ return "";
2731
+ if (isBinary(type))
2732
+ return new Uint8Array(0);
2733
+ if (isBool(type))
2734
+ return false;
2735
+ if (isInt(type))
2736
+ return type.bitWidth === 64 ? 0n : 0;
2737
+ if (isFloat(type))
2738
+ return 0;
2739
+ if (isList(type) || isMap(type))
2740
+ return [];
2741
+ if (isStruct(type)) {
2742
+ const out = {};
2743
+ for (const c of children(type))
2744
+ out[c.name] = c.nullable ? null : conformValue(c.type, undefined, false, c.name);
2745
+ return out;
2746
+ }
2747
+ return null;
2748
+ }
2749
+ var HAS_CONTAINER = new WeakMap;
2750
+ function hasContainer(type) {
2751
+ const cached = HAS_CONTAINER.get(type);
2752
+ if (cached !== undefined)
2753
+ return cached;
2754
+ let has = isList(type) || isMap(type);
2755
+ if (!has && isStruct(type))
2756
+ has = children(type).some((c) => hasContainer(c.type));
2757
+ HAS_CONTAINER.set(type, has);
2758
+ return has;
2759
+ }
2760
+ function conformValue(type, value, nullable, name) {
2761
+ if (value == null) {
2762
+ if (nullable)
2763
+ return value ?? null;
2764
+ if (isList(type) || isMap(type))
2765
+ return [];
2766
+ return value;
2767
+ }
2768
+ if (!hasContainer(type))
2769
+ return value;
2770
+ if (isList(type)) {
2771
+ const itemType = children(type)[0].type;
2772
+ const itemsNullable = OPTIONAL_ITEM_FIELDS.has(name);
2773
+ const items = Array.isArray(value) ? value : Array.from(value);
2774
+ let changed = !Array.isArray(value);
2775
+ const out = items.map((item) => {
2776
+ const next = item == null && !itemsNullable ? zeroValue(itemType) : conformValue(itemType, item, true, name);
2777
+ if (next !== item)
2778
+ changed = true;
2779
+ return next;
2780
+ });
2781
+ return changed ? out : value;
2782
+ }
2783
+ if (isMap(type)) {
2784
+ const valueType = mapValueType(type);
2785
+ const pairs = mapPairs(value);
2786
+ let changed = false;
2787
+ const out = pairs.map(([k, v]) => {
2788
+ const next = v == null ? zeroValue(valueType) : conformValue(valueType, v, true, name);
2789
+ if (next !== v)
2790
+ changed = true;
2791
+ return [k, next];
2792
+ });
2793
+ return changed ? out : value;
2794
+ }
2795
+ if (isStruct(type)) {
2796
+ let out = null;
2797
+ for (const c of children(type)) {
2798
+ const v = value[c.name];
2799
+ const next = conformValue(c.type, v, c.nullable, c.name);
2800
+ if (next !== v) {
2801
+ (out ??= { ...value })[c.name] = next;
2802
+ }
2803
+ }
2804
+ return out ?? value;
2805
+ }
2806
+ return value;
2807
+ }
2808
+ function conformRecord(schema, obj) {
2809
+ let out = null;
2810
+ for (const f of schema.fields) {
2811
+ const v = obj[f.name];
2812
+ const next = conformValue(f.type, v, f.nullable, f.name);
2813
+ if (next !== v) {
2814
+ (out ??= { ...obj })[f.name] = next;
2815
+ }
2816
+ }
2817
+ return out ?? obj;
2818
+ }
2819
+
2641
2820
  // src/protocol/serializers/shared.ts
2642
2821
  function toUint8Array2(val) {
2643
2822
  if (typeof val === "string")
@@ -3179,7 +3358,7 @@ import {
3179
3358
  Protocol
3180
3359
  } from "@query-farm/vgi-rpc";
3181
3360
  var VGI_PROTOCOL_NAME = "vgi.v2";
3182
- var VGI_PROTOCOL_VERSION = "2.1.0";
3361
+ var VGI_PROTOCOL_VERSION = "2.2.0";
3183
3362
  function exchangeStream(callbacks) {
3184
3363
  return { kind: "exchange", ...callbacks };
3185
3364
  }
@@ -4433,6 +4612,7 @@ function serializeColumnStatistics(stats, _cacheMaxAgeSeconds) {
4433
4612
  }
4434
4613
 
4435
4614
  // src/generated/vgi-protocol-schemas.ts
4615
+ var VGI_CATALOG_CONTRACT_HASH = "121e8fe1c074bce00a6d0fcec49d7a90f05e45498cd9ca8a5a3b4a9ae2377a2d";
4436
4616
  var CatalogInfoSchema = schema2([
4437
4617
  field2("name", utf82(), false),
4438
4618
  field2("implementation_version", utf82(), true),
@@ -4444,7 +4624,6 @@ var CatalogInfoSchema = schema2([
4444
4624
  var SchemaInfoSchema = schema2([
4445
4625
  field2("comment", utf82(), true),
4446
4626
  field2("tags", map2(field2("key", utf82(), false), field2("value", utf82(), true), false), false),
4447
- field2("attach_opaque_data", binary2(), false),
4448
4627
  field2("path", list2(field2("item", utf82(), true)), false),
4449
4628
  field2("estimated_object_count", map2(field2("key", utf82(), false), field2("value", int642(), true), false), true)
4450
4629
  ]);
@@ -4485,9 +4664,9 @@ var FunctionInfoSchema = schema2([
4485
4664
  field2("name", utf82(), false),
4486
4665
  field2("schema_path", list2(field2("item", utf82(), true)), false),
4487
4666
  field2("function_type", dictionary2(utf82(), int162()), false),
4488
- field2("arguments", binary2(), false),
4489
- field2("output_schema", binary2(), false),
4490
- field2("parameter_default_values", binary2(), true),
4667
+ field2("arguments", dictionary2(binary2(), int322()), false),
4668
+ field2("output_schema", dictionary2(binary2(), int322()), false),
4669
+ field2("parameter_default_values", dictionary2(binary2(), int322()), true),
4491
4670
  field2("stability", dictionary2(utf82(), int162()), true),
4492
4671
  field2("null_handling", dictionary2(utf82(), int162()), true),
4493
4672
  field2("argument_monotonicity", list2(field2("item", utf82(), true)), true),
@@ -4948,7 +5127,12 @@ var CatalogContentsResultSchema = schema2([
4948
5127
  field2("catalog_version", int642(), false),
4949
5128
  field2("etag", utf82(), true),
4950
5129
  field2("not_modified", bool2(), false),
4951
- field2("schemas", list2(field2("item", struct2([field2("path", list2(field2("item", utf82(), true)), false), field2("schema", binary2(), false), field2("tables", list2(field2("item", binary2(), true)), false), field2("views", list2(field2("item", binary2(), true)), false), field2("scalar_functions", list2(field2("item", binary2(), true)), false), field2("aggregate_functions", list2(field2("item", binary2(), true)), false), field2("table_functions", list2(field2("item", binary2(), true)), false), field2("scalar_macros", list2(field2("item", binary2(), true)), false), field2("table_macros", list2(field2("item", binary2(), true)), false), field2("indexes", list2(field2("item", binary2(), true)), false)]), true)), false)
5130
+ field2("schemas", binary2(), true),
5131
+ field2("tables", binary2(), true),
5132
+ field2("views", binary2(), true),
5133
+ field2("functions", binary2(), true),
5134
+ field2("macros", binary2(), true),
5135
+ field2("indexes", binary2(), true)
4952
5136
  ]);
4953
5137
  var CatalogCopyFromFormatsResultSchema = schema2([
4954
5138
  field2("items", list2(field2("item", binary2(), true)), false)
@@ -5406,13 +5590,6 @@ var TableFunctionStatisticsParamsSchema = schema2([
5406
5590
  function normalizeSchemaPath(path) {
5407
5591
  return typeof path === "string" ? [path] : Array.from(path, String);
5408
5592
  }
5409
- function schemaPathKey(path) {
5410
- const normalized = normalizeSchemaPath(path);
5411
- if (normalized.length === 0 || normalized.some((part) => part.length === 0)) {
5412
- throw new Error("schema paths must contain at least one non-empty component");
5413
- }
5414
- return normalized.map((part) => part.toLowerCase()).join("\x00");
5415
- }
5416
5593
 
5417
5594
  // src/protocol/handlers/shared.ts
5418
5595
  var RESULT_BINARY_SCHEMA = schema2([
@@ -5436,7 +5613,8 @@ function normalizeRequestSchemaPaths(params) {
5436
5613
  }
5437
5614
  function wrapResult(values, innerSchema) {
5438
5615
  const a = innerSchema;
5439
- const batch = batchFromColumns(Object.fromEntries(a.fields.map((f) => [f.name, [values[f.name] ?? null]])), a);
5616
+ const row = conformRecord(a, values);
5617
+ const batch = batchFromColumns(Object.fromEntries(a.fields.map((f) => [f.name, [row[f.name] ?? null]])), a);
5440
5618
  return { result: serializeBatch(batch) };
5441
5619
  }
5442
5620
  function overloadContext(req, catalogInterface) {
@@ -5459,21 +5637,24 @@ function overloadContext(req, catalogInterface) {
5459
5637
 
5460
5638
  // src/errors.ts
5461
5639
  class VgiError extends Error {
5462
- constructor(message) {
5640
+ errorCode;
5641
+ constructor(message, code) {
5463
5642
  super(message);
5464
5643
  this.name = "VgiError";
5644
+ if (code !== undefined)
5645
+ this.errorCode = code;
5465
5646
  }
5466
5647
  }
5467
5648
  class ArgumentValidationError extends VgiError {
5468
5649
  constructor(message) {
5469
- super(message);
5650
+ super(message, "INVALID_ARGUMENT");
5470
5651
  this.name = "ArgumentValidationError";
5471
5652
  }
5472
5653
  }
5473
5654
 
5474
5655
  class NoCatalogError extends VgiError {
5475
5656
  constructor() {
5476
- super("No catalog is configured for this worker");
5657
+ super("No catalog is configured for this worker", "UNIMPLEMENTED");
5477
5658
  this.name = "NoCatalogError";
5478
5659
  }
5479
5660
  }
@@ -7323,7 +7504,7 @@ function hex(buf) {
7323
7504
 
7324
7505
  // src/codec/asd.ts
7325
7506
  function encodeASD(schema, obj) {
7326
- return serializeBatch(batchFromRows([sortMapsForSchema(schema, obj)], schema));
7507
+ return serializeBatch(batchFromRows([sortMapsForSchema(schema, conformRecord(schema, obj))], schema));
7327
7508
  }
7328
7509
  function compareCodePoints(a, b) {
7329
7510
  const n = Math.min(a.length, b.length);
@@ -7340,7 +7521,7 @@ function compareCodePoints(a, b) {
7340
7521
  }
7341
7522
  return a.length - b.length;
7342
7523
  }
7343
- function mapPairs(raw) {
7524
+ function mapPairs2(raw) {
7344
7525
  if (Array.isArray(raw))
7345
7526
  return raw.map((e) => Array.isArray(e) ? [e[0], e[1]] : [e?.key, e?.value]);
7346
7527
  if (raw instanceof Map)
@@ -7375,7 +7556,7 @@ function sortMapsForType(type, value) {
7375
7556
  if (isMap(type)) {
7376
7557
  const entries = type.children[0].type;
7377
7558
  const valueType = entries.children[1].type;
7378
- return mapPairs(value).map(([k, v]) => [k, sortMapsForType(valueType, v)]).sort((x, y) => compareKeys(x[0], y[0]));
7559
+ return mapPairs2(value).map(([k, v]) => [k, sortMapsForType(valueType, v)]).sort((x, y) => compareKeys(x[0], y[0]));
7379
7560
  }
7380
7561
  if (isList(type)) {
7381
7562
  const child = type.children[0].type;
@@ -7402,6 +7583,109 @@ function sortMapsForSchema(schema, obj) {
7402
7583
  }
7403
7584
  return out ?? obj;
7404
7585
  }
7586
+ function normalizeValue(raw, type) {
7587
+ if (raw == null)
7588
+ return null;
7589
+ if (isList(type)) {
7590
+ const childType = type.children[0].type;
7591
+ const out = [];
7592
+ for (const item of raw)
7593
+ out.push(normalizeValue(item, childType));
7594
+ return out;
7595
+ }
7596
+ if (isMap(type)) {
7597
+ const entries = type.children[0].type;
7598
+ const valueType = entries.children[1].type;
7599
+ const out = {};
7600
+ const put = (k, v) => {
7601
+ out[String(k)] = normalizeValue(v, valueType);
7602
+ };
7603
+ if (raw[Symbol.iterator]) {
7604
+ for (const entry of raw) {
7605
+ if (Array.isArray(entry)) {
7606
+ put(entry[0], entry[1]);
7607
+ } else if (entry && typeof entry === "object") {
7608
+ put(entry.key ?? entry[0], entry.value ?? entry[1]);
7609
+ }
7610
+ }
7611
+ } else if (typeof raw === "object") {
7612
+ for (const [k, v] of Object.entries(raw))
7613
+ put(k, v);
7614
+ }
7615
+ return out;
7616
+ }
7617
+ if (isStruct(type)) {
7618
+ const childFields = type.children;
7619
+ const out = {};
7620
+ for (const cf of childFields) {
7621
+ out[cf.name] = normalizeValue(raw[cf.name], cf.type);
7622
+ }
7623
+ return out;
7624
+ }
7625
+ if (isDictionary(type)) {
7626
+ return normalizeValue(raw, type.dictionary);
7627
+ }
7628
+ if (isBinary(type)) {
7629
+ return toUint8Array3(raw);
7630
+ }
7631
+ if (isInt(type) && type.bitWidth === 64) {
7632
+ if (typeof raw === "bigint") {
7633
+ if (raw >= BigInt(Number.MIN_SAFE_INTEGER) && raw <= BigInt(Number.MAX_SAFE_INTEGER)) {
7634
+ return Number(raw);
7635
+ }
7636
+ return raw;
7637
+ }
7638
+ return raw;
7639
+ }
7640
+ if (isBool(type)) {
7641
+ return Boolean(raw);
7642
+ }
7643
+ return raw;
7644
+ }
7645
+ function toUint8Array3(val) {
7646
+ if (val instanceof Uint8Array)
7647
+ return val;
7648
+ if (val instanceof ArrayBuffer)
7649
+ return new Uint8Array(val);
7650
+ if (val && val.buffer instanceof ArrayBuffer) {
7651
+ return new Uint8Array(val.buffer, val.byteOffset, val.byteLength);
7652
+ }
7653
+ return new Uint8Array(0);
7654
+ }
7655
+ function encodeASDCollection(schema, records) {
7656
+ if (records.length === 0)
7657
+ return null;
7658
+ return serializeCollectionRows(schema, records.map((record) => sortMapsForSchema(schema, conformRecord(schema, record))), 1024);
7659
+ }
7660
+ function decodeASDCollection(schema, bytes) {
7661
+ if (bytes == null)
7662
+ return [];
7663
+ const output = [];
7664
+ const batches = deserializeBatches(bytes);
7665
+ const validateSchema = (actualSchema) => {
7666
+ if (actualSchema.fields.length !== schema.fields.length || schema.fields.some((field, i) => {
7667
+ const actual = actualSchema.fields[i];
7668
+ return actual.name !== field.name || actual.nullable !== field.nullable || typeSignature(actual.type) !== typeSignature(field.type);
7669
+ }))
7670
+ throw new Error("catalog collection has an incompatible metadata schema");
7671
+ };
7672
+ if (batches.length === 0)
7673
+ validateSchema(deserializeSchema(bytes));
7674
+ for (const batch of batches) {
7675
+ validateSchema(batch.schema);
7676
+ for (let row = 0;row < batch.numRows; row++) {
7677
+ const item = {};
7678
+ for (const field of schema.fields) {
7679
+ const value = batch.getChild(field.name)?.get(row);
7680
+ if (value == null && !field.nullable)
7681
+ throw new Error(`catalog collection has null ${field.name}`);
7682
+ item[field.name] = normalizeValue(value, field.type);
7683
+ }
7684
+ output.push(item);
7685
+ }
7686
+ }
7687
+ return output;
7688
+ }
7405
7689
 
7406
7690
  // src/generated/vgi-client.ts
7407
7691
  var encodeCatalogInfo = (v) => encodeASD(CatalogInfoSchema, v);
@@ -7435,54 +7719,110 @@ function buildCatalogAttachResult(init) {
7435
7719
  supports_catalog_contents: init.supports_catalog_contents ?? false
7436
7720
  };
7437
7721
  }
7438
- function buildSchemaContents(init) {
7439
- return {
7440
- path: init.path,
7441
- schema: init.schema,
7442
- tables: init.tables ?? [],
7443
- views: init.views ?? [],
7444
- scalar_functions: init.scalar_functions ?? [],
7445
- aggregate_functions: init.aggregate_functions ?? [],
7446
- table_functions: init.table_functions ?? [],
7447
- scalar_macros: init.scalar_macros ?? [],
7448
- table_macros: init.table_macros ?? [],
7449
- indexes: init.indexes ?? []
7450
- };
7451
- }
7452
7722
  function buildCatalogContentsResponse(init) {
7453
7723
  return {
7454
7724
  catalog_version: init.catalog_version,
7455
7725
  etag: init.etag ?? null,
7456
7726
  not_modified: init.not_modified ?? false,
7457
- schemas: init.schemas ?? []
7727
+ schemas: init.schemas ?? null,
7728
+ tables: init.tables ?? null,
7729
+ views: init.views ?? null,
7730
+ functions: init.functions ?? null,
7731
+ macros: init.macros ?? null,
7732
+ indexes: init.indexes ?? null
7458
7733
  };
7459
7734
  }
7460
7735
 
7461
- // src/catalog/item-encoding.ts
7462
- var ENCODED = new WeakMap;
7463
- function encodeFunctionInfoOnce(info) {
7464
- if (!Object.isFrozen(info))
7465
- return encodeFunctionInfo(info);
7466
- let encoded = ENCODED.get(info);
7467
- if (encoded === undefined) {
7468
- encoded = encodeFunctionInfo(info);
7469
- ENCODED.set(info, encoded);
7736
+ // src/protocol/handlers/catalog/contents.ts
7737
+ import { ExternalRef as ExternalRef2 } from "@query-farm/vgi-rpc";
7738
+
7739
+ // src/catalog/publication.ts
7740
+ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@query-farm/vgi-rpc";
7741
+
7742
+ // src/catalog/contents-codec.ts
7743
+ var schemaPathKey = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
7744
+ var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
7745
+ function encodeCatalogStreams(inventory) {
7746
+ const streams = {
7747
+ schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
7748
+ tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
7749
+ views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
7750
+ functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
7751
+ macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
7752
+ indexes: encodeASDCollection(IndexInfoSchema, inventory.flatMap((s) => s.indexes))
7753
+ };
7754
+ return streams;
7755
+ }
7756
+ function decodeCatalogStreams(response, ifNoneMatch) {
7757
+ if (response.not_modified) {
7758
+ if (response.etag == null || ifNoneMatch !== undefined && response.etag !== ifNoneMatch || CATALOG_STREAM_KINDS.some((kind) => response[kind] != null)) {
7759
+ throw new Error("invalid catalog_contents not_modified response");
7760
+ }
7761
+ return [];
7470
7762
  }
7471
- return encoded;
7763
+ const infos = decodeASDCollection(SchemaInfoSchema, response.schemas);
7764
+ const schemas = [];
7765
+ const index = new Map;
7766
+ for (const schema of infos) {
7767
+ if (!Array.isArray(schema.path) || schema.path.length === 0)
7768
+ throw new Error("catalog schema has an empty path");
7769
+ const key = schemaPathKey(schema.path);
7770
+ if (index.has(key))
7771
+ throw new Error("catalog contains duplicate schema paths");
7772
+ if (schema.path.length > 1 && !index.has(schemaPathKey(schema.path.slice(0, -1)))) {
7773
+ throw new Error("catalog schema is missing its preceding parent");
7774
+ }
7775
+ const entry = { schema, tables: [], views: [], scalar_functions: [], aggregate_functions: [], table_functions: [], scalar_macros: [], table_macros: [], indexes: [] };
7776
+ index.set(key, entry);
7777
+ schemas.push(entry);
7778
+ }
7779
+ const owner = (item) => {
7780
+ const entry = index.get(schemaPathKey(item.schema_path));
7781
+ if (!entry)
7782
+ throw new Error("catalog object references an absent schema");
7783
+ return entry;
7784
+ };
7785
+ for (const item of decodeASDCollection(TableInfoSchema, response.tables))
7786
+ owner(item).tables.push(item);
7787
+ for (const item of decodeASDCollection(ViewInfoSchema, response.views))
7788
+ owner(item).views.push(item);
7789
+ for (const item of decodeASDCollection(FunctionInfoSchema, response.functions)) {
7790
+ const entry = owner(item);
7791
+ switch (String(item.function_type).toUpperCase()) {
7792
+ case "SCALAR":
7793
+ entry.scalar_functions.push(item);
7794
+ break;
7795
+ case "AGGREGATE":
7796
+ entry.aggregate_functions.push(item);
7797
+ break;
7798
+ case "TABLE":
7799
+ case "TABLE_BUFFERING":
7800
+ entry.table_functions.push(item);
7801
+ break;
7802
+ default:
7803
+ throw new Error(`unknown catalog function type ${item.function_type}`);
7804
+ }
7805
+ }
7806
+ for (const item of decodeASDCollection(MacroInfoSchema, response.macros)) {
7807
+ const entry = owner(item);
7808
+ switch (String(item.macro_type).toUpperCase()) {
7809
+ case "SCALAR":
7810
+ entry.scalar_macros.push(item);
7811
+ break;
7812
+ case "TABLE":
7813
+ entry.table_macros.push(item);
7814
+ break;
7815
+ default:
7816
+ throw new Error(`unknown catalog macro type ${item.macro_type}`);
7817
+ }
7818
+ }
7819
+ for (const item of decodeASDCollection(IndexInfoSchema, response.indexes))
7820
+ owner(item).indexes.push(item);
7821
+ return schemas;
7472
7822
  }
7473
7823
 
7474
7824
  // src/catalog/contents-digest.ts
7475
- var KINDS = [
7476
- "tables",
7477
- "views",
7478
- "scalar_functions",
7479
- "aggregate_functions",
7480
- "table_functions",
7481
- "scalar_macros",
7482
- "table_macros",
7483
- "indexes"
7484
- ];
7485
- async function catalogContentsDigest(schemas) {
7825
+ async function catalogContentsDigest(streams, version = 0) {
7486
7826
  const utf8 = new TextEncoder;
7487
7827
  const parts = [];
7488
7828
  let total = 0;
@@ -7502,12 +7842,23 @@ async function catalogContentsDigest(schemas) {
7502
7842
  for (const v of values)
7503
7843
  chunk(v);
7504
7844
  };
7505
- count(schemas.length);
7506
- for (const entry of schemas) {
7507
- chunks(entry.path.map((p) => utf8.encode(p)));
7508
- chunk(entry.schema);
7509
- for (const kind of KINDS)
7510
- chunks(entry[kind]);
7845
+ if (Array.isArray(streams)) {
7846
+ count(streams.length);
7847
+ for (const entry of streams) {
7848
+ chunks(entry.path.map((p) => utf8.encode(p)));
7849
+ chunk(entry.schema);
7850
+ for (const kind of ["tables", "views", "scalar_functions", "aggregate_functions", "table_functions", "scalar_macros", "table_macros", "indexes"])
7851
+ chunks(entry[kind]);
7852
+ }
7853
+ } else {
7854
+ chunk(utf8.encode("vgi.catalog-contents.2.2"));
7855
+ count(version);
7856
+ for (const kind of CATALOG_STREAM_KINDS) {
7857
+ const value = streams[kind];
7858
+ count(value == null ? 0 : 1);
7859
+ if (value != null)
7860
+ chunk(value);
7861
+ }
7511
7862
  }
7512
7863
  const buf = new Uint8Array(total);
7513
7864
  let off = 0;
@@ -7522,7 +7873,297 @@ async function catalogContentsDigest(schemas) {
7522
7873
  return hex;
7523
7874
  }
7524
7875
 
7876
+ // src/catalog/publication-envelope.ts
7877
+ function validateCatalogPublicationEnvelope(bytes) {
7878
+ try {
7879
+ const stream = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
7880
+ let position = 0, messages = 0;
7881
+ while (position < bytes.length) {
7882
+ let length = stream.getInt32(position, true);
7883
+ position += 4;
7884
+ if (length === -1) {
7885
+ length = stream.getInt32(position, true);
7886
+ position += 4;
7887
+ }
7888
+ if (length === 0) {
7889
+ if (position !== bytes.length)
7890
+ throw new Error("trailing data");
7891
+ break;
7892
+ }
7893
+ if (length < 4 || length > bytes.length - position)
7894
+ throw new Error("invalid message length");
7895
+ const head = new DataView(bytes.buffer, bytes.byteOffset + position, length);
7896
+ const tableField = (table, field) => {
7897
+ const vtable = table - head.getInt32(table, true);
7898
+ const vlength = head.getUint16(vtable, true);
7899
+ if (vlength < 4 || vlength % 2 || vtable + vlength > length)
7900
+ throw new Error("invalid vtable");
7901
+ if (4 + 2 * field >= vlength)
7902
+ return null;
7903
+ const offset = head.getUint16(vtable + 4 + 2 * field, true);
7904
+ return offset === 0 ? null : table + offset;
7905
+ };
7906
+ const follow = (pointer) => pointer + head.getUint32(pointer, true);
7907
+ const root = head.getUint32(0, true);
7908
+ const typePosition = tableField(root, 1);
7909
+ const type = typePosition == null ? 0 : head.getUint8(typePosition);
7910
+ if (type !== (messages === 0 ? 1 : messages === 1 ? 3 : -1))
7911
+ throw new Error("expected one schema and one record batch");
7912
+ if (type === 3) {
7913
+ const header = tableField(root, 2);
7914
+ if (header == null)
7915
+ throw new Error("missing record header");
7916
+ const rows = tableField(follow(header), 0);
7917
+ if (rows == null || head.getBigInt64(rows, true) !== 1n)
7918
+ throw new Error("expected one response row");
7919
+ }
7920
+ const metadata = tableField(root, 4);
7921
+ if (metadata != null) {
7922
+ const vector = follow(metadata), count = head.getUint32(vector, true);
7923
+ if (count > length / 4)
7924
+ throw new Error("invalid metadata vector");
7925
+ for (let i = 0;i < count; i++) {
7926
+ const keyPointer = tableField(follow(vector + 4 + 4 * i), 0);
7927
+ if (keyPointer == null)
7928
+ continue;
7929
+ const keyStart = follow(keyPointer), keyLength = head.getUint32(keyStart, true);
7930
+ if (keyStart + 4 + keyLength > length)
7931
+ throw new Error("invalid metadata key");
7932
+ const key = new TextDecoder().decode(new Uint8Array(head.buffer, head.byteOffset + keyStart + 4, keyLength));
7933
+ if (key === "vgi_rpc.location" || key === "vgi_rpc.log_level")
7934
+ throw new Error("pointer/log metadata is not a catalog result");
7935
+ }
7936
+ }
7937
+ const bodyPosition = tableField(root, 3);
7938
+ const bodyLength = bodyPosition == null ? 0 : Number(head.getBigInt64(bodyPosition, true));
7939
+ position += length;
7940
+ if (!Number.isSafeInteger(bodyLength) || bodyLength < 0 || bodyLength > bytes.length - position)
7941
+ throw new Error("invalid body length");
7942
+ position += bodyLength;
7943
+ messages++;
7944
+ }
7945
+ if (messages !== 2)
7946
+ throw new Error("missing response batch");
7947
+ } catch (error) {
7948
+ throw new Error(`invalid published RPC envelope: ${error instanceof Error ? error.message : String(error)}`);
7949
+ }
7950
+ }
7951
+
7952
+ // src/catalog/publication.ts
7953
+ var OUTER_SCHEMA = schema2([field2("result", binary2(), false)]);
7954
+ var DEFAULT_MAX = 64 * 1024 * 1024;
7955
+ var utf83 = new TextEncoder;
7956
+ var equalBytes3 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
7957
+ async function digest(value) {
7958
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", utf83.encode(value)));
7959
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
7960
+ }
7961
+ function assertRenewedPublication(before, after) {
7962
+ const unchanged = (m) => JSON.stringify([m.key, m.formatVersion, m.protocolName, m.protocolVersion, m.contractHash, m.codecRevision, m.catalogVersion, m.etag, m.sha256, m.rawSize, m.storedSize, m.objectId, m.retainUntil, m.stable, m.validated]);
7963
+ if (unchanged(before) !== unchanged(after))
7964
+ throw new Error("renewal changed immutable catalog identity");
7965
+ }
7966
+ var manifestSame = (a, b) => a.manifestId === b.manifestId;
7967
+ class CatalogSnapshotManager {
7968
+ policy;
7969
+ cached = new Map;
7970
+ pending = new Map;
7971
+ constructor(policy) {
7972
+ this.policy = policy;
7973
+ for (const value of [policy.maxRawBytes, policy.maxStoredBytes, policy.maxCachedManifests]) {
7974
+ if (value != null && (!Number.isSafeInteger(value) || value <= 0))
7975
+ throw new Error("catalog publication limits must be positive safe integers");
7976
+ }
7977
+ if (policy.referenceGraceMs != null && (!Number.isSafeInteger(policy.referenceGraceMs) || policy.referenceGraceMs < 0))
7978
+ throw new Error("catalog publication reference grace must be a nonnegative safe integer");
7979
+ }
7980
+ usable(m) {
7981
+ const deadline = Date.now() + (this.policy.referenceGraceMs ?? 60000);
7982
+ return (m.stable || m.expiresAt != null) && (m.expiresAt == null || m.expiresAt > deadline) && (m.retainUntil == null || m.retainUntil > deadline);
7983
+ }
7984
+ async key(identity) {
7985
+ for (const value of [identity.catalogNamespace, identity.sourceRevision, identity.visibilityScope])
7986
+ if (!value)
7987
+ throw new Error("published catalogs require explicit namespace, revision and visibility scope");
7988
+ if (!Number.isSafeInteger(identity.catalogVersion))
7989
+ throw new Error("catalog version is not a safe integer");
7990
+ return digest(JSON.stringify([
7991
+ VGI_PROTOCOL_NAME,
7992
+ VGI_PROTOCOL_VERSION,
7993
+ VGI_CATALOG_CONTRACT_HASH,
7994
+ 1,
7995
+ identity.catalogNamespace,
7996
+ identity.sourceRevision,
7997
+ identity.visibilityScope,
7998
+ identity.catalogVersion,
7999
+ this.policy.repository.profile,
8000
+ this.policy.compression ?? "identity"
8001
+ ]));
8002
+ }
8003
+ remember(m) {
8004
+ this.cached.delete(m.key);
8005
+ this.cached.set(m.key, Object.freeze({ ...m }));
8006
+ while (this.cached.size > (this.policy.maxCachedManifests ?? 128))
8007
+ this.cached.delete(this.cached.keys().next().value);
8008
+ }
8009
+ async invalidate(key) {
8010
+ await this.pending.get(key)?.catch(() => {
8011
+ return;
8012
+ });
8013
+ const m = this.cached.get(key) ?? await this.policy.repository.lookup(key);
8014
+ this.cached.delete(key);
8015
+ if (m)
8016
+ await this.policy.repository.invalidate(key, m);
8017
+ }
8018
+ async validate(m, key, identity, expected) {
8019
+ if (m.formatVersion !== 1 || typeof m.manifestId !== "string" || !m.manifestId || m.key !== key || m.protocolName !== VGI_PROTOCOL_NAME || m.protocolVersion !== VGI_PROTOCOL_VERSION || m.contractHash !== VGI_CATALOG_CONTRACT_HASH || m.codecRevision !== 1 || m.catalogVersion !== identity.catalogVersion || m.validated !== true || typeof m.stable !== "boolean" || typeof m.etag !== "string" || !/^[0-9a-f]{64}$/.test(m.sha256) || !Number.isSafeInteger(m.rawSize) || !Number.isSafeInteger(m.storedSize) || m.rawSize <= 0 || m.storedSize <= 0 || m.rawSize > (this.policy.maxRawBytes ?? DEFAULT_MAX) || m.storedSize > (this.policy.maxStoredBytes ?? DEFAULT_MAX) || !this.usable(m))
8020
+ throw new Error("invalid or expired catalog publication manifest");
8021
+ const ref = new ExternalRef(m.url, m.sha256);
8022
+ const configuredFetch = this.policy.repository.resolver.fetch ?? fetch;
8023
+ const resolved = await resolveExternalLocation(ref.pointerBatch(OUTER_SCHEMA), {
8024
+ ...this.policy.repository.resolver,
8025
+ fetch: (input, init) => configuredFetch(input, { ...init, signal: AbortSignal.any([...init?.signal ? [init.signal] : [], AbortSignal.timeout(30000)]) }),
8026
+ maxFetchBytes: Math.min(this.policy.maxStoredBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxFetchBytes ?? Infinity),
8027
+ maxDecompressedBytes: Math.min(this.policy.maxRawBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxDecompressedBytes ?? Infinity),
8028
+ validateFetchedIpc: (bytes) => {
8029
+ this.policy.repository.resolver.validateFetchedIpc?.(bytes);
8030
+ if (bytes.length !== m.rawSize)
8031
+ throw new Error("catalog publication raw size mismatch");
8032
+ validateCatalogPublicationEnvelope(bytes);
8033
+ }
8034
+ });
8035
+ if (resolved.numRows !== 1 || resolved.schema.fields.length !== 1 || resolved.schema.fields[0].name !== "result" || typeSignature(resolved.schema.fields[0].type) !== typeSignature(binary2()) || resolved.schema.fields[0].nullable)
8036
+ throw new Error("invalid published RPC envelope");
8037
+ const bytes = resolved.getChild("result")?.get(0);
8038
+ if (!(bytes instanceof Uint8Array))
8039
+ throw new Error("published catalog has no result bytes");
8040
+ const decoded = decodeASDCollection(CatalogContentsResultSchema, bytes);
8041
+ if (decoded.length !== 1)
8042
+ throw new Error("published catalog must contain exactly one response row");
8043
+ const response = decoded[0];
8044
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion || response.etag !== m.etag)
8045
+ throw new Error("published catalog version or ETag mismatch");
8046
+ decodeCatalogStreams(response);
8047
+ if (expected)
8048
+ for (const kind of CATALOG_STREAM_KINDS) {
8049
+ const a = response[kind], b = expected[kind];
8050
+ if (a == null !== (b == null) || a != null && b != null && !equalBytes3(a, b))
8051
+ throw new Error("publication readback changed catalog metadata");
8052
+ }
8053
+ }
8054
+ async import(manifest, identity) {
8055
+ const key = await this.key(identity);
8056
+ await this.validate(manifest, key, identity);
8057
+ const winner = await this.policy.repository.commitIfAbsent(manifest);
8058
+ if (!manifestSame(manifest, winner))
8059
+ await this.validate(winner, key, identity);
8060
+ this.remember(winner);
8061
+ return winner;
8062
+ }
8063
+ async warm(identity, build) {
8064
+ const key = await this.key(identity);
8065
+ const cached = this.cached.get(key);
8066
+ if (cached && this.usable(cached))
8067
+ return cached;
8068
+ const active = this.pending.get(key);
8069
+ if (active)
8070
+ return active;
8071
+ const pending = this.recoverOrPublish(key, identity, build);
8072
+ this.pending.set(key, pending);
8073
+ try {
8074
+ const m = await pending;
8075
+ this.remember(m);
8076
+ return m;
8077
+ } finally {
8078
+ if (this.pending.get(key) === pending)
8079
+ this.pending.delete(key);
8080
+ }
8081
+ }
8082
+ async recoverOrPublish(key, identity, build) {
8083
+ const repository = this.policy.repository;
8084
+ let existing = await repository.lookup(key);
8085
+ if (existing) {
8086
+ try {
8087
+ if (!this.usable(existing) && repository.renew) {
8088
+ const renewed = await repository.renew(existing);
8089
+ if (renewed) {
8090
+ assertRenewedPublication(existing, renewed);
8091
+ existing = renewed;
8092
+ }
8093
+ }
8094
+ await this.validate(existing, key, identity);
8095
+ return existing;
8096
+ } catch {
8097
+ await repository.invalidate(key, existing);
8098
+ }
8099
+ }
8100
+ const response = await build();
8101
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion)
8102
+ throw new Error("publication requires a full snapshot of the requested version");
8103
+ decodeCatalogStreams(response);
8104
+ response.etag ??= await catalogContentsDigest(response, identity.catalogVersion);
8105
+ const payload = encodeASD(CatalogContentsResultSchema, response);
8106
+ let rawSize = 0, storedSize = 0;
8107
+ const bounded = { upload: async (data, encoding) => {
8108
+ if (encoding)
8109
+ throw new Error("catalog publication uploader requires identity encoding");
8110
+ rawSize = data.byteLength;
8111
+ if (rawSize > (this.policy.maxRawBytes ?? DEFAULT_MAX))
8112
+ throw new Error("catalog publication exceeds byte limit");
8113
+ let body = data;
8114
+ const compression = this.policy.compression ?? "identity";
8115
+ if (compression !== "identity" && compression !== "gzip" && compression !== "zstd")
8116
+ throw new Error("catalog publication compression must be identity, gzip or zstd");
8117
+ if (compression === "gzip") {
8118
+ body = new Uint8Array(await new Response(new Blob([data]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer());
8119
+ } else if (compression === "zstd") {
8120
+ const runtime = globalThis.Bun;
8121
+ if (typeof runtime?.zstdCompress === "function") {
8122
+ body = new Uint8Array(await runtime.zstdCompress(data));
8123
+ } else if (typeof process !== "undefined" && process.versions?.node) {
8124
+ const nodeZlib = "node:zlib";
8125
+ const zlib = await import(nodeZlib);
8126
+ if (typeof zlib.zstdCompressSync !== "function")
8127
+ throw new Error("zstd catalog publication requires Node >=22.15, Bun, or an encoder-capable runtime");
8128
+ body = new Uint8Array(zlib.zstdCompressSync(data));
8129
+ } else {
8130
+ throw new Error("zstd catalog publication requires an encoder-capable runtime; use gzip or identity here");
8131
+ }
8132
+ }
8133
+ storedSize = body.byteLength;
8134
+ if (storedSize > (this.policy.maxStoredBytes ?? DEFAULT_MAX))
8135
+ throw new Error("catalog publication exceeds byte limit");
8136
+ return repository.storage.upload(body, compression === "identity" ? "" : compression);
8137
+ } };
8138
+ const ref = await publishExternalResult(OUTER_SCHEMA, { result: payload }, bounded, { includeSha256: true });
8139
+ const m = {
8140
+ formatVersion: 1,
8141
+ manifestId: crypto.randomUUID(),
8142
+ key,
8143
+ protocolName: VGI_PROTOCOL_NAME,
8144
+ protocolVersion: VGI_PROTOCOL_VERSION,
8145
+ contractHash: VGI_CATALOG_CONTRACT_HASH,
8146
+ codecRevision: 1,
8147
+ catalogVersion: identity.catalogVersion,
8148
+ etag: response.etag,
8149
+ sha256: ref.sha256,
8150
+ rawSize,
8151
+ storedSize,
8152
+ url: ref.url,
8153
+ validated: true,
8154
+ ...await repository.describe(ref.url)
8155
+ };
8156
+ await this.validate(m, key, identity, response);
8157
+ const winner = await repository.commitIfAbsent(m);
8158
+ if (!manifestSame(m, winner))
8159
+ await this.validate(winner, key, identity);
8160
+ return winner;
8161
+ }
8162
+ }
8163
+
7525
8164
  // src/protocol/handlers/catalog/contents.ts
8165
+ var schemaPathKey2 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
8166
+ var PUBLICATIONS = new WeakMap;
7526
8167
  var CACHE = new WeakMap;
7527
8168
  async function buildCatalogContents(cat, owner, attach, version, ifNoneMatch) {
7528
8169
  const result = await cat.catalogContents(attach, ifNoneMatch);
@@ -7537,39 +8178,74 @@ async function buildCatalogContents(cat, owner, attach, version, ifNoneMatch) {
7537
8178
  return buildCatalogContentsResponse({ catalog_version: version, etag: etag0, not_modified: true });
7538
8179
  }
7539
8180
  const infos = [...result.schemas ?? []];
7540
- const keys = infos.map((c) => schemaPathKey(c.schema.path));
8181
+ const keys = infos.map((c) => schemaPathKey2(c.schema.path));
7541
8182
  const keySet = new Set(keys);
7542
8183
  if (keySet.size !== keys.length)
7543
8184
  throw new Error("catalog_contents returned duplicate schema paths");
7544
8185
  for (const c of infos) {
7545
- if (c.schema.path.length > 1 && !keySet.has(schemaPathKey(c.schema.path.slice(0, -1)))) {
8186
+ if (c.schema.path.length > 1 && !keySet.has(schemaPathKey2(c.schema.path.slice(0, -1)))) {
7546
8187
  throw new Error(`catalog_contents returned schema path ${JSON.stringify(c.schema.path)} without its parent`);
7547
8188
  }
7548
8189
  }
7549
- const schemas = infos.sort((a, b) => a.schema.path.length - b.schema.path.length).map((c) => buildSchemaContents({
7550
- path: [...c.schema.path],
7551
- schema: encodeSchemaInfo(c.schema),
7552
- tables: c.tables.map((t) => encodeTableInfo(t)),
7553
- views: c.views.map((v) => encodeViewInfo(v)),
7554
- scalar_functions: c.scalar_functions.map((f) => encodeFunctionInfoOnce(f)),
7555
- aggregate_functions: c.aggregate_functions.map((f) => encodeFunctionInfoOnce(f)),
7556
- table_functions: c.table_functions.map((f) => encodeFunctionInfoOnce(f)),
7557
- scalar_macros: c.scalar_macros.map((m) => encodeMacroInfo(m)),
7558
- table_macros: c.table_macros.map((m) => encodeMacroInfo(m)),
7559
- indexes: c.indexes.map((i) => encodeIndexInfo(i))
7560
- }));
8190
+ const streams = encodeCatalogStreams(infos.sort((a, b) => a.schema.path.length - b.schema.path.length));
7561
8191
  let etag = etag0;
7562
8192
  if (etag === null && owner.catalogContentsEtag === "content-hash") {
7563
- etag = await catalogContentsDigest(schemas);
8193
+ etag = await catalogContentsDigest(streams, version);
7564
8194
  }
7565
8195
  if (etag !== null && ifNoneMatch !== null && etag === ifNoneMatch) {
7566
8196
  return buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true });
7567
8197
  }
7568
- return buildCatalogContentsResponse({ catalog_version: version, etag, schemas });
8198
+ const response = buildCatalogContentsResponse({ catalog_version: version, etag, ...streams });
8199
+ decodeCatalogStreams(response);
8200
+ return response;
7569
8201
  }
7570
- async function serveCatalogContents(cat, attach, ifNoneMatch) {
8202
+ async function serveCatalogContents(cat, attach, ifNoneMatch, callContext, sealedAttach = attach) {
7571
8203
  const owner = cat.catalogContentsOwner(attach);
7572
8204
  const version = Number(await cat.version(attach));
8205
+ const policy = owner.catalogSnapshotPolicy;
8206
+ if (policy?.delivery === "published") {
8207
+ const request = { catalog: cat, attachOpaqueData: attach, callContext, catalogVersion: version };
8208
+ const inline = (etag) => wrapResult(buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true }), CatalogContentsResultSchema);
8209
+ const cheapEtag = await policy.etag?.(request);
8210
+ if (cheapEtag != null && cheapEtag === ifNoneMatch)
8211
+ return inline(cheapEtag);
8212
+ let manager = PUBLICATIONS.get(policy);
8213
+ if (!manager) {
8214
+ manager = new CatalogSnapshotManager(policy);
8215
+ PUBLICATIONS.set(policy, manager);
8216
+ }
8217
+ const scopeBytes = new Uint8Array(await crypto.subtle.digest("SHA-256", sealedAttach));
8218
+ const attachmentScope = "attachment:" + Array.from(scopeBytes, (b) => b.toString(16).padStart(2, "0")).join("");
8219
+ const identify = async (input) => {
8220
+ const id = await policy.identity(input);
8221
+ return { ...id, visibilityScope: id.visibilityScope ?? attachmentScope };
8222
+ };
8223
+ const identity = await identify(request);
8224
+ if (identity.catalogVersion !== version)
8225
+ throw new Error("snapshot identity version differs from the attached catalog");
8226
+ const assertCurrentIdentity = async () => {
8227
+ const currentVersion = Number(await cat.version(attach));
8228
+ const current = await identify({ ...request, catalogVersion: currentVersion });
8229
+ if (currentVersion !== version || await manager.key(identity) !== await manager.key(current))
8230
+ throw new Error("catalog changed while resolving its publication");
8231
+ };
8232
+ const buildSnapshot = async (validator) => {
8233
+ const response = await buildCatalogContents(cat, owner, attach, version, validator);
8234
+ await assertCurrentIdentity();
8235
+ return response;
8236
+ };
8237
+ try {
8238
+ const manifest = await manager.warm(identity, () => buildSnapshot(null));
8239
+ await assertCurrentIdentity();
8240
+ if (manifest.etag === ifNoneMatch)
8241
+ return inline(manifest.etag);
8242
+ return new ExternalRef2(manifest.url, manifest.sha256);
8243
+ } catch (error) {
8244
+ if (policy.onPublicationFailure !== "ordinary")
8245
+ throw error;
8246
+ return wrapResult(await buildSnapshot(ifNoneMatch), CatalogContentsResultSchema);
8247
+ }
8248
+ }
7573
8249
  if (owner.catalogContentsCacheable()) {
7574
8250
  let pending = CACHE.get(owner);
7575
8251
  let snapshot = pending ? await pending.catch(() => null) : null;
@@ -7599,6 +8275,19 @@ async function serveCatalogContents(cat, attach, ifNoneMatch) {
7599
8275
  return wrapResult(await buildCatalogContents(cat, owner, attach, version, ifNoneMatch), CatalogContentsResultSchema);
7600
8276
  }
7601
8277
 
8278
+ // src/catalog/item-encoding.ts
8279
+ var ENCODED = new WeakMap;
8280
+ function encodeFunctionInfoOnce(info) {
8281
+ if (!Object.isFrozen(info))
8282
+ return encodeFunctionInfo(info);
8283
+ let encoded = ENCODED.get(info);
8284
+ if (encoded === undefined) {
8285
+ encoded = encodeFunctionInfo(info);
8286
+ ENCODED.set(info, encoded);
8287
+ }
8288
+ return encoded;
8289
+ }
8290
+
7602
8291
  // src/catalog/interface.ts
7603
8292
  var encodeCopyFromFormatInfo = (v) => encodeASD(CopyFromFormatInfoSchema, {
7604
8293
  comment: v.comment ?? null,
@@ -7703,7 +8392,7 @@ async function checkReservedAttachOptions(catalog) {
7703
8392
  var ATTACH_TICKET_PREFIX = "vgia1.";
7704
8393
  var ATTACH_TICKET_OPTION = RESERVED_ATTACH_OPTION;
7705
8394
  var ATTACH_TICKETS_PROTOCOL_NAME = "vgi.attach_tickets.v1";
7706
- var ATTACH_TICKETS_PROTOCOL_VERSION = "1.0.0";
8395
+ var ATTACH_TICKETS_PROTOCOL_VERSION = "2.0.0";
7707
8396
  var TICKET_ENVELOPE_VERSION = 1;
7708
8397
  var MAX_OPTIONS_BYTES = 16 * 1024;
7709
8398
  var MAX_TICKET_CHARS = 32 * 1024;
@@ -7978,8 +8667,19 @@ var SEAL_ATTACH_REQUEST_SCHEMA = schema2([
7978
8667
  ]);
7979
8668
  var ATTACH_TICKET_SCHEMA = schema2([
7980
8669
  field2("ticket", utf82(), false),
7981
- field2("expires_at", float642(), false)
8670
+ field2("expires_at", timestamp2(TimeUnit2.MICROSECOND, "UTC"), true)
7982
8671
  ]);
8672
+ function expiresAtMicros(value) {
8673
+ if (value === null)
8674
+ return null;
8675
+ const ms = value.getTime();
8676
+ if (!Number.isFinite(ms))
8677
+ throw new TypeError("AttachTicket.expires_at must be a valid Date or null");
8678
+ return BigInt(ms) * 1000n;
8679
+ }
8680
+ function encodeAttachTicket(ticket) {
8681
+ return serializeBatch(batchFromColumns({ ticket: [ticket.ticket], expires_at: [expiresAtMicros(ticket.expires_at)] }, ATTACH_TICKET_SCHEMA));
8682
+ }
7983
8683
  function resolveTicketMaxTtl(grantKeys, env) {
7984
8684
  if (grantKeys)
7985
8685
  return Math.trunc(grantKeys.maxTtlSeconds);
@@ -8066,7 +8766,7 @@ async function sealAttach2(config, request, auth) {
8066
8766
  } catch (e) {
8067
8767
  throw new AttachTicketRequestError("seal_attach request is invalid", [["request", e.message]]);
8068
8768
  }
8069
- return { ticket: token, expires_at: expiresAt === 0 ? Number.POSITIVE_INFINITY : expiresAt };
8769
+ return { ticket: token, expires_at: expiresAt === 0 ? null : new Date(expiresAt * 1000) };
8070
8770
  }
8071
8771
  function buildAttachTicketsProtocol(config) {
8072
8772
  const p = new Protocol2(ATTACH_TICKETS_PROTOCOL_NAME, { protocolVersion: ATTACH_TICKETS_PROTOCOL_VERSION });
@@ -8077,8 +8777,7 @@ function buildAttachTicketsProtocol(config) {
8077
8777
  handler: async (params, ctx) => {
8078
8778
  const request = unwrapRequest(params.request);
8079
8779
  const sealed = await sealAttach2(config, request, ctx?.auth);
8080
- const batch = batchFromColumns({ ticket: [sealed.ticket], expires_at: [sealed.expires_at] }, ATTACH_TICKET_SCHEMA);
8081
- return { result: serializeBatch(batch) };
8780
+ return { result: encodeAttachTicket(sealed) };
8082
8781
  }
8083
8782
  });
8084
8783
  return p;
@@ -8164,10 +8863,13 @@ function catalogAdminHandlers(getCatalog, signingKey) {
8164
8863
  items: schemas.map((s) => encodeSchemaInfo(s))
8165
8864
  }, CatalogSchemasResultSchema);
8166
8865
  });
8167
- const catalogContents = catalogHandler(signingKey, async (params) => {
8168
- const ifNoneMatch = params.if_none_match == null ? null : String(params.if_none_match);
8169
- return serveCatalogContents(getCatalog(), toUint8Array(params.attach_opaque_data), ifNoneMatch);
8170
- });
8866
+ const catalogContents = async (params, ctx) => {
8867
+ const sealedAttach = toUint8Array(params.attach_opaque_data).slice();
8868
+ return catalogHandler(signingKey, async (opened, context) => {
8869
+ const ifNoneMatch = opened.if_none_match == null ? null : String(opened.if_none_match);
8870
+ return serveCatalogContents(getCatalog(), toUint8Array(opened.attach_opaque_data), ifNoneMatch, context, sealedAttach);
8871
+ })(params, ctx);
8872
+ };
8171
8873
  const catalogCopyFromFormats = catalogHandler(signingKey, async (params) => {
8172
8874
  const cat = getCatalog();
8173
8875
  const formats = await cat.copyFromFormats(toUint8Array(params.attach_opaque_data), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
@@ -8605,7 +9307,7 @@ function validatedHostedProtocols(hosting, primary) {
8605
9307
  }
8606
9308
  const name = p.name;
8607
9309
  if (name.startsWith(RESERVED_PREFIX)) {
8608
- throw new Error(`${owner} entry ${index} is named '${name}', which claims the reserved '${RESERVED_PREFIX}' prefix. ` + "Framework protocols are not supplied through this hook: reflection is hosted automatically, and " + "vgi_rpc.Identity.v1 is enabled by supplying resolveToken and/or mintGrant.");
9310
+ throw new Error(`${owner} entry ${index} is named '${name}', which claims the reserved '${RESERVED_PREFIX}' prefix. ` + "Framework protocols are not supplied through this hook: reflection is hosted automatically, and " + "vgi_rpc.Identity.v2 is enabled by supplying resolveToken and/or mintGrant.");
8609
9311
  }
8610
9312
  if (!/^[A-Za-z_][A-Za-z0-9_.]*$/.test(name)) {
8611
9313
  throw new Error(`${owner} entry ${index}: protocol name '${name}' is not an identifier, optionally dot-qualified ` + "(e.g. 'acme.Reports.v1').");
@@ -8655,7 +9357,7 @@ function resolveIntrospectPrincipals(explicit, env) {
8655
9357
  principals = raw.split(",").map((p) => p.trim()).filter((p) => p !== "");
8656
9358
  }
8657
9359
  if (principals.length === 0) {
8658
- throw new Error("This worker supplies resolveToken, which hosts the vgi_rpc.Identity.v1 protocol, but no " + `introspector allowlist was configured. Set ${INTROSPECT_PRINCIPALS_ENV} (comma-separated) or pass ` + `introspectPrincipals.
9360
+ throw new Error("This worker supplies resolveToken, which hosts the vgi_rpc.Identity.v2 protocol, but no " + `introspector allowlist was configured. Set ${INTROSPECT_PRINCIPALS_ENV} (comma-separated) or pass ` + `introspectPrincipals.
8659
9361
 
8660
9362
  ` + "There is no permissive default on purpose: introspection is a separate capability from " + "authentication, and allowing every authenticated caller lets any user resolve any other user's " + "credential to its owner. Remove resolveToken to leave the protocol unhosted entirely.");
8661
9363
  }
@@ -8890,4 +9592,4 @@ export {
8890
9592
  serveVgiWorker
8891
9593
  };
8892
9594
 
8893
- //# debugId=7D0DFE46FB512EAD64756E2164756E21
9595
+ //# debugId=1C595840C05DD34264756E2164756E21