@query-farm/vgi 0.48.1 → 0.48.3

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 (49) hide show
  1. package/README.md +51 -1
  2. package/dist/arrow/impl-arrowjs/iterate.d.ts +7 -3
  3. package/dist/arrow/impl-flechette/iterate.d.ts +2 -1
  4. package/dist/catalog/descriptors.d.ts +14 -0
  5. package/dist/catalog/read-only.d.ts +4 -5
  6. package/dist/client-entry.js +9 -25
  7. package/dist/client-entry.js.map +3 -3
  8. package/dist/functions/aggregate.d.ts +2 -1
  9. package/dist/functions/copy-from.d.ts +2 -1
  10. package/dist/functions/copy-to.d.ts +2 -1
  11. package/dist/functions/registry.d.ts +1 -0
  12. package/dist/functions/scalar.d.ts +18 -6
  13. package/dist/functions/table-buffering.d.ts +2 -1
  14. package/dist/functions/table-in-out.d.ts +3 -2
  15. package/dist/functions/table.d.ts +2 -1
  16. package/dist/functions/types.d.ts +8 -3
  17. package/dist/index.core.d.ts +3 -2
  18. package/dist/index.js +177 -61
  19. package/dist/index.js.map +21 -20
  20. package/dist/metadata/types.d.ts +3 -1
  21. package/dist/secrets/helpers.d.ts +31 -3
  22. package/dist/secrets/requirements.d.ts +38 -0
  23. package/dist/serve-entry.js +14 -28
  24. package/dist/serve-entry.js.map +6 -6
  25. package/dist/worker-cf-entry.d.ts +2 -2
  26. package/dist/worker-cf-entry.js +205 -53
  27. package/dist/worker-cf-entry.js.map +18 -16
  28. package/package.json +1 -1
  29. package/src/arrow/impl-arrowjs/iterate.ts +17 -40
  30. package/src/arrow/impl-flechette/iterate.ts +5 -24
  31. package/src/catalog/descriptors.ts +14 -0
  32. package/src/catalog/read-only.ts +24 -16
  33. package/src/functions/aggregate.ts +3 -2
  34. package/src/functions/copy-from.ts +3 -2
  35. package/src/functions/copy-to.ts +2 -1
  36. package/src/functions/registry.ts +6 -3
  37. package/src/functions/scalar.ts +33 -10
  38. package/src/functions/table-buffering.ts +6 -2
  39. package/src/functions/table-in-out.ts +34 -13
  40. package/src/functions/table.ts +12 -8
  41. package/src/functions/types.ts +15 -4
  42. package/src/index.core.ts +11 -1
  43. package/src/metadata/resolve.ts +2 -1
  44. package/src/metadata/serialize.ts +25 -5
  45. package/src/metadata/types.ts +3 -1
  46. package/src/protocol/handlers/function.ts +16 -3
  47. package/src/secrets/helpers.ts +96 -9
  48. package/src/secrets/requirements.ts +121 -0
  49. package/src/worker-cf-entry.ts +14 -0
@@ -1,6 +1,7 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
2
  // Function config interfaces and VgiFunction base type.
3
3
 
4
+ import type { RequiredSecret } from "../secrets/requirements.js";
4
5
  import type { VgiSchema, VgiBatch, VgiDataType } from "../arrow/index.js";
5
6
  import type { OutputCollector } from "@query-farm/vgi-rpc";
