@neondatabase/env 1.0.0 → 1.1.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 (59) hide show
  1. package/README.md +21 -1
  2. package/dist/cli.js +1304 -6
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{_shared/env-core/env.js → env.js} +62 -41
  5. package/dist/env.js.map +1 -0
  6. package/dist/index.d.ts +528 -3
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +197 -2
  9. package/dist/{lib/parse-env.js.map → index.js.map} +1 -1
  10. package/package.json +12 -7
  11. package/dist/_shared/auth_selection.d.ts +0 -95
  12. package/dist/_shared/auth_selection.d.ts.map +0 -1
  13. package/dist/_shared/auth_selection.js +0 -85
  14. package/dist/_shared/auth_selection.js.map +0 -1
  15. package/dist/_shared/credentials.d.ts +0 -186
  16. package/dist/_shared/credentials.d.ts.map +0 -1
  17. package/dist/_shared/credentials.js +0 -190
  18. package/dist/_shared/credentials.js.map +0 -1
  19. package/dist/_shared/env-core/env.d.ts +0 -424
  20. package/dist/_shared/env-core/env.d.ts.map +0 -1
  21. package/dist/_shared/env-core/env.js.map +0 -1
  22. package/dist/_shared/env-core/reuse-secrets.d.ts +0 -95
  23. package/dist/_shared/env-core/reuse-secrets.d.ts.map +0 -1
  24. package/dist/_shared/env-core/reuse-secrets.js +0 -181
  25. package/dist/_shared/env-core/reuse-secrets.js.map +0 -1
  26. package/dist/_shared/paths.d.ts +0 -116
  27. package/dist/_shared/paths.d.ts.map +0 -1
  28. package/dist/_shared/paths.js +0 -153
  29. package/dist/_shared/paths.js.map +0 -1
  30. package/dist/_shared/profiles.d.ts +0 -145
  31. package/dist/_shared/profiles.d.ts.map +0 -1
  32. package/dist/_shared/profiles.js +0 -228
  33. package/dist/_shared/profiles.js.map +0 -1
  34. package/dist/_shared/secure_file.d.ts +0 -25
  35. package/dist/_shared/secure_file.d.ts.map +0 -1
  36. package/dist/_shared/secure_file.js +0 -43
  37. package/dist/_shared/secure_file.js.map +0 -1
  38. package/dist/config/dist/lib/define-config.d.ts +0 -20
  39. package/dist/config/dist/lib/define-config.d.ts.map +0 -1
  40. package/dist/config/dist/lib/neon-api.d.ts +0 -375
  41. package/dist/config/dist/lib/neon-api.d.ts.map +0 -1
  42. package/dist/config/dist/lib/types.d.ts +0 -603
  43. package/dist/config/dist/lib/types.d.ts.map +0 -1
  44. package/dist/config/dist/v1.d.ts +0 -5
  45. package/dist/lib/cli/commands.d.ts +0 -68
  46. package/dist/lib/cli/commands.d.ts.map +0 -1
  47. package/dist/lib/cli/commands.js +0 -233
  48. package/dist/lib/cli/commands.js.map +0 -1
  49. package/dist/lib/cli/resolve-api-key.d.ts +0 -29
  50. package/dist/lib/cli/resolve-api-key.d.ts.map +0 -1
  51. package/dist/lib/cli/resolve-api-key.js +0 -74
  52. package/dist/lib/cli/resolve-api-key.js.map +0 -1
  53. package/dist/lib/cli/resolve-context.d.ts +0 -34
  54. package/dist/lib/cli/resolve-context.d.ts.map +0 -1
  55. package/dist/lib/cli/resolve-context.js +0 -88
  56. package/dist/lib/cli/resolve-context.js.map +0 -1
  57. package/dist/lib/parse-env.d.ts +0 -95
  58. package/dist/lib/parse-env.d.ts.map +0 -1
  59. package/dist/lib/parse-env.js +0 -198
