@query-farm/vgi 0.48.4 → 0.49.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 (60) hide show
  1. package/README.md +52 -1
  2. package/dist/attach-secret-keyfile.d.ts +11 -0
  3. package/dist/attach-secret-options.d.ts +96 -0
  4. package/dist/catalog/attach-option.d.ts +6 -0
  5. package/dist/catalog/composite.d.ts +2 -0
  6. package/dist/catalog/descriptors.d.ts +11 -0
  7. package/dist/catalog/interface.d.ts +54 -2
  8. package/dist/catalog/scan-planning.d.ts +76 -0
  9. package/dist/client-entry.js +32 -4
  10. package/dist/client-entry.js.map +9 -8
  11. package/dist/generated/vgi-client.d.ts +1 -0
  12. package/dist/generated/vgi-protocol-schemas.d.ts +1 -1
  13. package/dist/generated/vgi-service.d.ts +5 -1
  14. package/dist/index.core.d.ts +3 -0
  15. package/dist/index.js +3245 -2538
  16. package/dist/index.js.map +32 -29
  17. package/dist/protocol/dispatch.d.ts +13 -2
  18. package/dist/protocol/handlers/catalog/admin.d.ts +1 -1
  19. package/dist/protocol/handlers/catalog/index.d.ts +1 -1
  20. package/dist/protocol/handlers/catalog/index_methods.d.ts +1 -1
  21. package/dist/protocol/handlers/catalog/macro.d.ts +1 -1
  22. package/dist/protocol/handlers/catalog/shared.d.ts +28 -3
  23. package/dist/protocol/handlers/catalog/table.d.ts +1 -1
  24. package/dist/protocol/handlers/catalog/view.d.ts +1 -1
  25. package/dist/protocol/handlers/function.d.ts +2 -0
  26. package/dist/protocol/handlers/table-buffering.d.ts +1 -1
  27. package/dist/serve-entry.d.ts +5 -0
  28. package/dist/serve-entry.js +2026 -101
  29. package/dist/serve-entry.js.map +27 -20
  30. package/dist/worker-cf-entry.d.ts +2 -2
  31. package/dist/worker-cf-entry.js +823 -103
  32. package/dist/worker-cf-entry.js.map +27 -24
  33. package/dist/worker.d.ts +10 -0
  34. package/package.json +1 -1
  35. package/src/attach-secret-keyfile.ts +185 -0
  36. package/src/attach-secret-options.ts +418 -0
  37. package/src/catalog/attach-option.ts +6 -0
  38. package/src/catalog/column-metadata.ts +7 -0
  39. package/src/catalog/composite.ts +5 -0
  40. package/src/catalog/descriptors.ts +11 -0
  41. package/src/catalog/interface.ts +97 -2
  42. package/src/catalog/read-only.ts +14 -1
  43. package/src/catalog/scan-planning.ts +314 -0
  44. package/src/generated/vgi-client.ts +2 -1
  45. package/src/generated/vgi-protocol-schemas.ts +6 -2
  46. package/src/generated/vgi-service.ts +7 -2
  47. package/src/index.core.ts +21 -0
  48. package/src/protocol/dispatch.ts +16 -4
  49. package/src/protocol/handlers/catalog/admin.ts +33 -18
  50. package/src/protocol/handlers/catalog/index.ts +6 -5
  51. package/src/protocol/handlers/catalog/index_methods.ts +5 -3
  52. package/src/protocol/handlers/catalog/macro.ts +7 -5
  53. package/src/protocol/handlers/catalog/shared.ts +52 -6
  54. package/src/protocol/handlers/catalog/table.ts +43 -30
  55. package/src/protocol/handlers/catalog/view.ts +9 -7
  56. package/src/protocol/handlers/function.ts +11 -5
  57. package/src/protocol/handlers/table-buffering.ts +2 -1
  58. package/src/serve-entry.ts +6 -1
  59. package/src/worker-cf-entry.ts +9 -0
  60. package/src/worker.ts +12 -0