6
7
  import type {
@@ -94,7 +95,7 @@ export interface FunctionMeta {
94
95
  preservesOrder?: OrderPreservation | undefined;
95
96
  maxWorkers?: number | undefined;
96
97
  requiredSettings?: string[] | undefined;
97
- requiredSecrets?: string[] | undefined;
98
+ requiredSecrets?: RequiredSecret[] | undefined;
98
99
  orderDependent?: OrderDependence | undefined;
99
100
  distinctDependent?: DistinctDependence | undefined;
100
101
  /**
@@ -213,12 +214,22 @@ export interface FunctionMeta {
213
214
  copyToComment?: string | null | undefined;
214
215
  }
215
216
 
217
+ /** The user state a rebuilt HTTP turn restores, boxed so `null` state survives. */
218
+ export interface RestoredUserState {
219
+ state: unknown;
220
+ }
221
+
216
222
  export interface StreamHandlers {
217
- // For producer streams (table functions, finalize phase)
218
- producerInit?: (() => any) | undefined;
223
+ // For producer streams (table functions, finalize phase).
224
+ //
225
+ // `restored` is the user state an HTTP turn carried in its cursor. When it
226
+ // is given the handler must adopt it instead of computing a fresh one, so
227
+ // `initialState` runs once per stream, not once per turn (a rebuilt turn
228
+ // used to call it and then discard the result).
229
+ producerInit?: ((restored?: RestoredUserState) => any) | undefined;
219
230
  producerFn?: ((state: any, out: OutputCollector) => void | Promise<void>) | undefined;
220
231
  // For exchange streams (scalar, table-in-out input phase)
221
- exchangeInit?: (() => any) | undefined;
232
+ exchangeInit?: ((restored?: RestoredUserState) => any) | undefined;
222
233
  exchangeFn?: (
223
234
  state: any,
224
235
  input: VgiBatch,
package/src/index.core.ts CHANGED
@@ -31,7 +31,7 @@ export {
31
31
  } from "./cache-control.js";
32
32
 
33
33
  // Function factories (primary API)
34
- export { defineScalarFunction, type ScalarFunctionConfig, type ScalarBindParameters, type ScalarParameterDef } from "./functions/scalar.js";
34
+ export { defineScalarFunction, type ScalarFunctionConfig, type ScalarBindParameters, type ScalarComputeInfo, type ScalarParameterDef } from "./functions/scalar.js";
35
35
  export { defineTableFunction, type TableFunctionConfig, type TableBindParams, type TableProcessParams } from "./functions/table.js";
36
36
  export {
37
37
  defineAggregate,
@@ -262,10 +262,20 @@ export {
262
262
  type SecretsDict,
263
263
  secretType,
264
264
  secretsOfType,
265
+ secretOfType,
266
+ requireSecretOfType,
267
+ secretByName,
265
268
  secretForScope,
266
269
  secretForScopeOfType,
267
270
  } from "./secrets/helpers.js";
268
271
 
272
+ export {
273
+ type RequiredSecret,
274
+ type SecretRequirement,
275
+ type SecretRequirementSpec,
276
+ normalizeRequiredSecrets,
277
+ } from "./secrets/requirements.js";
278
+
269
279
  export {
270
280
  serializeSchema,
271
281
  deserializeSchema,
@@ -1,6 +1,7 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
2
  // Extract metadata from VgiFunction configs.
3
3
 
4
+ import { normalizeRequiredSecrets } from "../secrets/requirements.js";
4
5
  import {
5
6
  FunctionStability,
6
7
  NullHandling,
@@ -132,7 +133,7 @@ export function resolveMetadata(func: VgiFunction): ResolvedMetadata {
132
133
  nullHandling: meta.nullHandling ?? NullHandling.DEFAULT,
133
134
  argumentMonotonicity,
134
135
  requiredSettings: meta.requiredSettings ?? [],
135
- requiredSecrets: meta.requiredSecrets ?? [],
136
+ requiredSecrets: normalizeRequiredSecrets(meta.requiredSecrets, meta.name),
136
137
  projectionPushdown: meta.projectionPushdown ?? false,
137
138
  filterPushdown: meta.filterPushdown ?? false,
138
139
  samplingPushdown: meta.samplingPushdown ?? false,
@@ -18,6 +18,7 @@ import {
18
18
  } from "../arrow/index.js";
19
19
  import type { ResolvedMetadata, ParameterInfo, FunctionExample } from "./types.js";
20
20
  import type { ArgumentMonotonicity } from "../types.js";
21
+ import { normalizeRequiredSecrets, type SecretRequirement } from "../secrets/requirements.js";
21
22
 
22
23
  // ============================================================================
23
24
  // Schema definitions matching Python's _METADATA_SCHEMA exactly
@@ -54,6 +55,12 @@ const FILTER_CONTEXT_STRUCT = makeStruct([
54
55
  field("provider_fingerprint", utf8(), true),
55
56
  ]);
56
57
 
58
+ const SECRET_REQUIREMENT_STRUCT = makeStruct([
59
+ field("secret_type", utf8(), false),
60
+ field("secret_name", utf8(), true),
61
+ field("scope", utf8(), true),
62
+ ]);
63
+
57
64
  const METADATA_SCHEMA = makeSchema([
58
65
  field("name", utf8(), false),
59
66
  field("class_name", utf8(), false),
@@ -67,7 +74,7 @@ const METADATA_SCHEMA = makeSchema([
67
74
  field("null_handling", utf8(), false),
68
75
  field("argument_monotonicity", list(field("item", utf8(), true)), true),
69
76
  field("required_settings", list(field("item", utf8(), true)), false),
70
- field("required_secrets", list(field("item", utf8(), true)), false),
77
+ field("required_secrets", list(field("item", SECRET_REQUIREMENT_STRUCT, true)), false),
71
78
  field("projection_pushdown", bool(), false),
72
79
  field("filter_pushdown", bool(), false),
73
80
  field("filter_semantic_profiles", list(field("item", utf8(), true)), false),
@@ -116,7 +123,11 @@ function metadataToRow(m: ResolvedMetadata): Record<string, any> {
116
123
  null_handling: m.nullHandling,
117
124
  argument_monotonicity: m.argumentMonotonicity,
118
125
  required_settings: m.requiredSettings,
119
- required_secrets: m.requiredSecrets,
126
+ required_secrets: m.requiredSecrets.map((s) => ({
127
+ secret_type: s.secretType,
128
+ secret_name: s.secretName,
129
+ scope: s.scope,
130
+ })),
120
131
  projection_pushdown: m.projectionPushdown,
121
132
  filter_pushdown: m.filterPushdown,
122
133
  sampling_pushdown: m.samplingPushdown,
@@ -236,9 +247,18 @@ export function arrowToMetadatas(batch: VgiBatch): ResolvedMetadata[] {
236
247
  : [];
237
248
 
238
249
  const rawRequiredSecrets = get("required_secrets") as any ?? [];
239
- const requiredSecrets: string[] = rawRequiredSecrets
240
- ? [...rawRequiredSecrets].filter((s: any) => s != null)
241
- : [];
250
+ // Struct entries ({secret_type, secret_name, scope}); a bare string (the
251
+ // pre-0.48.3 list<utf8> layout) is still read as a type-only requirement.
252
+ const requiredSecrets: SecretRequirement[] = normalizeRequiredSecrets(
253
+ rawRequiredSecrets
254
+ ? [...rawRequiredSecrets].filter((s: any) => s != null).map((s: any) =>
255
+ typeof s === "string"
256
+ ? s
257
+ : { secretType: s.secret_type, secretName: s.secret_name ?? null, scope: s.scope ?? null },
258
+ )
259
+ : [],
260
+ (get("name") as string) ?? "<function>",
261
+ );
242
262
 
243
263
  results.push({
244
264
  name: (get("name") as string) ?? "",
@@ -1,6 +1,7 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
2
  // Metadata types for function introspection and DuckDB registration.
3
3
 
4
+ import type { SecretRequirement } from "../secrets/requirements.js";
4
5
  import {
5
6
  FunctionStability,
6
7
  NullHandling,
@@ -61,7 +62,8 @@ export interface ResolvedMetadata {
61
62
  nullHandling: NullHandling;
62
63
  argumentMonotonicity: ArgumentMonotonicity[] | null;
63
64
  requiredSettings: string[];
64
- requiredSecrets: string[];
65
+ /** Validated static secret requirements (FunctionInfo `required_secrets`). */
66
+ requiredSecrets: SecretRequirement[];
65
67
  projectionPushdown: boolean;
66
68
  filterPushdown: boolean;
67
69
  samplingPushdown: boolean;
@@ -374,6 +374,14 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
374
374
  // cursor carries the packed request unchanged on every turn.
375
375
  const carried = parseCarriedInitRequest(state.initRequestPacked);
376
376
  const request = carried.request;
377
+ // The cursor carries the wire request, whose attach is still the sealed
378
+ // envelope. Strip it exactly as the init turn did, before any user code
379
+ // or split resolution sees it: every turn of a stream must hand the
380
+ // function the catalog's own bytes, not just the first. (Unopenable is
381
+ // a hard error here, as on the init turn: the cursor is caller-bound.)
382
+ // `carried.request.bind_call` is a per-call copy, so this does not
383
+ // disturb the memoised parse other turns share.
384
+ request.bind_call.attach_opaque_data = await stripAttach(request.bind_call.attach_opaque_data, undefined);
377
385
  // Re-derive the split payloads. The cursor carries the wire request,
378
386
  // which has `split_tokens` but not the opened `split_payloads` — that
379
387
  // field only ever existed in memory on the init turn. Without this a
@@ -396,7 +404,9 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
396
404
  catalogInterface,
397
405
  checkAnchor: false,
398
406
  });
399
- const func = registry.get(state.functionName, await strippedContext(request.bind_call));
407
+ // Already stripped above, so resolve directly (strippedContext would try
408
+ // to open the plaintext again and fall back to an unscoped lookup).
409
+ const func = registry.get(state.functionName, overloadContext(request.bind_call, catalogInterface));
400
410
  const executionId = state.executionId;
401
411
  const opaqueData = state.opaqueData ?? null;
402
412
  const initResponse: GlobalInitResponse = {
@@ -409,10 +419,13 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
409
419
  // after the one that received a delta would scan under the init
410
420
  // snapshot again, because the extension sends each delta only once.
411
421
  handlers = func.createStreamHandlers(request, initResponse, state.filterHistory ?? null);
422
+ // Hand the carried user state to the init hook, so a handler that
423
+ // supports it skips initialState (which already ran on the init turn).
424
+ const restored = state.userState != null ? { state: state.userState } : undefined;
412
425
  if (handlers.producerInit) {
413
- handlerState = handlers.producerInit();
426
+ handlerState = handlers.producerInit(restored);
414
427
  } else if (handlers.exchangeInit) {
415
- handlerState = handlers.exchangeInit();
428
+ handlerState = handlers.exchangeInit(restored);
416
429
  }
417
430
  // Merge preserved user state (e.g. { remaining, currentIndex })
418
431
  if (state.userState != null && handlerState?.state !== undefined) {
@@ -1,10 +1,26 @@
1
1
  // Type- and scope-aware selection over resolved secrets.
2
2
  //
3
3
  // Resolved secrets reach a worker as a plain object keyed by each secret's
4
- // unique DuckDB secret name (so several secrets of the same type — e.g. one per
5
- // S3 bucket — coexist). Each secret carries its connector-serialized `type` (the
6
- // DuckDB secret type) and `scope` (newline-joined scope prefixes) fields, plus
7
- // type-specific fields. These helpers mirror `vgi::Secrets` in the Rust SDK.
4
+ // unique DuckDB secret NAME, not its type: an unnamed
5
+ // `CREATE SECRET (TYPE brave, ...)` arrives as `__default_brave`, and several
6
+ // secrets of one type (e.g. one per S3 bucket) coexist. Each secret carries its
7
+ // connector-serialized `type` (the DuckDB secret type), `name`, and `scope`
8
+ // (newline-joined scope prefixes) fields, plus type-specific fields.
9
+ //
10
+ // So never look a TYPE up as a key (`secrets["brave"]` finds the secret only
11
+ // when the user happened to name it after its type). Select with these helpers,
12
+ // which apply the same rules the client used to resolve the request
13
+ // (vgi-python `docs/protocol/vgi-secrets.md` section 5):
14
+ //
15
+ // by type -> secretOfType / secretsOfType / requireSecretOfType
16
+ // by name -> secretByName
17
+ // by scope -> secretForScopeOfType (longest prefix, else unscoped, else none)
18
+ //
19
+ // Every by-type selector matches the secret's `type` field. Only when no
20
+ // secret carries that type does it fall back to a secret whose KEY is the type
21
+ // and that has no `type` field at all: a bare key/value struct from a client
22
+ // that keys the batch by type (as vgi-python's standalone Client allows).
23
+ // These helpers mirror `vgi::Secrets` in the Rust SDK.
8
24
 
9
25
  export type SecretFields = Record<string, any>;
10
26
  export type SecretsDict = Record<string, SecretFields>;
@@ -20,28 +36,99 @@ export function secretType(secrets: SecretsDict, name: string): string | undefin
20
36
  return f && "type" in f ? scalarStr(f.type) : undefined;
21
37
  }
22
38
 
23
- /** Every resolved secret whose serialized `type` field matches `type`. */
39
+ /** True when the secret's serialized `type` field is absent or empty. */
40
+ function untyped(fields: SecretFields | undefined): boolean {
41
+ return !!fields && scalarStr(fields.type) === "";
42
+ }
43
+
44
+ /**
45
+ * The legacy by-key fallback: a secret stored under the key `type` that has no
46
+ * `type` field of its own (a client that keys the batch by type and sends bare
47
+ * key/value structs). A secret under that key whose `type` field names another
48
+ * type is NOT a match.
49
+ */
50
+ function keyedByType(secrets: SecretsDict, type: string): SecretFields | undefined {
51
+ const f = secrets?.[type];
52
+ return untyped(f) ? f : undefined;
53
+ }
54
+
55
+ /**
56
+ * Every resolved secret whose serialized `type` field matches `type`, in
57
+ * delivery order. Falls back to an untyped secret keyed by `type` only when no
58
+ * secret carries the type.
59
+ */
24
60
  export function secretsOfType(secrets: SecretsDict, type: string): SecretFields[] {
25
- return Object.values(secrets ?? {}).filter((f) => scalarStr(f.type) === type);
61
+ const typed = Object.values(secrets ?? {}).filter((f) => scalarStr(f.type) === type);
62
+ if (typed.length > 0) return typed;
63
+ const legacy = keyedByType(secrets, type);
64
+ return legacy ? [legacy] : [];
65
+ }
66
+
67
+ /**
68
+ * The secret a by-TYPE request refers to: a secret of `type` with an empty
69
+ * scope, else the first secret of `type`, else undefined. This is the rule the
70
+ * client applies to a `requiredSecrets: ["<type>"]` declaration, so it picks the
71
+ * secret that declaration resolved even when other same-type secrets (from
72
+ * scoped declarations) were delivered alongside it.
73
+ */
74
+ export function secretOfType(secrets: SecretsDict, type: string): SecretFields | undefined {
75
+ const all = secretsOfType(secrets, type);
76
+ return all.find((f) => scalarStr(f.scope) === "") ?? all[0];
77
+ }
78
+
79
+ /**
80
+ * Like {@link secretOfType}, but throws when no secret of `type` was resolved.
81
+ * Call it from `onBind` to fail the bind of a function that cannot run without
82
+ * credentials. The message names the type and never includes a secret value.
83
+ */
84
+ export function requireSecretOfType(secrets: SecretsDict, type: string): SecretFields {
85
+ const found = secretOfType(secrets, type);
86
+ if (!found) {
87
+ throw new Error(
88
+ `required secret of type '${type}' was not found; create one with CREATE SECRET (TYPE ${type}, ...)`,
89
+ );
90
+ }
91
+ return found;
92
+ }
93
+
94
+ /**
95
+ * The secret with DuckDB name `name` (its key in the resolved batch). With
96
+ * `type`, only if that secret's `type` field is `type` (or absent, for a bare
97
+ * key/value struct) — the rule the client applies to a by-name request.
98
+ */
99
+ export function secretByName(
100
+ secrets: SecretsDict,
101
+ name: string,
102
+ type?: string,
103
+ ): SecretFields | undefined {
104
+ if (!secrets || !Object.prototype.hasOwnProperty.call(secrets, name)) return undefined;
105
+ const f = secrets[name];
106
+ if (!f) return undefined;
107
+ if (type === undefined || untyped(f) || scalarStr(f.type) === type) return f;
108
+ return undefined;
26
109
  }
27
110
 
28
111
  /**
29
112
  * The secret whose `scope` is the longest prefix of `path`. The connector
30
113
  * serializes each secret's scope as a newline-joined list of prefixes; a secret
31
114
  * with no (or empty) scope matches as a last-resort fallback. Returns undefined
32
- * only when there are no candidate secrets.
115
+ * when no scope is a prefix of `path` and no unscoped secret was delivered.
33
116
  */
34
117
  export function secretForScope(secrets: SecretsDict, path: string): SecretFields | undefined {
35
118
  return selectForScope(secrets, path, undefined);
36
119
  }
37
120
 
38
- /** Like {@link secretForScope} but only over secrets of `type`. */
121
+ /**
122
+ * Like {@link secretForScope} but only over secrets of `type`: the one whose
123
+ * scope is the longest prefix of `path`, else one of `type` with an empty scope,
124
+ * else undefined.
125
+ */
39
126
  export function secretForScopeOfType(
40
127
  secrets: SecretsDict,
41
128
  path: string,
42
129
  type: string,
43
130
  ): SecretFields | undefined {
44
- return selectForScope(secrets, path, type);
131
+ return selectForScope(secrets, path, type) ?? keyedByType(secrets, type);
45
132
  }
46
133
 
47
134
  function selectForScope(
@@ -0,0 +1,121 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Static secret requirements: what a function declares in `requiredSecrets`.
3
+ //
4
+ // Each requirement becomes one FunctionInfo `required_secrets` entry
5
+ // (`{secret_type, scope, secret_name}`). At bind the client resolves every entry
6
+ // with DuckDB's secret manager and sends the matches, one struct column per
7
+ // secret, keyed by the secret's unique NAME (see `docs/protocol/vgi-secrets.md`
8
+ // in vgi-python). A requirement the SDK does not understand must never be
9
+ // dropped: the client would not be asked for the secret and the function would
10
+ // run without credentials. Anything unrecognised is a definition-time error.
11
+
12
+ /**
13
+ * A secret requirement in object form. `scope` asks the client for the secret of
14
+ * `secretType` whose scope is the longest prefix of it; `secretName` asks for one
15
+ * secret by its DuckDB name (and takes precedence over `scope`, as it does on
16
+ * the client). Neither means "a secret of this type with an empty scope".
17
+ *
18
+ * The snake_case spelling of the wire entry (`secret_type` / `secret_name`) is
19
+ * accepted too.
20
+ */
21
+ export interface SecretRequirementSpec {
22
+ secretType?: string;
23
+ scope?: string | null;
24
+ secretName?: string | null;
25
+ secret_type?: string;
26
+ secret_name?: string | null;
27
+ }
28
+
29
+ /**
30
+ * One `requiredSecrets` entry: a bare secret type (the simplest form — "a secret
31
+ * of this type"), or a {@link SecretRequirementSpec} with a scope or a name.
32
+ */
33
+ export type RequiredSecret = string | SecretRequirementSpec;
34
+
35
+ /** A validated, normalized requirement — the shape sent on the wire. */
36
+ export interface SecretRequirement {
37
+ secretType: string;
38
+ scope: string | null;
39
+ secretName: string | null;
40
+ }
41
+
42
+ const KNOWN_KEYS = new Set(["secretType", "secret_type", "scope", "secretName", "secret_name"]);
43
+
44
+ function optionalString(
45
+ value: unknown,
46
+ what: string,
47
+ where: string,
48
+ ): string | null {
49
+ if (value === undefined || value === null) return null;
50
+ if (typeof value !== "string") {
51
+ throw new TypeError(`${where}: ${what} must be a string, got ${typeof value}`);
52
+ }
53
+ return value === "" ? null : value;
54
+ }
55
+
56
+ /**
57
+ * Validate and normalize a `requiredSecrets` declaration. Throws on anything
58
+ * that is not a list of bare type strings / requirement objects, on an empty
59
+ * type, on unknown object keys (a typo such as `{ type: "s3" }` would otherwise
60
+ * declare nothing), and on conflicting camelCase/snake_case spellings.
61
+ * Duplicate requirements (same type, scope and name) are collapsed.
62
+ *
63
+ * @param value The declared `requiredSecrets` (undefined → no requirements).
64
+ * @param functionName Used in error messages.
65
+ */
66
+ export function normalizeRequiredSecrets(
67
+ value: unknown,
68
+ functionName = "<function>",
69
+ ): SecretRequirement[] {
70
+ if (value === undefined || value === null) return [];
71
+ const where = `requiredSecrets of '${functionName}'`;
72
+ if (!Array.isArray(value)) {
73
+ throw new TypeError(
74
+ `${where} must be an array of secret types or { secretType, scope?, secretName? } objects, got ${typeof value}`,
75
+ );
76
+ }
77
+ const out: SecretRequirement[] = [];
78
+ const seen = new Set<string>();
79
+ value.forEach((entry: unknown, i: number) => {
80
+ const at = `${where}[${i}]`;
81
+ let req: SecretRequirement;
82
+ if (typeof entry === "string") {
83
+ if (entry === "") throw new TypeError(`${at}: secret type must not be empty`);
84
+ req = { secretType: entry, scope: null, secretName: null };
85
+ } else if (entry !== null && typeof entry === "object" && !Array.isArray(entry)) {
86
+ const obj = entry as Record<string, unknown>;
87
+ const unknown = Object.keys(obj).filter((k) => !KNOWN_KEYS.has(k));
88
+ if (unknown.length > 0) {
89
+ throw new TypeError(
90
+ `${at}: unknown key(s) ${unknown.map((k) => `'${k}'`).join(", ")}; ` +
91
+ `expected secretType, scope, secretName`,
92
+ );
93
+ }
94
+ if (obj.secretType !== undefined && obj.secret_type !== undefined && obj.secretType !== obj.secret_type) {
95
+ throw new TypeError(`${at}: secretType and secret_type disagree`);
96
+ }
97
+ if (obj.secretName !== undefined && obj.secret_name !== undefined && obj.secretName !== obj.secret_name) {
98
+ throw new TypeError(`${at}: secretName and secret_name disagree`);
99
+ }
100
+ const secretType = obj.secretType ?? obj.secret_type;
101
+ if (typeof secretType !== "string" || secretType === "") {
102
+ throw new TypeError(`${at}: secretType must be a non-empty string`);
103
+ }
104
+ req = {
105
+ secretType,
106
+ scope: optionalString(obj.scope, "scope", at),
107
+ secretName: optionalString(obj.secretName ?? obj.secret_name, "secretName", at),
108
+ };
109
+ } else {
110
+ throw new TypeError(
111
+ `${at}: expected a secret type string or a { secretType, scope?, secretName? } object, got ` +
112
+ (entry === null ? "null" : Array.isArray(entry) ? "array" : typeof entry),
113
+ );
114
+ }
115
+ const key = JSON.stringify([req.secretType, req.scope, req.secretName]);
116
+ if (seen.has(key)) return;
117
+ seen.add(key);
118
+ out.push(req);
119
+ });
120
+ return out;
121
+ }
@@ -65,6 +65,15 @@ export {
65
65
  serializeColumnStatistics,
66
66
  BindResultSchema,
67
67
  ScanFunctionResultSchema,
68
+ // Resolved-secret selection (the batch is keyed by secret NAME, not type).
69
+ secretType,
70
+ secretsOfType,
71
+ secretOfType,
72
+ requireSecretOfType,
73
+ secretByName,
74
+ secretForScope,
75
+ secretForScopeOfType,
76
+ normalizeRequiredSecrets,
68
77
  } from "./index.core.js";
69
78
  // vgi.v3 records: constraints, capabilities, column expressions, indexes, macro overloads.
70
79
  export * from "./catalog/public-codecs.js";
@@ -90,6 +99,11 @@ export type {
90
99
  TableInOutBindParams,
91
100
  ConstraintRecordSpec,
92
101
  ConstraintRecordView,
102
+ SecretFields,
103
+ SecretsDict,
104
+ RequiredSecret,
105
+ SecretRequirement,
106
+ SecretRequirementSpec,
93
107
  } from "./index.core.js";
94
108
 
95
109
  export type { ProtocolConfig } from "./protocol/dispatch.js";