@@ -1,424 +0,0 @@
1
- import { Config, CredentialScope, ResolvedPreviewConfig } from "../../config/dist/lib/types.js";
2
- import { NeonApi, NeonBranchSnapshot } from "../../config/dist/lib/neon-api.js";
3
- import { resolveConfig } from "../../config/dist/lib/define-config.js";
4
- import "../../config/dist/v1.js";
5
-
6
- //#region src/_shared/env-core/env.d.ts
7
-
8
- declare const NEON_ENV_VAR_KEYS: {
9
- /**
10
- * Branch identity. `NEON_BRANCH` carries the branch **name** and is injected into the
11
- * Neon Functions runtime on every branch (including the default) by default. `env pull` /
12
- * `neon dev` / `neon-env run` emit it too so local dev mirrors the deployed runtime.
13
- */
14
- readonly branch: {
15
- readonly name: "NEON_BRANCH";
16
- };
17
- readonly postgres: {
18
- readonly databaseUrl: "DATABASE_URL";
19
- readonly databaseUrlUnpooled: "DATABASE_URL_UNPOOLED";
20
- };
21
- readonly auth: {
22
- readonly baseUrl: "NEON_AUTH_BASE_URL";
23
- readonly jwksUrl: "NEON_AUTH_JWKS_URL";
24
- };
25
- readonly dataApi: {
26
- readonly url: "NEON_DATA_API_URL";
27
- };
28
- /**
29
- * Object storage (Preview). The S3 SDKs read `AWS_*` from their standard config chain, so
30
- * a branch credential + `neon dev` / `env pull` makes object storage work from env alone.
31
- * `region` is injected under the SDK-standard `AWS_REGION`.
32
- */
33
- readonly storage: {
34
- readonly accessKeyId: "AWS_ACCESS_KEY_ID";
35
- readonly secretAccessKey: "AWS_SECRET_ACCESS_KEY";
36
- readonly endpoint: "AWS_ENDPOINT_URL_S3";
37
- readonly region: "AWS_REGION";
38
- };
39
- /**
40
- * AI Gateway (Preview). Exposed under the Neon-branded env vars the deployed Functions
41
- * runtime injects: `apiKey` is the minted credential's bearer (`NEON_AI_GATEWAY_TOKEN`)
42
- * and `baseUrl` is the bare branch gateway host (`NEON_AI_GATEWAY_BASE_URL`,
43
- * `scheme://host`, no path). Clients like `@neon/ai-sdk-provider` read these and append the
44
- * dialect route (`/v1`, `/openai/v1`, `/anthropic/v1`) themselves (https://github.com/vercel/ai/pull/15997).
45
- */
46
- readonly aiGateway: {
47
- readonly apiKey: "NEON_AI_GATEWAY_TOKEN";
48
- readonly baseUrl: "NEON_AI_GATEWAY_BASE_URL";
49
- };
50
- };
51
- /**
52
- * Branch identity for the resolved branch. Always present on a `fetchEnv` result (the branch
53
- * name is always known); on a `parseEnv` result it's present only when `NEON_BRANCH` was
54
- * injected into `process.env` (the Functions runtime injects it by default, as do `neon dev` /
55
- * `neon-env run` / `env pull`). `name` is the branch **name** (e.g. `main`, `preview/foo`).
56
- */
57
- interface NeonBranchEnv {
58
- name: string;
59
- }
60
- /** Per-namespace inner shapes. Exposed so consumers can name the parts independently. */
61
- interface NeonPostgresEnv {
62
- /**
63
- * Pooled connection string (via Neon's PgBouncer pooler). The right default for
64
- * serverless drivers (`@neondatabase/serverless`, edge runtimes, Postgres.js, …).
65
- */
66
- databaseUrl: string;
67
- /**
68
- * Direct (unpooled) connection string. Use this when you need session-level
69
- * features (`LISTEN`/`NOTIFY`, prepared statements across calls, transactions
70
- * spanning round-trips) that PgBouncer's transaction-mode pooling drops.
71
- */
72
- databaseUrlUnpooled: string;
73
- }
74
- /**
75
- * Bits of a Neon Auth integration for the resolved branch. Only present on `NeonEnv`
76
- * when the branch policy enables `auth`.
77
- *
78
- * Neon Auth exposes the `baseUrl` (which doubles as the publishable client identifier) and
79
- * the `jwksUrl` used to verify tokens it issues. `fetchEnv` reads both from the live
80
- * integration; `parseEnv` reads them from `process.env` (`NEON_AUTH_BASE_URL` /
81
- * `NEON_AUTH_JWKS_URL`).
82
- */
83
- interface NeonAuthEnv {
84
- baseUrl: string;
85
- /** JWKS URL for verifying tokens issued by Neon Auth (`NEON_AUTH_JWKS_URL`). */
86
- jwksUrl: string;
87
- }
88
- /** Bits of a Neon Data API integration. Only present when the branch policy enables it. */
89
- interface NeonDataApiEnv {
90
- url: string;
91
- }
92
- /**
93
- * S3-compatible object-storage access for the branch (Preview). Present on `NeonEnv` only
94
- * when the policy declares `preview.buckets`. Combines a minted branch credential's access
95
- * keys (`accessKeyId` = the credential's full token id, e.g. `nak_live_…`, which is what the
96
- * storage gateway authenticates against; `secretAccessKey` = its
97
- * `s3_secret_access_key`) with the branch's non-secret connection details
98
- * (`endpoint`/`region`, from `GET .../storage`). Projects to the AWS SDK's
99
- * standard config env (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_ENDPOINT_URL_S3`,
100
- * `AWS_REGION`) so the S3 client works from env alone. Neon's storage gateway always
101
- * requires path-style addressing, so set `forcePathStyle: true` on your S3 client.
102
- */
103
- interface NeonStorageEnv {
104
- accessKeyId: string;
105
- secretAccessKey: string;
106
- /** S3-compatible endpoint URL for the branch. */
107
- endpoint: string;
108
- /** AWS region string (e.g. `us-east-2`). Injected as `AWS_REGION`. */
109
- region: string;
110
- }
111
- /**
112
- * AI Gateway access for the branch (Preview). Present on `NeonEnv` only when the policy
113
- * enables `preview.aiGateway`. `apiKey` is the minted credential's bearer (`api_token`);
114
- * `baseUrl` is the bare branch-scoped gateway host
115
- * (`https://<branchId>-api.ai.<region>.…`, no path). Projects to the Neon-branded env
116
- * (`NEON_AI_GATEWAY_TOKEN`, `NEON_AI_GATEWAY_BASE_URL`); clients like `@neon/ai-sdk-provider`
117
- * append the dialect route (`/v1`, `/openai/v1`, `/anthropic/v1`) themselves.
118
- */
119
- interface NeonAiGatewayEnv {
120
- apiKey: string;
121
- baseUrl: string;
122
- }
123
- /**
124
- * Empty record alias used as the "false" branch of the conditional namespace adds below.
125
- * `Record<never, never>` is the no-op for intersection — the cleaner alternative to `{}`,
126
- * which biome rejects (it means "any non-null", not "empty object").
127
- */
128
- type NoNamespace = Record<never, never>;
129
- /**
130
- * Resolve a **static** service toggle (the value of `config.auth` / `config.dataApi`) to a
131
- * type-level boolean. The whole-thing wrapping (`[T] extends […]`) turns off distribution
132
- * so a union/`undefined` is checked as one unit:
133
- *
134
- * - `false` / `{ enabled: false }` / `undefined` → `false`
135
- * - `true` / `{ enabled: true }` / any other object (`{}`, `{ enabled?: boolean }`) → `true`
136
- * (a present toggle defaults to enabled)
137
- * - the bare `boolean | ServiceToggle | undefined` (the default `Config` param, no literal
138
- * info) → `false`, so an untyped policy yields just `{ postgres }`.
139
- */
140
- type ServiceOn<T> = [T] extends [false] ? false : [T] extends [{
141
- enabled: false;
142
- }] ? false : [T] extends [undefined] ? false : [T] extends [true] ? true : [T] extends [{
143
- enabled: true;
144
- }] ? true : [T] extends [object] ? true : false;
145
- /** True when `T` has at least one known key; `false` for `{}` / `never`. */
146
- type HasKeys<T> = [keyof T] extends [never] ? false : true;
147
- /**
148
- * Whether the policy's **static** `preview` block declares at least one object-storage bucket
149
- * (`preview.buckets`). Drives whether {@link NeonEnv} carries the `storage` namespace.
150
- *
151
- * The leading `[never]` guard is load-bearing: when a policy has no `preview` at all,
152
- * `NonNullable<C["preview"]>` is `never`, and without the guard the `extends { … }` probe
153
- * below would vacuously match (everything extends `never`-derived shapes) and `HasKeys<never>`
154
- * would resolve `true`, wrongly adding the namespace. The guard short-circuits to `false`.
155
- */
156
- type HasBuckets<C extends Config> = [NonNullable<C["preview"]>] extends [never] ? false : NonNullable<C["preview"]> extends {
157
- buckets: infer B;
158
- } ? HasKeys<NonNullable<B>> : false;
159
- /**
160
- * Whether the policy's **static** `preview` block enables the AI Gateway
161
- * (`preview.aiGateway`). Drives whether {@link NeonEnv} carries the `aiGateway` namespace.
162
- *
163
- * The leading `[never]` guard is load-bearing for the same reason as {@link HasBuckets}: when
164
- * a policy has no `preview`, `NonNullable<C["preview"]>` is `never`, and a naked `never` in the
165
- * `extends` below would *distribute* (collapsing the result — and the whole `NeonEnv`
166
- * intersection — to `never`). The tuple-wrapped guard short-circuits that to `false`.
167
- */
168
- type AiGatewayOn<C extends Config> = [NonNullable<C["preview"]>] extends [never] ? false : NonNullable<C["preview"]> extends {
169
- aiGateway: infer A;
170
- } ? ServiceOn<NonNullable<A>> : false;
171
- /**
172
- * Static, namespaced shape of `fetchEnv` / `parseEnv`'s return value. Generic over the
173
- * {@link Config} so the type system knows which optional namespaces are present.
174
- *
175
- * Because the secret-bearing toggles now live in the **static** top-level `config.auth` /
176
- * `config.dataApi` (not inside a per-branch closure), the namespace presence is a direct
177
- * read of those fields — no union-across-branches, no default-config escape hatch:
178
- *
179
- * - `postgres` is always present.
180
- * - `auth` is added iff `config.auth` is statically enabled.
181
- * - `dataApi` is added iff `config.dataApi` is statically enabled.
182
- * - `storage` is added iff `config.preview.buckets` declares at least one bucket.
183
- * - `aiGateway` is added iff `config.preview.aiGateway` is statically enabled.
184
- */
185
- type NeonEnv<C extends Config = Config> = {
186
- postgres: NeonPostgresEnv;
187
- /**
188
- * Branch identity (`NEON_BRANCH`). Optional because `parseEnv` only surfaces it when the
189
- * var was injected; `fetchEnv` always populates it.
190
- */
191
- branch?: NeonBranchEnv;
192
- } & (ServiceOn<NonNullable<C["auth"]>> extends true ? {
193
- auth: NeonAuthEnv;
194
- } : NoNamespace) & (ServiceOn<NonNullable<C["dataApi"]>> extends true ? {
195
- dataApi: NeonDataApiEnv;
196
- } : NoNamespace) & (HasBuckets<C> extends true ? {
197
- storage: NeonStorageEnv;
198
- } : NoNamespace) & (AiGatewayOn<C> extends true ? {
199
- aiGateway: NeonAiGatewayEnv;
200
- } : NoNamespace);
201
- /**
202
- * OS-level env-var keys grouped by the {@link NeonEnv} namespace they populate. Only the
203
- * **input** vars `parseEnv` validates are listed — the output-only aliases in
204
- * {@link NEON_ENV_VAR_KEYS} (`NEON_AI_GATEWAY_TOKEN`, …) are intentionally absent, so they
205
- * are not selectable in a `parseEnv(config, keys)` filter. Keep in sync with
206
- * {@link EnvKeyToProp}.
207
- */
208
- interface EnvKeysByNamespace {
209
- postgres: "DATABASE_URL" | "DATABASE_URL_UNPOOLED";
210
- branch: "NEON_BRANCH";
211
- auth: "NEON_AUTH_BASE_URL" | "NEON_AUTH_JWKS_URL";
212
- dataApi: "NEON_DATA_API_URL";
213
- storage: "AWS_ACCESS_KEY_ID" | "AWS_SECRET_ACCESS_KEY" | "AWS_ENDPOINT_URL_S3" | "AWS_REGION";
214
- aiGateway: "NEON_AI_GATEWAY_TOKEN" | "NEON_AI_GATEWAY_BASE_URL";
215
- }
216
- /** The {@link NeonEnv} namespace interface backing each namespace key. */
217
- interface NamespaceEnv {
218
- postgres: NeonPostgresEnv;
219
- branch: NeonBranchEnv;
220
- auth: NeonAuthEnv;
221
- dataApi: NeonDataApiEnv;
222
- storage: NeonStorageEnv;
223
- aiGateway: NeonAiGatewayEnv;
224
- }
225
- /** OS-level env-var key → the camelCase property it sets on its namespace object. */
226
- interface EnvKeyToProp {
227
- DATABASE_URL: "databaseUrl";
228
- DATABASE_URL_UNPOOLED: "databaseUrlUnpooled";
229
- NEON_BRANCH: "name";
230
- NEON_AUTH_BASE_URL: "baseUrl";
231
- NEON_AUTH_JWKS_URL: "jwksUrl";
232
- NEON_DATA_API_URL: "url";
233
- AWS_ACCESS_KEY_ID: "accessKeyId";
234
- AWS_SECRET_ACCESS_KEY: "secretAccessKey";
235
- AWS_ENDPOINT_URL_S3: "endpoint";
236
- AWS_REGION: "region";
237
- NEON_AI_GATEWAY_TOKEN: "apiKey";
238
- NEON_AI_GATEWAY_BASE_URL: "baseUrl";
239
- }
240
- /**
241
- * The OS-level env-var keys selectable for a given policy: the union of input vars across
242
- * exactly the namespaces {@link NeonEnv}<C> carries. Drives the typesafe autocomplete of the
243
- * `keys` filter — selecting a var from a namespace the policy does not enable is a type error
244
- * (e.g. `NEON_AUTH_BASE_URL` is only offered once the policy turns on `auth`).
245
- */
246
- type SelectableEnvKey<C extends Config> = EnvKeysByNamespace[keyof NeonEnv<C> & keyof EnvKeysByNamespace];
247
- /**
248
- * The result shape of a **filtered** `parseEnv(config, keys)` call: the namespaced
249
- * {@link NeonEnv} restricted to exactly the selected OS-level keys `K`. Namespaces with no
250
- * selected key are dropped, and within a kept namespace only the selected properties survive
251
- * — selecting just `["DATABASE_URL"]` yields `{ postgres: { databaseUrl: string } }`, with no
252
- * `databaseUrlUnpooled`.
253
- *
254
- * The policy gating lives on the `parseEnv` overload (which binds `K` to
255
- * {@link SelectableEnvKey}); this type only needs the selection, so it takes a bare
256
- * `K extends string` and filters with `Extract`. The outer mapped type's `as` clause drops
257
- * any namespace whose intersection with the selection is empty (`[…] extends [never]`,
258
- * tuple-wrapped to switch off distribution); the inner one re-keys each selected OS var to its
259
- * camelCase property and looks the value type up on the canonical namespace interface, so it
260
- * stays correct if a field ever stops being a plain `string`.
261
- */
262
- type FilteredNeonEnv<K extends string> = { [N in keyof EnvKeysByNamespace as [Extract<K, EnvKeysByNamespace[N]>] extends [never] ? never : N]: { [P in Extract<K, EnvKeysByNamespace[N]> as EnvKeyToProp[P & keyof EnvKeyToProp]]: NamespaceEnv[N][EnvKeyToProp[P & keyof EnvKeyToProp] & keyof NamespaceEnv[N]] } };
263
- interface FetchEnvOptions {
264
- /**
265
- * Neon project id. **Required** — the management API addresses branches through their
266
- * project. Resolve it in your CLI (e.g. neonctl) and pass it in.
267
- */
268
- projectId: string;
269
- /**
270
- * Neon branch — its **name** (e.g. `main`) or its id (`br-…`). **Required** (or pass the
271
- * legacy {@link FetchEnvOptions.branchId}). Resolved against the project's branches by
272
- * id first, then by name, so either form works.
273
- */
274
- branch?: string;
275
- /**
276
- * @deprecated Legacy id-only field. Prefer {@link FetchEnvOptions.branch}, which accepts
277
- * a branch name or id. Still honored for backward compatibility; ignored when `branch`
278
- * is set.
279
- */
280
- branchId?: string;
281
- /**
282
- * Neon API key. Resolved via the standard chain (option → `NEON_API_KEY` →
283
- * `~/.config/neonctl/credentials.json`) when omitted. Ignored when a custom `api`
284
- * is supplied.
285
- */
286
- apiKey?: string;
287
- /**
288
- * Neon **management** API base URL (not the Auth base URL). Falls back to
289
- * `NEON_API_HOST`, then production. Ignored when a custom `api` is supplied.
290
- */
291
- apiHost?: string;
292
- /**
293
- * Inject a custom NeonApi adapter. Primarily used by tests; production callers can rely
294
- * on the default real adapter built from `apiKey`.
295
- */
296
- api?: NeonApi;
297
- /**
298
- * Role name to fetch credentials for. When omitted, the connection role is auto-picked:
299
- * the only role on the branch, else Neon's default owner (`neondb_owner`), else the
300
- * single role left after dropping the managed Auth/Data API roles
301
- * (`authenticator`/`anonymous`/`authenticated`). Throws {@link PlatformError} with
302
- * `PLATFORM_AMBIGUOUS_BRANCH_AUTH` only when more than one app role remains.
303
- */
304
- roleName?: string;
305
- /**
306
- * Database name. When omitted, it is auto-picked: Neon's default `neondb` if present,
307
- * else the only database on the branch. Throws {@link PlatformError} with
308
- * `PLATFORM_AMBIGUOUS_BRANCH_AUTH` when the branch has several databases and none is
309
- * `neondb` (pass `databaseName` to disambiguate), and `PLATFORM_BRANCH_NOT_FOUND` when
310
- * the branch has no databases or the requested `databaseName` does not exist.
311
- */
312
- databaseName?: string;
313
- }
314
- /**
315
- * Resolve the project + branch this process should target, then fetch live Neon
316
- * connection strings for that branch over the network. Async — calls the Neon API.
317
- *
318
- * Use this from build scripts and the `neon-env run` command, where top-level await is
319
- * fine. For application code that needs a synchronous bootstrap (most frameworks: Drizzle
320
- * config, Next.js, Vite, etc.), inject env vars via `neon-env run -- <cmd>` and use
321
- * {@link parseEnv} instead — same {@link NeonEnv} shape, but a sync call against
322
- * `process.env`.
323
- *
324
- * Filesystem- and env-agnostic: pass `projectId` and the target `branch` (name or id)
325
- * explicitly (resolve them in your CLI, e.g. neonctl).
326
- *
327
- * ```ts
328
- * import config from "../neon";
329
- * import { fetchEnv } from "@neon/env";
330
- *
331
- * const env = await fetchEnv(config, { projectId: "patient-art-12345", branch: "main" });
332
- * const db = drizzle(neon(env.postgres.databaseUrl), { schema });
333
- * ```
334
- *
335
- * Pass `keys` to fetch only some of them — see the overload below.
336
- *
337
- * The package does **not** read `process.env`, mutate it, or touch the filesystem. Everything
338
- * it returns comes from the Neon API, so a value the API cannot produce (a one-time secret
339
- * issued to a previous call) is minted afresh rather than recovered. Callers that hold
340
- * persisted secrets and want to keep them use {@link fetchEnvReusingSecrets}, which decides
341
- * what is still valid and narrows this call's `keys` accordingly.
342
- */
343
- declare function fetchEnv<const C extends Config, const K extends SelectableEnvKey<C>>(config: C, options: FetchEnvOptions & {
344
- /**
345
- * Fetch only these OS-level env vars, instead of everything the policy enables. The
346
- * keys autocomplete from the policy ({@link SelectableEnvKey}), and the result is
347
- * narrowed to match ({@link FilteredNeonEnv}).
348
- *
349
- * The point is not just a smaller result: **work is skipped too.** Leave out
350
- * `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `NEON_AI_GATEWAY_TOKEN` and no branch
351
- * credential is minted at all, so a caller that already holds valid secrets can refresh
352
- * everything else without issuing a new one. The non-secret vars of the same features
353
- * (`AWS_ENDPOINT_URL_S3`, `AWS_REGION`, `NEON_AI_GATEWAY_BASE_URL`) are not
354
- * credential-backed and stay available on their own.
355
- *
356
- * The selection **intersects** with the policy rather than overriding it: naming a var
357
- * the branch policy does not enable is not an error, it simply yields nothing.
358
- */
359
- keys: readonly K[];
360
- }): Promise<FilteredNeonEnv<K>>;
361
- declare function fetchEnv<const C extends Config>(config: C, options: FetchEnvOptions): Promise<NeonEnv<C>>;
362
- /**
363
- * The {@link fetchEnv} body, with the key selection as a plain argument and no generic
364
- * narrowing. Exists for callers that compute the selection at runtime — notably
365
- * {@link fetchEnvReusingSecrets}, which decides which keys it still needs by checking the
366
- * branch — since the public overload's `keys` is bound to a literal union those callers cannot
367
- * produce without asserting.
368
- *
369
- * `keys === null` selects everything the policy enables.
370
- */
371
- declare function fetchEnvKeys(config: Config, options: FetchEnvOptions, keys: readonly string[] | null): Promise<ResolvedNeonEnv>;
372
- /**
373
- * Resolve the target branch and evaluate the policy against it — the first thing any
374
- * branch-scoped operation needs. Shared by {@link fetchEnv} and {@link fetchEnvReusingSecrets}
375
- * so the two agree on which branch they're talking about and what it has enabled.
376
- */
377
- declare function resolveBranchPolicy(config: Config, options: Pick<FetchEnvOptions, "projectId" | "branch" | "branchId">, api: NeonApi): Promise<{
378
- branch: NeonBranchSnapshot;
379
- desired: ReturnType<typeof resolveConfig>;
380
- }>;
381
- /**
382
- * Scopes the branch credential should carry for a resolved branch policy. Only object storage
383
- * and the AI Gateway *require* a credential; functions never force one (they have no credential
384
- * of their own), but `functions:invoke` is added to the scope set when a credential is already
385
- * being minted for storage / the AI Gateway, so the one credential can invoke the branch's
386
- * functions too. Returns `[]` only when nothing credential-bearing is enabled.
387
- */
388
- declare function previewCredentialScopes(preview: ResolvedPreviewConfig | undefined): CredentialScope[];
389
- /** The `name` this tool stamps on every credential it mints, so it can recognize its own. */
390
- declare function credentialName(branchName: string): string;
391
- /** The env-var keys a branch credential's secrets surface under, in emit order. */
392
- declare function credentialEnvKeys(flags: {
393
- storage: boolean;
394
- aiGateway: boolean;
395
- }): string[];
396
- /**
397
- * Every OS-level env var a resolved branch policy produces, in emit order. Lets a caller
398
- * subtract the ones it already holds and pass the rest as {@link fetchEnv}'s `keys`, without
399
- * re-deriving which vars a policy implies.
400
- */
401
- declare function policyEnvKeys(desired: ReturnType<typeof resolveConfig>): string[];
402
- declare function createApiFromOptions(options: FetchEnvOptions): NeonApi;
403
- /**
404
- * Project a fully-resolved {@link NeonEnv} into the OS-level `{ KEY: value }` pairs used
405
- * for cross-process transport. Named after the web-platform `.entries()` convention
406
- * (`URLSearchParams` / `Headers` / `FormData`); returns a `Record` rather than an
407
- * iterator of tuples since that's the shape env injection needs (wrap with
408
- * `Object.entries(...)` if you want literal `[key, value]` pairs). Used by `neon-env run`
409
- * to inject the vars into a subprocess's `process.env`.
410
- *
411
- * Walks the value at runtime so it works for any `NeonEnv<C>` regardless of which
412
- * conditional namespaces are present.
413
- */
414
- declare function toEntries(env: ResolvedNeonEnv): Record<string, string>;
415
- /**
416
- * Any resolved env {@link toEntries} can project: a full {@link NeonEnv}, or the narrowed
417
- * result of a `keys`-filtered {@link fetchEnv} / {@link parseEnv} call. Every namespace and
418
- * property is optional so a filtered result — which legitimately carries only what was asked
419
- * for — projects to exactly the vars it holds instead of failing to type-check.
420
- */
421
- type ResolvedNeonEnv = { [N in keyof NamespaceEnv]?: Partial<NamespaceEnv[N]> };
422
- //#endregion
423
- export { FetchEnvOptions, FilteredNeonEnv, NEON_ENV_VAR_KEYS, NeonAiGatewayEnv, NeonAuthEnv, NeonBranchEnv, NeonDataApiEnv, NeonEnv, NeonPostgresEnv, NeonStorageEnv, ResolvedNeonEnv, SelectableEnvKey, createApiFromOptions, credentialEnvKeys, credentialName, fetchEnv, fetchEnvKeys, policyEnvKeys, previewCredentialScopes, resolveBranchPolicy, toEntries };
424
- //# sourceMappingURL=env.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"env.d.ts","names":[],"sources":["../../../src/_shared/env-core/env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;;;;;;QAiCV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgDe,yBACL,wBACA,iBAAiB,YAEzB,YACC;;;;;;;;;;;;;;;;iBAgBO;IAEd,QAAQ,gBAAgB;iBACL,yBAAyB,gBACtC,YACC,kBACP,QAAQ,QAAQ;;;;;;;;;;iBAiBG,YAAA,SACb,iBACC,kDAEP,QAAQ;;;;;;iBAuMW,mBAAA,SACb,iBACC,KAAK,4DACT,UACH;UACM;WACC,kBAAkB;;;;;;;;;iBA8CZ,uBAAA,UACN,oCACP;;iBAaa,cAAA;;iBAKA,iBAAA;;;;;;;;;iBAoBA,aAAA,UACN,kBAAkB;iBA0FZ,oBAAA,UAA8B,kBAAkB;;;;;;;;;;;;iBA2KhD,SAAA,MAAe,kBAAkB;;;;;;;KA8BrC,eAAA,iBACC,gBAAgB,QAAQ,aAAa"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"env.js","names":[],"sources":["../../../src/_shared/env-core/env.ts"],"sourcesContent":["/**\n * The Neon env core — resolving a branch's env from the Neon API, and projecting it into\n * OS-level `{ KEY: value }` pairs.\n *\n * Shared source, not a package: `scripts/sync-shared.mjs` copies it into `@neon/env` (which\n * publishes it as `fetchEnv` / `toEntries`) and into the `neon` CLI (which needs the\n * credential-reuse half in `reuse-secrets.ts`). See `shared/env-core/README.md` for why it is\n * a copy rather than an import.\n *\n * The counterpart that reads `process.env` — `parseEnv` and its zod schemas — is not here. It\n * has no consumer outside `@neon/env`, so it stays in that package and imports this.\n */\n\nimport {\n\ttype Config,\n\ttype CredentialScope,\n\tcreateNeonApiFromOptions,\n\tderiveCredentialScopes,\n\tErrorCode,\n\ttype NeonApi,\n\ttype NeonBranchSnapshot,\n\ttype NeonBranchStorageSnapshot,\n\ttype NeonDatabaseSnapshot,\n\ttype NeonRoleSnapshot,\n\tPlatformError,\n\ttype ResolvedPreviewConfig,\n\tresolveConfig,\n} from \"@neon/config/v1\";\n\n/**\n * Mapping between the {@link NeonEnv} property paths and the OS-level env-var keys used\n * for cross-process transport (via `.env` files, `env run -- <cmd>`, or anything else\n * that talks to `process.env`).\n *\n * Each top-level key here is a {@link NeonEnv} namespace; the inner record maps the\n * camelCase property names exposed to TypeScript to the UPPER_SNAKE env-var names used\n * by the OS. Keep this in sync with {@link postgresEnvSchema} / {@link authEnvSchema} /\n * {@link dataApiEnvSchema}.\n */\n/**\n * Neon's default branch owner role, created with every project. This is the role a\n * `DATABASE_URL` should connect as.\n */\nconst NEON_DEFAULT_OWNER_ROLE = \"neondb_owner\";\n\n/**\n * Neon's default database, created with every project. When a branch has several databases\n * and none was requested, this is preferred for the `DATABASE_URL` so the common case (a\n * user added a second database next to `neondb`) auto-picks without asking.\n */\nconst NEON_DEFAULT_DATABASE = \"neondb\";\n\n/**\n * Roles Neon provisions for the Auth / Data API (PostgREST) stack. They exist to back\n * RLS-scoped Data API requests authenticated by JWT — never to hold a `DATABASE_URL` —\n * so they're skipped when auto-picking the connection role. Enabling Neon Auth or the\n * Data API (`neon config apply`) adds these next to the owner role, which is why a plain\n * branch routinely reports more than one role.\n */\nconst NEON_MANAGED_AUTH_ROLES: ReadonlySet<string> = new Set([\n\t\"authenticator\",\n\t\"anonymous\",\n\t\"authenticated\",\n]);\n\nexport const NEON_ENV_VAR_KEYS = {\n\t/**\n\t * Branch identity. `NEON_BRANCH` carries the branch **name** and is injected into the\n\t * Neon Functions runtime on every branch (including the default) by default. `env pull` /\n\t * `neon dev` / `neon-env run` emit it too so local dev mirrors the deployed runtime.\n\t */\n\tbranch: {\n\t\tname: \"NEON_BRANCH\",\n\t},\n\tpostgres: {\n\t\tdatabaseUrl: \"DATABASE_URL\",\n\t\tdatabaseUrlUnpooled: \"DATABASE_URL_UNPOOLED\",\n\t},\n\tauth: {\n\t\tbaseUrl: \"NEON_AUTH_BASE_URL\",\n\t\tjwksUrl: \"NEON_AUTH_JWKS_URL\",\n\t},\n\tdataApi: {\n\t\turl: \"NEON_DATA_API_URL\",\n\t},\n\t/**\n\t * Object storage (Preview). The S3 SDKs read `AWS_*` from their standard config chain, so\n\t * a branch credential + `neon dev` / `env pull` makes object storage work from env alone.\n\t * `region` is injected under the SDK-standard `AWS_REGION`.\n\t */\n\tstorage: {\n\t\taccessKeyId: \"AWS_ACCESS_KEY_ID\",\n\t\tsecretAccessKey: \"AWS_SECRET_ACCESS_KEY\",\n\t\tendpoint: \"AWS_ENDPOINT_URL_S3\",\n\t\tregion: \"AWS_REGION\",\n\t},\n\t/**\n\t * AI Gateway (Preview). Exposed under the Neon-branded env vars the deployed Functions\n\t * runtime injects: `apiKey` is the minted credential's bearer (`NEON_AI_GATEWAY_TOKEN`)\n\t * and `baseUrl` is the bare branch gateway host (`NEON_AI_GATEWAY_BASE_URL`,\n\t * `scheme://host`, no path). Clients like `@neon/ai-sdk-provider` read these and append the\n\t * dialect route (`/v1`, `/openai/v1`, `/anthropic/v1`) themselves (https://github.com/vercel/ai/pull/15997).\n\t */\n\taiGateway: {\n\t\tapiKey: \"NEON_AI_GATEWAY_TOKEN\",\n\t\tbaseUrl: \"NEON_AI_GATEWAY_BASE_URL\",\n\t},\n} as const;\n\n/**\n * Branch identity for the resolved branch. Always present on a `fetchEnv` result (the branch\n * name is always known); on a `parseEnv` result it's present only when `NEON_BRANCH` was\n * injected into `process.env` (the Functions runtime injects it by default, as do `neon dev` /\n * `neon-env run` / `env pull`). `name` is the branch **name** (e.g. `main`, `preview/foo`).\n */\nexport interface NeonBranchEnv {\n\tname: string;\n}\n\n/** Per-namespace inner shapes. Exposed so consumers can name the parts independently. */\nexport interface NeonPostgresEnv {\n\t/**\n\t * Pooled connection string (via Neon's PgBouncer pooler). The right default for\n\t * serverless drivers (`@neondatabase/serverless`, edge runtimes, Postgres.js, …).\n\t */\n\tdatabaseUrl: string;\n\t/**\n\t * Direct (unpooled) connection string. Use this when you need session-level\n\t * features (`LISTEN`/`NOTIFY`, prepared statements across calls, transactions\n\t * spanning round-trips) that PgBouncer's transaction-mode pooling drops.\n\t */\n\tdatabaseUrlUnpooled: string;\n}\n\n/**\n * Bits of a Neon Auth integration for the resolved branch. Only present on `NeonEnv`\n * when the branch policy enables `auth`.\n *\n * Neon Auth exposes the `baseUrl` (which doubles as the publishable client identifier) and\n * the `jwksUrl` used to verify tokens it issues. `fetchEnv` reads both from the live\n * integration; `parseEnv` reads them from `process.env` (`NEON_AUTH_BASE_URL` /\n * `NEON_AUTH_JWKS_URL`).\n */\nexport interface NeonAuthEnv {\n\tbaseUrl: string;\n\t/** JWKS URL for verifying tokens issued by Neon Auth (`NEON_AUTH_JWKS_URL`). */\n\tjwksUrl: string;\n}\n\n/** Bits of a Neon Data API integration. Only present when the branch policy enables it. */\nexport interface NeonDataApiEnv {\n\turl: string;\n}\n\n/**\n * S3-compatible object-storage access for the branch (Preview). Present on `NeonEnv` only\n * when the policy declares `preview.buckets`. Combines a minted branch credential's access\n * keys (`accessKeyId` = the credential's full token id, e.g. `nak_live_…`, which is what the\n * storage gateway authenticates against; `secretAccessKey` = its\n * `s3_secret_access_key`) with the branch's non-secret connection details\n * (`endpoint`/`region`, from `GET .../storage`). Projects to the AWS SDK's\n * standard config env (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_ENDPOINT_URL_S3`,\n * `AWS_REGION`) so the S3 client works from env alone. Neon's storage gateway always\n * requires path-style addressing, so set `forcePathStyle: true` on your S3 client.\n */\nexport interface NeonStorageEnv {\n\taccessKeyId: string;\n\tsecretAccessKey: string;\n\t/** S3-compatible endpoint URL for the branch. */\n\tendpoint: string;\n\t/** AWS region string (e.g. `us-east-2`). Injected as `AWS_REGION`. */\n\tregion: string;\n}\n\n/**\n * AI Gateway access for the branch (Preview). Present on `NeonEnv` only when the policy\n * enables `preview.aiGateway`. `apiKey` is the minted credential's bearer (`api_token`);\n * `baseUrl` is the bare branch-scoped gateway host\n * (`https://<branchId>-api.ai.<region>.…`, no path). Projects to the Neon-branded env\n * (`NEON_AI_GATEWAY_TOKEN`, `NEON_AI_GATEWAY_BASE_URL`); clients like `@neon/ai-sdk-provider`\n * append the dialect route (`/v1`, `/openai/v1`, `/anthropic/v1`) themselves.\n */\nexport interface NeonAiGatewayEnv {\n\tapiKey: string;\n\tbaseUrl: string;\n}\n\n/**\n * Empty record alias used as the \"false\" branch of the conditional namespace adds below.\n * `Record<never, never>` is the no-op for intersection — the cleaner alternative to `{}`,\n * which biome rejects (it means \"any non-null\", not \"empty object\").\n */\ntype NoNamespace = Record<never, never>;\n\n/**\n * Resolve a **static** service toggle (the value of `config.auth` / `config.dataApi`) to a\n * type-level boolean. The whole-thing wrapping (`[T] extends […]`) turns off distribution\n * so a union/`undefined` is checked as one unit:\n *\n * - `false` / `{ enabled: false }` / `undefined` → `false`\n * - `true` / `{ enabled: true }` / any other object (`{}`, `{ enabled?: boolean }`) → `true`\n * (a present toggle defaults to enabled)\n * - the bare `boolean | ServiceToggle | undefined` (the default `Config` param, no literal\n * info) → `false`, so an untyped policy yields just `{ postgres }`.\n */\ntype ServiceOn<T> = [T] extends [false]\n\t? false\n\t: [T] extends [{ enabled: false }]\n\t\t? false\n\t\t: [T] extends [undefined]\n\t\t\t? false\n\t\t\t: [T] extends [true]\n\t\t\t\t? true\n\t\t\t\t: [T] extends [{ enabled: true }]\n\t\t\t\t\t? true\n\t\t\t\t\t: [T] extends [object]\n\t\t\t\t\t\t? true\n\t\t\t\t\t\t: false;\n\n/** True when `T` has at least one known key; `false` for `{}` / `never`. */\ntype HasKeys<T> = [keyof T] extends [never] ? false : true;\n\n/**\n * Whether the policy's **static** `preview` block declares at least one object-storage bucket\n * (`preview.buckets`). Drives whether {@link NeonEnv} carries the `storage` namespace.\n *\n * The leading `[never]` guard is load-bearing: when a policy has no `preview` at all,\n * `NonNullable<C[\"preview\"]>` is `never`, and without the guard the `extends { … }` probe\n * below would vacuously match (everything extends `never`-derived shapes) and `HasKeys<never>`\n * would resolve `true`, wrongly adding the namespace. The guard short-circuits to `false`.\n */\ntype HasBuckets<C extends Config> = [NonNullable<C[\"preview\"]>] extends [never]\n\t? false\n\t: NonNullable<C[\"preview\"]> extends { buckets: infer B }\n\t\t? HasKeys<NonNullable<B>>\n\t\t: false;\n\n/**\n * Whether the policy's **static** `preview` block enables the AI Gateway\n * (`preview.aiGateway`). Drives whether {@link NeonEnv} carries the `aiGateway` namespace.\n *\n * The leading `[never]` guard is load-bearing for the same reason as {@link HasBuckets}: when\n * a policy has no `preview`, `NonNullable<C[\"preview\"]>` is `never`, and a naked `never` in the\n * `extends` below would *distribute* (collapsing the result — and the whole `NeonEnv`\n * intersection — to `never`). The tuple-wrapped guard short-circuits that to `false`.\n */\ntype AiGatewayOn<C extends Config> = [NonNullable<C[\"preview\"]>] extends [never]\n\t? false\n\t: NonNullable<C[\"preview\"]> extends { aiGateway: infer A }\n\t\t? ServiceOn<NonNullable<A>>\n\t\t: false;\n\n/**\n * Static, namespaced shape of `fetchEnv` / `parseEnv`'s return value. Generic over the\n * {@link Config} so the type system knows which optional namespaces are present.\n *\n * Because the secret-bearing toggles now live in the **static** top-level `config.auth` /\n * `config.dataApi` (not inside a per-branch closure), the namespace presence is a direct\n * read of those fields — no union-across-branches, no default-config escape hatch:\n *\n * - `postgres` is always present.\n * - `auth` is added iff `config.auth` is statically enabled.\n * - `dataApi` is added iff `config.dataApi` is statically enabled.\n * - `storage` is added iff `config.preview.buckets` declares at least one bucket.\n * - `aiGateway` is added iff `config.preview.aiGateway` is statically enabled.\n */\nexport type NeonEnv<C extends Config = Config> = {\n\tpostgres: NeonPostgresEnv;\n\t/**\n\t * Branch identity (`NEON_BRANCH`). Optional because `parseEnv` only surfaces it when the\n\t * var was injected; `fetchEnv` always populates it.\n\t */\n\tbranch?: NeonBranchEnv;\n} & (ServiceOn<NonNullable<C[\"auth\"]>> extends true\n\t? { auth: NeonAuthEnv }\n\t: NoNamespace) &\n\t(ServiceOn<NonNullable<C[\"dataApi\"]>> extends true\n\t\t? { dataApi: NeonDataApiEnv }\n\t\t: NoNamespace) &\n\t(HasBuckets<C> extends true ? { storage: NeonStorageEnv } : NoNamespace) &\n\t(AiGatewayOn<C> extends true\n\t\t? { aiGateway: NeonAiGatewayEnv }\n\t\t: NoNamespace);\n\n// ───────────────────────── env-var key filtering ─────────────────────────\n\n/**\n * OS-level env-var keys grouped by the {@link NeonEnv} namespace they populate. Only the\n * **input** vars `parseEnv` validates are listed — the output-only aliases in\n * {@link NEON_ENV_VAR_KEYS} (`NEON_AI_GATEWAY_TOKEN`, …) are intentionally absent, so they\n * are not selectable in a `parseEnv(config, keys)` filter. Keep in sync with\n * {@link EnvKeyToProp}.\n */\ninterface EnvKeysByNamespace {\n\tpostgres: \"DATABASE_URL\" | \"DATABASE_URL_UNPOOLED\";\n\tbranch: \"NEON_BRANCH\";\n\tauth: \"NEON_AUTH_BASE_URL\" | \"NEON_AUTH_JWKS_URL\";\n\tdataApi: \"NEON_DATA_API_URL\";\n\tstorage:\n\t\t| \"AWS_ACCESS_KEY_ID\"\n\t\t| \"AWS_SECRET_ACCESS_KEY\"\n\t\t| \"AWS_ENDPOINT_URL_S3\"\n\t\t| \"AWS_REGION\";\n\taiGateway: \"NEON_AI_GATEWAY_TOKEN\" | \"NEON_AI_GATEWAY_BASE_URL\";\n}\n\n/** The {@link NeonEnv} namespace interface backing each namespace key. */\ninterface NamespaceEnv {\n\tpostgres: NeonPostgresEnv;\n\tbranch: NeonBranchEnv;\n\tauth: NeonAuthEnv;\n\tdataApi: NeonDataApiEnv;\n\tstorage: NeonStorageEnv;\n\taiGateway: NeonAiGatewayEnv;\n}\n\n/** OS-level env-var key → the camelCase property it sets on its namespace object. */\ninterface EnvKeyToProp {\n\tDATABASE_URL: \"databaseUrl\";\n\tDATABASE_URL_UNPOOLED: \"databaseUrlUnpooled\";\n\tNEON_BRANCH: \"name\";\n\tNEON_AUTH_BASE_URL: \"baseUrl\";\n\tNEON_AUTH_JWKS_URL: \"jwksUrl\";\n\tNEON_DATA_API_URL: \"url\";\n\tAWS_ACCESS_KEY_ID: \"accessKeyId\";\n\tAWS_SECRET_ACCESS_KEY: \"secretAccessKey\";\n\tAWS_ENDPOINT_URL_S3: \"endpoint\";\n\tAWS_REGION: \"region\";\n\tNEON_AI_GATEWAY_TOKEN: \"apiKey\";\n\tNEON_AI_GATEWAY_BASE_URL: \"baseUrl\";\n}\n\n/**\n * The OS-level env-var keys selectable for a given policy: the union of input vars across\n * exactly the namespaces {@link NeonEnv}<C> carries. Drives the typesafe autocomplete of the\n * `keys` filter — selecting a var from a namespace the policy does not enable is a type error\n * (e.g. `NEON_AUTH_BASE_URL` is only offered once the policy turns on `auth`).\n */\nexport type SelectableEnvKey<C extends Config> =\n\tEnvKeysByNamespace[keyof NeonEnv<C> & keyof EnvKeysByNamespace];\n\n/**\n * The result shape of a **filtered** `parseEnv(config, keys)` call: the namespaced\n * {@link NeonEnv} restricted to exactly the selected OS-level keys `K`. Namespaces with no\n * selected key are dropped, and within a kept namespace only the selected properties survive\n * — selecting just `[\"DATABASE_URL\"]` yields `{ postgres: { databaseUrl: string } }`, with no\n * `databaseUrlUnpooled`.\n *\n * The policy gating lives on the `parseEnv` overload (which binds `K` to\n * {@link SelectableEnvKey}); this type only needs the selection, so it takes a bare\n * `K extends string` and filters with `Extract`. The outer mapped type's `as` clause drops\n * any namespace whose intersection with the selection is empty (`[…] extends [never]`,\n * tuple-wrapped to switch off distribution); the inner one re-keys each selected OS var to its\n * camelCase property and looks the value type up on the canonical namespace interface, so it\n * stays correct if a field ever stops being a plain `string`.\n */\nexport type FilteredNeonEnv<K extends string> = {\n\t[N in keyof EnvKeysByNamespace as [\n\t\tExtract<K, EnvKeysByNamespace[N]>,\n\t] extends [never]\n\t\t? never\n\t\t: N]: {\n\t\t[P in Extract<K, EnvKeysByNamespace[N]> as EnvKeyToProp[P &\n\t\t\tkeyof EnvKeyToProp]]: NamespaceEnv[N][EnvKeyToProp[P &\n\t\t\tkeyof EnvKeyToProp] &\n\t\t\tkeyof NamespaceEnv[N]];\n\t};\n};\n\nexport interface FetchEnvOptions {\n\t/**\n\t * Neon project id. **Required** — the management API addresses branches through their\n\t * project. Resolve it in your CLI (e.g. neonctl) and pass it in.\n\t */\n\tprojectId: string;\n\t/**\n\t * Neon branch — its **name** (e.g. `main`) or its id (`br-…`). **Required** (or pass the\n\t * legacy {@link FetchEnvOptions.branchId}). Resolved against the project's branches by\n\t * id first, then by name, so either form works.\n\t */\n\tbranch?: string;\n\t/**\n\t * @deprecated Legacy id-only field. Prefer {@link FetchEnvOptions.branch}, which accepts\n\t * a branch name or id. Still honored for backward compatibility; ignored when `branch`\n\t * is set.\n\t */\n\tbranchId?: string;\n\t/**\n\t * Neon API key. Resolved via the standard chain (option → `NEON_API_KEY` →\n\t * `~/.config/neonctl/credentials.json`) when omitted. Ignored when a custom `api`\n\t * is supplied.\n\t */\n\tapiKey?: string;\n\t/**\n\t * Neon **management** API base URL (not the Auth base URL). Falls back to\n\t * `NEON_API_HOST`, then production. Ignored when a custom `api` is supplied.\n\t */\n\tapiHost?: string;\n\t/**\n\t * Inject a custom NeonApi adapter. Primarily used by tests; production callers can rely\n\t * on the default real adapter built from `apiKey`.\n\t */\n\tapi?: NeonApi;\n\t/**\n\t * Role name to fetch credentials for. When omitted, the connection role is auto-picked:\n\t * the only role on the branch, else Neon's default owner (`neondb_owner`), else the\n\t * single role left after dropping the managed Auth/Data API roles\n\t * (`authenticator`/`anonymous`/`authenticated`). Throws {@link PlatformError} with\n\t * `PLATFORM_AMBIGUOUS_BRANCH_AUTH` only when more than one app role remains.\n\t */\n\troleName?: string;\n\t/**\n\t * Database name. When omitted, it is auto-picked: Neon's default `neondb` if present,\n\t * else the only database on the branch. Throws {@link PlatformError} with\n\t * `PLATFORM_AMBIGUOUS_BRANCH_AUTH` when the branch has several databases and none is\n\t * `neondb` (pass `databaseName` to disambiguate), and `PLATFORM_BRANCH_NOT_FOUND` when\n\t * the branch has no databases or the requested `databaseName` does not exist.\n\t */\n\tdatabaseName?: string;\n}\n\n/**\n * Resolve the project + branch this process should target, then fetch live Neon\n * connection strings for that branch over the network. Async — calls the Neon API.\n *\n * Use this from build scripts and the `neon-env run` command, where top-level await is\n * fine. For application code that needs a synchronous bootstrap (most frameworks: Drizzle\n * config, Next.js, Vite, etc.), inject env vars via `neon-env run -- <cmd>` and use\n * {@link parseEnv} instead — same {@link NeonEnv} shape, but a sync call against\n * `process.env`.\n *\n * Filesystem- and env-agnostic: pass `projectId` and the target `branch` (name or id)\n * explicitly (resolve them in your CLI, e.g. neonctl).\n *\n * ```ts\n * import config from \"../neon\";\n * import { fetchEnv } from \"@neon/env\";\n *\n * const env = await fetchEnv(config, { projectId: \"patient-art-12345\", branch: \"main\" });\n * const db = drizzle(neon(env.postgres.databaseUrl), { schema });\n * ```\n *\n * Pass `keys` to fetch only some of them — see the overload below.\n *\n * The package does **not** read `process.env`, mutate it, or touch the filesystem. Everything\n * it returns comes from the Neon API, so a value the API cannot produce (a one-time secret\n * issued to a previous call) is minted afresh rather than recovered. Callers that hold\n * persisted secrets and want to keep them use {@link fetchEnvReusingSecrets}, which decides\n * what is still valid and narrows this call's `keys` accordingly.\n */\nexport async function fetchEnv<\n\tconst C extends Config,\n\tconst K extends SelectableEnvKey<C>,\n>(\n\tconfig: C,\n\toptions: FetchEnvOptions & {\n\t\t/**\n\t\t * Fetch only these OS-level env vars, instead of everything the policy enables. The\n\t\t * keys autocomplete from the policy ({@link SelectableEnvKey}), and the result is\n\t\t * narrowed to match ({@link FilteredNeonEnv}).\n\t\t *\n\t\t * The point is not just a smaller result: **work is skipped too.** Leave out\n\t\t * `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `NEON_AI_GATEWAY_TOKEN` and no branch\n\t\t * credential is minted at all, so a caller that already holds valid secrets can refresh\n\t\t * everything else without issuing a new one. The non-secret vars of the same features\n\t\t * (`AWS_ENDPOINT_URL_S3`, `AWS_REGION`, `NEON_AI_GATEWAY_BASE_URL`) are not\n\t\t * credential-backed and stay available on their own.\n\t\t *\n\t\t * The selection **intersects** with the policy rather than overriding it: naming a var\n\t\t * the branch policy does not enable is not an error, it simply yields nothing.\n\t\t */\n\t\tkeys: readonly K[];\n\t},\n): Promise<FilteredNeonEnv<K>>;\nexport async function fetchEnv<const C extends Config>(\n\tconfig: C,\n\toptions: FetchEnvOptions,\n): Promise<NeonEnv<C>>;\nexport async function fetchEnv(\n\tconfig: Config,\n\toptions: FetchEnvOptions & { keys?: readonly string[] },\n): Promise<unknown> {\n\treturn fetchEnvKeys(config, options, options.keys ?? null);\n}\n\n/**\n * The {@link fetchEnv} body, with the key selection as a plain argument and no generic\n * narrowing. Exists for callers that compute the selection at runtime — notably\n * {@link fetchEnvReusingSecrets}, which decides which keys it still needs by checking the\n * branch — since the public overload's `keys` is bound to a literal union those callers cannot\n * produce without asserting.\n *\n * `keys === null` selects everything the policy enables.\n */\nexport async function fetchEnvKeys(\n\tconfig: Config,\n\toptions: FetchEnvOptions,\n\tkeys: readonly string[] | null,\n): Promise<ResolvedNeonEnv> {\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst projectId = options.projectId;\n\tconst { branch, desired } = await resolveBranchPolicy(config, options, api);\n\n\tconst selection = keys ? new Set<string>(keys) : null;\n\tconst wants = (key: string): boolean =>\n\t\tselection === null || selection.has(key);\n\n\tconst result: ResolvedNeonEnv = {};\n\tconst [roles, databases] = await Promise.all([\n\t\tapi.listBranchRoles(projectId, branch.id),\n\t\tapi.listBranchDatabases(projectId, branch.id),\n\t]);\n\n\tconst roleName = pickRoleName(roles, branch, options.roleName);\n\tconst databaseName = pickDatabaseName(\n\t\tdatabases,\n\t\tbranch,\n\t\toptions.databaseName,\n\t);\n\n\t// Fan out: always fetch both Postgres URIs — the direct one also derives the AI Gateway\n\t// host, so a selection that drops `DATABASE_URL_UNPOOLED` still needs it. Conditionally\n\t// fetch auth + dataApi based on the branch policy and the selection. Auth key fields are\n\t// only returned at integration creation time; for Better Auth they may legitimately be\n\t// empty, so they can come back as empty strings.\n\tconst K = NEON_ENV_VAR_KEYS;\n\tconst wantsAuth =\n\t\tdesired.authEnabled && (wants(K.auth.baseUrl) || wants(K.auth.jwksUrl));\n\tconst wantsDataApi = desired.dataApiEnabled && wants(K.dataApi.url);\n\n\tconst [pooled, unpooled, authSnapshot, dataApiSnapshot] = await Promise.all(\n\t\t[\n\t\t\tapi.getConnectionUri(projectId, {\n\t\t\t\tbranchId: branch.id,\n\t\t\t\tdatabaseName,\n\t\t\t\troleName,\n\t\t\t\tpooled: true,\n\t\t\t}),\n\t\t\tapi.getConnectionUri(projectId, {\n\t\t\t\tbranchId: branch.id,\n\t\t\t\tdatabaseName,\n\t\t\t\troleName,\n\t\t\t\tpooled: false,\n\t\t\t}),\n\t\t\twantsAuth\n\t\t\t\t? api.getNeonAuth(projectId, branch.id)\n\t\t\t\t: Promise.resolve(null),\n\t\t\twantsDataApi\n\t\t\t\t? api.getNeonDataApi(projectId, branch.id, databaseName)\n\t\t\t\t: Promise.resolve(null),\n\t\t],\n\t);\n\n\tconst postgres: Partial<NeonPostgresEnv> = {};\n\tif (wants(K.postgres.databaseUrl)) postgres.databaseUrl = pooled.uri;\n\tif (wants(K.postgres.databaseUrlUnpooled)) {\n\t\tpostgres.databaseUrlUnpooled = unpooled.uri;\n\t}\n\tif (Object.keys(postgres).length > 0) result.postgres = postgres;\n\n\t// Branch identity, mirroring what the Functions runtime injects on every branch. Surfaced\n\t// as `NEON_BRANCH` so local dev (`neon dev` / `neon-env run` / `env pull`) matches the\n\t// deployed runtime. Uses the branch name.\n\tif (wants(K.branch.name)) {\n\t\tresult.branch = { name: branch.name } satisfies NeonBranchEnv;\n\t}\n\n\tif (wantsAuth) {\n\t\tif (!authSnapshot) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.NotFound,\n\t\t\t\t[\n\t\t\t\t\t`fetchEnv: branch policy enables auth but no Neon Auth integration is enabled on branch ${branch.name} (${branch.id}).`,\n\t\t\t\t\t\"Enable it via `apply(config, { projectId, branchId })` (or `npx neon …`), in the Neon Console — then re-run fetchEnv. Or return auth.enabled=false.\",\n\t\t\t\t].join(\" \"),\n\t\t\t\t{\n\t\t\t\t\tdetails: { projectId, branchId: branch.id },\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tconst auth: Partial<NeonAuthEnv> = {};\n\t\tif (wants(K.auth.baseUrl)) auth.baseUrl = authSnapshot.baseUrl ?? \"\";\n\t\tif (wants(K.auth.jwksUrl)) auth.jwksUrl = authSnapshot.jwksUrl ?? \"\";\n\t\tresult.auth = auth;\n\t}\n\n\tif (wantsDataApi) {\n\t\tif (!dataApiSnapshot) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.NotFound,\n\t\t\t\t[\n\t\t\t\t\t`fetchEnv: branch policy enables dataApi but no Data API integration is enabled on branch ${branch.name} (${branch.id}) database ${databaseName}.`,\n\t\t\t\t\t\"Enable it via `apply(config, { projectId, branchId })` or in the Neon Console — then re-run fetchEnv. Or return dataApi.enabled=false.\",\n\t\t\t\t].join(\" \"),\n\t\t\t\t{\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tprojectId,\n\t\t\t\t\t\tbranchId: branch.id,\n\t\t\t\t\t\tdatabaseName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tresult.dataApi = { url: dataApiSnapshot.url } satisfies NeonDataApiEnv;\n\t}\n\n\t// Object storage + AI Gateway (Preview). A single branch credential backs whichever of\n\t// these the policy enables; functions never force one but ride along on its scopes. None\n\t// of this runs when the policy enables neither, so the Postgres / Auth / Data API path\n\t// never touches the credentials/storage endpoints (and keeps working on production, where\n\t// they may not exist yet).\n\tconst storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;\n\tconst gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;\n\tconst wantsStorage =\n\t\tstorageEnabled &&\n\t\t(wants(K.storage.accessKeyId) ||\n\t\t\twants(K.storage.secretAccessKey) ||\n\t\t\twants(K.storage.endpoint) ||\n\t\t\twants(K.storage.region));\n\tconst wantsGateway =\n\t\tgatewayEnabled &&\n\t\t(wants(K.aiGateway.apiKey) || wants(K.aiGateway.baseUrl));\n\t// A credential is minted only for its *secrets*. The endpoint, region and gateway host\n\t// are plain branch metadata, so selecting only those touches no credential at all — which\n\t// is how a caller holding valid secrets refreshes the rest without issuing a new one.\n\tconst wantsCredential =\n\t\t(storageEnabled &&\n\t\t\t(wants(K.storage.accessKeyId) ||\n\t\t\t\twants(K.storage.secretAccessKey))) ||\n\t\t(gatewayEnabled && wants(K.aiGateway.apiKey));\n\n\tif (wantsStorage || wantsGateway) {\n\t\t// Read the branch's storage settings *before* minting: a policy that declares buckets\n\t\t// on a branch without storage has to fail without having spent a credential on a\n\t\t// resolve that cannot succeed.\n\t\tlet storage: NeonBranchStorageSnapshot | null = null;\n\t\tif (wantsStorage) {\n\t\t\tstorage = await api.getProjectBranchStorage(projectId, branch.id);\n\t\t\tif (!storage) {\n\t\t\t\tthrow new PlatformError(\n\t\t\t\t\tErrorCode.NotFound,\n\t\t\t\t\t[\n\t\t\t\t\t\t`fetchEnv: branch policy declares object storage (preview.buckets) but storage is not enabled on branch ${branch.name} (${branch.id}).`,\n\t\t\t\t\t\t\"Enable it via `apply(config, { projectId, branchId })` (or in the Neon Console) — then re-run fetchEnv. Or remove preview.buckets.\",\n\t\t\t\t\t].join(\" \"),\n\t\t\t\t\t{ details: { projectId, branchId: branch.id } },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst secrets = wantsCredential\n\t\t\t? await mintBranchCredential({\n\t\t\t\t\tapi,\n\t\t\t\t\tprojectId,\n\t\t\t\t\tbranchId: branch.id,\n\t\t\t\t\tbranchName: branch.name,\n\t\t\t\t\tscopes: previewCredentialScopes(desired.preview),\n\t\t\t\t})\n\t\t\t: null;\n\n\t\tif (storage) {\n\t\t\tconst storageEnv: Partial<NeonStorageEnv> = {};\n\t\t\tif (secrets && wants(K.storage.accessKeyId)) {\n\t\t\t\tstorageEnv.accessKeyId = secrets.accessKeyId;\n\t\t\t}\n\t\t\tif (secrets && wants(K.storage.secretAccessKey)) {\n\t\t\t\tstorageEnv.secretAccessKey = secrets.secretAccessKey;\n\t\t\t}\n\t\t\tif (wants(K.storage.endpoint)) {\n\t\t\t\tstorageEnv.endpoint = storage.s3Endpoint;\n\t\t\t}\n\t\t\tif (wants(K.storage.region)) storageEnv.region = storage.region;\n\t\t\tresult.storage = storageEnv;\n\t\t}\n\t\tif (wantsGateway) {\n\t\t\tconst gateway: Partial<NeonAiGatewayEnv> = {};\n\t\t\tif (secrets && wants(K.aiGateway.apiKey)) {\n\t\t\t\tgateway.apiKey = secrets.apiToken;\n\t\t\t}\n\t\t\tif (wants(K.aiGateway.baseUrl)) {\n\t\t\t\t// Bare branch-scoped gateway host derived from the branch's connection URI —\n\t\t\t\t// not the control-plane API origin (which doesn't serve the gateway). Clients\n\t\t\t\t// append the dialect route (/v1, /openai/v1, /anthropic/v1) themselves.\n\t\t\t\tgateway.baseUrl = aiGatewayBaseUrl(branch.id, unpooled.uri);\n\t\t\t}\n\t\t\tresult.aiGateway = gateway;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Resolve the target branch and evaluate the policy against it — the first thing any\n * branch-scoped operation needs. Shared by {@link fetchEnv} and {@link fetchEnvReusingSecrets}\n * so the two agree on which branch they're talking about and what it has enabled.\n */\nexport async function resolveBranchPolicy(\n\tconfig: Config,\n\toptions: Pick<FetchEnvOptions, \"projectId\" | \"branch\" | \"branchId\">,\n\tapi: NeonApi,\n): Promise<{\n\tbranch: NeonBranchSnapshot;\n\tdesired: ReturnType<typeof resolveConfig>;\n}> {\n\tconst projectId = options.projectId;\n\tconst branches = await api.listBranches(projectId);\n\tif (branches.length === 0) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.BranchNotFound,\n\t\t\t[\n\t\t\t\t`fetchEnv: project ${projectId} has no branches.`,\n\t\t\t\t\"Deploy your neon.ts policy (or create a branch) first, or pick a different project id.\",\n\t\t\t].join(\" \"),\n\t\t\t{ details: { projectId } },\n\t\t);\n\t}\n\n\tconst branchRef = options.branch ?? options.branchId;\n\tif (!branchRef) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.BranchNotFound,\n\t\t\t[\n\t\t\t\t\"fetchEnv: no branch provided.\",\n\t\t\t\t\"Pass `branch` with a branch name (e.g. `main`) or id (`br-…`).\",\n\t\t\t].join(\" \"),\n\t\t\t{ details: { projectId } },\n\t\t);\n\t}\n\tconst branch = resolveBranch(branchRef, branches);\n\tconst desired = resolveConfig(config, {\n\t\tname: branch.name,\n\t\tid: branch.id,\n\t\texists: true,\n\t\t...(branch.parentId ? { parentId: branch.parentId } : {}),\n\t\tisDefault: branch.isDefault,\n\t\tisProtected: branch.protected,\n\t\t...(branch.expiresAt ? { expiresAt: branch.expiresAt } : {}),\n\t});\n\treturn { branch, desired };\n}\n\n/**\n * Scopes the branch credential should carry for a resolved branch policy. Only object storage\n * and the AI Gateway *require* a credential; functions never force one (they have no credential\n * of their own), but `functions:invoke` is added to the scope set when a credential is already\n * being minted for storage / the AI Gateway, so the one credential can invoke the branch's\n * functions too. Returns `[]` only when nothing credential-bearing is enabled.\n */\nexport function previewCredentialScopes(\n\tpreview: ResolvedPreviewConfig | undefined,\n): CredentialScope[] {\n\tif (!preview) return [];\n\tconst storage = preview.buckets.length > 0;\n\tconst aiGateway = preview.aiGatewayEnabled;\n\tif (!storage && !aiGateway) return [];\n\treturn deriveCredentialScopes({\n\t\tstorage,\n\t\taiGateway,\n\t\tfunctions: preview.functions.length > 0,\n\t});\n}\n\n/** The `name` this tool stamps on every credential it mints, so it can recognize its own. */\nexport function credentialName(branchName: string): string {\n\treturn `neon-env ${branchName}`;\n}\n\n/** The env-var keys a branch credential's secrets surface under, in emit order. */\nexport function credentialEnvKeys(flags: {\n\tstorage: boolean;\n\taiGateway: boolean;\n}): string[] {\n\treturn [\n\t\t...(flags.storage\n\t\t\t? [\n\t\t\t\t\tNEON_ENV_VAR_KEYS.storage.accessKeyId,\n\t\t\t\t\tNEON_ENV_VAR_KEYS.storage.secretAccessKey,\n\t\t\t\t]\n\t\t\t: []),\n\t\t...(flags.aiGateway ? [NEON_ENV_VAR_KEYS.aiGateway.apiKey] : []),\n\t];\n}\n\n/**\n * Every OS-level env var a resolved branch policy produces, in emit order. Lets a caller\n * subtract the ones it already holds and pass the rest as {@link fetchEnv}'s `keys`, without\n * re-deriving which vars a policy implies.\n */\nexport function policyEnvKeys(\n\tdesired: ReturnType<typeof resolveConfig>,\n): string[] {\n\tconst K = NEON_ENV_VAR_KEYS;\n\treturn [\n\t\tK.postgres.databaseUrl,\n\t\tK.postgres.databaseUrlUnpooled,\n\t\tK.branch.name,\n\t\t...(desired.authEnabled ? [K.auth.baseUrl, K.auth.jwksUrl] : []),\n\t\t...(desired.dataApiEnabled ? [K.dataApi.url] : []),\n\t\t...((desired.preview?.buckets.length ?? 0) > 0\n\t\t\t? [\n\t\t\t\t\tK.storage.accessKeyId,\n\t\t\t\t\tK.storage.secretAccessKey,\n\t\t\t\t\tK.storage.endpoint,\n\t\t\t\t\tK.storage.region,\n\t\t\t\t]\n\t\t\t: []),\n\t\t...(desired.preview?.aiGatewayEnabled\n\t\t\t? [K.aiGateway.apiKey, K.aiGateway.baseUrl]\n\t\t\t: []),\n\t];\n}\n\n/**\n * Mint the branch credential backing object storage / the AI Gateway.\n *\n * `api_token` and `s3_secret_access_key` come back **exactly once** — they are not stored\n * server-side and the list endpoint returns metadata only — so the caller's copy is the only\n * copy. That is why {@link fetchEnv} mints rather than fetches: there is nothing to fetch. A\n * caller that already holds a valid copy should leave the secret keys out of `keys` (see\n * {@link fetchEnvReusingSecrets}) instead of minting one it will discard.\n */\nasync function mintBranchCredential(args: {\n\tapi: NeonApi;\n\tprojectId: string;\n\tbranchId: string;\n\tbranchName: string;\n\tscopes: CredentialScope[];\n}): Promise<{\n\taccessKeyId: string;\n\tsecretAccessKey: string;\n\tapiToken: string;\n}> {\n\tconst minted = await args.api.createCredential(\n\t\targs.projectId,\n\t\targs.branchId,\n\t\t{\n\t\t\tscopes: args.scopes,\n\t\t\tprincipalType: \"user\",\n\t\t\tname: credentialName(args.branchName),\n\t\t},\n\t);\n\treturn {\n\t\t// The storage gateway authenticates against the full token id (e.g.\n\t\t// `nak_live_…`), not the short token id — using the short id yields\n\t\t// `InvalidAccessKeyId` on every S3 request.\n\t\taccessKeyId: minted.tokenId,\n\t\tsecretAccessKey: minted.s3SecretAccessKey,\n\t\tapiToken: minted.apiToken,\n\t};\n}\n\n/**\n * The AI Gateway is a **branch-scoped host** — `<branchId>-api.ai.<host-suffix>` — NOT the\n * control-plane API origin. Derive the suffix from the branch's own Postgres connection host\n * by dropping only the endpoint label (the first segment) and keeping everything after it,\n * including any infra cell prefix (`c-N.`): a connection host of\n * `ep-x.c-3.us-east-2.aws.neon.tech` yields the gateway host\n * `<branchId>-api.ai.c-3.us-east-2.aws.neon.tech`. The cell prefix is **load-bearing** —\n * the gateway is cell-routed, so dropping `c-N.` resolves to the wrong (or no) host.\n */\nfunction aiGatewayHost(branchId: string, connectionUri: string): string {\n\tlet connectionHost = \"\";\n\ttry {\n\t\tconnectionHost = new URL(connectionUri).hostname;\n\t} catch {\n\t\tconnectionHost = \"\";\n\t}\n\t// Drop the endpoint label (first segment, e.g. `ep-x` / `ep-x-pooler`), keeping the rest\n\t// of the host verbatim — including any infra cell prefix (`c-N.`) the gateway routes on:\n\t// `[c-N.]<region>.<cloud>.neon.<tld>`.\n\tconst suffix = connectionHost.split(\".\").slice(1).join(\".\");\n\treturn `${branchId}-api.ai.${suffix}`;\n}\n\n/** The AI Gateway's bare base URL (`NEON_AI_GATEWAY_BASE_URL`) on the branch gateway host. */\nfunction aiGatewayBaseUrl(branchId: string, connectionUri: string): string {\n\treturn `https://${aiGatewayHost(branchId, connectionUri)}`;\n}\n\nexport function createApiFromOptions(options: FetchEnvOptions): NeonApi {\n\treturn createNeonApiFromOptions(\"fetchEnv\", {\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.apiHost ? { apiHost: options.apiHost } : {}),\n\t});\n}\n\n/**\n * Resolve a branch ref — a name or an id — to a concrete branch. Matches by id first\n * (exact `br-…`), then by name; both are unique within a project, so the lookup is\n * unambiguous. This lets `.neon` files written by `neonctl` (which pin the branch *name*)\n * and explicit `br-…` ids both work.\n */\nfunction resolveBranch(\n\tbranch: string,\n\tbranches: NeonBranchSnapshot[],\n): NeonBranchSnapshot {\n\tconst match =\n\t\tbranches.find((b) => b.id === branch) ??\n\t\tbranches.find((b) => b.name === branch);\n\tif (match) return match;\n\tthrow new PlatformError(\n\t\tErrorCode.BranchNotFound,\n\t\t[\n\t\t\t`fetchEnv: branch ${JSON.stringify(branch)} not found on project (matched by id or name).`,\n\t\t\t`Existing branches: ${branches.map((b) => `${b.name} (${b.id})`).join(\", \")}.`,\n\t\t].join(\" \"),\n\t\t{\n\t\t\tdetails: {\n\t\t\t\tbranch,\n\t\t\t\tavailable: branches.map((b) => `${b.name} (${b.id})`),\n\t\t\t},\n\t\t},\n\t);\n}\n\nfunction pickRoleName(\n\troles: NeonRoleSnapshot[],\n\tbranch: NeonBranchSnapshot,\n\trequested: string | undefined,\n): string {\n\tif (requested) {\n\t\tif (!roles.some((r) => r.name === requested)) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.BranchNotFound,\n\t\t\t\t[\n\t\t\t\t\t`fetchEnv: role \"${requested}\" not found on branch ${branch.name} (${branch.id}).`,\n\t\t\t\t\t`Existing roles: ${roles.map((r) => r.name).join(\", \") || \"(none)\"}.`,\n\t\t\t\t].join(\" \"),\n\t\t\t\t{\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tbranchId: branch.id,\n\t\t\t\t\t\troleName: requested,\n\t\t\t\t\t\tavailableRoles: roles.map((r) => r.name),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\treturn requested;\n\t}\n\tif (roles.length === 0) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.BranchNotFound,\n\t\t\t[\n\t\t\t\t`fetchEnv: branch ${branch.name} (${branch.id}) has no roles.`,\n\t\t\t\t\"Create one via the Neon console or pass `roleName` explicitly.\",\n\t\t\t].join(\" \"),\n\t\t\t{ details: { branchId: branch.id } },\n\t\t);\n\t}\n\tif (roles.length === 1) return roles[0].name;\n\n\t// Multiple roles. Enabling Neon Auth / the Data API provisions the PostgREST roles\n\t// (authenticator/anonymous/authenticated) alongside the project owner, so a normal\n\t// branch ends up with >1 role even though only the owner backs a `DATABASE_URL`.\n\t// Default to Neon's owner role; if the project was created with a custom owner name,\n\t// fall back to the single role left after dropping the managed auth roles. Only a\n\t// genuinely ambiguous set (more than one app role) still asks the caller to choose.\n\tconst owner = roles.find((r) => r.name === NEON_DEFAULT_OWNER_ROLE);\n\tif (owner) return owner.name;\n\n\tconst appRoles = roles.filter((r) => !NEON_MANAGED_AUTH_ROLES.has(r.name));\n\tif (appRoles.length === 1) return appRoles[0].name;\n\n\tthrow new PlatformError(\n\t\tErrorCode.AmbiguousBranchAuth,\n\t\t[\n\t\t\t`fetchEnv: branch ${branch.name} (${branch.id}) has ${roles.length} roles and none is \"${NEON_DEFAULT_OWNER_ROLE}\"; cannot auto-pick.`,\n\t\t\t`Pass \\`roleName\\` explicitly. Available: ${roles.map((r) => r.name).join(\", \")}.`,\n\t\t].join(\" \"),\n\t\t{\n\t\t\tdetails: {\n\t\t\t\tbranchId: branch.id,\n\t\t\t\tavailableRoles: roles.map((r) => r.name),\n\t\t\t},\n\t\t},\n\t);\n}\n\nfunction pickDatabaseName(\n\tdatabases: NeonDatabaseSnapshot[],\n\tbranch: NeonBranchSnapshot,\n\trequested: string | undefined,\n): string {\n\tif (requested) {\n\t\tif (!databases.some((d) => d.name === requested)) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.BranchNotFound,\n\t\t\t\t[\n\t\t\t\t\t`fetchEnv: database \"${requested}\" not found on branch ${branch.name} (${branch.id}).`,\n\t\t\t\t\t`Existing databases: ${databases.map((d) => d.name).join(\", \") || \"(none)\"}.`,\n\t\t\t\t].join(\" \"),\n\t\t\t\t{\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tbranchId: branch.id,\n\t\t\t\t\t\tdatabaseName: requested,\n\t\t\t\t\t\tavailableDatabases: databases.map((d) => d.name),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\treturn requested;\n\t}\n\tif (databases.length === 0) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.BranchNotFound,\n\t\t\t[\n\t\t\t\t`fetchEnv: branch ${branch.name} (${branch.id}) has no databases.`,\n\t\t\t\t\"Create one via the Neon console or pass `databaseName` explicitly.\",\n\t\t\t].join(\" \"),\n\t\t\t{ details: { branchId: branch.id } },\n\t\t);\n\t}\n\n\t// Prefer Neon's default `neondb`. On the common \"added a second database\" branch this\n\t// auto-picks it, so a lone or `neondb`-including branch resolves without asking.\n\tconst neondb = databases.find((d) => d.name === NEON_DEFAULT_DATABASE);\n\tif (neondb) return neondb.name;\n\n\tif (databases.length === 1) return databases[0].name;\n\n\t// Several databases and no `neondb` to fall back on. Auto-picking any of them would be\n\t// perceived as random and is bad DX, so fail loudly and let the caller disambiguate.\n\tthrow new PlatformError(\n\t\tErrorCode.AmbiguousBranchAuth,\n\t\t[\n\t\t\t`fetchEnv: branch ${branch.name} (${branch.id}) has ${databases.length} databases and none is named \"${NEON_DEFAULT_DATABASE}\"; cannot auto-pick.`,\n\t\t\t`Rename one to \"${NEON_DEFAULT_DATABASE}\" or keep a single database on the branch (or, when calling fetchEnv directly, pass \\`databaseName\\`). Available: ${databases.map((d) => d.name).join(\", \")}.`,\n\t\t].join(\" \"),\n\t\t{\n\t\t\tdetails: {\n\t\t\t\tbranchId: branch.id,\n\t\t\t\tavailableDatabases: databases.map((d) => d.name),\n\t\t\t},\n\t\t},\n\t);\n}\n\n// ───────────────────────── env-var mapping helpers ─────────────────────────\n\n/**\n * Project a fully-resolved {@link NeonEnv} into the OS-level `{ KEY: value }` pairs used\n * for cross-process transport. Named after the web-platform `.entries()` convention\n * (`URLSearchParams` / `Headers` / `FormData`); returns a `Record` rather than an\n * iterator of tuples since that's the shape env injection needs (wrap with\n * `Object.entries(...)` if you want literal `[key, value]` pairs). Used by `neon-env run`\n * to inject the vars into a subprocess's `process.env`.\n *\n * Walks the value at runtime so it works for any `NeonEnv<C>` regardless of which\n * conditional namespaces are present.\n */\nexport function toEntries(env: ResolvedNeonEnv): Record<string, string> {\n\tconst out: Record<string, string> = {};\n\tconst put = (key: string, value: string | undefined): void => {\n\t\tif (value !== undefined) out[key] = value;\n\t};\n\tconst K = NEON_ENV_VAR_KEYS;\n\tput(K.postgres.databaseUrl, env.postgres?.databaseUrl);\n\tput(K.postgres.databaseUrlUnpooled, env.postgres?.databaseUrlUnpooled);\n\tput(K.branch.name, env.branch?.name);\n\tput(K.auth.baseUrl, env.auth?.baseUrl);\n\tput(K.auth.jwksUrl, env.auth?.jwksUrl);\n\tput(K.dataApi.url, env.dataApi?.url);\n\tput(K.storage.accessKeyId, env.storage?.accessKeyId);\n\tput(K.storage.secretAccessKey, env.storage?.secretAccessKey);\n\tput(K.storage.endpoint, env.storage?.endpoint);\n\tput(K.storage.region, env.storage?.region);\n\t// Neon-branded gateway vars only: the bearer and the bare branch gateway host\n\t// (scheme://host, no path) — the @neon/ai-sdk-provider appends the dialect route\n\t// (/v1, /openai/v1, /anthropic/v1) itself (https://github.com/vercel/ai/pull/15997).\n\tput(K.aiGateway.apiKey, env.aiGateway?.apiKey);\n\tput(K.aiGateway.baseUrl, env.aiGateway?.baseUrl);\n\treturn out;\n}\n\n/**\n * Any resolved env {@link toEntries} can project: a full {@link NeonEnv}, or the narrowed\n * result of a `keys`-filtered {@link fetchEnv} / {@link parseEnv} call. Every namespace and\n * property is optional so a filtered result — which legitimately carries only what was asked\n * for — projects to exactly the vars it holds instead of failing to type-check.\n */\nexport type ResolvedNeonEnv = {\n\t[N in keyof NamespaceEnv]?: Partial<NamespaceEnv[N]>;\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