@@ -684,6 +684,18 @@ function isBool(t) {
684
684
  function isDecimal(t) {
685
685
  return t.typeId === TypeId.Decimal;
686
686
  }
687
+ function isDate(t) {
688
+ return t.typeId === TypeId.Date;
689
+ }
690
+ function isTime(t) {
691
+ return t.typeId === TypeId.Time;
692
+ }
693
+ function isTimestamp(t) {
694
+ return t.typeId === TypeId.Timestamp;
695
+ }
696
+ function isInterval(t) {
697
+ return t.typeId === TypeId.Interval;
698
+ }
687
699
  function isList(t) {
688
700
  return t.typeId === TypeId.List;
689
701
  }
@@ -693,6 +705,9 @@ function isStruct(t) {
693
705
  function isMap(t) {
694
706
  return t.typeId === TypeId.Map;
695
707
  }
708
+ function isDuration(t) {
709
+ return t.typeId === TypeId.Duration;
710
+ }
696
711
  function isDictionary(t) {
697
712
  return t.typeId === TypeId.Dictionary;
698
713
  }
@@ -2474,6 +2489,1303 @@ function toUint8Array(val) {
2474
2489
  }
2475
2490
  return new Uint8Array(0);
2476
2491
  }
2492
+ // src/filter-pushdown/capabilities.ts
2493
+ var SUPPORTED_EXTENSION_FUNCTIONS = new Set(["duckdb.spatial/intersects_extent@1"]);
2494
+ function filterFunctionIdentityKey(identity) {
2495
+ return `${identity.namespace}/${identity.name}@${identity.version}`;
2496
+ }
2497
+ function supportsExtensionFilterFunction(identity) {
2498
+ return SUPPORTED_EXTENSION_FUNCTIONS.has(filterFunctionIdentityKey(identity));
2499
+ }
2500
+
2501
+ // src/filter-pushdown/types.ts
2502
+ var FILTER_ENCODING = "vgi.filters.v2";
2503
+ var FILTER_VERSION = "2";
2504
+ var DUCKDB_STANDARD_V1 = "vgi.duckdb.standard.v1";
2505
+ var NO_EVALUATION_CONTEXT = "vgi.none.v1";
2506
+ var DUCKDB_SESSION_CONTEXT = "vgi.duckdb.session.v1";
2507
+ var ComparisonOp;
2508
+ ((ComparisonOp) => {
2509
+ ComparisonOp["EQ"] = "eq";
2510
+ ComparisonOp["NE"] = "ne";
2511
+ ComparisonOp["LT"] = "lt";
2512
+ ComparisonOp["LE"] = "le";
2513
+ ComparisonOp["GT"] = "gt";
2514
+ ComparisonOp["GE"] = "ge";
2515
+ ComparisonOp["DISTINCT_FROM"] = "distinct_from";
2516
+ ComparisonOp["NOT_DISTINCT_FROM"] = "not_distinct_from";
2517
+ })(ComparisonOp ||= {});
2518
+
2519
+ // src/filter-pushdown/evaluate.ts
2520
+ var RESOLVED_COLUMNS = new WeakMap;
2521
+ function resolveColumn(batch, columnName) {
2522
+ let byName = RESOLVED_COLUMNS.get(batch);
2523
+ if (!byName) {
2524
+ byName = new Map;
2525
+ RESOLVED_COLUMNS.set(batch, byName);
2526
+ }
2527
+ let resolved = byName.get(columnName);
2528
+ if (resolved === undefined) {
2529
+ const index = batch.schema.fields.findIndex((field) => field.name === columnName);
2530
+ if (index < 0) {
2531
+ throw new FilterV2Error(`filter column ${columnName} is unavailable in emitted batch`);
2532
+ }
2533
+ const column = batch.getChildAt(index);
2534
+ const field = batch.schema.fields[index];
2535
+ resolved = column && field ? { type: field.type, column } : null;
2536
+ byName.set(columnName, resolved);
2537
+ }
2538
+ return resolved;
2539
+ }
2540
+ function deepEqual(left, right) {
2541
+ if (typeof left === "number" && typeof right === "number") {
2542
+ return left === right || Number.isNaN(left) && Number.isNaN(right);
2543
+ }
2544
+ if (left instanceof Uint8Array && right instanceof Uint8Array) {
2545
+ return left.length === right.length && left.every((value, index) => value === right[index]);
2546
+ }
2547
+ if (Array.isArray(left) && Array.isArray(right)) {
2548
+ return left.length === right.length && left.every((value, index) => deepEqual(value, right[index]));
2549
+ }
2550
+ if (left && right && typeof left === "object" && typeof right === "object") {
2551
+ const entries = Object.entries(left);
2552
+ const rightObject = right;
2553
+ return entries.length === Object.keys(rightObject).length && entries.every(([key, value]) => (key in rightObject) && deepEqual(value, rightObject[key]));
2554
+ }
2555
+ return left === right;
2556
+ }
2557
+ function orderedCompare(left, right) {
2558
+ if (typeof left === "number" && typeof right === "number") {
2559
+ const leftNan = Number.isNaN(left);
2560
+ const rightNan = Number.isNaN(right);
2561
+ if (leftNan || rightNan)
2562
+ return leftNan === rightNan ? 0 : leftNan ? 1 : -1;
2563
+ }
2564
+ if (deepEqual(left, right))
2565
+ return 0;
2566
+ return left < right ? -1 : 1;
2567
+ }
2568
+ function compare(left, right, op) {
2569
+ if (op === "distinct_from" /* DISTINCT_FROM */) {
2570
+ return left === null || right === null ? left !== right : !deepEqual(left, right);
2571
+ }
2572
+ if (op === "not_distinct_from" /* NOT_DISTINCT_FROM */) {
2573
+ return left === null || right === null ? left === right : deepEqual(left, right);
2574
+ }
2575
+ if (left === null || right === null)
2576
+ return null;
2577
+ const order = orderedCompare(left, right);
2578
+ switch (op) {
2579
+ case "eq" /* EQ */:
2580
+ return order === 0;
2581
+ case "ne" /* NE */:
2582
+ return order !== 0;
2583
+ case "lt" /* LT */:
2584
+ return order < 0;
2585
+ case "le" /* LE */:
2586
+ return order <= 0;
2587
+ case "gt" /* GT */:
2588
+ return order > 0;
2589
+ case "ge" /* GE */:
2590
+ return order >= 0;
2591
+ default:
2592
+ throw new FilterV2Error(`unknown comparison operator ${op}`);
2593
+ }
2594
+ }
2595
+ function andKleene(values) {
2596
+ if (values.some((value) => value === false))
2597
+ return false;
2598
+ return values.some((value) => value === null) ? null : true;
2599
+ }
2600
+ function orKleene(values) {
2601
+ if (values.some((value) => value === true))
2602
+ return true;
2603
+ return values.some((value) => value === null) ? null : false;
2604
+ }
2605
+ function integerBounds(type) {
2606
+ if (!isInt(type))
2607
+ return null;
2608
+ const width = BigInt(type.bitWidth ?? 32);
2609
+ const signed = type.isSigned ?? type.signed ?? true;
2610
+ return signed ? [-(1n << width - 1n), (1n << width - 1n) - 1n] : [0n, (1n << width) - 1n];
2611
+ }
2612
+ function castValue(value, type) {
2613
+ if (value === null)
2614
+ return null;
2615
+ if (isUtf8(type))
2616
+ return String(value);
2617
+ if (isBool(type)) {
2618
+ if (typeof value === "boolean")
2619
+ return value;
2620
+ if (value === 0 || value === 0n || value === "false")
2621
+ return false;
2622
+ if (value === 1 || value === 1n || value === "true")
2623
+ return true;
2624
+ throw new FilterV2Error(`cannot cast ${String(value)} to BOOLEAN`);
2625
+ }
2626
+ if (isFloat(type)) {
2627
+ const result = Number(value);
2628
+ if (Number.isNaN(result) && String(value).toLowerCase() !== "nan") {
2629
+ throw new FilterV2Error(`cannot cast ${String(value)} to floating point`);
2630
+ }
2631
+ return result;
2632
+ }
2633
+ const bounds = integerBounds(type);
2634
+ if (bounds) {
2635
+ let result;
2636
+ try {
2637
+ result = typeof value === "bigint" ? value : BigInt(typeof value === "number" ? Math.trunc(value) : String(value));
2638
+ } catch {
2639
+ throw new FilterV2Error(`cannot cast ${String(value)} to integer`);
2640
+ }
2641
+ if (result < bounds[0] || result > bounds[1])
2642
+ throw new FilterV2Error("integer cast overflow");
2643
+ return type.bitWidth === 64 ? result : Number(result);
2644
+ }
2645
+ throw new FilterV2Error(`no vgi.duckdb.standard.v1 cast evaluator for Arrow type ${type.typeId}`);
2646
+ }
2647
+ function numericBinary(op, left, right, context) {
2648
+ if (left === null || right === null)
2649
+ return null;
2650
+ if (typeof left !== "number" && typeof left !== "bigint" || typeof right !== "number" && typeof right !== "bigint") {
2651
+ throw new FilterV2Error("arithmetic operands must be numeric");
2652
+ }
2653
+ if (typeof left === "bigint" && typeof right === "bigint") {
2654
+ if ((op === "divide" || op === "modulo") && right === 0n)
2655
+ throw new FilterV2Error("division by zero");
2656
+ switch (op) {
2657
+ case "add":
2658
+ return left + right;
2659
+ case "subtract":
2660
+ return left - right;
2661
+ case "multiply":
2662
+ return left * right;
2663
+ case "divide":
2664
+ return context.integerDivision ? left / right : Number(left) / Number(right);
2665
+ case "modulo":
2666
+ return left % right;
2667
+ }
2668
+ }
2669
+ const a = Number(left);
2670
+ const b = Number(right);
2671
+ if ((op === "divide" || op === "modulo") && b === 0 && context.ieeeFloatingPointOps === false) {
2672
+ throw new FilterV2Error("division by zero");
2673
+ }
2674
+ switch (op) {
2675
+ case "add":
2676
+ return a + b;
2677
+ case "subtract":
2678
+ return a - b;
2679
+ case "multiply":
2680
+ return a * b;
2681
+ case "divide":
2682
+ return a / b;
2683
+ case "modulo":
2684
+ return a % b;
2685
+ }
2686
+ }
2687
+
2688
+ class WkbBoundsReader {
2689
+ view;
2690
+ offset = 0;
2691
+ constructor(bytes) {
2692
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2693
+ }
2694
+ read() {
2695
+ const bounds = this.geometry();
2696
+ if (this.offset !== this.view.byteLength)
2697
+ throw new FilterV2Error("WKB has trailing bytes");
2698
+ return bounds;
2699
+ }
2700
+ require(length) {
2701
+ if (length < 0 || this.offset + length > this.view.byteLength)
2702
+ throw new FilterV2Error("truncated WKB geometry");
2703
+ }
2704
+ byte() {
2705
+ this.require(1);
2706
+ return this.view.getUint8(this.offset++);
2707
+ }
2708
+ uint32(littleEndian) {
2709
+ this.require(4);
2710
+ const value = this.view.getUint32(this.offset, littleEndian);
2711
+ this.offset += 4;
2712
+ return value;
2713
+ }
2714
+ float64(littleEndian) {
2715
+ this.require(8);
2716
+ const value = this.view.getFloat64(this.offset, littleEndian);
2717
+ this.offset += 8;
2718
+ return value;
2719
+ }
2720
+ point(littleEndian, dimensions) {
2721
+ const x = this.float64(littleEndian);
2722
+ const y = this.float64(littleEndian);
2723
+ for (let dimension = 2;dimension < dimensions; dimension++)
2724
+ this.float64(littleEndian);
2725
+ if (Number.isNaN(x) && Number.isNaN(y))
2726
+ return null;
2727
+ if (!Number.isFinite(x) || !Number.isFinite(y))
2728
+ throw new FilterV2Error("WKB coordinate must be finite");
2729
+ return { minX: x, minY: y, maxX: x, maxY: y };
2730
+ }
2731
+ count(littleEndian) {
2732
+ const count = this.uint32(littleEndian);
2733
+ if (count > Math.floor((this.view.byteLength - this.offset) / 4)) {
2734
+ throw new FilterV2Error("WKB element count exceeds payload size");
2735
+ }
2736
+ return count;
2737
+ }
2738
+ merge(left, right) {
2739
+ if (!left)
2740
+ return right;
2741
+ if (!right)
2742
+ return left;
2743
+ return {
2744
+ minX: Math.min(left.minX, right.minX),
2745
+ minY: Math.min(left.minY, right.minY),
2746
+ maxX: Math.max(left.maxX, right.maxX),
2747
+ maxY: Math.max(left.maxY, right.maxY)
2748
+ };
2749
+ }
2750
+ points(littleEndian, dimensions) {
2751
+ let bounds = null;
2752
+ const count = this.count(littleEndian);
2753
+ for (let index = 0;index < count; index++)
2754
+ bounds = this.merge(bounds, this.point(littleEndian, dimensions));
2755
+ return bounds;
2756
+ }
2757
+ geometry() {
2758
+ const byteOrder = this.byte();
2759
+ if (byteOrder !== 0 && byteOrder !== 1)
2760
+ throw new FilterV2Error("invalid WKB byte order");
2761
+ const littleEndian = byteOrder === 1;
2762
+ const encodedType = this.uint32(littleEndian);
2763
+ const hasZ = (encodedType & 2147483648) !== 0;
2764
+ const hasM = (encodedType & 1073741824) !== 0;
2765
+ const hasSrid = (encodedType & 536870912) !== 0;
2766
+ let type = encodedType & 268435455;
2767
+ let dimensions = 2 + Number(hasZ) + Number(hasM);
2768
+ if (type >= 3000) {
2769
+ type -= 3000;
2770
+ dimensions = 4;
2771
+ } else if (type >= 2000) {
2772
+ type -= 2000;
2773
+ dimensions = 3;
2774
+ } else if (type >= 1000) {
2775
+ type -= 1000;
2776
+ dimensions = 3;
2777
+ }
2778
+ if (hasSrid)
2779
+ this.uint32(littleEndian);
2780
+ if (type === 1)
2781
+ return this.point(littleEndian, dimensions);
2782
+ if (type === 2)
2783
+ return this.points(littleEndian, dimensions);
2784
+ if (type === 3) {
2785
+ let bounds = null;
2786
+ const rings = this.count(littleEndian);
2787
+ for (let ring = 0;ring < rings; ring++)
2788
+ bounds = this.merge(bounds, this.points(littleEndian, dimensions));
2789
+ return bounds;
2790
+ }
2791
+ if (type >= 4 && type <= 7) {
2792
+ let bounds = null;
2793
+ const geometries = this.count(littleEndian);
2794
+ for (let index = 0;index < geometries; index++)
2795
+ bounds = this.merge(bounds, this.geometry());
2796
+ return bounds;
2797
+ }
2798
+ throw new FilterV2Error(`unsupported WKB geometry type ${type}`);
2799
+ }
2800
+ }
2801
+ function wkbBBox(bytes) {
2802
+ if (!(bytes instanceof Uint8Array))
2803
+ throw new FilterV2Error("spatial extent arguments must be WKB binary values");
2804
+ return new WkbBoundsReader(bytes).read();
2805
+ }
2806
+ function evaluateCall(expression, args) {
2807
+ if (args.some((value) => value === null))
2808
+ return null;
2809
+ if (typeof expression.function === "string") {
2810
+ const [left, right] = args;
2811
+ switch (expression.function) {
2812
+ case "starts_with":
2813
+ return String(left).startsWith(String(right));
2814
+ case "ends_with":
2815
+ return String(left).endsWith(String(right));
2816
+ case "contains":
2817
+ return String(left).includes(String(right));
2818
+ case "list_contains":
2819
+ return Array.isArray(left) && left.some((value) => value !== null && deepEqual(value, right));
2820
+ }
2821
+ }
2822
+ if (filterFunctionIdentityKey(expression.function) === "duckdb.spatial/intersects_extent@1") {
2823
+ const left = wkbBBox(args[0]);
2824
+ const right = wkbBBox(args[1]);
2825
+ return !!left && !!right && !(left.maxX < right.minX || left.minX > right.maxX || left.maxY < right.minY || left.minY > right.maxY);
2826
+ }
2827
+ throw new FilterV2Error("no evaluator for extension filter function");
2828
+ }
2829
+ function evaluateExpression(expression, batch, row, context) {
2830
+ switch (expression.node) {
2831
+ case "column_ref": {
2832
+ const resolved = resolveColumn(batch, expression.columnName);
2833
+ return resolved ? readCanonicalValue(resolved.type, resolved.column, row) : null;
2834
+ }
2835
+ case "field_ref": {
2836
+ const parent = evaluateExpression(expression.expression, batch, row, context);
2837
+ if (parent === null)
2838
+ return null;
2839
+ if (Array.isArray(parent))
2840
+ return parent[expression.fieldIndex] ?? null;
2841
+ return parent[expression.fieldName] ?? null;
2842
+ }
2843
+ case "literal":
2844
+ return expression.value;
2845
+ case "comparison":
2846
+ return compare(evaluateExpression(expression.left, batch, row, context), evaluateExpression(expression.right, batch, row, context), expression.op);
2847
+ case "and":
2848
+ return andKleene(expression.children.map((child) => evaluateExpression(child, batch, row, context)));
2849
+ case "or":
2850
+ return orKleene(expression.children.map((child) => evaluateExpression(child, batch, row, context)));
2851
+ case "not": {
2852
+ const value = evaluateExpression(expression.expression, batch, row, context);
2853
+ return value === null ? null : !value;
2854
+ }
2855
+ case "is_null": {
2856
+ const result = evaluateExpression(expression.expression, batch, row, context) === null;
2857
+ return expression.negated ? !result : result;
2858
+ }
2859
+ case "in": {
2860
+ const input = evaluateExpression(expression.expression, batch, row, context);
2861
+ if (input === null)
2862
+ return null;
2863
+ const matched = expression.set.values.some((value) => value !== null && deepEqual(input, value));
2864
+ let result = matched ? true : expression.set.values.some((value) => value === null) ? null : false;
2865
+ if (expression.negated && result !== null)
2866
+ result = !result;
2867
+ return result;
2868
+ }
2869
+ case "cast":
2870
+ return castValue(evaluateExpression(expression.expression, batch, row, context), expression.field.type);
2871
+ case "arithmetic":
2872
+ return numericBinary(expression.op, evaluateExpression(expression.left, batch, row, context), evaluateExpression(expression.right, batch, row, context), context);
2873
+ case "negate": {
2874
+ const value = evaluateExpression(expression.expression, batch, row, context);
2875
+ return value === null ? null : typeof value === "bigint" ? -value : -Number(value);
2876
+ }
2877
+ case "call":
2878
+ return evaluateCall(expression, expression.arguments.map((argument) => evaluateExpression(argument, batch, row, context)));
2879
+ case "runtime_filter":
2880
+ throw new FilterV2Error("runtime-filter artifact evaluator is unavailable");
2881
+ }
2882
+ }
2883
+ function expressionColumns(expression, output = new Map) {
2884
+ switch (expression.node) {
2885
+ case "column_ref":
2886
+ output.set(expression.columnIndex, expression.columnName);
2887
+ break;
2888
+ case "field_ref":
2889
+ case "not":
2890
+ case "is_null":
2891
+ case "cast":
2892
+ case "negate":
2893
+ expressionColumns(expression.expression, output);
2894
+ break;
2895
+ case "comparison":
2896
+ case "arithmetic":
2897
+ expressionColumns(expression.left, output);
2898
+ expressionColumns(expression.right, output);
2899
+ break;
2900
+ case "and":
2901
+ case "or":
2902
+ expression.children.forEach((child) => expressionColumns(child, output));
2903
+ break;
2904
+ case "in":
2905
+ expressionColumns(expression.expression, output);
2906
+ break;
2907
+ case "call":
2908
+ expression.arguments.forEach((argument) => expressionColumns(argument, output));
2909
+ break;
2910
+ case "runtime_filter":
2911
+ expressionColumns(expression.input, output);
2912
+ break;
2913
+ }
2914
+ return output;
2915
+ }
2916
+ function booleanColumnLeaf(expression) {
2917
+ const column = (node) => node.node === "column_ref" && node.dataType !== undefined && isBool(node.dataType) ? node.columnName : undefined;
2918
+ if (expression.node === "not") {
2919
+ const name = column(expression.expression);
2920
+ return name === undefined ? undefined : { columnName: name, value: false };
2921
+ }
2922
+ const name = column(expression);
2923
+ return name === undefined ? undefined : { columnName: name, value: true };
2924
+ }
2925
+ function discreteValues(expression, columnName) {
2926
+ const leaf = booleanColumnLeaf(expression);
2927
+ if (leaf && leaf.columnName === columnName)
2928
+ return [leaf.value];
2929
+ if (expression.node === "comparison" && expression.op === "eq" /* EQ */) {
2930
+ if (expression.left.node === "column_ref" && expression.left.columnName === columnName && expression.right.node === "literal")
2931
+ return [expression.right.value];
2932
+ if (expression.right.node === "column_ref" && expression.right.columnName === columnName && expression.left.node === "literal")
2933
+ return [expression.left.value];
2934
+ }
2935
+ if (expression.node === "in" && expression.expression.node === "column_ref" && expression.expression.columnName === columnName && !expression.negated)
2936
+ return expression.set.values;
2937
+ if (expression.node === "and") {
2938
+ for (const child of expression.children) {
2939
+ const values = discreteValues(child, columnName);
2940
+ if (values)
2941
+ return values;
2942
+ }
2943
+ }
2944
+ if (expression.node === "or") {
2945
+ const branches = expression.children.map((child) => discreteValues(child, columnName));
2946
+ if (branches.some((values) => values === null))
2947
+ return null;
2948
+ const result = [];
2949
+ for (const values of branches) {
2950
+ for (const value of values)
2951
+ if (!result.some((known) => deepEqual(known, value)))
2952
+ result.push(value);
2953
+ }
2954
+ return result;
2955
+ }
2956
+ return null;
2957
+ }
2958
+
2959
+ class PushdownFilters {
2960
+ predicates;
2961
+ evaluationContext;
2962
+ options;
2963
+ revisions;
2964
+ requiredIds;
2965
+ version = "2";
2966
+ constructor(predicates, evaluationContext, options, revisions = new Map, requiredIds = new Set) {
2967
+ this.predicates = predicates;
2968
+ this.evaluationContext = evaluationContext;
2969
+ this.options = options;
2970
+ this.revisions = revisions;
2971
+ this.requiredIds = requiredIds;
2972
+ }
2973
+ get filters() {
2974
+ return this.predicates.map((predicate) => predicate.expression);
2975
+ }
2976
+ applyDelta(batch) {
2977
+ return applyFilterDelta(this, batch);
2978
+ }
2979
+ withPredicateOrder(order) {
2980
+ const predicates = this.predicates;
2981
+ if (predicates.length === order.length && predicates.every((predicate, i) => predicate.id === order[i])) {
2982
+ return this;
2983
+ }
2984
+ const byId = new Map(predicates.map((predicate) => [predicate.id, predicate]));
2985
+ if (order.length !== byId.size || new Set(order).size !== order.length || !order.every((id) => byId.has(id))) {
2986
+ throw new FilterV2Error("recorded predicate order does not match the replayed filter state");
2987
+ }
2988
+ return new PushdownFilters(order.map((id) => byId.get(id)), this.evaluationContext, this.options, new Map(this.revisions), new Set(this.requiredIds));
2989
+ }
2990
+ evaluate(batch) {
2991
+ const mask = new Uint8Array(batch.numRows);
2992
+ mask.fill(1);
2993
+ for (const predicate of this.predicates) {
2994
+ if (predicate.expression.node === "runtime_filter" && !predicate.expression.supported)
2995
+ continue;
2996
+ let values;
2997
+ try {
2998
+ values = Array.from({ length: batch.numRows }, (_, row) => evaluateExpression(predicate.expression, batch, row, this.evaluationContext));
2999
+ } catch (error) {
3000
+ if (predicate.mode === "advisory")
3001
+ continue;
3002
+ throw error;
3003
+ }
3004
+ for (let row = 0;row < batch.numRows; row++)
3005
+ mask[row] &= values[row] === true ? 1 : 0;
3006
+ }
3007
+ return mask;
3008
+ }
3009
+ apply(batch) {
3010
+ if (!batch.numRows || !this.predicates.length)
3011
+ return batch;
3012
+ return filterBatch(batch, this.evaluate(batch));
3013
+ }
3014
+ filteredColumns() {
3015
+ const columns = new Set;
3016
+ for (const predicate of this.predicates) {
3017
+ for (const name of expressionColumns(predicate.expression).values())
3018
+ columns.add(name);
3019
+ }
3020
+ return [...columns].sort();
3021
+ }
3022
+ hasFilterForColumn(columnName) {
3023
+ return this.filteredColumns().includes(columnName);
3024
+ }
3025
+ getColumnValues(columnName) {
3026
+ for (const predicate of this.predicates) {
3027
+ const values = discreteValues(predicate.expression, columnName);
3028
+ if (values)
3029
+ return values;
3030
+ }
3031
+ return null;
3032
+ }
3033
+ toSql() {
3034
+ return this.predicates.map((predicate) => predicateToSql(predicate.expression)).join(" AND ");
3035
+ }
3036
+ }
3037
+ function quote(value) {
3038
+ if (value === null)
3039
+ return "NULL";
3040
+ if (typeof value === "string")
3041
+ return `'${value.replaceAll("'", "''")}'`;
3042
+ if (value instanceof Uint8Array)
3043
+ return `X'${[...value].map((byte) => byte.toString(16).padStart(2, "0")).join("")}'`;
3044
+ if (Array.isArray(value))
3045
+ return `[${value.map(quote).join(", ")}]`;
3046
+ return String(value);
3047
+ }
3048
+ function predicateToSql(expression) {
3049
+ const leaf = booleanColumnLeaf(expression);
3050
+ return leaf ? `${leaf.columnName} = ${quote(leaf.value)}` : expressionToSql(expression);
3051
+ }
3052
+ function expressionToSql(expression) {
3053
+ switch (expression.node) {
3054
+ case "column_ref":
3055
+ return expression.columnName;
3056
+ case "field_ref":
3057
+ return `${expressionToSql(expression.expression)}.${expression.fieldName}`;
3058
+ case "literal":
3059
+ return quote(expression.value);
3060
+ case "comparison": {
3061
+ const symbols = {
3062
+ ["eq" /* EQ */]: "=",
3063
+ ["ne" /* NE */]: "!=",
3064
+ ["lt" /* LT */]: "<",
3065
+ ["le" /* LE */]: "<=",
3066
+ ["gt" /* GT */]: ">",
3067
+ ["ge" /* GE */]: ">=",
3068
+ ["distinct_from" /* DISTINCT_FROM */]: "IS DISTINCT FROM",
3069
+ ["not_distinct_from" /* NOT_DISTINCT_FROM */]: "IS NOT DISTINCT FROM"
3070
+ };
3071
+ return `${expressionToSql(expression.left)} ${symbols[expression.op]} ${expressionToSql(expression.right)}`;
3072
+ }
3073
+ case "and":
3074
+ case "or":
3075
+ return `(${expression.children.map(predicateToSql).join(` ${expression.node.toUpperCase()} `)})`;
3076
+ case "not":
3077
+ return `(NOT ${expressionToSql(expression.expression)})`;
3078
+ case "is_null":
3079
+ return `${expressionToSql(expression.expression)} IS ${expression.negated ? "NOT " : ""}NULL`;
3080
+ case "in":
3081
+ return `${expressionToSql(expression.expression)} ${expression.negated ? "NOT " : ""}IN (${expression.set.values.map(quote).join(", ")})`;
3082
+ case "cast":
3083
+ return `CAST(${expressionToSql(expression.expression)} AS type_${expression.typeRef})`;
3084
+ case "arithmetic": {
3085
+ const symbols = { add: "+", subtract: "-", multiply: "*", divide: "/", modulo: "%" };
3086
+ return `(${expressionToSql(expression.left)} ${symbols[expression.op]} ${expressionToSql(expression.right)})`;
3087
+ }
3088
+ case "negate":
3089
+ return `(-${expressionToSql(expression.expression)})`;
3090
+ case "call": {
3091
+ const name = typeof expression.function === "string" ? expression.function : filterFunctionIdentityKey(expression.function);
3092
+ return `${name}(${expression.arguments.map(expressionToSql).join(", ")})`;
3093
+ }
3094
+ case "runtime_filter":
3095
+ return `${filterFunctionIdentityKey(expression.algorithm)}(${expressionToSql(expression.input)})`;
3096
+ }
3097
+ }
3098
+
3099
+ // src/filter-pushdown/deserialize.ts
3100
+ var MAX_JSON_BYTES = 1 << 20;
3101
+ var MAX_DEPTH = 64;
3102
+ var MAX_NODES = 1e4;
3103
+ var MAX_PREDICATES = 1024;
3104
+ var MAX_PREDICATE_IDS = 4096;
3105
+ var MAX_ARGUMENTS = 256;
3106
+ var MAX_ID_BYTES = 128;
3107
+ var MAX_FINGERPRINT_BYTES = 256;
3108
+ var PAYLOAD_NAME = /^(?:value|type|artifact)_(?:0|[1-9][0-9]*)$/;
3109
+ var IDENTITY_NAMESPACE = /^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9_]*)*$/;
3110
+ var IDENTITY_NAME = /^[a-z][a-z0-9_]*$/;
3111
+ var MODES = new Set(["required", "advisory"]);
3112
+ var SOURCES = new Set(["query", "join", "top_n", "split_refinement", "other"]);
3113
+ var STANDARD_FUNCTIONS = new Set([
3114
+ "starts_with",
3115
+ "ends_with",
3116
+ "contains",
3117
+ "list_contains"
3118
+ ]);
3119
+ var KNOWN_RUNTIME_ALGORITHMS = new Set([
3120
+ "duckdb.runtime_filter/bloom@1",
3121
+ "duckdb.runtime_filter/prefix_range@1"
3122
+ ]);
3123
+ var KNOWN_ARROW_EXTENSIONS = new Set([
3124
+ "arrow.bool8",
3125
+ "arrow.json",
3126
+ "arrow.uuid",
3127
+ "geoarrow.linestring",
3128
+ "geoarrow.multilinestring",
3129
+ "geoarrow.multipoint",
3130
+ "geoarrow.multipolygon",
3131
+ "geoarrow.point",
3132
+ "geoarrow.polygon",
3133
+ "geoarrow.wkb"
3134
+ ]);
3135
+
3136
+ class FilterV2Error extends Error {
3137
+ constructor(message) {
3138
+ super(message);
3139
+ this.name = "FilterV2Error";
3140
+ }
3141
+ }
3142
+ function utf8Length(value) {
3143
+ return new TextEncoder().encode(value).byteLength;
3144
+ }
3145
+ function expectObject(value, where) {
3146
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
3147
+ throw new FilterV2Error(`${where} must be a JSON object`);
3148
+ }
3149
+ return value;
3150
+ }
3151
+ function expectArray(value, where) {
3152
+ if (!Array.isArray(value))
3153
+ throw new FilterV2Error(`${where} must be a JSON array`);
3154
+ return value;
3155
+ }
3156
+ function expectString(value, where, allowEmpty = false) {
3157
+ if (typeof value !== "string" || !allowEmpty && value.length === 0) {
3158
+ throw new FilterV2Error(`${where} must be a${allowEmpty ? "" : " nonempty"} string`);
3159
+ }
3160
+ return value;
3161
+ }
3162
+ function expectBoolean(value, where) {
3163
+ if (typeof value !== "boolean")
3164
+ throw new FilterV2Error(`${where} must be a Boolean`);
3165
+ return value;
3166
+ }
3167
+ function expectUint(value, where, positive = false) {
3168
+ if (!Number.isSafeInteger(value) || value < (positive ? 1 : 0)) {
3169
+ throw new FilterV2Error(`${where} must be a safely representable unsigned integer`);
3170
+ }
3171
+ return value;
3172
+ }
3173
+ function expectKeys(object, required, optional, where) {
3174
+ const allowed = new Set([...required, ...optional]);
3175
+ const missing = required.filter((key) => !(key in object));
3176
+ const unknown = Object.keys(object).filter((key) => !allowed.has(key));
3177
+ if (missing.length)
3178
+ throw new FilterV2Error(`${where} is missing ${missing.join(", ")}`);
3179
+ if (unknown.length)
3180
+ throw new FilterV2Error(`${where} has unknown properties ${unknown.join(", ")}`);
3181
+ }
3182
+ function validateArrowExtensions(field) {
3183
+ const names = [
3184
+ field.metadata?.get("ARROW:extension:name"),
3185
+ field.type.extensionName,
3186
+ field.type.extension_name
3187
+ ].filter((value) => typeof value === "string");
3188
+ for (const name of names) {
3189
+ if (!KNOWN_ARROW_EXTENSIONS.has(name))
3190
+ throw new FilterV2Error(`unknown Arrow extension type ${name}`);
3191
+ }
3192
+ const children = field.type.children;
3193
+ children?.forEach(validateArrowExtensions);
3194
+ }
3195
+
3196
+ class StrictJsonParser {
3197
+ text;
3198
+ offset = 0;
3199
+ constructor(text) {
3200
+ this.text = text;
3201
+ }
3202
+ parse() {
3203
+ const result = this.value();
3204
+ this.space();
3205
+ if (this.offset !== this.text.length)
3206
+ throw this.error("trailing JSON data");
3207
+ return result;
3208
+ }
3209
+ error(message) {
3210
+ return new FilterV2Error(`invalid filter JSON at byte ${this.offset}: ${message}`);
3211
+ }
3212
+ space() {
3213
+ while (/\s/.test(this.text[this.offset] ?? ""))
3214
+ this.offset++;
3215
+ }
3216
+ value() {
3217
+ this.space();
3218
+ const ch = this.text[this.offset];
3219
+ if (ch === "{")
3220
+ return this.object();
3221
+ if (ch === "[")
3222
+ return this.array();
3223
+ if (ch === '"')
3224
+ return this.string();
3225
+ for (const [word, value] of [["true", true], ["false", false], ["null", null]]) {
3226
+ if (this.text.startsWith(word, this.offset)) {
3227
+ this.offset += word.length;
3228
+ return value;
3229
+ }
3230
+ }
3231
+ const match = this.text.slice(this.offset).match(/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/);
3232
+ if (match) {
3233
+ this.offset += match[0].length;
3234
+ const number = Number(match[0]);
3235
+ if (!Number.isFinite(number))
3236
+ throw this.error("non-finite number");
3237
+ return number;
3238
+ }
3239
+ throw this.error("expected a JSON value");
3240
+ }
3241
+ string() {
3242
+ const start = this.offset++;
3243
+ let escaped = false;
3244
+ while (this.offset < this.text.length) {
3245
+ const ch = this.text[this.offset++];
3246
+ if (!escaped && ch === '"') {
3247
+ try {
3248
+ return JSON.parse(this.text.slice(start, this.offset));
3249
+ } catch {
3250
+ throw this.error("invalid string escape");
3251
+ }
3252
+ }
3253
+ if (!escaped && ch.charCodeAt(0) < 32)
3254
+ throw this.error("control character in string");
3255
+ if (!escaped && ch === "\\")
3256
+ escaped = true;
3257
+ else
3258
+ escaped = false;
3259
+ }
3260
+ throw this.error("unterminated string");
3261
+ }
3262
+ object() {
3263
+ this.offset++;
3264
+ const result = {};
3265
+ const names = new Set;
3266
+ this.space();
3267
+ if (this.text[this.offset] === "}") {
3268
+ this.offset++;
3269
+ return result;
3270
+ }
3271
+ while (true) {
3272
+ this.space();
3273
+ if (this.text[this.offset] !== '"')
3274
+ throw this.error("expected object key");
3275
+ const key = this.string();
3276
+ if (names.has(key))
3277
+ throw this.error(`duplicate object key ${JSON.stringify(key)}`);
3278
+ names.add(key);
3279
+ this.space();
3280
+ if (this.text[this.offset++] !== ":")
3281
+ throw this.error("expected ':'");
3282
+ result[key] = this.value();
3283
+ this.space();
3284
+ const separator = this.text[this.offset++];
3285
+ if (separator === "}")
3286
+ return result;
3287
+ if (separator !== ",")
3288
+ throw this.error("expected ',' or '}'");
3289
+ }
3290
+ }
3291
+ array() {
3292
+ this.offset++;
3293
+ const result = [];
3294
+ this.space();
3295
+ if (this.text[this.offset] === "]") {
3296
+ this.offset++;
3297
+ return result;
3298
+ }
3299
+ while (true) {
3300
+ result.push(this.value());
3301
+ this.space();
3302
+ const separator = this.text[this.offset++];
3303
+ if (separator === "]")
3304
+ return result;
3305
+ if (separator !== ",")
3306
+ throw this.error("expected ',' or ']'");
3307
+ }
3308
+ }
3309
+ }
3310
+ function metadataValue(schema, key) {
3311
+ const value = schema.metadata?.get(key);
3312
+ if (value === undefined)
3313
+ throw new FilterV2Error(`missing schema metadata ${key}`);
3314
+ return value;
3315
+ }
3316
+ function parseContext(schema) {
3317
+ if (metadataValue(schema, "vgi_filter_encoding") !== FILTER_ENCODING) {
3318
+ throw new FilterV2Error("unsupported filter encoding");
3319
+ }
3320
+ if (metadataValue(schema, "vgi_filter_version") !== FILTER_VERSION) {
3321
+ throw new FilterV2Error("unsupported filter version");
3322
+ }
3323
+ const profile = metadataValue(schema, "vgi_evaluation_context");
3324
+ const contextKeys = [
3325
+ "vgi_time_zone",
3326
+ "vgi_calendar",
3327
+ "vgi_default_collation",
3328
+ "vgi_ieee_floating_point_ops",
3329
+ "vgi_integer_division",
3330
+ "vgi_context_provider_fingerprint"
3331
+ ];
3332
+ if (profile === NO_EVALUATION_CONTEXT) {
3333
+ if (contextKeys.some((key) => schema.metadata.has(key))) {
3334
+ throw new FilterV2Error("vgi.none.v1 forbids DuckDB session context metadata");
3335
+ }
3336
+ return { profile };
3337
+ }
3338
+ if (profile !== DUCKDB_SESSION_CONTEXT)
3339
+ throw new FilterV2Error(`unknown evaluation context ${profile}`);
3340
+ const required = contextKeys.slice(0, 5);
3341
+ for (const key of required)
3342
+ metadataValue(schema, key);
3343
+ const bool = (key) => {
3344
+ const value = metadataValue(schema, key);
3345
+ if (value !== "true" && value !== "false")
3346
+ throw new FilterV2Error(`${key} must be true or false`);
3347
+ return value === "true";
3348
+ };
3349
+ const fingerprint = schema.metadata.get("vgi_context_provider_fingerprint");
3350
+ if (fingerprint !== undefined && (!fingerprint || utf8Length(fingerprint) > MAX_FINGERPRINT_BYTES)) {
3351
+ throw new FilterV2Error("invalid context provider fingerprint");
3352
+ }
3353
+ return {
3354
+ profile,
3355
+ timeZone: metadataValue(schema, "vgi_time_zone"),
3356
+ calendar: metadataValue(schema, "vgi_calendar"),
3357
+ defaultCollation: metadataValue(schema, "vgi_default_collation"),
3358
+ ieeeFloatingPointOps: bool("vgi_ieee_floating_point_ops"),
3359
+ integerDivision: bool("vgi_integer_division"),
3360
+ providerFingerprint: fingerprint
3361
+ };
3362
+ }
3363
+
3364
+ class FilterParser {
3365
+ batch;
3366
+ options;
3367
+ nodes = 0;
3368
+ context;
3369
+ document;
3370
+ constructor(batch, options) {
3371
+ this.batch = batch;
3372
+ this.options = options;
3373
+ if (batch.numRows !== 1)
3374
+ throw new FilterV2Error("filter batch must contain exactly one row");
3375
+ const first = batch.schema.fields[0];
3376
+ if (!first || first.name !== "filter_spec" || first.nullable || !isUtf8(first.type)) {
3377
+ throw new FilterV2Error("first field must be filter_spec: utf8 not null");
3378
+ }
3379
+ const names = batch.schema.fields.map((field) => field.name);
3380
+ if (new Set(names).size !== names.length)
3381
+ throw new FilterV2Error("filter payload names must be unique");
3382
+ for (let i = 1;i < names.length; i++) {
3383
+ const name = names[i];
3384
+ if (!PAYLOAD_NAME.test(name))
3385
+ throw new FilterV2Error(`noncanonical payload name ${name}`);
3386
+ if (name.startsWith("type_") && this.valueAt(i) !== null) {
3387
+ throw new FilterV2Error(`${name} must contain NULL`);
3388
+ }
3389
+ }
3390
+ this.context = parseContext(batch.schema);
3391
+ this.validateContextCapability();
3392
+ const raw = this.valueAt(0);
3393
+ if (typeof raw !== "string" || utf8Length(raw) > MAX_JSON_BYTES) {
3394
+ throw new FilterV2Error("filter_spec must be UTF-8 JSON no larger than 1 MiB");
3395
+ }
3396
+ this.document = expectObject(new StrictJsonParser(raw).parse(), "filter document");
3397
+ }
3398
+ valueAt(index) {
3399
+ const column = this.batch.getChildAt(index);
3400
+ const field = this.batch.schema.fields[index];
3401
+ if (!column || !field)
3402
+ throw new FilterV2Error(`missing payload column ${index}`);
3403
+ return readCanonicalValue(field.type, column, 0);
3404
+ }
3405
+ validateContextCapability() {
3406
+ if (this.context.profile === NO_EVALUATION_CONTEXT)
3407
+ return;
3408
+ const matching = (this.options.evaluationContexts ?? []).filter((value) => value.profile === this.context.profile);
3409
+ if (!matching.length)
3410
+ throw new FilterV2Error(`evaluation context ${this.context.profile} was not advertised`);
3411
+ if (this.context.providerFingerprint !== undefined && !matching.some((value) => value.providerFingerprint === this.context.providerFingerprint)) {
3412
+ throw new FilterV2Error("evaluation context fingerprint was not advertised");
3413
+ }
3414
+ }
3415
+ header(kind, member) {
3416
+ expectKeys(this.document, ["encoding", "semantics", "kind", member], [], "filter document");
3417
+ if (this.document.encoding !== FILTER_ENCODING)
3418
+ throw new FilterV2Error("document encoding must be vgi.filters.v2");
3419
+ if (this.document.semantics !== DUCKDB_STANDARD_V1)
3420
+ throw new FilterV2Error("unsupported filter semantics");
3421
+ if (this.document.kind !== kind)
3422
+ throw new FilterV2Error(`expected a ${kind} document`);
3423
+ return expectArray(this.document[member], member);
3424
+ }
3425
+ snapshot() {
3426
+ const entries = this.header("snapshot", "predicates");
3427
+ if (entries.length > MAX_PREDICATES)
3428
+ throw new FilterV2Error("snapshot predicate limit exceeded");
3429
+ const predicates = entries.map((value, index) => this.predicate(expectObject(value, `predicates[${index}]`), `predicates[${index}]`));
3430
+ const ids = new Set;
3431
+ for (const predicate of predicates) {
3432
+ if (predicate.revision !== 0)
3433
+ throw new FilterV2Error("snapshot revisions must be zero");
3434
+ if (ids.has(predicate.id))
3435
+ throw new FilterV2Error(`duplicate predicate id ${predicate.id}`);
3436
+ ids.add(predicate.id);
3437
+ }
3438
+ return new PushdownFilters(predicates, this.context, this.options, new Map(predicates.map((p) => [p.id, 0])), new Set(predicates.filter((p) => p.mode === "required").map((p) => p.id)));
3439
+ }
3440
+ delta(prior) {
3441
+ if (JSON.stringify(this.context) !== JSON.stringify(prior.evaluationContext)) {
3442
+ throw new FilterV2Error("evaluation context changed within one scan");
3443
+ }
3444
+ const entries = this.header("delta", "updates");
3445
+ const live = new Map(prior.predicates.map((predicate) => [predicate.id, predicate]));
3446
+ const revisions = new Map(prior.revisions);
3447
+ const parsed = [];
3448
+ const seen = new Set;
3449
+ for (let index = 0;index < entries.length; index++) {
3450
+ const where = `updates[${index}]`;
3451
+ const object = expectObject(entries[index], where);
3452
+ const operation = expectString(object.operation, `${where}.operation`);
3453
+ const common = operation === "upsert" ? ["operation", "id", "revision", "mode", "source", "expression"] : ["operation", "id", "revision"];
3454
+ expectKeys(object, common, [], where);
3455
+ if (operation !== "upsert" && operation !== "remove")
3456
+ throw new FilterV2Error(`${where} has invalid operation`);
3457
+ const id = this.predicateId(object.id, where);
3458
+ const revision = expectUint(object.revision, `${where}.revision`);
3459
+ if (seen.has(id))
3460
+ throw new FilterV2Error(`duplicate delta predicate id ${id}`);
3461
+ seen.add(id);
3462
+ if (prior.requiredIds.has(id))
3463
+ throw new FilterV2Error(`delta targets required predicate ${id}`);
3464
+ if (operation === "upsert") {
3465
+ const mode = expectString(object.mode, `${where}.mode`);
3466
+ const source = expectString(object.source, `${where}.source`);
3467
+ if (!MODES.has(mode) || !SOURCES.has(source)) {
3468
+ throw new FilterV2Error(`${where} has unknown mode or source`);
3469
+ }
3470
+ expectObject(object.expression, `${where}.expression`);
3471
+ if (mode !== "advisory")
3472
+ throw new FilterV2Error("delta upserts must be advisory");
3473
+ }
3474
+ if (revision <= (revisions.get(id) ?? -1))
3475
+ continue;
3476
+ parsed.push({ id, revision, predicate: operation === "upsert" ? this.predicate(object, where, true) : undefined });
3477
+ }
3478
+ if (new Set([...revisions.keys(), ...parsed.map((entry) => entry.id)]).size > MAX_PREDICATE_IDS) {
3479
+ throw new FilterV2Error("delta predicate-id limit exceeded");
3480
+ }
3481
+ for (const update of parsed) {
3482
+ revisions.set(update.id, update.revision);
3483
+ if (update.predicate)
3484
+ live.set(update.id, update.predicate);
3485
+ else
3486
+ live.delete(update.id);
3487
+ }
3488
+ return new PushdownFilters([...live.values()], this.context, prior.options, revisions, new Set(prior.requiredIds));
3489
+ }
3490
+ predicateId(value, where) {
3491
+ const id = expectString(value, `${where}.id`);
3492
+ if (utf8Length(id) > MAX_ID_BYTES)
3493
+ throw new FilterV2Error(`${where}.id is too long`);
3494
+ return id;
3495
+ }
3496
+ predicate(object, where, update = false) {
3497
+ expectKeys(object, [...update ? ["operation"] : [], "id", "revision", "mode", "source", "expression"], [], where);
3498
+ const mode = expectString(object.mode, `${where}.mode`);
3499
+ const source = expectString(object.source, `${where}.source`);
3500
+ if (!MODES.has(mode) || !SOURCES.has(source))
3501
+ throw new FilterV2Error(`${where} has unknown mode or source`);
3502
+ const expression = this.expression(expectObject(object.expression, `${where}.expression`), 1, true);
3503
+ if (this.context.profile === NO_EVALUATION_CONTEXT && requiresSessionContext(expression)) {
3504
+ throw new FilterV2Error("context-dependent expression requires vgi.duckdb.session.v1");
3505
+ }
3506
+ if (expression.node === "runtime_filter" && mode !== "advisory") {
3507
+ throw new FilterV2Error("runtime_filter predicates must be advisory");
3508
+ }
3509
+ if (expression.node !== "runtime_filter" && !isBooleanExpression(expression)) {
3510
+ throw new FilterV2Error("predicate root must resolve to BOOLEAN");
3511
+ }
3512
+ return {
3513
+ id: this.predicateId(object.id, where),
3514
+ revision: expectUint(object.revision, `${where}.revision`),
3515
+ mode,
3516
+ source,
3517
+ expression
3518
+ };
3519
+ }
3520
+ payload(prefix, rawRef) {
3521
+ const ref = expectUint(rawRef, `${prefix}_ref`);
3522
+ const name = `${prefix}_${ref}`;
3523
+ const indexes = this.batch.schema.fields.flatMap((field, index) => field.name === name ? [index] : []);
3524
+ const index = indexes.length === 1 ? indexes[0] : undefined;
3525
+ if (index === undefined)
3526
+ throw new FilterV2Error(`missing or duplicate payload ${name}`);
3527
+ return { ref, field: this.batch.schema.fields[index], value: this.valueAt(index) };
3528
+ }
3529
+ identity(raw, where) {
3530
+ const object = expectObject(raw, where);
3531
+ expectKeys(object, ["namespace", "name", "version"], [], where);
3532
+ const identity = {
3533
+ namespace: expectString(object.namespace, `${where}.namespace`),
3534
+ name: expectString(object.name, `${where}.name`),
3535
+ version: expectUint(object.version, `${where}.version`, true)
3536
+ };
3537
+ if (!IDENTITY_NAMESPACE.test(identity.namespace) || !IDENTITY_NAME.test(identity.name)) {
3538
+ throw new FilterV2Error(`${where} has a noncanonical identity`);
3539
+ }
3540
+ return identity;
3541
+ }
3542
+ expression(object, depth, root = false) {
3543
+ if (depth > MAX_DEPTH)
3544
+ throw new FilterV2Error("expression depth limit exceeded");
3545
+ if (++this.nodes > MAX_NODES)
3546
+ throw new FilterV2Error("expression node limit exceeded");
3547
+ const node = object.node;
3548
+ const child = (value) => this.expression(expectObject(value, "child expression"), depth + 1);
3549
+ if (node === "column_ref") {
3550
+ expectKeys(object, ["node", "column_index", "column_name"], [], "column_ref");
3551
+ const columnIndex = expectUint(object.column_index, "column_ref.column_index");
3552
+ const columnName = expectString(object.column_name, "column_ref.column_name");
3553
+ const field = this.options.outputSchema.fields[columnIndex];
3554
+ if (!field || field.name !== columnName) {
3555
+ throw new FilterV2Error(`column_ref ${columnName} does not match index ${columnIndex}`);
3556
+ }
3557
+ validateArrowExtensions(field);
3558
+ return { node, columnIndex, columnName, dataType: field.type };
3559
+ }
3560
+ if (node === "field_ref") {
3561
+ expectKeys(object, ["node", "expression", "field_index", "field_name"], [], "field_ref");
3562
+ const expression = child(object.expression);
3563
+ const parent = expressionType(expression);
3564
+ if (!parent || !isStruct(parent))
3565
+ throw new FilterV2Error("field_ref input must be STRUCT");
3566
+ const fieldIndex = expectUint(object.field_index, "field_ref.field_index");
3567
+ const fieldName = expectString(object.field_name, "field_ref.field_name");
3568
+ const field = parent.children?.[fieldIndex];
3569
+ if (!field || field.name !== fieldName)
3570
+ throw new FilterV2Error("field_ref name/index mismatch");
3571
+ return { node, expression, fieldIndex, fieldName, dataType: field.type };
3572
+ }
3573
+ if (node === "literal") {
3574
+ expectKeys(object, ["node", "value_ref"], [], "literal");
3575
+ const payload = this.payload("value", object.value_ref);
3576
+ validateArrowExtensions(payload.field);
3577
+ return { node, valueRef: payload.ref, field: payload.field, value: payload.value };
3578
+ }
3579
+ if (node === "comparison") {
3580
+ expectKeys(object, ["node", "op", "left", "right"], [], "comparison");
3581
+ const op = expectString(object.op, "comparison.op");
3582
+ if (!Object.values(ComparisonOp).includes(op))
3583
+ throw new FilterV2Error(`unknown comparison operator ${op}`);
3584
+ return { node, op, left: child(object.left), right: child(object.right) };
3585
+ }
3586
+ if (node === "and" || node === "or") {
3587
+ expectKeys(object, ["node", "children"], [], node);
3588
+ const children = expectArray(object.children, `${node}.children`).map(child);
3589
+ if (children.length < 2 || children.some((value) => !isBooleanExpression(value))) {
3590
+ throw new FilterV2Error(`${node} requires at least two Boolean children`);
3591
+ }
3592
+ return { node, children };
3593
+ }
3594
+ if (node === "not") {
3595
+ expectKeys(object, ["node", "expression"], [], "not");
3596
+ const expression = child(object.expression);
3597
+ if (!isBooleanExpression(expression))
3598
+ throw new FilterV2Error("not input must be Boolean");
3599
+ return { node, expression };
3600
+ }
3601
+ if (node === "is_null") {
3602
+ expectKeys(object, ["node", "expression", "negated"], [], "is_null");
3603
+ return { node, expression: child(object.expression), negated: expectBoolean(object.negated, "is_null.negated") };
3604
+ }
3605
+ if (node === "in") {
3606
+ expectKeys(object, ["node", "expression", "set", "negated"], [], "in");
3607
+ const setObject = expectObject(object.set, "in.set");
3608
+ const kind = setObject.kind;
3609
+ let parsedSet;
3610
+ if (kind === "literal") {
3611
+ expectKeys(setObject, ["kind", "value_ref"], [], "in.set");
3612
+ const payload = this.payload("value", setObject.value_ref);
3613
+ validateArrowExtensions(payload.field);
3614
+ if (!isList(payload.field.type) || !Array.isArray(payload.value)) {
3615
+ throw new FilterV2Error("literal IN payload must be a non-NULL list");
3616
+ }
3617
+ parsedSet = { kind, valueRef: payload.ref, field: payload.field, values: payload.value };
3618
+ } else if (kind === "external") {
3619
+ expectKeys(setObject, ["kind", "batch_index", "column_index", "column_name"], [], "in.set");
3620
+ const batchIndex = expectUint(setObject.batch_index, "in.set.batch_index");
3621
+ const columnIndex = expectUint(setObject.column_index, "in.set.column_index");
3622
+ const columnName = expectString(setObject.column_name, "in.set.column_name");
3623
+ const batch = this.options.joinKeyBatches?.[batchIndex];
3624
+ const field = batch?.schema.fields[columnIndex];
3625
+ const column = batch?.getChildAt(columnIndex);
3626
+ if (!batch || !field || !column || field.name !== columnName) {
3627
+ throw new FilterV2Error("external IN reference is unavailable or mismatched");
3628
+ }
3629
+ validateArrowExtensions(field);
3630
+ const values = Array.from({ length: batch.numRows }, (_, index) => readCanonicalValue(field.type, column, index));
3631
+ parsedSet = { kind, batchIndex, columnIndex, columnName, values, batch };
3632
+ } else {
3633
+ throw new FilterV2Error("unknown IN set kind");
3634
+ }
3635
+ return { node, expression: child(object.expression), set: parsedSet, negated: expectBoolean(object.negated, "in.negated") };
3636
+ }
3637
+ if (node === "cast") {
3638
+ expectKeys(object, ["node", "expression", "type_ref"], [], "cast");
3639
+ const payload = this.payload("type", object.type_ref);
3640
+ validateArrowExtensions(payload.field);
3641
+ if (payload.value !== null)
3642
+ throw new FilterV2Error("cast type payload must be NULL");
3643
+ return { node, expression: child(object.expression), typeRef: payload.ref, field: payload.field };
3644
+ }
3645
+ if (node === "arithmetic") {
3646
+ expectKeys(object, ["node", "op", "left", "right"], [], "arithmetic");
3647
+ const op = expectString(object.op, "arithmetic.op");
3648
+ if (!["add", "subtract", "multiply", "divide", "modulo"].includes(op)) {
3649
+ throw new FilterV2Error(`unknown arithmetic operator ${op}`);
3650
+ }
3651
+ return { node, op, left: child(object.left), right: child(object.right) };
3652
+ }
3653
+ if (node === "negate") {
3654
+ expectKeys(object, ["node", "expression"], [], "negate");
3655
+ return { node, expression: child(object.expression) };
3656
+ }
3657
+ if (node === "call") {
3658
+ expectKeys(object, ["node", "function", "arguments"], ["options"], "call");
3659
+ let fn;
3660
+ if (typeof object.function === "string") {
3661
+ if (!STANDARD_FUNCTIONS.has(object.function)) {
3662
+ throw new FilterV2Error(`unknown standard filter function ${object.function}`);
3663
+ }
3664
+ fn = object.function;
3665
+ } else {
3666
+ fn = this.identity(object.function, "call.function");
3667
+ const key = filterFunctionIdentityKey(fn);
3668
+ if (!supportsExtensionFilterFunction(fn))
3669
+ throw new FilterV2Error(`unknown extension function ${key}`);
3670
+ if (!(this.options.extensionFunctions ?? []).some((value) => filterFunctionIdentityKey(value) === key)) {
3671
+ throw new FilterV2Error(`extension function ${key} was not advertised`);
3672
+ }
3673
+ }
3674
+ const args = expectArray(object.arguments, "call.arguments");
3675
+ if (args.length > MAX_ARGUMENTS)
3676
+ throw new FilterV2Error("call argument limit exceeded");
3677
+ if (args.length !== 2)
3678
+ throw new FilterV2Error("registered v2 filter functions require exactly two arguments");
3679
+ const parsedArgs = args.map(child);
3680
+ if (typeof fn === "string")
3681
+ validateStandardCall(fn, parsedArgs);
3682
+ const options = object.options === undefined ? undefined : expectObject(object.options, "call.options");
3683
+ if (typeof fn === "string" && options !== undefined)
3684
+ throw new FilterV2Error("standard functions forbid options");
3685
+ if (options && Object.keys(options).length)
3686
+ throw new FilterV2Error("extension function options are unsupported");
3687
+ return { node, function: fn, arguments: parsedArgs, options };
3688
+ }
3689
+ if (node === "runtime_filter") {
3690
+ expectKeys(object, ["node", "algorithm", "input", "artifact_ref", "null_handling"], [], "runtime_filter");
3691
+ if (!root)
3692
+ throw new FilterV2Error("runtime_filter is allowed only at a predicate root");
3693
+ const algorithm = this.identity(object.algorithm, "runtime_filter.algorithm");
3694
+ const key = filterFunctionIdentityKey(algorithm);
3695
+ if (!KNOWN_RUNTIME_ALGORITHMS.has(key))
3696
+ throw new FilterV2Error(`unknown runtime filter ${key}`);
3697
+ const payload = this.payload("artifact", object.artifact_ref);
3698
+ validateArrowExtensions(payload.field);
3699
+ const nullHandling = expectString(object.null_handling, "runtime_filter.null_handling");
3700
+ if (nullHandling !== "pass" && nullHandling !== "reject")
3701
+ throw new FilterV2Error("invalid runtime null handling");
3702
+ const supported = (this.options.runtimeAlgorithms ?? []).some((value) => filterFunctionIdentityKey(value) === key);
3703
+ if (supported)
3704
+ throw new FilterV2Error("runtime algorithm was advertised without an evaluator");
3705
+ return {
3706
+ node,
3707
+ algorithm,
3708
+ input: child(object.input),
3709
+ artifactRef: payload.ref,
3710
+ field: payload.field,
3711
+ artifact: payload.value,
3712
+ nullHandling,
3713
+ supported
3714
+ };
3715
+ }
3716
+ throw new FilterV2Error(`unknown expression node ${String(node)}`);
3717
+ }
3718
+ }
3719
+ function expressionType(expression) {
3720
+ switch (expression.node) {
3721
+ case "column_ref":
3722
+ return expression.dataType;
3723
+ case "field_ref":
3724
+ return expression.dataType;
3725
+ case "literal":
3726
+ return expression.field.type;
3727
+ case "cast":
3728
+ return expression.field.type;
3729
+ default:
3730
+ return;
3731
+ }
3732
+ }
3733
+ function validateStandardCall(fn, args) {
3734
+ const types = args.map(expressionType);
3735
+ let matches = false;
3736
+ if (fn === "starts_with" || fn === "ends_with" || fn === "contains") {
3737
+ matches = types.every((type) => type !== undefined && isUtf8(type));
3738
+ } else if (fn === "list_contains") {
3739
+ const listType = types[0];
3740
+ const needleType = types[1];
3741
+ const element = listType && isList(listType) ? listType.children?.[0]?.type : undefined;
3742
+ matches = element !== undefined && needleType !== undefined && typeSignature(element) === typeSignature(needleType);
3743
+ }
3744
+ if (!matches)
3745
+ throw new FilterV2Error(`${fn} arguments do not bind under vgi.duckdb.standard.v1`);
3746
+ }
3747
+ function isBooleanExpression(expression) {
3748
+ if (["comparison", "and", "or", "not", "is_null", "in", "runtime_filter", "call"].includes(expression.node)) {
3749
+ return true;
3750
+ }
3751
+ const type = expressionType(expression);
3752
+ return type !== undefined && isBool(type);
3753
+ }
3754
+ function requiresSessionContext(expression) {
3755
+ switch (expression.node) {
3756
+ case "arithmetic":
3757
+ return expression.op === "divide" || expression.op === "modulo" || requiresSessionContext(expression.left) || requiresSessionContext(expression.right);
3758
+ case "cast":
3759
+ const source = expressionType(expression.expression);
3760
+ const contextual = (type) => !!type && (isUtf8(type) || isDate(type) || isTime(type) || isTimestamp(type));
3761
+ return contextual(source) && contextual(expression.field.type) || requiresSessionContext(expression.expression);
3762
+ case "field_ref":
3763
+ case "not":
3764
+ case "is_null":
3765
+ case "negate":
3766
+ return requiresSessionContext(expression.expression);
3767
+ case "comparison":
3768
+ return requiresSessionContext(expression.left) || requiresSessionContext(expression.right);
3769
+ case "and":
3770
+ case "or":
3771
+ return expression.children.some(requiresSessionContext);
3772
+ case "in":
3773
+ return requiresSessionContext(expression.expression);
3774
+ case "call":
3775
+ return expression.arguments.some(requiresSessionContext);
3776
+ case "runtime_filter":
3777
+ return requiresSessionContext(expression.input);
3778
+ default:
3779
+ return false;
3780
+ }
3781
+ }
3782
+ function deserializeFilters(batch, options) {
3783
+ return new FilterParser(batch, options).snapshot();
3784
+ }
3785
+ function applyFilterDelta(prior, batch) {
3786
+ return new FilterParser(batch, prior.options).delta(prior);
3787
+ }
3788
+
2477
3789
  // src/filter-pushdown/history.ts
2478
3790
  var MAX_ENCODED_DELTA_BYTES = 24 << 20;
2479
3791
  var MAX_DELTA_IPC_BYTES = 17 << 20;
@@ -3411,7 +4723,7 @@ import {
3411
4723
  Protocol
3412
4724
  } from "@query-farm/vgi-rpc";
3413
4725
  var VGI_PROTOCOL_NAME = "vgi.v3";
3414
- var VGI_PROTOCOL_VERSION = "3.1.0";
4726
+ var VGI_PROTOCOL_VERSION = "3.2.0";
3415
4727
  function exchangeStream(callbacks) {
3416
4728
  return { kind: "exchange", ...callbacks };
3417
4729
  }
@@ -4281,7 +5593,8 @@ var VGI_V3_METHODS = [
4281
5593
  field2("name", utf82(), false),
4282
5594
  field2("at_unit", utf82(), true),
4283
5595
  field2("at_value", utf82(), true),
4284
- field2("transaction_opaque_data", binary2(), true)
5596
+ field2("transaction_opaque_data", binary2(), true),
5597
+ field2("pushdown_filters", binary2(), true)
4285
5598
  ]),
4286
5599
  result: schema2([
4287
5600
  field2("result", binary2(), false)
@@ -4883,7 +6196,7 @@ function createVgiProtocol(service) {
4883
6196
  }
4884
6197
 
4885
6198
  // src/generated/vgi-protocol-schemas.ts
4886
- var VGI_CATALOG_CONTRACT_HASH = "1d12ce672b43ca1510721f89637bb374d27693b100d357ac2ead99fcddc27e9f";
6199
+ var VGI_CATALOG_CONTRACT_HASH = "d9304d52d78b0ceb90319d9a83759781df4a711b72443790654335c8cfcad9bf";
4887
6200
  var CatalogInfoSchema = schema2([
4888
6201
  field2("name", utf82(), false),
4889
6202
  field2("implementation_version", utf82(), true),
@@ -4919,7 +6232,8 @@ var TableInfoSchema = schema2([
4919
6232
  field2("bind_result", binary2(), true),
4920
6233
  field2("required_filters", list2(field2("item", list2(field2("item", list2(field2("item", utf82(), true)), true)), true)), false),
4921
6234
  field2("options", binary2(), true),
4922
- field2("layout", binary2(), true)
6235
+ field2("layout", binary2(), true),
6236
+ field2("scan_planning", utf82(), false)
4923
6237
  ]);
4924
6238
  var ViewInfoSchema = schema2([
4925
6239
  field2("comment", utf82(), true),
@@ -5243,7 +6557,9 @@ var ScanBranchSchema = schema2([
5243
6557
  field2("format_name", utf82(), true),
5244
6558
  field2("format_locations", list2(field2("item", utf82(), true)), true),
5245
6559
  field2("format_options", binary2(), true),
5246
- field2("schema_path", list2(field2("item", utf82(), true)), true)
6560
+ field2("schema_path", list2(field2("item", utf82(), true)), true),
6561
+ field2("row_count", int642(), true),
6562
+ field2("column_statistics", binary2(), true)
5247
6563
  ]);
5248
6564
  var ScanSplitSchema = schema2([
5249
6565
  field2("payload", binary2(), false),
@@ -6086,7 +7402,8 @@ var CatalogTableScanBranchesGetParamsSchema = schema2([
6086
7402
  field2("name", utf82(), false),
6087
7403
  field2("at_unit", utf82(), true),
6088
7404
  field2("at_value", utf82(), true),
6089
- field2("transaction_opaque_data", binary2(), true)
7405
+ field2("transaction_opaque_data", binary2(), true),
7406
+ field2("pushdown_filters", binary2(), true)
6090
7407
  ]);
6091
7408
  var CatalogTableScanFunctionGetParamsSchema = schema2([
6092
7409
  field2("attach_opaque_data", binary2(), false),
@@ -8270,13 +9587,382 @@ async function openBytes(token, key, aad, version, field = "opaque data") {
8270
9587
  }
8271
9588
  }
8272
9589
 
9590
+ // src/attach-secret-keyfile.ts
9591
+ function builtins() {
9592
+ const proc = globalThis.process;
9593
+ const get = proc?.getBuiltinModule?.bind(proc);
9594
+ const fs = get?.("node:fs");
9595
+ const os = get?.("node:os");
9596
+ const path = get?.("node:path");
9597
+ if (!fs || !os || !path)
9598
+ throw new Error("this runtime has no filesystem for the host-local attach secret key file.");
9599
+ return { fs, os, path };
9600
+ }
9601
+ var ATTACH_SECRET_KEY_FILE_ENV = "VGI_ATTACH_SECRET_KEY_FILE";
9602
+ var KEY_LEN = 32;
9603
+ var FILE_NAME = "attach-secret-options.key";
9604
+ var REMEDY = "Set VGI_SIGNING_KEY (or configure attachSecretKey), or point VGI_ATTACH_SECRET_KEY_FILE at a valid key file.";
9605
+ function username() {
9606
+ try {
9607
+ const name = builtins().os.userInfo().username;
9608
+ if (name)
9609
+ return name;
9610
+ } catch {}
9611
+ return process.env.USER || process.env.USERNAME || String(process.getuid?.() ?? "user");
9612
+ }
9613
+ function isDirectory(path) {
9614
+ try {
9615
+ return builtins().fs.statSync(path).isDirectory();
9616
+ } catch {
9617
+ return false;
9618
+ }
9619
+ }
9620
+ function hostLocalAttachSecretKeyPath(env = globalThis.process?.env ?? {}) {
9621
+ const { os, path: { join } } = builtins();
9622
+ const explicit = env[ATTACH_SECRET_KEY_FILE_ENV];
9623
+ if (explicit)
9624
+ return explicit;
9625
+ const xdg = env.XDG_RUNTIME_DIR;
9626
+ if (xdg && isDirectory(xdg))
9627
+ return join(xdg, "vgi", FILE_NAME);
9628
+ return join(os.tmpdir(), `vgi-${username()}`, FILE_NAME);
9629
+ }
9630
+ var POSIX = typeof process === "undefined" || process.platform !== "win32";
9631
+ function checkOwnedPrivate(path, mode, uid, what) {
9632
+ if (!POSIX)
9633
+ return;
9634
+ const me = process.getuid?.();
9635
+ if (me !== undefined && uid !== me) {
9636
+ throw new Error(`attach secret key ${what} ${path} is not owned by the current user. ${REMEDY}`);
9637
+ }
9638
+ if ((mode & 63) !== 0) {
9639
+ throw new Error(`attach secret key ${what} ${path} is accessible by group/other (mode ${(mode & 511).toString(8)}); ` + `it must be ${what === "directory" ? "0700" : "0600"}. ${REMEDY}`);
9640
+ }
9641
+ }
9642
+ function ensureDir(dir) {
9643
+ const { mkdirSync, lstatSync } = builtins().fs;
9644
+ try {
9645
+ mkdirSync(dir, { recursive: true, mode: 448 });
9646
+ } catch (e) {
9647
+ if (e.code !== "EEXIST")
9648
+ throw e;
9649
+ }
9650
+ const st = lstatSync(dir);
9651
+ if (!st.isDirectory())
9652
+ throw new Error(`attach secret key directory ${dir} is not a directory. ${REMEDY}`);
9653
+ checkOwnedPrivate(dir, st.mode, st.uid, "directory");
9654
+ }
9655
+ function readKey(path) {
9656
+ const { openSync, fstatSync, readSync, closeSync, constants } = builtins().fs;
9657
+ let fd;
9658
+ try {
9659
+ fd = openSync(path, constants.O_RDONLY | (POSIX ? constants.O_NOFOLLOW : 0));
9660
+ } catch (e) {
9661
+ if (e.code === "ENOENT")
9662
+ return null;
9663
+ throw new Error(`attach secret key file ${path} cannot be opened (${e.code}). ${REMEDY}`);
9664
+ }
9665
+ try {
9666
+ const st = fstatSync(fd);
9667
+ if (!st.isFile())
9668
+ throw new Error(`attach secret key file ${path} is not a regular file. ${REMEDY}`);
9669
+ checkOwnedPrivate(path, st.mode, st.uid, "file");
9670
+ const buf = new Uint8Array(KEY_LEN + 1);
9671
+ let n = 0;
9672
+ for (;; ) {
9673
+ const got = readSync(fd, buf, n, buf.length - n, null);
9674
+ if (got <= 0)
9675
+ break;
9676
+ n += got;
9677
+ if (n === buf.length)
9678
+ break;
9679
+ }
9680
+ if (n !== KEY_LEN || st.size !== KEY_LEN) {
9681
+ throw new Error(`attach secret key file ${path} must contain exactly ${KEY_LEN} raw bytes (found ${st.size}). ${REMEDY}`);
9682
+ }
9683
+ return buf.subarray(0, KEY_LEN);
9684
+ } finally {
9685
+ closeSync(fd);
9686
+ }
9687
+ }
9688
+ function createKey(path) {
9689
+ const { openSync, writeSync, fsyncSync, closeSync, linkSync, unlinkSync, constants } = builtins().fs;
9690
+ const { dirname, join } = builtins().path;
9691
+ const tmp = join(dirname(path), `.${FILE_NAME}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
9692
+ const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384);
9693
+ try {
9694
+ const key = crypto.getRandomValues(new Uint8Array(KEY_LEN));
9695
+ let off = 0;
9696
+ while (off < KEY_LEN)
9697
+ off += writeSync(fd, key, off, KEY_LEN - off);
9698
+ fsyncSync(fd);
9699
+ } finally {
9700
+ closeSync(fd);
9701
+ }
9702
+ try {
9703
+ linkSync(tmp, path);
9704
+ } catch (e) {
9705
+ if (e.code !== "EEXIST") {
9706
+ unlinkSync(tmp);
9707
+ throw e;
9708
+ }
9709
+ }
9710
+ unlinkSync(tmp);
9711
+ }
9712
+ function loadHostLocalAttachSecretKey(path = hostLocalAttachSecretKeyPath()) {
9713
+ ensureDir(builtins().path.dirname(path));
9714
+ const existing = readKey(path);
9715
+ if (existing)
9716
+ return existing;
9717
+ createKey(path);
9718
+ const created = readKey(path);
9719
+ if (!created)
9720
+ throw new Error(`attach secret key file ${path} vanished after creation. ${REMEDY}`);
9721
+ return created;
9722
+ }
9723
+ var cached;
9724
+ async function hostLocalAttachSecretKey() {
9725
+ const path = hostLocalAttachSecretKeyPath();
9726
+ if (cached?.path === path)
9727
+ return cached.key;
9728
+ const key = loadHostLocalAttachSecretKey(path);
9729
+ cached = { path, key };
9730
+ return key;
9731
+ }
9732
+
9733
+ // src/attach-secret-options.ts
9734
+ var UTF82 = new TextEncoder;
9735
+ var ATTACH_SECRET_OPTIONS_INFO = "vgi.attach_secret_options.v1";
9736
+ var ATTACH_SECRET_OPTIONS_VERSION = 1;
9737
+ var TRAILER_MAGIC = Uint8Array.of(0, 86, 71, 73, 65, 79, 1, 255);
9738
+ var TRAILER_FIXED = 4 + TRAILER_MAGIC.length;
9739
+ var NONCE_LEN2 = 24;
9740
+ var TAG_LEN2 = 16;
9741
+ var AAD_PREFIX = UTF82.encode(`${ATTACH_SECRET_OPTIONS_INFO}\x00`);
9742
+ var UUID_LEN = 16;
9743
+ var FIELD = "attach_opaque_data";
9744
+
9745
+ class AttachSecretKeyUnavailableError extends Error {
9746
+ constructor(message) {
9747
+ super(message);
9748
+ this.name = "AttachSecretKeyUnavailableError";
9749
+ }
9750
+ }
9751
+ var subkeys = new Map;
9752
+ function hexOf(b) {
9753
+ let s = "";
9754
+ for (let i = 0;i < b.length; i++)
9755
+ s += b[i].toString(16).padStart(2, "0");
9756
+ return s;
9757
+ }
9758
+ function deriveAttachSecretKey(root) {
9759
+ const id = hexOf(root);
9760
+ let derived = subkeys.get(id);
9761
+ if (!derived) {
9762
+ derived = (async () => {
9763
+ const ikm = await crypto.subtle.importKey("raw", root, "HKDF", false, ["deriveBits"]);
9764
+ const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: UTF82.encode(ATTACH_SECRET_OPTIONS_INFO) }, ikm, 256);
9765
+ return new Uint8Array(bits);
9766
+ })();
9767
+ subkeys.set(id, derived);
9768
+ derived.catch(() => subkeys.delete(id));
9769
+ }
9770
+ return derived;
9771
+ }
9772
+ function defaultHostLocal() {
9773
+ return hostLocalAttachSecretKey();
9774
+ }
9775
+ function noKeyMessage() {
9776
+ return "A secret ATTACH option has a value but this worker has no key to encrypt it with: configure " + "`attachSecretKey`, run with a signing key (VGI_SIGNING_KEY), or run where the host-local key file " + "(VGI_ATTACH_SECRET_KEY_FILE) can be used.";
9777
+ }
9778
+ async function rootKey(source) {
9779
+ if (source.explicit && source.explicit.length > 0)
9780
+ return source.explicit;
9781
+ if (source.signingKey && source.signingKey.length > 0)
9782
+ return source.signingKey;
9783
+ return (source.hostLocal ?? defaultHostLocal)();
9784
+ }
9785
+ function aadFor(uuid) {
9786
+ const out = new Uint8Array(AAD_PREFIX.length + uuid.length);
9787
+ out.set(AAD_PREFIX, 0);
9788
+ out.set(uuid, AAD_PREFIX.length);
9789
+ return out;
9790
+ }
9791
+ function u32le(n) {
9792
+ const b = new Uint8Array(4);
9793
+ new DataView(b.buffer).setUint32(0, n, true);
9794
+ return b;
9795
+ }
9796
+ function readU32le(b, off) {
9797
+ return new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(off, true);
9798
+ }
9799
+ function concat2(...parts) {
9800
+ let total = 0;
9801
+ for (const p of parts)
9802
+ total += p.length;
9803
+ const out = new Uint8Array(total);
9804
+ let off = 0;
9805
+ for (const p of parts) {
9806
+ out.set(p, off);
9807
+ off += p.length;
9808
+ }
9809
+ return out;
9810
+ }
9811
+ function splitOptions(optionsIpc, secretNames) {
9812
+ if (!optionsIpc || optionsIpc.length === 0)
9813
+ return null;
9814
+ const batch = deserializeBatch(optionsIpc);
9815
+ if (batch.numRows === 0 || batch.schema.fields.length === 0)
9816
+ return null;
9817
+ const row = iterRows(batch).next().value ?? {};
9818
+ const plainFields = [];
9819
+ const secretFields = [];
9820
+ const plainCols = {};
9821
+ const secretCols = {};
9822
+ for (const f of batch.schema.fields) {
9823
+ const value = row[f.name];
9824
+ if (secretNames.has(f.name.toLowerCase()) && value !== null && value !== undefined) {
9825
+ secretFields.push(f);
9826
+ secretCols[f.name] = [value];
9827
+ } else {
9828
+ plainFields.push(f);
9829
+ plainCols[f.name] = [value ?? null];
9830
+ }
9831
+ }
9832
+ return {
9833
+ plain: plainFields.length ? serializeBatch(batchFromColumns(plainCols, schema2(plainFields))) : null,
9834
+ secret: secretFields.length ? serializeBatch(batchFromColumns(secretCols, schema2(secretFields))) : null
9835
+ };
9836
+ }
9837
+ async function packAttachOptionsTrailer(uuid, optionsIpc, secretNames, keys, fixedNonce) {
9838
+ const split = splitOptions(optionsIpc, secretNames);
9839
+ if (split === null)
9840
+ return new Uint8Array(0);
9841
+ const plain = split.plain ?? new Uint8Array(0);
9842
+ let secret = new Uint8Array(0);
9843
+ if (split.secret) {
9844
+ let root;
9845
+ try {
9846
+ root = await rootKey(keys);
9847
+ } catch (e) {
9848
+ if (e instanceof AttachSecretKeyUnavailableError)
9849
+ throw e;
9850
+ throw new AttachSecretKeyUnavailableError(`${noKeyMessage()} ${e.message}`);
9851
+ }
9852
+ const key = await deriveAttachSecretKey(root);
9853
+ const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN2));
9854
+ const ct = xchacha20poly1305(key, nonce, aadFor(uuid)).encrypt(split.secret);
9855
+ secret = concat2(Uint8Array.of(ATTACH_SECRET_OPTIONS_VERSION), nonce, ct);
9856
+ }
9857
+ const body = concat2(u32le(plain.length), plain, secret);
9858
+ return concat2(body, u32le(body.length), TRAILER_MAGIC);
9859
+ }
9860
+ function endsWithMagic(b) {
9861
+ if (b.length < TRAILER_MAGIC.length)
9862
+ return false;
9863
+ const off = b.length - TRAILER_MAGIC.length;
9864
+ for (let i = 0;i < TRAILER_MAGIC.length; i++)
9865
+ if (b[off + i] !== TRAILER_MAGIC[i])
9866
+ return false;
9867
+ return true;
9868
+ }
9869
+ function decodeOptions(ipc) {
9870
+ const batch = deserializeBatch(ipc);
9871
+ if (batch.numRows === 0)
9872
+ return {};
9873
+ return { ...iterRows(batch).next().value ?? {} };
9874
+ }
9875
+ var registry = new WeakMap;
9876
+ var EMPTY = Object.freeze({});
9877
+ async function openFrameworkAttach(full, keys) {
9878
+ if (full.length < UUID_LEN)
9879
+ return full;
9880
+ const copy = full.slice();
9881
+ let end = copy.length;
9882
+ let options = EMPTY;
9883
+ if (copy.length >= UUID_LEN + TRAILER_FIXED && endsWithMagic(copy)) {
9884
+ const bodyLen = readU32le(copy, copy.length - TRAILER_FIXED);
9885
+ const bodyStart = copy.length - TRAILER_FIXED - bodyLen;
9886
+ if (bodyLen < 4 || bodyStart < UUID_LEN)
9887
+ throw new OpaqueDataRejectedError(FIELD);
9888
+ const body = copy.subarray(bodyStart, copy.length - TRAILER_FIXED);
9889
+ const plainLen = readU32le(body, 0);
9890
+ if (4 + plainLen > body.length)
9891
+ throw new OpaqueDataRejectedError(FIELD);
9892
+ const plain = body.subarray(4, 4 + plainLen);
9893
+ const secret = body.subarray(4 + plainLen);
9894
+ const values = {};
9895
+ try {
9896
+ if (plain.length)
9897
+ Object.assign(values, decodeOptions(plain));
9898
+ } catch {
9899
+ throw new OpaqueDataRejectedError(FIELD);
9900
+ }
9901
+ if (secret.length) {
9902
+ if (secret.length < 1 + NONCE_LEN2 + TAG_LEN2 || secret[0] !== ATTACH_SECRET_OPTIONS_VERSION) {
9903
+ throw new OpaqueDataRejectedError(FIELD);
9904
+ }
9905
+ let opened;
9906
+ try {
9907
+ const key = await deriveAttachSecretKey(await rootKey(keys));
9908
+ const nonce = secret.subarray(1, 1 + NONCE_LEN2);
9909
+ opened = xchacha20poly1305(key, nonce, aadFor(copy.subarray(0, UUID_LEN))).decrypt(secret.subarray(1 + NONCE_LEN2));
9910
+ } catch {
9911
+ throw new OpaqueDataRejectedError(FIELD);
9912
+ }
9913
+ try {
9914
+ Object.assign(values, decodeOptions(opened));
9915
+ } catch {
9916
+ throw new OpaqueDataRejectedError(FIELD);
9917
+ }
9918
+ }
9919
+ options = Object.freeze(values);
9920
+ end = bodyStart;
9921
+ }
9922
+ registry.set(copy.buffer, options);
9923
+ return copy.subarray(UUID_LEN, end);
9924
+ }
9925
+ async function secretAttachOptionNames(catalog, name, deserialize) {
9926
+ const names = new Set;
9927
+ if (typeof catalog.attachOptionSpecs === "function") {
9928
+ for (const spec of catalog.attachOptionSpecs(name) ?? [])
9929
+ if (spec.secret)
9930
+ names.add(spec.name.toLowerCase());
9931
+ }
9932
+ if (typeof catalog.catalogsInfo === "function") {
9933
+ let infos;
9934
+ try {
9935
+ infos = await catalog.catalogsInfo();
9936
+ } catch {
9937
+ infos = [];
9938
+ }
9939
+ for (const info of infos ?? []) {
9940
+ if (info.name !== name)
9941
+ continue;
9942
+ for (const raw of info.attach_option_specs ?? []) {
9943
+ try {
9944
+ const spec = deserialize(raw);
9945
+ if (spec.secret)
9946
+ names.add(spec.name.toLowerCase());
9947
+ } catch {}
9948
+ }
9949
+ }
9950
+ }
9951
+ return names;
9952
+ }
9953
+
8273
9954
  // src/protocol/handlers/catalog/shared.ts
8274
- async function sealAttach(plaintext, auth, signingKey) {
9955
+ async function sealAttach(plaintext, auth, signingKey, options) {
8275
9956
  const uuid = new Uint8Array(ATTACH_UUID_LEN);
8276
9957
  crypto.getRandomValues(uuid);
8277
- const minted = new Uint8Array(ATTACH_UUID_LEN + plaintext.length);
9958
+ const trailer = options ? await packAttachOptionsTrailer(uuid, options.optionsIpc, options.secretNames, {
9959
+ explicit: options.attachSecretKey,
9960
+ signingKey
9961
+ }) : new Uint8Array(0);
9962
+ const minted = new Uint8Array(ATTACH_UUID_LEN + plaintext.length + trailer.length);
8278
9963
  minted.set(uuid, 0);
8279
9964
  minted.set(plaintext, ATTACH_UUID_LEN);
9965
+ minted.set(trailer, ATTACH_UUID_LEN + plaintext.length);
8280
9966
  if (!signingKey)
8281
9967
  return minted;
8282
9968
  return sealBytes(minted, signingKey, attachAad(auth), ATTACH_ENVELOPE_VERSION);
@@ -8286,9 +9972,9 @@ async function openAttachFull(envelope, auth, signingKey) {
8286
9972
  return envelope;
8287
9973
  return openBytes(envelope, signingKey, attachAad(auth), ATTACH_ENVELOPE_VERSION, "attach_opaque_data");
8288
9974
  }
8289
- async function openAttach(envelope, auth, signingKey) {
9975
+ async function openAttach(envelope, auth, signingKey, attachSecretKey) {
8290
9976
  const full = await openAttachFull(envelope, auth, signingKey);
8291
- return full.length < ATTACH_UUID_LEN ? full : full.subarray(ATTACH_UUID_LEN);
9977
+ return openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
8292
9978
  }
8293
9979
  async function sealTransaction(plaintext, attachEnvelope, auth, signingKey) {
8294
9980
  if (!signingKey)
@@ -8300,7 +9986,8 @@ async function openTransaction(envelope, attachEnvelope, auth, signingKey) {
8300
9986
  return envelope;
8301
9987
  return openBytes(envelope, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION, "transaction_opaque_data");
8302
9988
  }
8303
- async function unwrapParamsOpaque(params, ctx, signingKey) {
9989
+ async function unwrapParamsOpaque(params, ctx, keys) {
9990
+ const { signingKey, attachSecretKey } = keys;
8304
9991
  const auth = ctx?.auth;
8305
9992
  let sealedAttach = new Uint8Array(0);
8306
9993
  if (params.attach_opaque_data != null) {
@@ -8308,7 +9995,7 @@ async function unwrapParamsOpaque(params, ctx, signingKey) {
8308
9995
  if (env.length > 0) {
8309
9996
  sealedAttach = env;
8310
9997
  const full = signingKey ? await openBytes(env, signingKey, attachAad(auth), ATTACH_ENVELOPE_VERSION, "attach_opaque_data") : env;
8311
- params.attach_opaque_data = full.length < ATTACH_UUID_LEN ? full : full.subarray(ATTACH_UUID_LEN);
9998
+ params.attach_opaque_data = await openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
8312
9999
  }
8313
10000
  }
8314
10001
  if (signingKey && params.transaction_opaque_data != null) {
@@ -8318,14 +10005,15 @@ async function unwrapParamsOpaque(params, ctx, signingKey) {
8318
10005
  }
8319
10006
  }
8320
10007
  }
8321
- function catalogHandler(signingKey, handler) {
10008
+ function catalogHandler(keysOrSigningKey, handler) {
10009
+ const keys = keysOrSigningKey instanceof Uint8Array || keysOrSigningKey === undefined ? { signingKey: keysOrSigningKey } : keysOrSigningKey;
8322
10010
  return async (wire, ctx) => {
8323
10011
  let params = wire;
8324
10012
  if (params.request != null && params.attach_opaque_data === undefined && params.name === undefined) {
8325
10013
  params = unwrapRequest(params.request);
8326
10014
  }
8327
10015
  normalizeRequestSchemaPaths(params);
8328
- await unwrapParamsOpaque(params, ctx, signingKey);
10016
+ await unwrapParamsOpaque(params, ctx, keys);
8329
10017
  return handler(params, ctx);
8330
10018
  };
8331
10019
  }
@@ -8467,7 +10155,7 @@ var RESERVED_FLAGS_MASK = 254;
8467
10155
  var FINGERPRINT_LEN = 16;
8468
10156
  var HEADER_LEN = 4 + FINGERPRINT_LEN;
8469
10157
  var SEAL_VERSION = 1;
8470
- var AAD_PREFIX = new TextEncoder().encode("vgi.split_token.v1\x00");
10158
+ var AAD_PREFIX2 = new TextEncoder().encode("vgi.split_token.v1\x00");
8471
10159
  var SPLIT_TOKEN_INVALID = "SPLIT_TOKEN_INVALID";
8472
10160
  var SPLIT_SNAPSHOT_EXPIRED = "SPLIT_SNAPSHOT_EXPIRED";
8473
10161
  class SplitTokenError extends Error {
@@ -8478,7 +10166,7 @@ class SplitTokenError extends Error {
8478
10166
  this.kind = kind;
8479
10167
  }
8480
10168
  }
8481
- function concat2(...parts) {
10169
+ function concat3(...parts) {
8482
10170
  const total = parts.reduce((n, p) => n + p.length, 0);
8483
10171
  const out = new Uint8Array(total);
8484
10172
  let at = 0;
@@ -8499,13 +10187,13 @@ function equalBytes2(a, b) {
8499
10187
  async function bindFingerprint(schemaPath, functionName, args, settings, projection) {
8500
10188
  const enc = new TextEncoder;
8501
10189
  const zero = Uint8Array.of(0);
8502
- const field = (label, value) => concat2(enc.encode(label), zero, value, zero);
8503
- const message = concat2(AAD_PREFIX, field("schema_path", enc.encode(JSON.stringify(schemaPath))), field("function_name", enc.encode(functionName)), field("arguments", args), field("settings", settings), field("projection_ids", projection));
10190
+ const field = (label, value) => concat3(enc.encode(label), zero, value, zero);
10191
+ const message = concat3(AAD_PREFIX2, field("schema_path", enc.encode(JSON.stringify(schemaPath))), field("function_name", enc.encode(functionName)), field("arguments", args), field("settings", settings), field("projection_ids", projection));
8504
10192
  const digest = await crypto.subtle.digest("SHA-256", message);
8505
10193
  return new Uint8Array(digest).slice(0, FINGERPRINT_LEN);
8506
10194
  }
8507
10195
  function splitTokenAad(header, auth) {
8508
- return concat2(header, identityTail(auth));
10196
+ return concat3(header, identityTail(auth));
8509
10197
  }
8510
10198
  function splitAnchor(catalogVersion) {
8511
10199
  const out = new Uint8Array(8);
@@ -8524,11 +10212,11 @@ async function buildSplitToken(opts) {
8524
10212
  head[0] = SPLIT_TOKEN_FORMAT_VERSION;
8525
10213
  head[1] = signingKey ? FLAG_PAYLOAD_SEALED : 0;
8526
10214
  new DataView(head.buffer).setUint16(2, anchor.length, true);
8527
- const body = concat2(head, fingerprint, anchor);
10215
+ const body = concat3(head, fingerprint, anchor);
8528
10216
  if (!signingKey)
8529
- return concat2(body, payload);
10217
+ return concat3(body, payload);
8530
10218
  const sealed = await sealBytes(payload, signingKey, splitTokenAad(body, auth), SEAL_VERSION);
8531
- return concat2(body, sealed);
10219
+ return concat3(body, sealed);
8532
10220
  }
8533
10221
  async function openSplitToken(token, opts = {}) {
8534
10222
  const { signingKey, auth, expectedFingerprint, currentAnchor } = opts;
@@ -8576,7 +10264,7 @@ async function openSplitToken(token, opts = {}) {
8576
10264
  }
8577
10265
 
8578
10266
  // src/protocol/handlers/function.ts
8579
- async function liveSplitAnchor(catalogInterface, bindCall, auth, signingKey) {
10267
+ async function liveSplitAnchor(catalogInterface, bindCall, auth, signingKey, attachSecretKey) {
8580
10268
  if (!catalogInterface?.version || bindCall.attach_opaque_data == null)
8581
10269
  return;
8582
10270
  const raw = toUint8Array(bindCall.attach_opaque_data);
@@ -8588,7 +10276,7 @@ async function liveSplitAnchor(catalogInterface, bindCall, auth, signingKey) {
8588
10276
  }
8589
10277
  const forms = [
8590
10278
  async () => raw,
8591
- async () => openAttach(raw, auth, signingKey)
10279
+ async () => openAttach(raw, auth, signingKey, attachSecretKey)
8592
10280
  ];
8593
10281
  for (const form of forms) {
8594
10282
  try {
@@ -8602,7 +10290,7 @@ async function resolveSplitPayloads(request, innerParams, opts) {
8602
10290
  return;
8603
10291
  const fp = fingerprintInputs(toUint8Array(innerParams.bind_call));
8604
10292
  const expected = await bindFingerprint(fp.schemaPath, fp.functionName, fp.args, fp.settings, new Uint8Array(0));
8605
- const currentAnchor = opts.checkAnchor ? await liveSplitAnchor(opts.catalogInterface, request.bind_call, opts.auth, opts.signingKey) : undefined;
10293
+ const currentAnchor = opts.checkAnchor ? await liveSplitAnchor(opts.catalogInterface, request.bind_call, opts.auth, opts.signingKey, opts.attachSecretKey) : undefined;
8606
10294
  request.split_payloads = [];
8607
10295
  for (const token of request.split_tokens) {
8608
10296
  request.split_payloads.push(await openSplitToken(token, {
@@ -8614,14 +10302,14 @@ async function resolveSplitPayloads(request, innerParams, opts) {
8614
10302
  }
8615
10303
  }
8616
10304
  function functionHandlers(config) {
8617
- const { registry, signingKey, catalogInterface } = config;
10305
+ const { registry, signingKey, catalogInterface, attachSecretKey } = config;
8618
10306
  async function stripAttach(attach, ctx) {
8619
10307
  if (attach == null)
8620
10308
  return null;
8621
10309
  const env = toUint8Array(attach);
8622
10310
  if (env.length === 0)
8623
10311
  return env;
8624
- return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey);
10312
+ return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
8625
10313
  }
8626
10314
  async function openOpaque(bindCall, ctx) {
8627
10315
  const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
@@ -8666,6 +10354,7 @@ function functionHandlers(config) {
8666
10354
  await resolveSplitPayloads(request, innerParams, {
8667
10355
  auth,
8668
10356
  signingKey,
10357
+ attachSecretKey,
8669
10358
  catalogInterface,
8670
10359
  checkAnchor: true
8671
10360
  });
@@ -8711,6 +10400,7 @@ function functionHandlers(config) {
8711
10400
  await resolveSplitPayloads(request, { bind_call: carried.bindCallIpc }, {
8712
10401
  auth: currentRequestAuth(),
8713
10402
  signingKey,
10403
+ attachSecretKey,
8714
10404
  catalogInterface,
8715
10405
  checkAnchor: false
8716
10406
  });
@@ -8782,7 +10472,7 @@ function functionHandlers(config) {
8782
10472
  const plan = func.plan ? await func.plan(request) : { splits: [{ payload: new Uint8Array(0) }] };
8783
10473
  const fp = fingerprintInputs(toUint8Array(innerParams.bind_call));
8784
10474
  const fingerprint = await bindFingerprint(fp.schemaPath, fp.functionName, fp.args, fp.settings, new Uint8Array(0));
8785
- const anchor = plan.catalogVersion != null ? splitAnchor(plan.catalogVersion) : await liveSplitAnchor(catalogInterface, request.bind_call, ctx?.auth, signingKey) ?? splitAnchor(0);
10475
+ const anchor = plan.catalogVersion != null ? splitAnchor(plan.catalogVersion) : await liveSplitAnchor(catalogInterface, request.bind_call, ctx?.auth, signingKey, attachSecretKey) ?? splitAnchor(0);
8786
10476
  const blobs = [];
8787
10477
  for (const split of plan.splits) {
8788
10478
  const token = await buildSplitToken({
@@ -9308,7 +10998,7 @@ function splitLenPrefixed(buf, count) {
9308
10998
  }
9309
10999
 
9310
11000
  // src/protocol/handlers/table-buffering.ts
9311
- function tableBufferingHandlers(registry, signingKey) {
11001
+ function tableBufferingHandlers(registry, signingKey, attachSecretKey) {
9312
11002
  function resolveBuffering(name, schemaPath) {
9313
11003
  const func = registry.get(name, {
9314
11004
  arguments: new Arguments,
@@ -9325,7 +11015,7 @@ function tableBufferingHandlers(registry, signingKey) {
9325
11015
  const functionName = inner.function_name;
9326
11016
  const executionId = toUint8Array(inner.execution_id);
9327
11017
  const rawAttach = inner.attach_opaque_data ? toUint8Array(inner.attach_opaque_data) : null;
9328
- const attach = rawAttach && rawAttach.length > 0 ? await openAttach(rawAttach, ctx?.auth, signingKey) : rawAttach;
11018
+ const attach = rawAttach && rawAttach.length > 0 ? await openAttach(rawAttach, ctx?.auth, signingKey, attachSecretKey) : rawAttach;
9329
11019
  const transactionId = inner.transaction_id ? toUint8Array(inner.transaction_id) : null;
9330
11020
  const func = resolveBuffering(functionName, inner.schema_path ?? null);
9331
11021
  const bound = new BoundStorage(storage, executionId);
@@ -9755,6 +11445,219 @@ function servedTableInfo(info) {
9755
11445
  return served === schema ? info : { ...info, columns: serializeSchema(served) };
9756
11446
  }
9757
11447
 
11448
+ // src/catalog/scan-planning.ts
11449
+ var SCAN_PLANNING_BIND = "bind";
11450
+ var SCAN_PLANNING_FILTERED = "filtered";
11451
+ var SCAN_PLANNING_MODES = Object.freeze([SCAN_PLANNING_BIND, SCAN_PLANNING_FILTERED]);
11452
+ function validateScanPlanning(tableName, scanPlanning, hasInlineScanFunction) {
11453
+ const mode = scanPlanning ?? SCAN_PLANNING_BIND;
11454
+ if (mode !== SCAN_PLANNING_BIND && mode !== SCAN_PLANNING_FILTERED) {
11455
+ throw new Error(`Table '${tableName}': scan_planning must be one of ${JSON.stringify(SCAN_PLANNING_MODES)}, got ${JSON.stringify(mode)}`);
11456
+ }
11457
+ if (mode === SCAN_PLANNING_FILTERED && hasInlineScanFunction) {
11458
+ throw new Error(`Table '${tableName}': scan_planning='filtered' cannot be combined with an inlined scan_function; ` + "the scan redirect must be resolved per query with the query's filters");
11459
+ }
11460
+ return mode;
11461
+ }
11462
+
11463
+ class ScanPlanningFilters {
11464
+ raw;
11465
+ tableColumns;
11466
+ _decoded = null;
11467
+ constructor(raw, tableColumns) {
11468
+ this.raw = raw;
11469
+ this.tableColumns = tableColumns;
11470
+ }
11471
+ decode() {
11472
+ if (this._decoded == null) {
11473
+ this._decoded = (async () => {
11474
+ const columns = await this.tableColumns();
11475
+ if (columns == null) {
11476
+ throw new Error("pushdown_filters: the table's declared columns could not be resolved");
11477
+ }
11478
+ return deserializeFilters(deserializeBatch(this.raw), { outputSchema: columns });
11479
+ })();
11480
+ this._decoded.catch(() => {
11481
+ this._decoded = null;
11482
+ });
11483
+ }
11484
+ return this._decoded;
11485
+ }
11486
+ async mayMatch(statistics) {
11487
+ return filtersMayMatch(await this.decode(), statistics);
11488
+ }
11489
+ }
11490
+ function filtersMayMatch(filters, statistics) {
11491
+ const list = Symbol.iterator in statistics ? statistics : Object.values(statistics);
11492
+ const byName = new Map;
11493
+ for (const stat of list)
11494
+ byName.set(stat.columnName, stat);
11495
+ if (byName.size === 0)
11496
+ return true;
11497
+ for (const predicate of filters.predicates) {
11498
+ if (provablyFalse(predicate.expression, byName))
11499
+ return false;
11500
+ }
11501
+ return true;
11502
+ }
11503
+ var FLIPPED = {
11504
+ ["eq" /* EQ */]: "eq" /* EQ */,
11505
+ ["ne" /* NE */]: "ne" /* NE */,
11506
+ ["lt" /* LT */]: "gt" /* GT */,
11507
+ ["le" /* LE */]: "ge" /* GE */,
11508
+ ["gt" /* GT */]: "lt" /* LT */,
11509
+ ["ge" /* GE */]: "le" /* LE */
11510
+ };
11511
+ function columnStat(expr, stats) {
11512
+ if (expr.node !== "column_ref")
11513
+ return null;
11514
+ const stat = stats.get(expr.columnName);
11515
+ return stat == null ? null : { stat, type: stat.arrowType ?? expr.dataType };
11516
+ }
11517
+ function outside(ref, value, valueType) {
11518
+ const lo = ref.stat.min ?? null;
11519
+ const hi = ref.stat.max ?? null;
11520
+ const cmpLo = lo == null ? null : compare2(lo, ref.type, value, valueType);
11521
+ const cmpHi = hi == null ? null : compare2(hi, ref.type, value, valueType);
11522
+ return cmpLo != null && cmpLo > 0 || cmpHi != null && cmpHi < 0;
11523
+ }
11524
+ function provablyFalse(expr, stats) {
11525
+ switch (expr.node) {
11526
+ case "and":
11527
+ return expr.children.some((child) => provablyFalse(child, stats));
11528
+ case "or":
11529
+ return expr.children.length > 0 && expr.children.every((child) => provablyFalse(child, stats));
11530
+ case "comparison": {
11531
+ let op = expr.op;
11532
+ let ref = columnStat(expr.left, stats);
11533
+ let literal = expr.right;
11534
+ if (ref == null) {
11535
+ ref = columnStat(expr.right, stats);
11536
+ literal = expr.left;
11537
+ op = FLIPPED[expr.op];
11538
+ }
11539
+ if (ref == null || op == null || !(op in FLIPPED) || literal.node !== "literal")
11540
+ return false;
11541
+ if (ref.stat.hasNotNull === false)
11542
+ return true;
11543
+ const c = literal.value;
11544
+ if (c == null)
11545
+ return true;
11546
+ const litType = literal.field?.type;
11547
+ const lo = ref.stat.min ?? null;
11548
+ const hi = ref.stat.max ?? null;
11549
+ const cmpLo = lo == null ? null : compare2(lo, ref.type, c, litType);
11550
+ const cmpHi = hi == null ? null : compare2(hi, ref.type, c, litType);
11551
+ switch (op) {
11552
+ case "eq" /* EQ */:
11553
+ return cmpLo != null && cmpLo > 0 || cmpHi != null && cmpHi < 0;
11554
+ case "ne" /* NE */:
11555
+ return cmpLo === 0 && cmpHi === 0;
11556
+ case "lt" /* LT */:
11557
+ return cmpLo != null && cmpLo >= 0;
11558
+ case "le" /* LE */:
11559
+ return cmpLo != null && cmpLo > 0;
11560
+ case "gt" /* GT */:
11561
+ return cmpHi != null && cmpHi <= 0;
11562
+ case "ge" /* GE */:
11563
+ return cmpHi != null && cmpHi < 0;
11564
+ default:
11565
+ return false;
11566
+ }
11567
+ }
11568
+ case "in": {
11569
+ if (expr.negated || expr.set.kind !== "literal")
11570
+ return false;
11571
+ const ref = columnStat(expr.expression, stats);
11572
+ if (ref == null)
11573
+ return false;
11574
+ if (ref.stat.hasNotNull === false)
11575
+ return true;
11576
+ if (ref.stat.min == null && ref.stat.max == null)
11577
+ return false;
11578
+ const setType = expr.set.field?.type;
11579
+ const values = expr.set.values.filter((v) => v != null);
11580
+ if (values.length === 0)
11581
+ return true;
11582
+ return values.every((v) => outside(ref, v, setType));
11583
+ }
11584
+ case "is_null": {
11585
+ const ref = columnStat(expr.expression, stats);
11586
+ if (ref == null)
11587
+ return false;
11588
+ return expr.negated ? ref.stat.hasNotNull === false : ref.stat.hasNull === false;
11589
+ }
11590
+ default:
11591
+ return false;
11592
+ }
11593
+ }
11594
+ function compare2(a, aType, b, bType) {
11595
+ const x = comparable(a, aType);
11596
+ const y = comparable(b, bType);
11597
+ if (x == null || y == null || x.kind !== y.kind)
11598
+ return null;
11599
+ const u = x.value;
11600
+ const v = y.value;
11601
+ if (typeof u === "number" && Number.isNaN(u))
11602
+ return null;
11603
+ if (typeof v === "number" && Number.isNaN(v))
11604
+ return null;
11605
+ if (typeof u === "string" && typeof v === "string")
11606
+ return compareCodePoints2(u, v);
11607
+ return u < v ? -1 : u > v ? 1 : 0;
11608
+ }
11609
+ function compareCodePoints2(a, b) {
11610
+ const ia = a[Symbol.iterator]();
11611
+ const ib = b[Symbol.iterator]();
11612
+ for (;; ) {
11613
+ const x = ia.next();
11614
+ const y = ib.next();
11615
+ if (x.done || y.done)
11616
+ return x.done && y.done ? 0 : x.done ? -1 : 1;
11617
+ const cx = x.value.codePointAt(0);
11618
+ const cy = y.value.codePointAt(0);
11619
+ if (cx !== cy)
11620
+ return cx < cy ? -1 : 1;
11621
+ }
11622
+ }
11623
+ var MS_PER_DAY2 = 86400000;
11624
+ var NS_PER_UNIT = [1000000000n, 1000000n, 1000n, 1n];
11625
+ function comparable(v, type) {
11626
+ if (type != null) {
11627
+ if (isDate(type)) {
11628
+ if (v instanceof Date)
11629
+ return { kind: "date", value: v.getTime() };
11630
+ if (typeof v === "number" || typeof v === "bigint") {
11631
+ return { kind: "date", value: type.unit === 0 ? Number(v) * MS_PER_DAY2 : Number(v) };
11632
+ }
11633
+ return null;
11634
+ }
11635
+ if (isTimestamp(type)) {
11636
+ const scale = NS_PER_UNIT[type.unit ?? -1];
11637
+ if (scale == null)
11638
+ return null;
11639
+ if (v instanceof Date)
11640
+ return { kind: "timestamp", value: BigInt(v.getTime()) * 1000000n };
11641
+ if (typeof v === "bigint")
11642
+ return { kind: "timestamp", value: v * scale };
11643
+ if (typeof v === "number" && Number.isSafeInteger(v))
11644
+ return { kind: "timestamp", value: BigInt(v) * scale };
11645
+ return null;
11646
+ }
11647
+ if (isDecimal(type) || isTime(type) || isInterval(type) || isDuration(type))
11648
+ return null;
11649
+ }
11650
+ if (v instanceof Date)
11651
+ return null;
11652
+ if (typeof v === "number" || typeof v === "bigint")
11653
+ return { kind: "numeric", value: v };
11654
+ if (typeof v === "string")
11655
+ return { kind: "string", value: v };
11656
+ if (typeof v === "boolean")
11657
+ return { kind: "boolean", value: v ? 1 : 0 };
11658
+ return null;
11659
+ }
11660
+
9758
11661
  // src/catalog/column-metadata.ts
9759
11662
  function scalarText(value) {
9760
11663
  for (let i = 0;i < value.length; i++) {
@@ -9886,12 +11789,16 @@ function validateColumnMetadataIpc(bytes) {
9886
11789
  vector(schema, 1, (f) => field(f, 0));
9887
11790
  }
9888
11791
  function validateTableInfoColumns(info) {
11792
+ validateScanPlanning(info.name, info.scan_planning, info.scan_function != null);
9889
11793
  if (info.columns.length) {
9890
11794
  validateColumnMetadataIpc(info.columns);
9891
11795
  validateColumnExpressionsIpc(info.columns, info.schema_path);
9892
11796
  }
9893
11797
  }
9894
11798
  function servedValidatedTableInfo(info) {
11799
+ const scanPlanning = validateScanPlanning(info.name, info.scan_planning, info.scan_function != null);
11800
+ if (info.scan_planning !== scanPlanning)
11801
+ info = { ...info, scan_planning: scanPlanning };
9895
11802
  if (info.columns.length)
9896
11803
  validateColumnMetadataIpc(info.columns);
9897
11804
  const served = servedTableInfo(info);
@@ -10595,9 +12502,9 @@ var TICKET_ENVELOPE_VERSION = 1;
10595
12502
  var MAX_OPTIONS_BYTES = 16 * 1024;
10596
12503
  var MAX_TICKET_CHARS = 32 * 1024;
10597
12504
  var CLOCK_SKEW_SECONDS = 60;
10598
- var UTF82 = new TextEncoder;
12505
+ var UTF83 = new TextEncoder;
10599
12506
  var STRICT_UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
10600
- var TICKET_AAD_DOMAIN = UTF82.encode("vgi.attach_ticket.v1\x00");
12507
+ var TICKET_AAD_DOMAIN = UTF83.encode("vgi.attach_ticket.v1\x00");
10601
12508
  var TICKET_ID = /^[0-9a-f]{32}$/;
10602
12509
  var B64URL = /^[A-Za-z0-9_-]+$/;
10603
12510
  var MAX_TEXT = 65535;
@@ -10651,14 +12558,14 @@ class SealAttachDeniedError extends Error {
10651
12558
  }
10652
12559
  }
10653
12560
  function attachTicketAad(principal) {
10654
- const p = UTF82.encode(principal);
12561
+ const p = UTF83.encode(principal);
10655
12562
  const out = new Uint8Array(TICKET_AAD_DOMAIN.length + p.length);
10656
12563
  out.set(TICKET_AAD_DOMAIN, 0);
10657
12564
  out.set(p, TICKET_AAD_DOMAIN.length);
10658
12565
  return out;
10659
12566
  }
10660
12567
  function packText(value, name) {
10661
- const raw = UTF82.encode(value);
12568
+ const raw = UTF83.encode(value);
10662
12569
  if (raw.length > MAX_TEXT)
10663
12570
  throw new Error(`${name} is longer than 65535 bytes`);
10664
12571
  const out = new Uint8Array(2 + raw.length);
@@ -10982,8 +12889,9 @@ function buildAttachTicketsProtocol(config) {
10982
12889
  }
10983
12890
 
10984
12891
  // src/protocol/handlers/catalog/admin.ts
10985
- function catalogAdminHandlers(getCatalog, signingKey) {
10986
- const catalogCatalogs = catalogHandler(signingKey, async () => {
12892
+ function catalogAdminHandlers(getCatalog, signingKey, attachSecretKey) {
12893
+ const keys = { signingKey, attachSecretKey };
12894
+ const catalogCatalogs = catalogHandler(keys, async () => {
10987
12895
  const cat = getCatalog();
10988
12896
  const infos = cat.catalogsInfo ? await cat.catalogsInfo() : cat.catalogs().map((name) => ({
10989
12897
  name,
@@ -11014,29 +12922,31 @@ function catalogAdminHandlers(getCatalog, signingKey) {
11014
12922
  result.catalog_capabilities = encodeCatalogCapabilities(catalogCapabilities(advertised));
11015
12923
  result.selected_capabilities = encodeCatalogCapabilities(selectCatalogCapabilities(advertised, clientCapabilities, result.supports_transactions ?? false));
11016
12924
  }
11017
- const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey);
12925
+ const optionsIpc = innerParams.options == null ? null : toUint8Array(innerParams.options);
12926
+ const secretNames = optionsIpc && optionsIpc.length > 0 ? await secretAttachOptionNames(cat, innerParams.name, deserializeAttachOptionSpec) : new Set;
12927
+ const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey, { optionsIpc, secretNames, attachSecretKey });
11018
12928
  return wrapResult(buildCatalogAttachResult({
11019
12929
  ...result,
11020
12930
  attach_opaque_data: sealedAttach,
11021
12931
  supports_column_statistics: result.supports_column_statistics ?? true
11022
12932
  }), CatalogAttachResultSchema);
11023
12933
  };
11024
- const catalogDetach = catalogHandler(signingKey, async (params) => {
12934
+ const catalogDetach = catalogHandler(keys, async (params) => {
11025
12935
  const cat = getCatalog();
11026
12936
  await cat.detach(toUint8Array(params.attach_opaque_data));
11027
12937
  return {};
11028
12938
  });
11029
- const catalogCreate = catalogHandler(signingKey, async (params) => {
12939
+ const catalogCreate = catalogHandler(keys, async (params) => {
11030
12940
  const cat = getCatalog();
11031
12941
  await cat.create(params.name, params.on_conflict, params.options);
11032
12942
  return {};
11033
12943
  });
11034
- const catalogDrop = catalogHandler(signingKey, async (params) => {
12944
+ const catalogDrop = catalogHandler(keys, async (params) => {
11035
12945
  const cat = getCatalog();
11036
12946
  await cat.drop(params.name);
11037
12947
  return {};
11038
12948
  });
11039
- const catalogVersion = catalogHandler(signingKey, async (params) => {
12949
+ const catalogVersion = catalogHandler(keys, async (params) => {
11040
12950
  const cat = getCatalog();
11041
12951
  const version = await cat.version(toUint8Array(params.attach_opaque_data), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11042
12952
  return wrapResult({ version }, CatalogVersionResultSchema);
@@ -11044,23 +12954,23 @@ function catalogAdminHandlers(getCatalog, signingKey) {
11044
12954
  const catalogTransactionBegin = async (params, ctx) => {
11045
12955
  const auth = ctx?.auth;
11046
12956
  const sealedAttach = params.attach_opaque_data != null ? toUint8Array(params.attach_opaque_data) : new Uint8Array(0);
11047
- const attachPlain = await openAttach(sealedAttach, auth, signingKey);
12957
+ const attachPlain = await openAttach(sealedAttach, auth, signingKey, attachSecretKey);
11048
12958
  const cat = getCatalog();
11049
12959
  const txPlain = await cat.transactionBegin(attachPlain);
11050
12960
  const transaction_opaque_data = txPlain != null ? await sealTransaction(toUint8Array(txPlain), sealedAttach, auth, signingKey) : null;
11051
12961
  return wrapResult({ transaction_opaque_data }, CatalogTransactionBeginResultSchema);
11052
12962
  };
11053
- const catalogTransactionCommit = catalogHandler(signingKey, async (params) => {
12963
+ const catalogTransactionCommit = catalogHandler(keys, async (params) => {
11054
12964
  const cat = getCatalog();
11055
12965
  await cat.transactionCommit(toUint8Array(params.attach_opaque_data), toUint8Array(params.transaction_opaque_data));
11056
12966
  return {};
11057
12967
  });
11058
- const catalogTransactionRollback = catalogHandler(signingKey, async (params) => {
12968
+ const catalogTransactionRollback = catalogHandler(keys, async (params) => {
11059
12969
  const cat = getCatalog();
11060
12970
  await cat.transactionRollback(toUint8Array(params.attach_opaque_data), toUint8Array(params.transaction_opaque_data));
11061
12971
  return {};
11062
12972
  });
11063
- const catalogSchemas = catalogHandler(signingKey, async (params) => {
12973
+ const catalogSchemas = catalogHandler(keys, async (params) => {
11064
12974
  const cat = getCatalog();
11065
12975
  const schemas = await cat.schemas(toUint8Array(params.attach_opaque_data), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11066
12976
  return wrapResult({
@@ -11069,52 +12979,52 @@ function catalogAdminHandlers(getCatalog, signingKey) {
11069
12979
  });
11070
12980
  const catalogContents = async (params, ctx) => {
11071
12981
  const sealedAttach = toUint8Array(params.attach_opaque_data).slice();
11072
- return catalogHandler(signingKey, async (opened, context) => {
12982
+ return catalogHandler(keys, async (opened, context) => {
11073
12983
  const ifNoneMatch = opened.if_none_match == null ? null : String(opened.if_none_match);
11074
12984
  return serveCatalogContents(getCatalog(), toUint8Array(opened.attach_opaque_data), ifNoneMatch, context, sealedAttach);
11075
12985
  })(params, ctx);
11076
12986
  };
11077
- const catalogCopyFromFormats = catalogHandler(signingKey, async (params) => {
12987
+ const catalogCopyFromFormats = catalogHandler(keys, async (params) => {
11078
12988
  const cat = getCatalog();
11079
12989
  const formats = await cat.copyFromFormats(toUint8Array(params.attach_opaque_data), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11080
12990
  return wrapResult({
11081
12991
  items: formats.map((f) => encodeCopyFromFormatInfo(f))
11082
12992
  }, CatalogCopyFromFormatsResultSchema);
11083
12993
  });
11084
- const catalogSchemaGet = catalogHandler(signingKey, async (params) => {
12994
+ const catalogSchemaGet = catalogHandler(keys, async (params) => {
11085
12995
  const cat = getCatalog();
11086
12996
  const info = await cat.schemaGet(toUint8Array(params.attach_opaque_data), params.path, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11087
12997
  return wrapResult({
11088
12998
  items: info ? [encodeSchemaInfo(info)] : []
11089
12999
  }, CatalogSchemaGetResultSchema);
11090
13000
  });
11091
- const catalogSchemaCreate = catalogHandler(signingKey, async (params) => {
13001
+ const catalogSchemaCreate = catalogHandler(keys, async (params) => {
11092
13002
  if (params.options != null)
11093
13003
  throw new MethodNotImplementedError2("catalog_schema_create requires negotiated vgi.schema.options.create.v1");
11094
13004
  const cat = getCatalog();
11095
13005
  await cat.schemaCreate(toUint8Array(params.attach_opaque_data), Array.from(params.path), params.comment, catalogStringMap(params.tags), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined, decodeDictValue(params.on_conflict));
11096
13006
  return {};
11097
13007
  });
11098
- const catalogSchemaDrop = catalogHandler(signingKey, async (params) => {
13008
+ const catalogSchemaDrop = catalogHandler(keys, async (params) => {
11099
13009
  const cat = getCatalog();
11100
13010
  await cat.schemaDrop(toUint8Array(params.attach_opaque_data), params.path, params.ignore_not_found, params.cascade, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11101
13011
  return {};
11102
13012
  });
11103
- const catalogSchemaContentsTables = catalogHandler(signingKey, async (params) => {
13013
+ const catalogSchemaContentsTables = catalogHandler(keys, async (params) => {
11104
13014
  const cat = getCatalog();
11105
13015
  const tables = await cat.schemaContentsTables(toUint8Array(params.attach_opaque_data), params.path, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11106
13016
  return wrapResult({
11107
13017
  items: tables.map((t) => encodeValidatedTableInfo(t))
11108
13018
  }, CatalogSchemaContentsTablesResultSchema);
11109
13019
  });
11110
- const catalogSchemaContentsViews = catalogHandler(signingKey, async (params) => {
13020
+ const catalogSchemaContentsViews = catalogHandler(keys, async (params) => {
11111
13021
  const cat = getCatalog();
11112
13022
  const views = await cat.schemaContentsViews(toUint8Array(params.attach_opaque_data), params.path, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11113
13023
  return wrapResult({
11114
13024
  items: views.map((v) => encodeViewInfo(v))
11115
13025
  }, CatalogSchemaContentsViewsResultSchema);
11116
13026
  });
11117
- const catalogSchemaContentsFunctions = catalogHandler(signingKey, async (params) => {
13027
+ const catalogSchemaContentsFunctions = catalogHandler(keys, async (params) => {
11118
13028
  const cat = getCatalog();
11119
13029
  const funcs = await cat.schemaContentsFunctions(toUint8Array(params.attach_opaque_data), params.path, decodeDictValue(params.type), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11120
13030
  return wrapResult({
@@ -11191,15 +13101,16 @@ function requireFlatColumnPath(value, operation) {
11191
13101
  }
11192
13102
  return path;
11193
13103
  }
11194
- function catalogTableHandlers(getCatalog, signingKey) {
11195
- const catalogTableGet = catalogHandler(signingKey, async (params) => {
13104
+ function catalogTableHandlers(getCatalog, signingKey, attachSecretKey) {
13105
+ const keys = { signingKey, attachSecretKey };
13106
+ const catalogTableGet = catalogHandler(keys, async (params) => {
11196
13107
  const cat = getCatalog();
11197
13108
  const info = await cat.tableGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.at_unit, params.at_value, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11198
13109
  return wrapResult({
11199
13110
  items: info ? [encodeValidatedTableInfo(info)] : []
11200
13111
  }, CatalogTableGetResultSchema);
11201
13112
  });
11202
- const catalogTableCreate = catalogHandler(signingKey, async (params) => {
13113
+ const catalogTableCreate = catalogHandler(keys, async (params) => {
11203
13114
  if (params.constraint_definitions == null)
11204
13115
  throw new Error("constraint_definitions is required");
11205
13116
  const definitions = Array.from(params.constraint_definitions, (d) => toUint8Array(d));
@@ -11220,7 +13131,7 @@ function catalogTableHandlers(getCatalog, signingKey) {
11220
13131
  await cat.tableCreate(attach, params.schema_path, params.name, toUint8Array(params.columns), params.on_conflict, definitions, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11221
13132
  return {};
11222
13133
  });
11223
- const catalogTableConstraintsApply = catalogHandler(signingKey, async (params) => {
13134
+ const catalogTableConstraintsApply = catalogHandler(keys, async (params) => {
11224
13135
  const attach = toUint8Array(params.attach_opaque_data);
11225
13136
  const cat = getCatalog();
11226
13137
  const caps = await cat.catalogCapabilities(attach);
@@ -11253,50 +13164,60 @@ function catalogTableHandlers(getCatalog, signingKey) {
11253
13164
  }
11254
13165
  return wrapResult({ table, definition_revision: revision, constraints: snapshot.constraints.map((c) => toUint8Array(c)) }, CatalogTableConstraintsApplyResultSchema);
11255
13166
  });
11256
- const catalogTableDrop = catalogHandler(signingKey, async (params) => {
13167
+ const catalogTableDrop = catalogHandler(keys, async (params) => {
11257
13168
  const cat = getCatalog();
11258
13169
  await cat.tableDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11259
13170
  return {};
11260
13171
  });
11261
- const catalogTableColumnStatisticsGet = catalogHandler(signingKey, async (params) => {
13172
+ const catalogTableColumnStatisticsGet = catalogHandler(keys, async (params) => {
11262
13173
  const cat = getCatalog();
11263
13174
  const stats = await cat.tableColumnStatisticsGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11264
13175
  return { result: stats?.bytes ?? null };
11265
13176
  });
11266
- const catalogTableScanFunctionGet = catalogHandler(signingKey, async (params) => {
13177
+ const catalogTableScanFunctionGet = catalogHandler(keys, async (params) => {
11267
13178
  const cat = getCatalog();
11268
13179
  const scanResult = await cat.tableScanFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.at_unit, params.at_value, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11269
13180
  return wrapResult(scanResult, ScanFunctionResultSchema);
11270
13181
  });
11271
13182
  const optionalTx = (params) => params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined;
11272
- const catalogTableInsertFunctionGet = catalogHandler(signingKey, async (params) => {
13183
+ const catalogTableInsertFunctionGet = catalogHandler(keys, async (params) => {
11273
13184
  const result = await getCatalog().tableInsertFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params), params.writable_branch_function_name ?? null);
11274
13185
  return wrapResult(result, ScanFunctionResultSchema);
11275
13186
  });
11276
- const catalogTableUpdateFunctionGet = catalogHandler(signingKey, async (params) => {
13187
+ const catalogTableUpdateFunctionGet = catalogHandler(keys, async (params) => {
11277
13188
  const result = await getCatalog().tableUpdateFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params));
11278
13189
  return wrapResult(result, ScanFunctionResultSchema);
11279
13190
  });
11280
- const catalogTableDeleteFunctionGet = catalogHandler(signingKey, async (params) => {
13191
+ const catalogTableDeleteFunctionGet = catalogHandler(keys, async (params) => {
11281
13192
  const result = await getCatalog().tableDeleteFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params));
11282
13193
  return wrapResult(result, ScanFunctionResultSchema);
11283
13194
  });
11284
- const catalogTableScanBranchesGet = catalogHandler(signingKey, async (params) => {
13195
+ const catalogTableScanBranchesGet = catalogHandler(keys, async (params) => {
11285
13196
  const cat = getCatalog();
11286
- const branchesResult = await cat.tableScanBranchesGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.at_unit, params.at_value, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13197
+ const attach = toUint8Array(params.attach_opaque_data);
13198
+ const tx = params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined;
13199
+ const schemaPath = params.schema_path;
13200
+ const name = params.name;
13201
+ const atUnit = params.at_unit;
13202
+ const atValue = params.at_value;
13203
+ const filters = params.pushdown_filters != null ? new ScanPlanningFilters(toUint8Array(params.pushdown_filters), async () => {
13204
+ const info = await cat.tableGet(attach, schemaPath, name, atUnit, atValue, tx);
13205
+ return info && info.columns.length ? deserializeSchema(toUint8Array(info.columns)) : null;
13206
+ }) : null;
13207
+ const branchesResult = await cat.tableScanBranchesPlan(attach, schemaPath, name, atUnit, atValue, tx, filters);
11287
13208
  return wrapResult(branchesResult, ScanBranchesResultSchema);
11288
13209
  });
11289
- const catalogTableCommentSet = catalogHandler(signingKey, async (params) => {
13210
+ const catalogTableCommentSet = catalogHandler(keys, async (params) => {
11290
13211
  const cat = getCatalog();
11291
13212
  await cat.tableCommentSet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.comment, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11292
13213
  return {};
11293
13214
  });
11294
- const catalogTableRename = catalogHandler(signingKey, async (params) => {
13215
+ const catalogTableRename = catalogHandler(keys, async (params) => {
11295
13216
  const cat = getCatalog();
11296
13217
  await cat.tableRename(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.new_name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11297
13218
  return {};
11298
13219
  });
11299
- const catalogTableColumnAdd = catalogHandler(signingKey, async (params) => {
13220
+ const catalogTableColumnAdd = catalogHandler(keys, async (params) => {
11300
13221
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_add");
11301
13222
  validateColumnMetadataIpc(toUint8Array(params.column_definition));
11302
13223
  validateColumnExpressionsIpc(toUint8Array(params.column_definition), params.schema_path);
@@ -11304,49 +13225,49 @@ function catalogTableHandlers(getCatalog, signingKey) {
11304
13225
  await cat.tableColumnAdd(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, toUint8Array(params.column_definition), params.ignore_not_found, params.if_column_not_exists, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11305
13226
  return {};
11306
13227
  });
11307
- const catalogTableColumnDrop = catalogHandler(signingKey, async (params) => {
13228
+ const catalogTableColumnDrop = catalogHandler(keys, async (params) => {
11308
13229
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_drop");
11309
13230
  const cat = getCatalog();
11310
13231
  await cat.tableColumnDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.ignore_not_found, params.if_column_exists, params.cascade, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11311
13232
  return {};
11312
13233
  });
11313
- const catalogTableColumnRename = catalogHandler(signingKey, async (params) => {
13234
+ const catalogTableColumnRename = catalogHandler(keys, async (params) => {
11314
13235
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_rename");
11315
13236
  const cat = getCatalog();
11316
13237
  await cat.tableColumnRename(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.new_column_name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11317
13238
  return {};
11318
13239
  });
11319
- const catalogTableColumnCommentSet = catalogHandler(signingKey, async (params) => {
13240
+ const catalogTableColumnCommentSet = catalogHandler(keys, async (params) => {
11320
13241
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_comment_set");
11321
13242
  const cat = getCatalog();
11322
13243
  await cat.tableColumnCommentSet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.comment, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11323
13244
  return {};
11324
13245
  });
11325
- const catalogTableColumnDefaultSet = catalogHandler(signingKey, async (params) => {
13246
+ const catalogTableColumnDefaultSet = catalogHandler(keys, async (params) => {
11326
13247
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_default_set");
11327
13248
  const cat = getCatalog();
11328
13249
  await cat.tableColumnDefaultSet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, toUint8Array(params.expression), params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11329
13250
  return {};
11330
13251
  });
11331
- const catalogTableColumnDefaultDrop = catalogHandler(signingKey, async (params) => {
13252
+ const catalogTableColumnDefaultDrop = catalogHandler(keys, async (params) => {
11332
13253
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_default_drop");
11333
13254
  const cat = getCatalog();
11334
13255
  await cat.tableColumnDefaultDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11335
13256
  return {};
11336
13257
  });
11337
- const catalogTableColumnTypeChange = catalogHandler(signingKey, async (params) => {
13258
+ const catalogTableColumnTypeChange = catalogHandler(keys, async (params) => {
11338
13259
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_type_change");
11339
13260
  const cat = getCatalog();
11340
13261
  await cat.tableColumnTypeChange(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, toUint8Array(params.column_definition), params.expression == null ? null : toUint8Array(params.expression), params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11341
13262
  return {};
11342
13263
  });
11343
- const catalogTableNotNullSet = catalogHandler(signingKey, async (params) => {
13264
+ const catalogTableNotNullSet = catalogHandler(keys, async (params) => {
11344
13265
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_not_null_set");
11345
13266
  const cat = getCatalog();
11346
13267
  await cat.tableNotNullSet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11347
13268
  return {};
11348
13269
  });
11349
- const catalogTableNotNullDrop = catalogHandler(signingKey, async (params) => {
13270
+ const catalogTableNotNullDrop = catalogHandler(keys, async (params) => {
11350
13271
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_not_null_drop");
11351
13272
  const cat = getCatalog();
11352
13273
  await cat.tableNotNullDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
@@ -11378,15 +13299,16 @@ function catalogTableHandlers(getCatalog, signingKey) {
11378
13299
  }
11379
13300
 
11380
13301
  // src/protocol/handlers/catalog/view.ts
11381
- function catalogViewHandlers(getCatalog, signingKey) {
11382
- const catalogViewGet = catalogHandler(signingKey, async (params) => {
13302
+ function catalogViewHandlers(getCatalog, signingKey, attachSecretKey) {
13303
+ const keys = { signingKey, attachSecretKey };
13304
+ const catalogViewGet = catalogHandler(keys, async (params) => {
11383
13305
  const cat = getCatalog();
11384
13306
  const info = await cat.viewGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11385
13307
  return wrapResult({
11386
13308
  items: info ? [encodeViewInfo(info)] : []
11387
13309
  }, CatalogViewGetResultSchema);
11388
13310
  });
11389
- const catalogViewCreate = catalogHandler(signingKey, async (params) => {
13311
+ const catalogViewCreate = catalogHandler(keys, async (params) => {
11390
13312
  if (params.security !== "regular")
11391
13313
  throw new Error(`view security mode ${params.security} is unsupported`);
11392
13314
  const tags = catalogStringMap(params.tags);
@@ -11397,22 +13319,22 @@ function catalogViewHandlers(getCatalog, signingKey) {
11397
13319
  await cat.viewCreate(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.definition, decodeDictValue(params.on_conflict), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined, params.aliases ?? [], params.comment, tags, columnComments);
11398
13320
  return {};
11399
13321
  });
11400
- const catalogViewDrop = catalogHandler(signingKey, async (params) => {
13322
+ const catalogViewDrop = catalogHandler(keys, async (params) => {
11401
13323
  const cat = getCatalog();
11402
13324
  await cat.viewDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11403
13325
  return {};
11404
13326
  });
11405
- const catalogViewRename = catalogHandler(signingKey, async (params) => {
13327
+ const catalogViewRename = catalogHandler(keys, async (params) => {
11406
13328
  const cat = getCatalog();
11407
13329
  await cat.viewRename(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.new_name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11408
13330
  return {};
11409
13331
  });
11410
- const catalogViewCommentSet = catalogHandler(signingKey, async (params) => {
13332
+ const catalogViewCommentSet = catalogHandler(keys, async (params) => {
11411
13333
  const cat = getCatalog();
11412
13334
  await cat.viewCommentSet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.comment, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11413
13335
  return {};
11414
13336
  });
11415
- const catalogViewColumnCommentSet = catalogHandler(signingKey, async (params) => {
13337
+ const catalogViewColumnCommentSet = catalogHandler(keys, async (params) => {
11416
13338
  const path = Array.from(params.column_path);
11417
13339
  if (path.length !== 1 || !path[0] || path[0].includes("\x00"))
11418
13340
  throw new Error("view column comments require one raw output identifier");
@@ -11423,15 +13345,16 @@ function catalogViewHandlers(getCatalog, signingKey) {
11423
13345
  }
11424
13346
 
11425
13347
  // src/protocol/handlers/catalog/macro.ts
11426
- function catalogMacroHandlers(getCatalog, signingKey) {
11427
- const catalogMacroGet = catalogHandler(signingKey, async (params) => {
13348
+ function catalogMacroHandlers(getCatalog, signingKey, attachSecretKey) {
13349
+ const keys = { signingKey, attachSecretKey };
13350
+ const catalogMacroGet = catalogHandler(keys, async (params) => {
11428
13351
  const cat = getCatalog();
11429
13352
  const info = await cat.macroGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11430
13353
  return wrapResult({
11431
13354
  items: info ? [encodeMacroInfo(info)] : []
11432
13355
  }, CatalogMacroGetResultSchema);
11433
13356
  });
11434
- const catalogMacroCreate = catalogHandler(signingKey, async (params) => {
13357
+ const catalogMacroCreate = catalogHandler(keys, async (params) => {
11435
13358
  const cat = getCatalog();
11436
13359
  const innerParams = decodeASD(MacroCreateRequestSchema, encodeASD(MacroCreateRequestSchema, params));
11437
13360
  if (!innerParams.overloads?.length)
@@ -11439,12 +13362,12 @@ function catalogMacroHandlers(getCatalog, signingKey) {
11439
13362
  await cat.macroCreate(toUint8Array(innerParams.attach_opaque_data), innerParams.schema_path, innerParams.name, innerParams.macro_type, innerParams.overloads, innerParams.on_conflict, innerParams.transaction_opaque_data ? toUint8Array(innerParams.transaction_opaque_data) : undefined);
11440
13363
  return {};
11441
13364
  });
11442
- const catalogMacroDrop = catalogHandler(signingKey, async (params) => {
13365
+ const catalogMacroDrop = catalogHandler(keys, async (params) => {
11443
13366
  const cat = getCatalog();
11444
13367
  await cat.macroDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11445
13368
  return {};
11446
13369
  });
11447
- const catalogSchemaContentsMacros = catalogHandler(signingKey, async (params) => {
13370
+ const catalogSchemaContentsMacros = catalogHandler(keys, async (params) => {
11448
13371
  const cat = getCatalog();
11449
13372
  const macros = await cat.schemaContentsMacros(toUint8Array(params.attach_opaque_data), params.path, decodeDictValue(params.type), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11450
13373
  return wrapResult({
@@ -11455,15 +13378,16 @@ function catalogMacroHandlers(getCatalog, signingKey) {
11455
13378
  }
11456
13379
 
11457
13380
  // src/protocol/handlers/catalog/index_methods.ts
11458
- function catalogIndexHandlers(getCatalog, signingKey) {
11459
- const catalogSchemaContentsIndexes = catalogHandler(signingKey, async (params) => {
13381
+ function catalogIndexHandlers(getCatalog, signingKey, attachSecretKey) {
13382
+ const keys = { signingKey, attachSecretKey };
13383
+ const catalogSchemaContentsIndexes = catalogHandler(keys, async (params) => {
11460
13384
  const cat = getCatalog();
11461
13385
  const indexes = await cat.schemaContentsIndexes(toUint8Array(params.attach_opaque_data), params.path, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11462
13386
  return wrapResult({
11463
13387
  items: indexes.map((i) => encodeIndexInfo(i))
11464
13388
  }, CatalogSchemaContentsIndexesResultSchema);
11465
13389
  });
11466
- const catalogIndexGet = catalogHandler(signingKey, async (params) => {
13390
+ const catalogIndexGet = catalogHandler(keys, async (params) => {
11467
13391
  const cat = getCatalog();
11468
13392
  const info = await cat.indexGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
11469
13393
  return wrapResult({
@@ -11474,14 +13398,14 @@ function catalogIndexHandlers(getCatalog, signingKey) {
11474
13398
  }
11475
13399
 
11476
13400
  // src/protocol/handlers/catalog/index.ts
11477
- function catalogHandlers(catalog, signingKey) {
13401
+ function catalogHandlers(catalog, signingKey, attachSecretKey) {
11478
13402
  const getCatalog = makeGetCatalog(catalog);
11479
13403
  return {
11480
- ...catalogAdminHandlers(getCatalog, signingKey),
11481
- ...catalogTableHandlers(getCatalog, signingKey),
11482
- ...catalogViewHandlers(getCatalog, signingKey),
11483
- ...catalogMacroHandlers(getCatalog, signingKey),
11484
- ...catalogIndexHandlers(getCatalog, signingKey)
13404
+ ...catalogAdminHandlers(getCatalog, signingKey, attachSecretKey),
13405
+ ...catalogTableHandlers(getCatalog, signingKey, attachSecretKey),
13406
+ ...catalogViewHandlers(getCatalog, signingKey, attachSecretKey),
13407
+ ...catalogMacroHandlers(getCatalog, signingKey, attachSecretKey),
13408
+ ...catalogIndexHandlers(getCatalog, signingKey, attachSecretKey)
11485
13409
  };
11486
13410
  }
11487
13411
 
@@ -11492,11 +13416,12 @@ function buildVgiService(config) {
11492
13416
  ...functionHandlers({
11493
13417
  registry: config.registry,
11494
13418
  signingKey: config.signingKey,
13419
+ attachSecretKey: config.attachSecretKey,
11495
13420
  catalogInterface: config.catalogInterface
11496
13421
  }),
11497
13422
  ...aggregateHandlers(config.registry),
11498
- ...tableBufferingHandlers(config.registry, config.signingKey),
11499
- ...catalogHandlers(config.catalogInterface, config.signingKey)
13423
+ ...tableBufferingHandlers(config.registry, config.signingKey, config.attachSecretKey),
13424
+ ...catalogHandlers(config.catalogInterface, config.signingKey, config.attachSecretKey)
11500
13425
  };
11501
13426
  }
11502
13427
  function buildVgiProtocol(config) {
@@ -11877,7 +13802,7 @@ function createVgiWorkerFetch(opts) {
11877
13802
  }
11878
13803
  const trustedProxyAddresses = bridge?.trustedProxyAddresses ?? ["127.0.0.1"];
11879
13804
  return createVgiFetch({
11880
- protocol: { registry: opts.registry, catalogInterface: opts.catalogInterface },
13805
+ protocol: { registry: opts.registry, catalogInterface: opts.catalogInterface, attachSecretKey: opts.attachSecretKey },
11881
13806
  signingKey,
11882
13807
  signingKeyConfigured,
11883
13808
  tokenTtl,
@@ -11943,4 +13868,4 @@ export {
11943
13868
  serveVgiWorker
11944
13869
  };
11945
13870
 
11946
- //# debugId=448535FCB65D277D64756E2164756E21
13871
+ //# debugId=5DB2BEB30336CB9464756E2164756E21