@neondatabase/env 0.14.0 → 0.14.1

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.
@@ -7,13 +7,12 @@ import { join, resolve } from "node:path";
7
7
  **Deliberately impure.** It reads environment variables and touches the filesystem, which
8
8
  * `@neon/config` — the package this used to be a subpath of — must never do from its root
9
9
  * export. It lives here instead of there precisely so that a policy-facing package does not
10
- * carry implementor-only code, and so `neon-init`, which has no workspace dependencies, can use
11
- * the same resolution as everything else.
10
+ * carry implementor-only code.
12
11
  *
13
12
  * It exists because three separate readers each grew their own answer to "where is the
14
13
  * config directory", and all three disagreed: `packages/cli` honoured `XDG_CONFIG_HOME` but
15
- * not `NEONCTL_CONFIG_DIR`, `packages/env` honoured the env var but not XDG, and
16
- * `packages/init` hardcoded `~/.config/neonctl`. With `XDG_CONFIG_HOME` set, the CLI wrote
14
+ * not `NEONCTL_CONFIG_DIR`, `packages/env` honoured the env var but not XDG, and the init
15
+ * flow hardcoded `~/.config/neonctl`. With `XDG_CONFIG_HOME` set, the CLI wrote
17
16
  * credentials somewhere the other two never looked.
18
17
  *
19
18
  * ## The directory
@@ -1 +1 @@
1
- {"version":3,"file":"paths.js","names":[],"sources":["../../src/_shared/paths.ts"],"sourcesContent":["/**\n * # Where the Neon CLIs keep their files on disk\n *\n **Deliberately impure.** It reads environment variables and touches the filesystem, which\n * `@neon/config` — the package this used to be a subpath of — must never do from its root\n * export. It lives here instead of there precisely so that a policy-facing package does not\n * carry implementor-only code, and so `neon-init`, which has no workspace dependencies, can use\n * the same resolution as everything else.\n *\n * It exists because three separate readers each grew their own answer to \"where is the\n * config directory\", and all three disagreed: `packages/cli` honoured `XDG_CONFIG_HOME` but\n * not `NEONCTL_CONFIG_DIR`, `packages/env` honoured the env var but not XDG, and\n * `packages/init` hardcoded `~/.config/neonctl`. With `XDG_CONFIG_HOME` set, the CLI wrote\n * credentials somewhere the other two never looked.\n *\n * ## The directory\n *\n * `neon` is the current name; `neonctl` is the legacy one, kept readable forever. Resolution,\n * each entry winning over the next:\n *\n * 1. An explicit directory (a `--config-dir` flag) — **exact**, no legacy fallback.\n * 2. `NEON_CONFIG_DIR` — exact.\n * 3. `NEONCTL_CONFIG_DIR` (legacy name) — exact.\n * 4. `$XDG_CONFIG_HOME/neon`, else `<home>/.config/neon`.\n *\n * An explicitly chosen directory is never paired with a fallback: `--config-dir /tmp/ci` that\n * quietly read `~/.config/neonctl` would defeat the point of passing it.\n *\n * ## The files\n *\n * {@link resolveConfigFile} answers \"which path should I use for this file\", and it is the\n * same answer for reading and writing:\n *\n * - Present in `neon/` → use it.\n * - Present only in `neonctl/` → **use it there, in place.** An existing credentials file is\n * never copied or moved, so nothing is left behind to go stale and no other tool starts\n * reading an abandoned token.\n * - Present in neither → the new location. New files only ever appear under `neon/`.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\n/** Current directory name. New files are created here. */\nexport const CONFIG_DIR_NAME = \"neon\";\n\n/** Legacy directory name, read forever so existing installs keep working untouched. */\nexport const LEGACY_CONFIG_DIR_NAME = \"neonctl\";\n\nexport interface ConfigPathOptions {\n\t/**\n\t * An explicit directory, e.g. from a `--config-dir` flag. Used exactly as given: no\n\t * environment variables are consulted and the legacy directory is never searched.\n\t */\n\tdir?: string;\n\t/** Environment to read. Defaults to `process.env`. Injectable for tests. */\n\tenv?: NodeJS.ProcessEnv;\n}\n\n/** Where files are created. See the module docs for the precedence. */\nexport function configDir(options: ConfigPathOptions = {}): string {\n\tconst explicit = explicitDir(options);\n\tif (explicit) return explicit;\n\treturn join(configHome(options.env ?? process.env), CONFIG_DIR_NAME);\n}\n\n/**\n * The legacy directory, or `undefined` when the location was chosen explicitly (in which\n * case there is no legacy counterpart to fall back to).\n */\nexport function legacyConfigDir(\n\toptions: ConfigPathOptions = {},\n): string | undefined {\n\tif (explicitDir(options)) return undefined;\n\treturn join(configHome(options.env ?? process.env), LEGACY_CONFIG_DIR_NAME);\n}\n\nexport interface ResolvedConfigFile {\n\t/** The path to use, for both reading and writing. */\n\tpath: string;\n\t/** The directory `path` lives in. */\n\tdir: string;\n\t/** True when the file was found in the legacy `neonctl` directory. */\n\tisLegacy: boolean;\n\t/** Whether the file exists at `path` right now. */\n\texists: boolean;\n}\n\n/**\n * Resolve one file inside the config directory. Prefers the current location, falls back to\n * an existing legacy file **in place**, and otherwise points at the current location so new\n * files are created there.\n */\nexport function resolveConfigFile(\n\tfileName: string,\n\toptions: ConfigPathOptions = {},\n): ResolvedConfigFile {\n\tconst dir = configDir(options);\n\tconst current = resolve(dir, fileName);\n\tif (existsSync(current))\n\t\treturn { path: current, dir, isLegacy: false, exists: true };\n\n\tconst legacyDir = legacyConfigDir(options);\n\tif (legacyDir) {\n\t\tconst legacy = resolve(legacyDir, fileName);\n\t\tif (existsSync(legacy))\n\t\t\treturn {\n\t\t\t\tpath: legacy,\n\t\t\t\tdir: legacyDir,\n\t\t\t\tisLegacy: true,\n\t\t\t\texists: true,\n\t\t\t};\n\t}\n\n\treturn { path: current, dir, isLegacy: false, exists: false };\n}\n\n/** `$XDG_CONFIG_HOME`, else `<home>/.config`. Falls back to a relative `.config` with no home. */\nfunction configHome(env: NodeJS.ProcessEnv): string {\n\tconst xdg = nonEmpty(env.XDG_CONFIG_HOME);\n\tif (xdg) return xdg;\n\tconst home = nonEmpty(env.HOME) ?? nonEmpty(env.USERPROFILE);\n\treturn home ? join(home, \".config\") : \".config\";\n}\n\nfunction explicitDir(options: ConfigPathOptions): string | undefined {\n\tconst env = options.env ?? process.env;\n\treturn (\n\t\tnonEmpty(options.dir) ??\n\t\tnonEmpty(env.NEON_CONFIG_DIR) ??\n\t\tnonEmpty(env.NEONCTL_CONFIG_DIR)\n\t);\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? undefined : trimmed;\n}\n\nexport const CREDENTIALS_FILE = \"credentials.json\";\n\n/**\n * Default for `--config-dir`: `$XDG_CONFIG_HOME/neon`, else `~/.config/neon`.\n *\n * The directory was called `neonctl` until the CLI was renamed. An existing one is still read —\n * see {@link credentialsPath} — but it is never written to, moved, or deleted.\n */\nexport const defaultDir = configDir();\n\n/**\n * Where this invocation's `credentials.json` lives.\n *\n * When `--config-dir` was left at its default, an existing file in the legacy `neonctl`\n * directory is used **in place**: an install that predates the rename keeps working, and its\n * credentials are never duplicated into a second location where one copy could go stale while\n * another tool still reads it.\n *\n * A `--config-dir` the user actually passed is used exactly as given. Falling back out of an\n * explicitly chosen directory would defeat the reason for choosing it — a CI run pointed at a\n * scratch directory must never pick up a developer's real credentials.\n */\nexport const credentialsPath = (dir: string): string =>\n\tresolveConfigFile(CREDENTIALS_FILE, dir === defaultDir ? {} : { dir }).path;\n\n/**\n * Whether a credentials file is one the CLI created, rather than a path a profile adopted.\n *\n * Anything that deletes a credential has to ask this first. A profile entry may point anywhere —\n * that is what makes adopting an existing directory a one-line edit — and a file we did not\n * create is not ours to remove.\n */\nexport const isInsideConfigDir = (\n\tconfigDirectory: string,\n\tfile: string,\n): boolean => `${resolve(file)}/`.startsWith(`${resolve(configDirectory)}/`);\n\n/**\n * Whether a credentials file is one the CLI owns, counting the legacy `neonctl` directory.\n *\n * {@link credentialsPath} deliberately reads an existing legacy file in place rather than\n * migrating it, so for a default config directory that file is ours even though it sits outside\n * `neon/`. Judging ownership on the current directory alone would call an install that predates\n * the rename \"adopted\".\n */\nexport const isOwnedCredentialPath = (\n\tconfigDirectory: string,\n\tfile: string,\n): boolean => {\n\tif (isInsideConfigDir(configDirectory, file)) return true;\n\tif (configDirectory !== defaultDir) return false;\n\tconst legacy = legacyConfigDir();\n\treturn legacy !== undefined && isInsideConfigDir(legacy, file);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,kBAAkB;;AAG/B,MAAa,yBAAyB;;AAatC,SAAgB,UAAU,UAA6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ACrC;AAEA,MAAa,mBAAmB;;;;;;;AAQhC,MAAa,aAAa,UAAU;;;;;;;;;;;;;AAcpC,MAAa,mBAAmB,QAC/B,kBAAkB,kBAAkB,QAAQ,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"paths.js","names":[],"sources":["../../src/_shared/paths.ts"],"sourcesContent":["/**\n * # Where the Neon CLIs keep their files on disk\n *\n **Deliberately impure.** It reads environment variables and touches the filesystem, which\n * `@neon/config` — the package this used to be a subpath of — must never do from its root\n * export. It lives here instead of there precisely so that a policy-facing package does not\n * carry implementor-only code.\n *\n * It exists because three separate readers each grew their own answer to \"where is the\n * config directory\", and all three disagreed: `packages/cli` honoured `XDG_CONFIG_HOME` but\n * not `NEONCTL_CONFIG_DIR`, `packages/env` honoured the env var but not XDG, and the init\n * flow hardcoded `~/.config/neonctl`. With `XDG_CONFIG_HOME` set, the CLI wrote\n * credentials somewhere the other two never looked.\n *\n * ## The directory\n *\n * `neon` is the current name; `neonctl` is the legacy one, kept readable forever. Resolution,\n * each entry winning over the next:\n *\n * 1. An explicit directory (a `--config-dir` flag) — **exact**, no legacy fallback.\n * 2. `NEON_CONFIG_DIR` — exact.\n * 3. `NEONCTL_CONFIG_DIR` (legacy name) — exact.\n * 4. `$XDG_CONFIG_HOME/neon`, else `<home>/.config/neon`.\n *\n * An explicitly chosen directory is never paired with a fallback: `--config-dir /tmp/ci` that\n * quietly read `~/.config/neonctl` would defeat the point of passing it.\n *\n * ## The files\n *\n * {@link resolveConfigFile} answers \"which path should I use for this file\", and it is the\n * same answer for reading and writing:\n *\n * - Present in `neon/` → use it.\n * - Present only in `neonctl/` → **use it there, in place.** An existing credentials file is\n * never copied or moved, so nothing is left behind to go stale and no other tool starts\n * reading an abandoned token.\n * - Present in neither → the new location. New files only ever appear under `neon/`.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\n/** Current directory name. New files are created here. */\nexport const CONFIG_DIR_NAME = \"neon\";\n\n/** Legacy directory name, read forever so existing installs keep working untouched. */\nexport const LEGACY_CONFIG_DIR_NAME = \"neonctl\";\n\nexport interface ConfigPathOptions {\n\t/**\n\t * An explicit directory, e.g. from a `--config-dir` flag. Used exactly as given: no\n\t * environment variables are consulted and the legacy directory is never searched.\n\t */\n\tdir?: string;\n\t/** Environment to read. Defaults to `process.env`. Injectable for tests. */\n\tenv?: NodeJS.ProcessEnv;\n}\n\n/** Where files are created. See the module docs for the precedence. */\nexport function configDir(options: ConfigPathOptions = {}): string {\n\tconst explicit = explicitDir(options);\n\tif (explicit) return explicit;\n\treturn join(configHome(options.env ?? process.env), CONFIG_DIR_NAME);\n}\n\n/**\n * The legacy directory, or `undefined` when the location was chosen explicitly (in which\n * case there is no legacy counterpart to fall back to).\n */\nexport function legacyConfigDir(\n\toptions: ConfigPathOptions = {},\n): string | undefined {\n\tif (explicitDir(options)) return undefined;\n\treturn join(configHome(options.env ?? process.env), LEGACY_CONFIG_DIR_NAME);\n}\n\nexport interface ResolvedConfigFile {\n\t/** The path to use, for both reading and writing. */\n\tpath: string;\n\t/** The directory `path` lives in. */\n\tdir: string;\n\t/** True when the file was found in the legacy `neonctl` directory. */\n\tisLegacy: boolean;\n\t/** Whether the file exists at `path` right now. */\n\texists: boolean;\n}\n\n/**\n * Resolve one file inside the config directory. Prefers the current location, falls back to\n * an existing legacy file **in place**, and otherwise points at the current location so new\n * files are created there.\n */\nexport function resolveConfigFile(\n\tfileName: string,\n\toptions: ConfigPathOptions = {},\n): ResolvedConfigFile {\n\tconst dir = configDir(options);\n\tconst current = resolve(dir, fileName);\n\tif (existsSync(current))\n\t\treturn { path: current, dir, isLegacy: false, exists: true };\n\n\tconst legacyDir = legacyConfigDir(options);\n\tif (legacyDir) {\n\t\tconst legacy = resolve(legacyDir, fileName);\n\t\tif (existsSync(legacy))\n\t\t\treturn {\n\t\t\t\tpath: legacy,\n\t\t\t\tdir: legacyDir,\n\t\t\t\tisLegacy: true,\n\t\t\t\texists: true,\n\t\t\t};\n\t}\n\n\treturn { path: current, dir, isLegacy: false, exists: false };\n}\n\n/** `$XDG_CONFIG_HOME`, else `<home>/.config`. Falls back to a relative `.config` with no home. */\nfunction configHome(env: NodeJS.ProcessEnv): string {\n\tconst xdg = nonEmpty(env.XDG_CONFIG_HOME);\n\tif (xdg) return xdg;\n\tconst home = nonEmpty(env.HOME) ?? nonEmpty(env.USERPROFILE);\n\treturn home ? join(home, \".config\") : \".config\";\n}\n\nfunction explicitDir(options: ConfigPathOptions): string | undefined {\n\tconst env = options.env ?? process.env;\n\treturn (\n\t\tnonEmpty(options.dir) ??\n\t\tnonEmpty(env.NEON_CONFIG_DIR) ??\n\t\tnonEmpty(env.NEONCTL_CONFIG_DIR)\n\t);\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? undefined : trimmed;\n}\n\nexport const CREDENTIALS_FILE = \"credentials.json\";\n\n/**\n * Default for `--config-dir`: `$XDG_CONFIG_HOME/neon`, else `~/.config/neon`.\n *\n * The directory was called `neonctl` until the CLI was renamed. An existing one is still read —\n * see {@link credentialsPath} — but it is never written to, moved, or deleted.\n */\nexport const defaultDir = configDir();\n\n/**\n * Where this invocation's `credentials.json` lives.\n *\n * When `--config-dir` was left at its default, an existing file in the legacy `neonctl`\n * directory is used **in place**: an install that predates the rename keeps working, and its\n * credentials are never duplicated into a second location where one copy could go stale while\n * another tool still reads it.\n *\n * A `--config-dir` the user actually passed is used exactly as given. Falling back out of an\n * explicitly chosen directory would defeat the reason for choosing it — a CI run pointed at a\n * scratch directory must never pick up a developer's real credentials.\n */\nexport const credentialsPath = (dir: string): string =>\n\tresolveConfigFile(CREDENTIALS_FILE, dir === defaultDir ? {} : { dir }).path;\n\n/**\n * Whether a credentials file is one the CLI created, rather than a path a profile adopted.\n *\n * Anything that deletes a credential has to ask this first. A profile entry may point anywhere —\n * that is what makes adopting an existing directory a one-line edit — and a file we did not\n * create is not ours to remove.\n */\nexport const isInsideConfigDir = (\n\tconfigDirectory: string,\n\tfile: string,\n): boolean => `${resolve(file)}/`.startsWith(`${resolve(configDirectory)}/`);\n\n/**\n * Whether a credentials file is one the CLI owns, counting the legacy `neonctl` directory.\n *\n * {@link credentialsPath} deliberately reads an existing legacy file in place rather than\n * migrating it, so for a default config directory that file is ours even though it sits outside\n * `neon/`. Judging ownership on the current directory alone would call an install that predates\n * the rename \"adopted\".\n */\nexport const isOwnedCredentialPath = (\n\tconfigDirectory: string,\n\tfile: string,\n): boolean => {\n\tif (isInsideConfigDir(configDirectory, file)) return true;\n\tif (configDirectory !== defaultDir) return false;\n\tconst legacy = legacyConfigDir();\n\treturn legacy !== undefined && isInsideConfigDir(legacy, file);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAa,kBAAkB;;AAG/B,MAAa,yBAAyB;;AAatC,SAAgB,UAAU,UAA6B,CAAC,GAAW;CAClE,MAAM,WAAW,YAAY,OAAO;CACpC,IAAI,UAAU,OAAO;CACrB,OAAO,KAAK,WAAW,QAAQ,OAAO,QAAQ,GAAG,GAAG,eAAe;AACpE;;;;;AAMA,SAAgB,gBACf,UAA6B,CAAC,GACT;CACrB,IAAI,YAAY,OAAO,GAAG,OAAO,KAAA;CACjC,OAAO,KAAK,WAAW,QAAQ,OAAO,QAAQ,GAAG,GAAG,sBAAsB;AAC3E;;;;;;AAkBA,SAAgB,kBACf,UACA,UAA6B,CAAC,GACT;CACrB,MAAM,MAAM,UAAU,OAAO;CAC7B,MAAM,UAAU,QAAQ,KAAK,QAAQ;CACrC,IAAI,WAAW,OAAO,GACrB,OAAO;EAAE,MAAM;EAAS;EAAK,UAAU;EAAO,QAAQ;CAAK;CAE5D,MAAM,YAAY,gBAAgB,OAAO;CACzC,IAAI,WAAW;EACd,MAAM,SAAS,QAAQ,WAAW,QAAQ;EAC1C,IAAI,WAAW,MAAM,GACpB,OAAO;GACN,MAAM;GACN,KAAK;GACL,UAAU;GACV,QAAQ;EACT;CACF;CAEA,OAAO;EAAE,MAAM;EAAS;EAAK,UAAU;EAAO,QAAQ;CAAM;AAC7D;;AAGA,SAAS,WAAW,KAAgC;CACnD,MAAM,MAAM,SAAS,IAAI,eAAe;CACxC,IAAI,KAAK,OAAO;CAChB,MAAM,OAAO,SAAS,IAAI,IAAI,KAAK,SAAS,IAAI,WAAW;CAC3D,OAAO,OAAO,KAAK,MAAM,SAAS,IAAI;AACvC;AAEA,SAAS,YAAY,SAAgD;CACpE,MAAM,MAAM,QAAQ,OAAO,QAAQ;CACnC,OACC,SAAS,QAAQ,GAAG,KACpB,SAAS,IAAI,eAAe,KAC5B,SAAS,IAAI,kBAAkB;AAEjC;AAEA,SAAS,SAAS,OAA+C;CAChE,IAAI,OAAO,UAAU,UAAU,OAAO,KAAA;CACtC,MAAM,UAAU,MAAM,KAAK;CAC3B,OAAO,YAAY,KAAK,KAAA,IAAY;AACrC;AAEA,MAAa,mBAAmB;;;;;;;AAQhC,MAAa,aAAa,UAAU;;;;;;;;;;;;;AAcpC,MAAa,mBAAmB,QAC/B,kBAAkB,kBAAkB,QAAQ,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC"}
package/dist/cli.js CHANGED
@@ -49,9 +49,10 @@ const command = String(argv._[0]);
49
49
  const cwd = process.cwd();
50
50
  let result;
51
51
  switch (command) {
52
- case "run":
52
+ case "run": {
53
+ const passthrough = Array.isArray(argv["--"]) ? argv["--"].map(String) : [];
53
54
  result = await runEnvRun({
54
- command: Array.isArray(argv["--"]) ? argv["--"].map(String) : [],
55
+ command: passthrough,
55
56
  ...typeof argv.config === "string" ? { configPath: argv.config } : {},
56
57
  ...typeof argv["project-id"] === "string" ? { projectId: argv["project-id"] } : {},
57
58
  ...typeof argv.branch === "string" ? { branch: argv.branch } : {},
@@ -59,6 +60,7 @@ switch (command) {
59
60
  ...typeof argv.profile === "string" ? { profile: argv.profile } : {}
60
61
  }, { cwd });
61
62
  break;
63
+ }
62
64
  case "export":
63
65
  result = await runEnvExport({
64
66
  format: argv.format === "json" ? "json" : "dotenv",
@@ -81,7 +83,8 @@ if (argv.debug && result.exitCode !== 0 && result.debugInfo) process.stderr.writ
81
83
  process.exit(result.exitCode);
82
84
  function readPackageVersion() {
83
85
  try {
84
- const raw = readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf-8");
86
+ const pkgUrl = new URL("../package.json", import.meta.url);
87
+ const raw = readFileSync(fileURLToPath(pkgUrl), "utf-8");
85
88
  const parsed = JSON.parse(raw);
86
89
  return typeof parsed.version === "string" ? parsed.version : "0.0.0";
87
90
  } catch {
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport {\n\ttype CommandResult,\n\trunEnvExport,\n\trunEnvRun,\n} from \"./lib/cli/commands.js\";\n\nconst pkgVersion = readPackageVersion();\n\nconst argv = yargs(hideBin(process.argv))\n\t.scriptName(\"neon-env\")\n\t.usage(\"$0 <command> [options]\")\n\t.parserConfiguration({ \"populate--\": true })\n\t.option(\"debug\", {\n\t\ttype: \"boolean\",\n\t\tdefault: false,\n\t\tdescribe:\n\t\t\t\"Print stack traces and structured error details when something fails\",\n\t})\n\t.command(\n\t\t\"run\",\n\t\t\"Run a command with Neon env vars (from your neon.ts policy) injected into its environment. Use `--` to separate the command: `neon-env run -- npm run dev`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.command(\n\t\t\"export\",\n\t\t\"Print the branch's Neon env vars (from your neon.ts policy) to stdout, as dotenv lines or JSON. Useful for piping into other env tools, e.g. `neon-env export --format json`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"format\", {\n\t\t\t\t\tchoices: [\"dotenv\", \"json\"] as const,\n\t\t\t\t\tdefault: \"dotenv\",\n\t\t\t\t\tdescribe: \"Output format: dotenv (KEY=value lines) or json\",\n\t\t\t\t})\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.demandCommand(1, \"Run `neon-env --help` to see the available commands.\")\n\t.strict()\n\t.help()\n\t.version(pkgVersion)\n\t.parseSync();\n\nconst command = String(argv._[0]);\nconst cwd = process.cwd();\n\nlet result: CommandResult;\nswitch (command) {\n\tcase \"run\": {\n\t\tconst passthrough = Array.isArray(argv[\"--\"])\n\t\t\t? argv[\"--\"].map(String)\n\t\t\t: [];\n\t\tresult = await runEnvRun(\n\t\t\t{\n\t\t\t\tcommand: passthrough,\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tcase \"export\": {\n\t\tresult = await runEnvExport(\n\t\t\t{\n\t\t\t\tformat: argv.format === \"json\" ? \"json\" : \"dotenv\",\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tresult = {\n\t\t\texitCode: 1,\n\t\t\tstdout: \"\",\n\t\t\tstderr: `Unknown command: ${command}\\n`,\n\t\t};\n}\n\nif (result.stdout) process.stdout.write(result.stdout);\nif (result.stderr) process.stderr.write(result.stderr);\nif (argv.debug && result.exitCode !== 0 && result.debugInfo) {\n\tprocess.stderr.write(`\\n--- debug ---\\n${result.debugInfo}\\n`);\n}\nprocess.exit(result.exitCode);\n\nfunction readPackageVersion(): string {\n\t// The built CLI lives at `dist/cli.js`, so `package.json` is one directory up. When\n\t// running from source (tsx, vitest), the file lives at `src/cli.ts` and `package.json`\n\t// is again one directory up. Single resolution covers both layouts.\n\ttry {\n\t\tconst pkgUrl = new URL(\"../package.json\", import.meta.url);\n\t\tconst raw = readFileSync(fileURLToPath(pkgUrl), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as { version?: unknown };\n\t\treturn typeof parsed.version === \"string\" ? parsed.version : \"0.0.0\";\n\t} catch {\n\t\treturn \"0.0.0\";\n\t}\n}\n"],"mappings":";;;;;;;AAYA,MAAM,aAAa,mBAAmB;AAEtC,MAAM,OAAO,MAAM,QAAQ,QAAQ,IAAI,CAAC,CAAC,CACvC,WAAW,UAAU,CAAC,CACtB,MAAM,wBAAwB,CAAC,CAC/B,oBAAoB,EAAE,cAAc,KAAK,CAAC,CAAC,CAC3C,OAAO,SAAS;CAChB,MAAM;CACN,SAAS;CACT,UACC;AACF,CAAC,CAAC,CACD,QACA,OACA,gKACC,MACA,E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,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport {\n\ttype CommandResult,\n\trunEnvExport,\n\trunEnvRun,\n} from \"./lib/cli/commands.js\";\n\nconst pkgVersion = readPackageVersion();\n\nconst argv = yargs(hideBin(process.argv))\n\t.scriptName(\"neon-env\")\n\t.usage(\"$0 <command> [options]\")\n\t.parserConfiguration({ \"populate--\": true })\n\t.option(\"debug\", {\n\t\ttype: \"boolean\",\n\t\tdefault: false,\n\t\tdescribe:\n\t\t\t\"Print stack traces and structured error details when something fails\",\n\t})\n\t.command(\n\t\t\"run\",\n\t\t\"Run a command with Neon env vars (from your neon.ts policy) injected into its environment. Use `--` to separate the command: `neon-env run -- npm run dev`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.command(\n\t\t\"export\",\n\t\t\"Print the branch's Neon env vars (from your neon.ts policy) to stdout, as dotenv lines or JSON. Useful for piping into other env tools, e.g. `neon-env export --format json`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"format\", {\n\t\t\t\t\tchoices: [\"dotenv\", \"json\"] as const,\n\t\t\t\t\tdefault: \"dotenv\",\n\t\t\t\t\tdescribe: \"Output format: dotenv (KEY=value lines) or json\",\n\t\t\t\t})\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.demandCommand(1, \"Run `neon-env --help` to see the available commands.\")\n\t.strict()\n\t.help()\n\t.version(pkgVersion)\n\t.parseSync();\n\nconst command = String(argv._[0]);\nconst cwd = process.cwd();\n\nlet result: CommandResult;\nswitch (command) {\n\tcase \"run\": {\n\t\tconst passthrough = Array.isArray(argv[\"--\"])\n\t\t\t? argv[\"--\"].map(String)\n\t\t\t: [];\n\t\tresult = await runEnvRun(\n\t\t\t{\n\t\t\t\tcommand: passthrough,\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tcase \"export\": {\n\t\tresult = await runEnvExport(\n\t\t\t{\n\t\t\t\tformat: argv.format === \"json\" ? \"json\" : \"dotenv\",\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tresult = {\n\t\t\texitCode: 1,\n\t\t\tstdout: \"\",\n\t\t\tstderr: `Unknown command: ${command}\\n`,\n\t\t};\n}\n\nif (result.stdout) process.stdout.write(result.stdout);\nif (result.stderr) process.stderr.write(result.stderr);\nif (argv.debug && result.exitCode !== 0 && result.debugInfo) {\n\tprocess.stderr.write(`\\n--- debug ---\\n${result.debugInfo}\\n`);\n}\nprocess.exit(result.exitCode);\n\nfunction readPackageVersion(): string {\n\t// The built CLI lives at `dist/cli.js`, so `package.json` is one directory up. When\n\t// running from source (tsx, vitest), the file lives at `src/cli.ts` and `package.json`\n\t// is again one directory up. Single resolution covers both layouts.\n\ttry {\n\t\tconst pkgUrl = new URL(\"../package.json\", import.meta.url);\n\t\tconst raw = readFileSync(fileURLToPath(pkgUrl), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as { version?: unknown };\n\t\treturn typeof parsed.version === \"string\" ? parsed.version : \"0.0.0\";\n\t} catch {\n\t\treturn \"0.0.0\";\n\t}\n}\n"],"mappings":";;;;;;;AAYA,MAAM,aAAa,mBAAmB;AAEtC,MAAM,OAAO,MAAM,QAAQ,QAAQ,IAAI,CAAC,CAAC,CACvC,WAAW,UAAU,CAAC,CACtB,MAAM,wBAAwB,CAAC,CAC/B,oBAAoB,EAAE,cAAc,KAAK,CAAC,CAAC,CAC3C,OAAO,SAAS;CAChB,MAAM;CACN,SAAS;CACT,UACC;AACF,CAAC,CAAC,CACD,QACA,OACA,gKACC,MACA,EACE,OAAO,UAAU;CACjB,MAAM;CACN,UACC;AACF,CAAC,CAAC,CACD,OAAO,cAAc;CACrB,MAAM;CACN,UAAU;AACX,CAAC,CAAC,CACD,OAAO,UAAU;CACjB,MAAM;CACN,UACC;AACF,CAAC,CAAC,CACD,OAAO,WAAW;CAClB,MAAM;CACN,UAAU;AACX,CAAC,CAAC,CACD,OAAO,WAAW;CAClB,MAAM;CACN,UACC;AACF,CAAC,CACJ,CAAC,CACA,QACA,UACA,kLACC,MACA,EACE,OAAO,UAAU;CACjB,SAAS,CAAC,UAAU,MAAM;CAC1B,SAAS;CACT,UAAU;AACX,CAAC,CAAC,CACD,OAAO,UAAU;CACjB,MAAM;CACN,UACC;AACF,CAAC,CAAC,CACD,OAAO,cAAc;CACrB,MAAM;CACN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O,IACtB,CAAC;GACJ,GAAI,OAAO,KAAK,eAAe,WAC5B,EAAE,QAAQ,KAAK,WAAW,IAC1B,CAAC;GACJ,GAAI,OAAO,KAAK,YAAY,WACzB,EAAE,SAAS,KAAK,QAAQ,IACxB,CAAC;EACL,GACA,EAAE,IAAI,CACP;EACA;CAED,SACC,SAAS;EACR,UAAU;EACV,QAAQ;EACR,QAAQ,oBAAoB,QAAQ;CACrC;AACF;AAEA,IAAI,OAAO,QAAQ,QAAQ,OAAO,MAAM,OAAO,MAAM;AACrD,IAAI,OAAO,QAAQ,QAAQ,OAAO,MAAM,OAAO,MAAM;AACrD,IAAI,KAAK,SAAS,OAAO,aAAa,KAAK,OAAO,WACjD,QAAQ,OAAO,MAAM,oBAAoB,OAAO,UAAU,GAAG;AAE9D,QAAQ,KAAK,OAAO,QAAQ;AAE5B,SAAS,qBAA6B;CAIrC,IAAI;EACH,MAAM,SAAS,IAAI,IAAI,mBAAmB,YAAY,GAAG;EACzD,MAAM,MAAM,aAAa,cAAc,MAAM,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,OAAO,OAAO,OAAO,YAAY,WAAW,OAAO,UAAU;CAC9D,QAAQ;EACP,OAAO;CACR;AACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":["ComputeUnit","DurationUnit","DurationString","SuspendTimeoutSuggestion","TtlSuggestion","DurationField","Suggestions","NonNullable","ComputeSettings","BranchTarget","ServiceToggle","ServiceToggleInput","ServiceEnabled","T","PostgresConfig","DATA_API_AUTH_PROVIDERS","DataApiAuthProvider","DataApiSettings","DataApiConfigBase","DataApiNeonAuthConfig","DataApiExternalAuthConfig","DataApiConfig","DataApiInput","FunctionRuntime","FunctionDevConfig","FunctionDef","Record","CredentialScope","CredentialPrincipalType","BucketAccessLevel","BucketDef","PreviewInput","FunctionTuning","PreviewTuning","Slug","Partial","BranchTuning","FunctionSlugsOf","Preview","F","Extract","BranchTuningFn","Config","Auth","DataApi","ResolvedFunctionConfig","ResolvedBucketConfig","ResolvedPreviewConfig","ResolvedDataApiConfig","ResolvedBranchConfig","AppliedChange","ConflictReport","PushResult"],"sources":["../../../../../config/dist/lib/types.d.ts"],"sourcesContent":["//#region src/lib/types.d.ts\n/**\n * Valid Neon Compute Unit values.\n * Most plans support 0.25, 0.5, 1, 2, 4, 8. Higher values may be available on Business plans.\n */\ntype ComputeUnit = 0.25 | 0.5 | 1 | 2 | 4 | 8;\n/** Time units accepted in a {@link DurationString}: seconds, minutes, hours, days, weeks. */\ntype DurationUnit = \"s\" | \"m\" | \"h\" | \"d\" | \"w\";\n/**\n * A Neon duration string: a positive integer **followed by a unit** — `s` (seconds),\n * `m` (minutes), `h` (hours), `d` (days), or `w` (weeks). Used by\n * {@link ComputeSettings.suspendTimeout} and {@link BranchTuning.ttl}.\n *\n * A **unit is required**: a bare numeric string like `\"7\"` is rejected at the type level. To\n * express a raw number of seconds, pass a `number` (`300`) — not a string (`\"300\"`). This\n * removes the old ambiguity where `\"7\"` silently meant 7 *seconds* instead of, say, `\"7d\"`.\n *\n * @example \"5m\" // 5 minutes\n * @example \"1h\" // 1 hour\n * @example \"7d\" // 7 days\n */\ntype DurationString = `${number}${DurationUnit}`;\n/**\n * Autocomplete suggestions for {@link ComputeSettings.suspendTimeout}. Every value sits inside\n * the Neon API's allowed scale-to-zero band: **60s–604800s** (1 minute – 1 week). This is *not*\n * a closed set — the field also accepts any other {@link DurationString} or a `number` of\n * seconds; out-of-range values type-check but are rejected at apply time.\n */\ntype SuspendTimeoutSuggestion = \"1m\" | \"5m\" | \"15m\" | \"30m\" | \"1h\" | \"6h\" | \"12h\" | \"1d\" | \"7d\";\n/**\n * Autocomplete suggestions for {@link BranchTuning.ttl}. Every value sits within the Neon API's\n * branch-expiration limit (**max 30 days** from creation; the Console's own presets are 1h / 1d\n * / 7d). This is *not* a closed set — the field also accepts any other {@link DurationString} or\n * a `number` of seconds; values over 30 days are rejected at apply time.\n */\ntype TtlSuggestion = \"1h\" | \"6h\" | \"12h\" | \"1d\" | \"3d\" | \"7d\" | \"14d\" | \"30d\";\n/**\n * Compose a field's duration type: its curated autocomplete `Suggestions` plus the open\n * `DurationString` template (so any `<integer><unit>` string still type-checks) and a `number`\n * of seconds. Intersecting the template arm with `NonNullable<unknown>` stops TypeScript from\n * collapsing the literal suggestions into the template, which is what preserves the autocomplete.\n */\ntype DurationField<Suggestions extends DurationString> = Suggestions | (DurationString & NonNullable<unknown>) | number;\n/**\n * Compute settings applied to the read/write endpoint of a branch.\n *\n * Mirrors the subset of {@link https://api-docs.neon.tech/reference/getting-started-with-neon-api Neon endpoint}\n * fields that we expose as IaC primitives. Anything left undefined falls back to the project's\n * `default_endpoint_settings` (which themselves fall back to Neon defaults).\n */\ninterface ComputeSettings {\n /**\n * Minimum number of Compute Units. Set to 0.25 for true scale-to-zero.\n * @example 0.25 // scale-to-zero\n * @example 1 // always-on with 1 CU minimum\n */\n autoscalingLimitMinCu?: ComputeUnit;\n /**\n * Maximum number of Compute Units for autoscaling.\n * @example 2\n * @example 8\n */\n autoscalingLimitMaxCu?: ComputeUnit;\n /**\n * How long an idle compute waits before suspending (Neon's scale-to-zero). Accepts a\n * {@link DurationString} (autocompletes common values), a number of seconds, or `false`.\n *\n * - `false` — never suspend (always-on compute)\n * - {@link DurationString} — e.g. `\"5m\"`; autocompletes the in-range values `\"1m\"`, `\"5m\"`,\n * `\"15m\"`, `\"30m\"`, `\"1h\"`, `\"6h\"`, `\"12h\"`, `\"1d\"`, `\"7d\"`, and accepts any other\n * `<integer><unit>` (units: `s`, `m`, `h`, `d`, `w`). A **unit is required** — for raw\n * seconds pass a `number`, not a string.\n * - `number` — custom timeout in **seconds**, must be in `60`–`604800` (1 minute to 1 week)\n * - `undefined` — use the Neon default (currently 300s / 5 minutes)\n *\n * Whichever form you use, the resolved timeout must fall in `60`–`604800` seconds (the Neon\n * API limit); the suggestions are all within that band, anything else is checked at apply.\n *\n * @example false // never suspend (always-on)\n * @example \"5m\" // suspend after 5 minutes idle\n * @example \"1h\" // suspend after 1 hour idle\n * @example 300 // 5 minutes, expressed in seconds\n */\n suspendTimeout?: false | DurationField<SuspendTimeoutSuggestion>;\n}\n/**\n * Read-only descriptor of the branch a {@link Config} policy is being evaluated for — the\n * `branch` argument passed to your `defineConfig({ branch: (branch) => … })` closure. It describes\n * **which** branch this invocation decides for; it is not a live branch handle and must not\n * be mutated. Switch on its fields and return the desired {@link BranchConfig}.\n */\ninterface BranchTarget {\n /** Branch name being evaluated. For `branch dev`, this is the generated branch name. */\n name: string;\n /** Neon branch id when the branch already exists. Undefined during pre-create eval. */\n id?: string;\n /** Whether this branch already exists on Neon. */\n exists: boolean;\n /** Parent branch id from Neon when known. */\n parentId?: string;\n /** Whether Neon marks this branch as the project default. */\n isDefault?: boolean;\n /** Whether Neon currently marks this branch protected. */\n isProtected?: boolean;\n /** Current expiration timestamp from Neon, when set. */\n expiresAt?: string;\n}\n/**\n * Object form of a branch-scoped service toggle. `{}` or `{ enabled: true }` enables it;\n * `{ enabled: false }` opts out. Used as the object half of {@link ServiceToggleInput}.\n */\ninterface ServiceToggle {\n /** Defaults to `true` when the service namespace is present. Set `false` to opt out. */\n enabled?: boolean;\n}\n/**\n * How a branch-scoped service (Neon Auth, Data API, AI Gateway) is toggled in a policy.\n *\n * - `true` / `{}` / `{ enabled: true }` — enabled.\n * - `false` / `{ enabled: false }` — disabled.\n * - omitted (`undefined`) — not part of the policy at all.\n *\n * These toggles are **static** (they live in the top-level `defineConfig({ … })` object,\n * not in the per-branch `branch` closure) so the secret set they imply can be derived at\n * the type level — that's what makes `NeonEnv<typeof config>` exact.\n */\ntype ServiceToggleInput = boolean | ServiceToggle;\n/**\n * Resolve a **static** service toggle (`true` / `false` / `{ enabled?: boolean }` / object /\n * `undefined`) to a type-level boolean. The tuple wrapping (`[T] extends […]`) disables\n * distribution so a union/`undefined` is judged as a single 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 | … | undefined` (no literal info) → `false`\n *\n * Shared by the {@link Config} static cross-field checks and the `@neon/env`\n * `NeonEnv` namespace derivation, so both read \"is this service on?\" identically.\n */\ntype ServiceEnabled<T> = [T] extends [false] ? false : [T] extends [{\n enabled: false;\n}] ? false : [T] extends [undefined] ? false : [T] extends [true] ? true : [T] extends [{\n enabled: true;\n}] ? true : [T] extends [object] ? true : false;\ninterface PostgresConfig {\n computeSettings?: ComputeSettings;\n}\n/**\n * Authentication providers a Data API integration can verify JWTs against, as written in\n * `neon.ts`. Friendly authoring values (mapped to the Neon API's `neon_auth` / `external`\n * at the API boundary):\n *\n * - `\"neon\"` — verify tokens minted by **Neon Auth** on the same branch. Neon supplies the\n * JWKS URL / provider wiring for you, so the `jwksUrl` / `providerName` / `jwtAudience`\n * fields are forbidden (a type error) on this variant — and the policy must also enable\n * top-level `auth` (Neon Auth) so the tokens exist.\n * - `\"external\"` — verify tokens from a third-party IdP (Clerk, Stytch, Auth0, …). You\n * provide `jwksUrl` (and optionally `providerName` / `jwtAudience`).\n */\ndeclare const DATA_API_AUTH_PROVIDERS: readonly [\"neon\", \"external\"];\ntype DataApiAuthProvider = (typeof DATA_API_AUTH_PROVIDERS)[number];\n/**\n * Reusable runtime settings for a Data API integration (the Neon API `DataAPISettings`,\n * camelCased to match the rest of `neon.ts`). Every field is optional; omitted fields keep\n * the Neon defaults shown below. These are the **only** Data API fields that can change on\n * an already-enabled integration — drift here is reconciled as an *update* (requires\n * `updateExisting` / `--update-existing`); the create-only auth wiring above cannot.\n */\ninterface DataApiSettings {\n /** Enable the aggregates feature (`db_aggregates_enabled`). Default `true`. */\n dbAggregatesEnabled?: boolean;\n /** Database role used for anonymous requests (`db_anon_role`). Default `\"anonymous\"`. */\n dbAnonRole?: string;\n /** Extra schemas appended to the search path (`db_extra_search_path`). */\n dbExtraSearchPath?: string;\n /** Maximum rows returned in a single request (`db_max_rows`). */\n dbMaxRows?: number;\n /** Schemas exposed via the API (`db_schemas`). Default `[\"public\"]`. */\n dbSchemas?: string[];\n /** JWT claim key used for role extraction (`jwt_role_claim_key`). Default `\".role\"`. */\n jwtRoleClaimKey?: string;\n /** Maximum lifetime of the JWT cache, in seconds (`jwt_cache_max_lifetime`). */\n jwtCacheMaxLifetime?: number;\n /** OpenAPI spec mode (`openapi_mode`). Default `\"disabled\"`. */\n openapiMode?: \"ignore-privileges\" | \"disabled\";\n /** CORS allowed origins (`server_cors_allowed_origins`). */\n serverCorsAllowedOrigins?: string;\n /** Emit server-timing headers (`server_timing_enabled`). */\n serverTimingEnabled?: boolean;\n}\n/** Fields shared by every {@link DataApiConfig} variant. */\ninterface DataApiConfigBase {\n /** Defaults to `true` when the `dataApi` namespace is present. Set `false` to opt out. */\n enabled?: boolean;\n /** Reusable runtime settings. Drift here is reconciled as an update. */\n settings?: DataApiSettings;\n}\n/**\n * Data API verified by **Neon Auth** (`authProvider: \"neon\"`, the default). The external\n * IdP fields are statically forbidden (`?: never`) because Neon supplies them; declaring any\n * of them is a type error directing you to `authProvider: \"external\"`.\n */\ninterface DataApiNeonAuthConfig extends DataApiConfigBase {\n authProvider?: \"neon\";\n /** Forbidden with `authProvider: \"neon\"` — Neon provides the JWKS URL. */\n jwksUrl?: never;\n /** Forbidden with `authProvider: \"neon\"` — the provider is Neon Auth. */\n providerName?: never;\n /** Forbidden with `authProvider: \"neon\"` — Neon manages the audience. */\n jwtAudience?: never;\n}\n/**\n * Data API verified by an **external** IdP (`authProvider: \"external\"`). You provide the\n * JWKS URL (and optionally a provider label / expected audience).\n */\ninterface DataApiExternalAuthConfig extends DataApiConfigBase {\n authProvider: \"external\";\n /** URL that publishes the IdP's JWKS (JSON Web Key Set). */\n jwksUrl?: string;\n /** Human label for the IdP (e.g. \"Clerk\", \"Stytch\", \"Auth0\"). */\n providerName?: string;\n /**\n * Expected `aud` claim. ⚠️ This only **rejects** tokens carrying a *different* audience;\n * tokens with no `aud` claim are still accepted.\n */\n jwtAudience?: string;\n}\n/**\n * Object form of the `dataApi` toggle. A discriminated union on {@link DataApiAuthProvider}:\n * the `\"neon\"` variant forbids the external-IdP fields, the `\"external\"` variant allows them.\n */\ntype DataApiConfig = DataApiNeonAuthConfig | DataApiExternalAuthConfig;\n/**\n * How the Data API is toggled in a policy: a bare boolean (like the other service toggles)\n * or the richer {@link DataApiConfig} object. `true` / `{}` / `{ enabled: true }` enable it\n * with Neon defaults; `false` / `{ enabled: false }` opt out.\n */\ntype DataApiInput = boolean | DataApiConfig;\n/**\n * Supported function runtimes. Mirrors the Neon Functions deploy API `runtime` enum.\n * Only `nodejs24` exists today; kept as a union so adding runtimes later is a\n * non-breaking, type-checked change.\n */\ntype FunctionRuntime = \"nodejs24\";\n/**\n * Local-development settings for a function, used by `neon dev` when it serves every\n * function declared in `neon.ts` (i.e. invoked with no `--source`). Never affects deploy.\n */\ninterface FunctionDevConfig {\n /**\n * Port the local server binds. Bound exactly (and `neon dev` fails loudly if it is taken)\n * when set; a free port is found automatically when omitted.\n */\n port?: number;\n}\n/**\n * Static definition of a Neon Function (Preview feature). Declares that the function\n * **exists** on every branch; its branch-unique slug is the **record key** in\n * {@link PreviewInput.functions} (not a field here), so slugs are statically enumerable,\n * cannot duplicate, and the `branch` closure can only tune slugs that are declared here.\n *\n * A function is invoked like a Cloudflare/Vercel handler — its source module\n * `export default { fetch }` or `export async function handler(req): Response`. The\n * `source` path is bundled (esbuild) and uploaded as a deployment; the newest deployment\n * becomes active.\n *\n * Runtime tuning is **not** here — it varies per branch and lives in the `branch` closure\n * (see {@link FunctionTuning}). Memory is fixed by the platform policy for now and is not\n * user-configurable.\n */\ninterface FunctionDef {\n /** Free-form display name. @example \"Hello World\" */\n name: string;\n /**\n * Path to the function's entry module, **relative to `neon.ts`** (or absolute). The\n * module's default export (`{ fetch }`) or `handler` export is the function entry. This\n * path is resolved against the loaded `neon.ts` location and bundled with esbuild at\n * deploy time.\n *\n * We require a string path rather than an imported handler because a JS function value\n * carries no reference back to its source file, so esbuild has nothing to bundle from.\n * @example \"./functions/hello-world.ts\"\n */\n source: string;\n /**\n * Environment variables injected into the deployed function, keyed by the var name the\n * function reads at runtime. The **keys** are static (preserved at the type level so\n * `parseEnv(config, \"<slug>\").function.<key>` is typed); the **values** are arbitrary\n * strings evaluated when `neon.ts` is loaded (typically `process.env.X`) and uploaded\n * at `config apply`. Every value must be a defined string — a `process.env.X` that is\n * `undefined` (unset) errors at validation time rather than silently shipping\n * `undefined`.\n * @example { resendApiKey: process.env.RESEND_API_KEY ?? \"\" }\n */\n env?: Record<string, string>;\n /**\n * Packages the bundler must leave alone, by name — the deploy-time equivalent of\n * Next.js's `serverExternalPackages`. Every entry is passed to esbuild's `external`,\n * so the import survives into the bundle instead of being followed.\n *\n * Reach for this when bundling a package is impossible rather than merely undesirable.\n * The cases that come up: a native `.node` addon or a `node-gyp` dependency esbuild has\n * no loader for, and an optional peer dependency a library references on a code path\n * this function never takes. Both fail the deploy at bundle time with a resolve or\n * loader error naming the package, and neither is fixable from the function's own\n * source.\n *\n * **An external package is not resolvable at runtime.** The deployed archive is a\n * single `index.mjs` with no `node_modules` beside it, so anything listed here throws\n * `Cannot find module` if the function actually reaches it. This option therefore only\n * unblocks an import that is never evaluated; it does not make a dependency usable.\n *\n * A dependency the handler actually calls has to be bundled, and whether that is\n * possible depends on what it is. A pure-JavaScript package can be bundled, and a\n * failure to do so is usually something specific and fixable. A package backed by a\n * native `.node` binary cannot be bundled by anything — the binary is a compiled\n * object the platform loads from a real path — so such a package cannot work on\n * Functions until the deployed archive can carry files alongside the bundle. Do not\n * reach for `externalPackages` to try: it moves the error from deploy to invoke.\n *\n * Note that a native package may bundle without ever needing this option. `sharp`, for\n * instance, loads its binary through `createRequire`, which esbuild does not follow, so\n * it bundles cleanly and then fails at invoke with \"Could not load the sharp module\".\n *\n * Entries are package names, optionally with a subpath (`pkg`, `@scope/pkg`,\n * `pkg/sub`), matching esbuild. A relative or absolute path is rejected at validation\n * time: those are local modules, and a local module that cannot be bundled is a\n * different problem.\n * @example [\"microsandbox\", \"@mongodb-js/zstd\"]\n */\n externalPackages?: string[];\n /**\n * Local-development settings used by `neon dev` when serving every function from\n * `neon.ts`. Ignored at deploy time. See {@link FunctionDevConfig}.\n */\n dev?: FunctionDevConfig;\n}\n/**\n * A single capability a branch-scoped service credential may exercise (Preview). A\n * credential is granted a set of these and may only perform the listed actions. Mirrors\n * the Neon API `CredentialScope` enum (`x-stability-level: beta`):\n *\n * - `storage:read` / `storage:write` — object-storage (bucket) access via the S3 key.\n * - `ai_gateway:invoke` — call the AI Gateway with the bearer `api_token`.\n * - `functions:invoke` — invoke Neon Functions with the bearer `api_token`.\n *\n * The set a policy needs is derived from its enabled Preview features (see\n * {@link deriveCredentialScopes}); it is never authored by hand.\n */\ntype CredentialScope = \"storage:read\" | \"storage:write\" | \"ai_gateway:invoke\" | \"functions:invoke\";\n/**\n * Who a credential acts as. `user` is the developer/app principal minted for local dev and\n * app bootstrap (`fetchEnv` / `env pull`); `function` is a deployed-function principal\n * (carries a `function_id`). The env tooling only mints `user` credentials today.\n */\ntype CredentialPrincipalType = \"user\" | \"function\";\n/** Anonymous-access level for a branchable object-storage bucket. */\ntype BucketAccessLevel = \"private\" | \"public_read\";\n/**\n * Static definition of a branchable object-storage bucket (Preview feature). The bucket's\n * name is the **record key** in {@link PreviewInput.buckets}, so names are statically\n * enumerable and cannot duplicate.\n */\ninterface BucketDef {\n /**\n * Anonymous access level. `private` (default) requires authenticated reads/writes;\n * `public_read` allows anonymous GetObject/HeadObject.\n */\n access?: BucketAccessLevel;\n}\n/**\n * Static, branch-scoped **Preview** features. Grouped under `preview` to signal they are\n * backed by Neon `x-stability-level: beta` endpoints and may change before GA. Everything\n * here is existential (it determines what exists on the branch); per-branch tuning lives in\n * the `branch` closure.\n */\ninterface PreviewInput {\n /** Enable/disable the AI Gateway on the branch (toggle, like auth / dataApi). */\n aiGateway?: ServiceToggleInput;\n /** Functions to deploy, keyed by branch-unique slug (`^[a-z0-9]{1,20}$`). */\n functions?: Record<string, FunctionDef>;\n /** Object-storage buckets to create, keyed by bucket name. */\n buckets?: Record<string, BucketDef>;\n}\n/**\n * Per-branch deploy tuning for a single function. Returned (per slug) by the `branch`\n * closure. Deliberately **cannot** change the function's existence, source, name, env\n * **keys**, or memory — only runtime selection is currently configurable — so the static\n * secret/function set stays sound.\n */\ninterface FunctionTuning {\n /** Runtime to execute the function with. Defaults to `\"nodejs24\"`. */\n runtime?: FunctionRuntime;\n}\n/**\n * Per-branch tuning of Preview features. Only existing function slugs (those declared in\n * the static {@link PreviewInput.functions}) may be tuned — `Slug` is constrained to the\n * declared keys by {@link BranchTuningFn}.\n */\ninterface PreviewTuning<Slug extends string = string> {\n functions?: Partial<Record<Slug, FunctionTuning>>;\n}\n/**\n * The per-branch tuning object returned by the `branch` closure. It can adjust branch\n * lifecycle (`parent`, `ttl`, `protected`), Postgres compute settings, and per-function\n * deploy tuning — but **cannot** add/remove services or functions. That guarantee is what\n * keeps the static secret set (and therefore `NeonEnv`) exact.\n */\ninterface BranchTuning<Slug extends string = string> {\n /** Parent branch name used when creating a new branch. Not a Postgres setting. */\n parent?: string;\n /**\n * Branch time-to-live: how long after creation the branch should auto-expire. Applied\n * when creating a new branch and reconciled on existing branches (when `updateExisting`\n * is set). Accepts a {@link DurationString} (autocompletes common values) or a number of\n * seconds. Omit to keep the branch indefinitely.\n *\n * - {@link DurationString} — e.g. `\"7d\"`; autocompletes `\"1h\"`, `\"6h\"`, `\"12h\"`, `\"1d\"`,\n * `\"3d\"`, `\"7d\"`, `\"14d\"`, `\"30d\"`, and accepts any other `<integer><unit>` (units: `s`,\n * `m`, `h`, `d`, `w` — e.g. `\"12h\"`, `\"2w\"`). A **unit is required** — `\"7\"` is rejected;\n * for raw seconds pass a `number`.\n * - `number` — custom TTL in **seconds** (e.g. `3600`)\n * - `undefined` — no expiry; the branch persists until explicitly deleted\n *\n * The Neon API caps branch expiration at **30 days** from creation, so the resolved TTL must\n * be `> 0` and `<= 30d`; the suggestions stay within that limit and anything longer is\n * rejected at apply.\n *\n * @example \"1d\" // ephemeral preview branch: expires a day after creation\n * @example \"7d\" // one-week TTL\n * @example \"30d\" // the maximum the API allows\n * @example 3600 // 1 hour, expressed in seconds\n */\n ttl?: DurationField<TtlSuggestion>;\n /** Whether the selected branch should be protected. Undefined means \"leave as-is\". */\n protected?: boolean;\n postgres?: PostgresConfig;\n preview?: PreviewTuning<Slug>;\n}\n/** Extract the declared function slugs from a {@link PreviewInput} for closure typing. */\ntype FunctionSlugsOf<Preview extends PreviewInput | undefined> = Preview extends {\n functions: infer F;\n} ? Extract<keyof F, string> : string;\n/**\n * Signature of the `branch` closure. Generic over the static {@link PreviewInput} so the\n * `preview.functions` keys it may tune are constrained to the slugs actually declared.\n */\ntype BranchTuningFn<Preview extends PreviewInput | undefined = PreviewInput | undefined> = (branch: BranchTarget) => BranchTuning<FunctionSlugsOf<Preview>>;\n/**\n * A validated Neon branch policy — the value `defineConfig({ … })` returns and `neon.ts`\n * default-exports.\n *\n * Split into a **static** existential set (top-level `auth` / `dataApi` GA toggles plus the\n * beta `preview` block) and a **dynamic** per-branch `branch` closure for tuning. The\n * static half is what makes the secret set — and therefore `NeonEnv<typeof config>` and\n * `parseEnv` — exact; the closure can tune but never change what exists.\n *\n * Generic over the three static fields so the type system can read the exact toggle/slug\n * literals; the defaults make the bare `Config` a usable \"any policy\" type for runtime\n * function signatures.\n */\ninterface Config<Auth extends ServiceToggleInput | undefined = ServiceToggleInput | undefined, DataApi extends DataApiInput | undefined = DataApiInput | undefined, Preview extends PreviewInput | undefined = PreviewInput | undefined> {\n /** Neon Auth integration toggle (GA). Static — drives `NeonEnv.auth`. */\n auth?: Auth;\n /**\n * Neon Data API integration (GA). Static — drives `NeonEnv.dataApi`. A boolean/toggle, or\n * a {@link DataApiConfig} object selecting the auth provider (`\"neon\"` / `\"external\"`) and\n * runtime {@link DataApiSettings}. With `authProvider: \"neon\"` the policy must also enable\n * top-level `auth`.\n */\n dataApi?: DataApi;\n /** Beta (Preview) feature set: AI Gateway, functions, buckets. Static. */\n preview?: Preview;\n /** Per-branch tuning closure. Cannot change the static existential set. */\n branch?: BranchTuningFn<Preview>;\n}\n/**\n * A function with all deploy defaults applied. `resolveConfig` fills in `runtime` so\n * downstream diff/apply never has to re-derive it.\n */\ninterface ResolvedFunctionConfig {\n slug: string;\n name: string;\n source: string;\n env: Record<string, string>;\n /**\n * Packages the bundler leaves unresolved, passed through from\n * {@link FunctionDef.externalPackages}. Absent rather than empty when undeclared, so a\n * policy that never mentions it resolves to the same shape it always did.\n */\n externalPackages?: string[];\n runtime: FunctionRuntime;\n /**\n * Local-development settings, passed through untouched from {@link FunctionDef.dev}\n * (no defaults applied). Only consumed by `neon dev`; deploy ignores it.\n */\n dev?: FunctionDevConfig;\n}\n/** A bucket with its access level defaulted to `private`. */\ninterface ResolvedBucketConfig {\n name: string;\n access: BucketAccessLevel;\n}\n/**\n * Normalized {@link PreviewInput}. Only present on {@link ResolvedBranchConfig} when the\n * policy returned a `preview` block. `aiGatewayEnabled` follows the same\n * \"present-and-not-`false`\" semantics as `authEnabled` / `dataApiEnabled`.\n */\ninterface ResolvedPreviewConfig {\n functions: ResolvedFunctionConfig[];\n buckets: ResolvedBucketConfig[];\n aiGatewayEnabled: boolean;\n}\n/**\n * Normalized Data API integration. Present on {@link ResolvedBranchConfig} only when the\n * policy enables `dataApi`. `authProvider` always resolves (defaults to `\"neon\"`); the\n * external-IdP wiring is present only for `\"external\"`; `settings` carries the camelCase\n * runtime settings (reconciled as an update when they drift).\n */\ninterface ResolvedDataApiConfig {\n authProvider: DataApiAuthProvider;\n jwksUrl?: string;\n providerName?: string;\n jwtAudience?: string;\n settings?: DataApiSettings;\n}\ninterface ResolvedBranchConfig {\n parent?: string;\n ttlSeconds?: number;\n protected?: boolean;\n postgres?: PostgresConfig;\n authEnabled: boolean;\n dataApiEnabled: boolean;\n /**\n * Resolved Data API integration. Present iff {@link dataApiEnabled} is `true`. Carries the\n * create-time auth wiring and the updatable {@link DataApiSettings}.\n */\n dataApi?: ResolvedDataApiConfig;\n preview?: ResolvedPreviewConfig;\n}\n/**\n * One concrete change `pushConfig` made (or, in dry-run, would make) on the remote.\n */\ninterface AppliedChange {\n /**\n * `service` covers branch-scoped integrations driven by the branch policy (e.g.\n * Neon Auth, Data API).\n */\n kind: \"branch\" | \"service\";\n action: \"create\" | \"update\" | \"noop\";\n identifier: string;\n details?: Record<string, unknown>;\n}\n/**\n * A diff entry that conflicts with the desired config. `pushConfig` throws\n * {@link PushConflictError} on the first call when conflicts exist; pass\n * `updateExisting: true` to apply mutable drift (settings, `protected`, TTL, project\n * rename). Immutable fields (region, Postgres major version) are always conflicts —\n * recreate the project to change them.\n */\ninterface ConflictReport {\n kind: \"branch\";\n identifier: string;\n field: string;\n current: unknown;\n desired: unknown;\n reason: string;\n}\n/**\n * Result of a `pushConfig` invocation.\n */\ninterface PushResult {\n projectId: string;\n orgId?: string;\n branchId: string;\n branchName: string;\n /**\n * `true` when `pushConfig` was called with `{ dryRun: true }`. `applied` then records\n * what **would** be applied on a real push; no API mutations were performed.\n */\n dryRun: boolean;\n applied: AppliedChange[];\n conflicts: ConflictReport[];\n}\n//#endregion\nexport { AppliedChange, BranchTarget, BranchTuning, BranchTuningFn, BucketAccessLevel, BucketDef, ComputeSettings, ComputeUnit, Config, ConflictReport, CredentialPrincipalType, CredentialScope, DATA_API_AUTH_PROVIDERS, DataApiAuthProvider, DataApiConfig, DataApiExternalAuthConfig, DataApiInput, DataApiNeonAuthConfig, DataApiSettings, DurationString, DurationUnit, FunctionDef, FunctionDevConfig, FunctionRuntime, FunctionTuning, PostgresConfig, PreviewInput, PreviewTuning, PushResult, ResolvedBranchConfig, ResolvedBucketConfig, ResolvedDataApiConfig, ResolvedFunctionConfig, ResolvedPreviewConfig, ServiceEnabled, ServiceToggle, ServiceToggleInput };\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;A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;;;;;KAcHG,eAAAA;;;;;;KAMAC,uBAAAA;;KAEAC,iBAAAA;;;;;;UAMKC,SAAAA;;;;;WAKCD;;;;;;;;UAQDE,YAAAA;;cAEIpB;;cAEAe,eAAeD;;YAEjBC,eAAeI;;;;;;;;UAQjBE,cAAAA;;YAEET;;;;;;;UAOFU;cACIE,QAAQT,OAAOQ,MAAMF;;;;;;;;UAQzBI;;;;;;;;;;;;;;;;;;;;;;;;;QAyBF/B,cAAcD;;;aAGTU;YACDmB,cAAcC;;;KAGrBG,gCAAgCN,4BAA4BO;;IAE7DE,cAAcD;;;;;KAKbE,+BAA+BV,2BAA2BA,qCAAqCtB,iBAAiB2B,aAAaC,gBAAgBC;;;;;;;;;;;;;;UAcxII,oBAAoB/B,iCAAiCA,gDAAgDW,2BAA2BA,0CAA0CS,2BAA2BA;;SAEtMY;;;;;;;YAOGC;;YAEAN;;WAEDG,eAAeH;;;;;;UAMhBO,sBAAAA;;;;OAIHnB;;;;;;;WAOIH;;;;;QAKHC;;;UAGEsB,oBAAAA;;UAEAjB;;;;;;;UAOAkB,qBAAAA;aACGF;WACFC;;;;;;;;;UASDE,qBAAAA;gBACMhC;;;;aAIHC;;UAEHgC,oBAAAA;;;;aAIGnC;;;;;;;YAODkC;YACAD"}
1
+ {"version":3,"file":"types.d.ts","names":["ComputeUnit","DurationUnit","DurationString","SuspendTimeoutSuggestion","TtlSuggestion","DurationField","Suggestions","NonNullable","ComputeSettings","BranchTarget","ServiceToggle","ServiceToggleInput","ServiceEnabled","T","PostgresConfig","DATA_API_AUTH_PROVIDERS","DataApiAuthProvider","DataApiSettings","DataApiConfigBase","DataApiNeonAuthConfig","DataApiExternalAuthConfig","DataApiConfig","DataApiInput","FunctionRuntime","FunctionDevConfig","FunctionDef","Record","CredentialScope","CredentialPrincipalType","BucketAccessLevel","BucketDef","PreviewInput","FunctionTuning","PreviewTuning","Slug","Partial","BranchTuning","FunctionSlugsOf","Preview","F","Extract","BranchTuningFn","Config","Auth","DataApi","ResolvedFunctionConfig","ResolvedBucketConfig","ResolvedPreviewConfig","ResolvedDataApiConfig","ResolvedBranchConfig","AppliedChange","ConflictReport","PushResult"],"sources":["../../../../../config/dist/lib/types.d.ts"],"sourcesContent":["//#region src/lib/types.d.ts\n/**\n * Valid Neon Compute Unit values.\n * Most plans support 0.25, 0.5, 1, 2, 4, 8. Higher values may be available on Business plans.\n */\ntype ComputeUnit = 0.25 | 0.5 | 1 | 2 | 4 | 8;\n/** Time units accepted in a {@link DurationString}: seconds, minutes, hours, days, weeks. */\ntype DurationUnit = \"s\" | \"m\" | \"h\" | \"d\" | \"w\";\n/**\n * A Neon duration string: a positive integer **followed by a unit** — `s` (seconds),\n * `m` (minutes), `h` (hours), `d` (days), or `w` (weeks). Used by\n * {@link ComputeSettings.suspendTimeout} and {@link BranchTuning.ttl}.\n *\n * A **unit is required**: a bare numeric string like `\"7\"` is rejected at the type level. To\n * express a raw number of seconds, pass a `number` (`300`) — not a string (`\"300\"`). This\n * removes the old ambiguity where `\"7\"` silently meant 7 *seconds* instead of, say, `\"7d\"`.\n *\n * @example \"5m\" // 5 minutes\n * @example \"1h\" // 1 hour\n * @example \"7d\" // 7 days\n */\ntype DurationString = `${number}${DurationUnit}`;\n/**\n * Autocomplete suggestions for {@link ComputeSettings.suspendTimeout}. Every value sits inside\n * the Neon API's allowed scale-to-zero band: **60s–604800s** (1 minute – 1 week). This is *not*\n * a closed set — the field also accepts any other {@link DurationString} or a `number` of\n * seconds; out-of-range values type-check but are rejected at apply time.\n */\ntype SuspendTimeoutSuggestion = \"1m\" | \"5m\" | \"15m\" | \"30m\" | \"1h\" | \"6h\" | \"12h\" | \"1d\" | \"7d\";\n/**\n * Autocomplete suggestions for {@link BranchTuning.ttl}. Every value sits within the Neon API's\n * branch-expiration limit (**max 30 days** from creation; the Console's own presets are 1h / 1d\n * / 7d). This is *not* a closed set — the field also accepts any other {@link DurationString} or\n * a `number` of seconds; values over 30 days are rejected at apply time.\n */\ntype TtlSuggestion = \"1h\" | \"6h\" | \"12h\" | \"1d\" | \"3d\" | \"7d\" | \"14d\" | \"30d\";\n/**\n * Compose a field's duration type: its curated autocomplete `Suggestions` plus the open\n * `DurationString` template (so any `<integer><unit>` string still type-checks) and a `number`\n * of seconds. Intersecting the template arm with `NonNullable<unknown>` stops TypeScript from\n * collapsing the literal suggestions into the template, which is what preserves the autocomplete.\n */\ntype DurationField<Suggestions extends DurationString> = Suggestions | (DurationString & NonNullable<unknown>) | number;\n/**\n * Compute settings applied to the read/write endpoint of a branch.\n *\n * Mirrors the subset of {@link https://api-docs.neon.tech/reference/getting-started-with-neon-api Neon endpoint}\n * fields that we expose as IaC primitives. Anything left undefined falls back to the project's\n * `default_endpoint_settings` (which themselves fall back to Neon defaults).\n */\ninterface ComputeSettings {\n /**\n * Minimum number of Compute Units. Set to 0.25 for true scale-to-zero.\n * @example 0.25 // scale-to-zero\n * @example 1 // always-on with 1 CU minimum\n */\n autoscalingLimitMinCu?: ComputeUnit;\n /**\n * Maximum number of Compute Units for autoscaling.\n * @example 2\n * @example 8\n */\n autoscalingLimitMaxCu?: ComputeUnit;\n /**\n * How long an idle compute waits before suspending (Neon's scale-to-zero). Accepts a\n * {@link DurationString} (autocompletes common values), a number of seconds, or `false`.\n *\n * - `false` — never suspend (always-on compute)\n * - {@link DurationString} — e.g. `\"5m\"`; autocompletes the in-range values `\"1m\"`, `\"5m\"`,\n * `\"15m\"`, `\"30m\"`, `\"1h\"`, `\"6h\"`, `\"12h\"`, `\"1d\"`, `\"7d\"`, and accepts any other\n * `<integer><unit>` (units: `s`, `m`, `h`, `d`, `w`). A **unit is required** — for raw\n * seconds pass a `number`, not a string.\n * - `number` — custom timeout in **seconds**, must be in `60`–`604800` (1 minute to 1 week)\n * - `undefined` — use the Neon default (currently 300s / 5 minutes)\n *\n * Whichever form you use, the resolved timeout must fall in `60`–`604800` seconds (the Neon\n * API limit); the suggestions are all within that band, anything else is checked at apply.\n *\n * @example false // never suspend (always-on)\n * @example \"5m\" // suspend after 5 minutes idle\n * @example \"1h\" // suspend after 1 hour idle\n * @example 300 // 5 minutes, expressed in seconds\n */\n suspendTimeout?: false | DurationField<SuspendTimeoutSuggestion>;\n}\n/**\n * Read-only descriptor of the branch a {@link Config} policy is being evaluated for — the\n * `branch` argument passed to your `defineConfig({ branch: (branch) => … })` closure. It describes\n * **which** branch this invocation decides for; it is not a live branch handle and must not\n * be mutated. Switch on its fields and return the desired {@link BranchConfig}.\n */\ninterface BranchTarget {\n /** Branch name being evaluated. For `branch dev`, this is the generated branch name. */\n name: string;\n /** Neon branch id when the branch already exists. Undefined during pre-create eval. */\n id?: string;\n /** Whether this branch already exists on Neon. */\n exists: boolean;\n /** Parent branch id from Neon when known. */\n parentId?: string;\n /** Whether Neon marks this branch as the project default. */\n isDefault?: boolean;\n /** Whether Neon currently marks this branch protected. */\n isProtected?: boolean;\n /** Current expiration timestamp from Neon, when set. */\n expiresAt?: string;\n}\n/**\n * Object form of a branch-scoped service toggle. `{}` or `{ enabled: true }` enables it;\n * `{ enabled: false }` opts out. Used as the object half of {@link ServiceToggleInput}.\n */\ninterface ServiceToggle {\n /** Defaults to `true` when the service namespace is present. Set `false` to opt out. */\n enabled?: boolean;\n}\n/**\n * How a branch-scoped service (Neon Auth, Data API, AI Gateway) is toggled in a policy.\n *\n * - `true` / `{}` / `{ enabled: true }` — enabled.\n * - `false` / `{ enabled: false }` — disabled.\n * - omitted (`undefined`) — not part of the policy at all.\n *\n * These toggles are **static** (they live in the top-level `defineConfig({ … })` object,\n * not in the per-branch `branch` closure) so the secret set they imply can be derived at\n * the type level — that's what makes `NeonEnv<typeof config>` exact.\n */\ntype ServiceToggleInput = boolean | ServiceToggle;\n/**\n * Resolve a **static** service toggle (`true` / `false` / `{ enabled?: boolean }` / object /\n * `undefined`) to a type-level boolean. The tuple wrapping (`[T] extends […]`) disables\n * distribution so a union/`undefined` is judged as a single 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 | … | undefined` (no literal info) → `false`\n *\n * Shared by the {@link Config} static cross-field checks and the `@neon/env`\n * `NeonEnv` namespace derivation, so both read \"is this service on?\" identically.\n */\ntype ServiceEnabled<T> = [T] extends [false] ? false : [T] extends [{\n enabled: false;\n}] ? false : [T] extends [undefined] ? false : [T] extends [true] ? true : [T] extends [{\n enabled: true;\n}] ? true : [T] extends [object] ? true : false;\ninterface PostgresConfig {\n computeSettings?: ComputeSettings;\n}\n/**\n * Authentication providers a Data API integration can verify JWTs against, as written in\n * `neon.ts`. Friendly authoring values (mapped to the Neon API's `neon_auth` / `external`\n * at the API boundary):\n *\n * - `\"neon\"` — verify tokens minted by **Neon Auth** on the same branch. Neon supplies the\n * JWKS URL / provider wiring for you, so the `jwksUrl` / `providerName` / `jwtAudience`\n * fields are forbidden (a type error) on this variant — and the policy must also enable\n * top-level `auth` (Neon Auth) so the tokens exist.\n * - `\"external\"` — verify tokens from a third-party IdP (Clerk, Stytch, Auth0, …). You\n * provide `jwksUrl` (and optionally `providerName` / `jwtAudience`).\n */\ndeclare const DATA_API_AUTH_PROVIDERS: readonly [\"neon\", \"external\"];\ntype DataApiAuthProvider = (typeof DATA_API_AUTH_PROVIDERS)[number];\n/**\n * Reusable runtime settings for a Data API integration (the Neon API `DataAPISettings`,\n * camelCased to match the rest of `neon.ts`). Every field is optional; omitted fields keep\n * the Neon defaults shown below. These are the **only** Data API fields that can change on\n * an already-enabled integration — drift here is reconciled as an *update* (requires\n * `updateExisting` / `--update-existing`); the create-only auth wiring above cannot.\n */\ninterface DataApiSettings {\n /** Enable the aggregates feature (`db_aggregates_enabled`). Default `true`. */\n dbAggregatesEnabled?: boolean;\n /** Database role used for anonymous requests (`db_anon_role`). Default `\"anonymous\"`. */\n dbAnonRole?: string;\n /** Extra schemas appended to the search path (`db_extra_search_path`). */\n dbExtraSearchPath?: string;\n /** Maximum rows returned in a single request (`db_max_rows`). */\n dbMaxRows?: number;\n /** Schemas exposed via the API (`db_schemas`). Default `[\"public\"]`. */\n dbSchemas?: string[];\n /** JWT claim key used for role extraction (`jwt_role_claim_key`). Default `\".role\"`. */\n jwtRoleClaimKey?: string;\n /** Maximum lifetime of the JWT cache, in seconds (`jwt_cache_max_lifetime`). */\n jwtCacheMaxLifetime?: number;\n /** OpenAPI spec mode (`openapi_mode`). Default `\"disabled\"`. */\n openapiMode?: \"ignore-privileges\" | \"disabled\";\n /** CORS allowed origins (`server_cors_allowed_origins`). */\n serverCorsAllowedOrigins?: string;\n /** Emit server-timing headers (`server_timing_enabled`). */\n serverTimingEnabled?: boolean;\n}\n/** Fields shared by every {@link DataApiConfig} variant. */\ninterface DataApiConfigBase {\n /** Defaults to `true` when the `dataApi` namespace is present. Set `false` to opt out. */\n enabled?: boolean;\n /** Reusable runtime settings. Drift here is reconciled as an update. */\n settings?: DataApiSettings;\n}\n/**\n * Data API verified by **Neon Auth** (`authProvider: \"neon\"`, the default). The external\n * IdP fields are statically forbidden (`?: never`) because Neon supplies them; declaring any\n * of them is a type error directing you to `authProvider: \"external\"`.\n */\ninterface DataApiNeonAuthConfig extends DataApiConfigBase {\n authProvider?: \"neon\";\n /** Forbidden with `authProvider: \"neon\"` — Neon provides the JWKS URL. */\n jwksUrl?: never;\n /** Forbidden with `authProvider: \"neon\"` — the provider is Neon Auth. */\n providerName?: never;\n /** Forbidden with `authProvider: \"neon\"` — Neon manages the audience. */\n jwtAudience?: never;\n}\n/**\n * Data API verified by an **external** IdP (`authProvider: \"external\"`). You provide the\n * JWKS URL (and optionally a provider label / expected audience).\n */\ninterface DataApiExternalAuthConfig extends DataApiConfigBase {\n authProvider: \"external\";\n /** URL that publishes the IdP's JWKS (JSON Web Key Set). */\n jwksUrl?: string;\n /** Human label for the IdP (e.g. \"Clerk\", \"Stytch\", \"Auth0\"). */\n providerName?: string;\n /**\n * Expected `aud` claim. ⚠️ This only **rejects** tokens carrying a *different* audience;\n * tokens with no `aud` claim are still accepted.\n */\n jwtAudience?: string;\n}\n/**\n * Object form of the `dataApi` toggle. A discriminated union on {@link DataApiAuthProvider}:\n * the `\"neon\"` variant forbids the external-IdP fields, the `\"external\"` variant allows them.\n */\ntype DataApiConfig = DataApiNeonAuthConfig | DataApiExternalAuthConfig;\n/**\n * How the Data API is toggled in a policy: a bare boolean (like the other service toggles)\n * or the richer {@link DataApiConfig} object. `true` / `{}` / `{ enabled: true }` enable it\n * with Neon defaults; `false` / `{ enabled: false }` opt out.\n */\ntype DataApiInput = boolean | DataApiConfig;\n/**\n * Supported function runtimes. Mirrors the Neon Functions deploy API `runtime` enum.\n * Only `nodejs24` exists today; kept as a union so adding runtimes later is a\n * non-breaking, type-checked change.\n */\ntype FunctionRuntime = \"nodejs24\";\n/**\n * Local-development settings for a function, used by `neon dev` when it serves every\n * function declared in `neon.ts` (i.e. invoked with no `--source`). Never affects deploy.\n */\ninterface FunctionDevConfig {\n /**\n * Port the local server binds. Bound exactly (and `neon dev` fails loudly if it is taken)\n * when set; a free port is found automatically when omitted.\n */\n port?: number;\n}\n/**\n * Static definition of a Neon Function (Preview feature). Declares that the function\n * **exists** on every branch; its branch-unique slug is the **record key** in\n * {@link PreviewInput.functions} (not a field here), so slugs are statically enumerable,\n * cannot duplicate, and the `branch` closure can only tune slugs that are declared here.\n *\n * A function is invoked like a Cloudflare/Vercel handler — its source module\n * `export default { fetch }` or `export async function handler(req): Response`. The\n * `source` path is bundled (esbuild) and uploaded as a deployment; the newest deployment\n * becomes active.\n *\n * Runtime tuning is **not** here — it varies per branch and lives in the `branch` closure\n * (see {@link FunctionTuning}). Memory is fixed by the platform policy for now and is not\n * user-configurable.\n */\ninterface FunctionDef {\n /** Free-form display name. @example \"Hello World\" */\n name: string;\n /**\n * Path to the function's entry module, **relative to `neon.ts`** (or absolute). The\n * module's default export (`{ fetch }`) or `handler` export is the function entry. This\n * path is resolved against the loaded `neon.ts` location and bundled with esbuild at\n * deploy time.\n *\n * We require a string path rather than an imported handler because a JS function value\n * carries no reference back to its source file, so esbuild has nothing to bundle from.\n * @example \"./functions/hello-world.ts\"\n */\n source: string;\n /**\n * Environment variables injected into the deployed function, keyed by the var name the\n * function reads at runtime. The **keys** are static (preserved at the type level so\n * `parseEnv(config, \"<slug>\").function.<key>` is typed); the **values** are arbitrary\n * strings evaluated when `neon.ts` is loaded (typically `process.env.X`) and uploaded\n * at `config apply`. Every value must be a defined string — a `process.env.X` that is\n * `undefined` (unset) errors at validation time rather than silently shipping\n * `undefined`.\n * @example { resendApiKey: process.env.RESEND_API_KEY ?? \"\" }\n */\n env?: Record<string, string>;\n /**\n * Packages the bundler must leave alone, by name — the deploy-time equivalent of\n * Next.js's `serverExternalPackages`. Every entry is passed to esbuild's `external`,\n * so the import survives into the bundle instead of being followed.\n *\n * Reach for this when bundling a package is impossible rather than merely undesirable.\n * The cases that come up: a native `.node` addon or a `node-gyp` dependency esbuild has\n * no loader for, and an optional peer dependency a library references on a code path\n * this function never takes. Both fail the deploy at bundle time with a resolve or\n * loader error naming the package, and neither is fixable from the function's own\n * source.\n *\n * **An external package is not resolvable at runtime.** The deployed archive is a\n * single `index.mjs` with no `node_modules` beside it, so anything listed here throws\n * `Cannot find module` if the function actually reaches it. This option therefore only\n * unblocks an import that is never evaluated; it does not make a dependency usable.\n *\n * A dependency the handler actually calls has to be bundled, and whether that is\n * possible depends on what it is. A pure-JavaScript package can be bundled, and a\n * failure to do so is usually something specific and fixable. A package backed by a\n * native `.node` binary cannot be bundled by anything — the binary is a compiled\n * object the platform loads from a real path — so such a package cannot work on\n * Functions until the deployed archive can carry files alongside the bundle. Do not\n * reach for `externalPackages` to try: it moves the error from deploy to invoke.\n *\n * Note that a native package may bundle without ever needing this option. `sharp`, for\n * instance, loads its binary through `createRequire`, which esbuild does not follow, so\n * it bundles cleanly and then fails at invoke with \"Could not load the sharp module\".\n *\n * Entries are package names, optionally with a subpath (`pkg`, `@scope/pkg`,\n * `pkg/sub`), matching esbuild. A relative or absolute path is rejected at validation\n * time: those are local modules, and a local module that cannot be bundled is a\n * different problem.\n * @example [\"microsandbox\", \"@mongodb-js/zstd\"]\n */\n externalPackages?: string[];\n /**\n * Local-development settings used by `neon dev` when serving every function from\n * `neon.ts`. Ignored at deploy time. See {@link FunctionDevConfig}.\n */\n dev?: FunctionDevConfig;\n}\n/**\n * A single capability a branch-scoped service credential may exercise (Preview). A\n * credential is granted a set of these and may only perform the listed actions. Mirrors\n * the Neon API `CredentialScope` enum (`x-stability-level: beta`):\n *\n * - `storage:read` / `storage:write` — object-storage (bucket) access via the S3 key.\n * - `ai_gateway:invoke` — call the AI Gateway with the bearer `api_token`.\n * - `functions:invoke` — invoke Neon Functions with the bearer `api_token`.\n *\n * The set a policy needs is derived from its enabled Preview features (see\n * {@link deriveCredentialScopes}); it is never authored by hand.\n */\ntype CredentialScope = \"storage:read\" | \"storage:write\" | \"ai_gateway:invoke\" | \"functions:invoke\";\n/**\n * Who a credential acts as. `user` is the developer/app principal minted for local dev and\n * app bootstrap (`fetchEnv` / `env pull`); `function` is a deployed-function principal\n * (carries a `function_id`). The env tooling only mints `user` credentials today.\n */\ntype CredentialPrincipalType = \"user\" | \"function\";\n/** Anonymous-access level for a branchable object-storage bucket. */\ntype BucketAccessLevel = \"private\" | \"public_read\";\n/**\n * Static definition of a branchable object-storage bucket (Preview feature). The bucket's\n * name is the **record key** in {@link PreviewInput.buckets}, so names are statically\n * enumerable and cannot duplicate.\n */\ninterface BucketDef {\n /**\n * Anonymous access level. `private` (default) requires authenticated reads/writes;\n * `public_read` allows anonymous GetObject/HeadObject.\n */\n access?: BucketAccessLevel;\n}\n/**\n * Static, branch-scoped **Preview** features. Grouped under `preview` to signal they are\n * backed by Neon `x-stability-level: beta` endpoints and may change before GA. Everything\n * here is existential (it determines what exists on the branch); per-branch tuning lives in\n * the `branch` closure.\n */\ninterface PreviewInput {\n /** Enable/disable the AI Gateway on the branch (toggle, like auth / dataApi). */\n aiGateway?: ServiceToggleInput;\n /** Functions to deploy, keyed by branch-unique slug (`^[a-z0-9]{1,20}$`). */\n functions?: Record<string, FunctionDef>;\n /** Object-storage buckets to create, keyed by bucket name. */\n buckets?: Record<string, BucketDef>;\n}\n/**\n * Per-branch deploy tuning for a single function. Returned (per slug) by the `branch`\n * closure. Deliberately **cannot** change the function's existence, source, name, env\n * **keys**, or memory — only runtime selection is currently configurable — so the static\n * secret/function set stays sound.\n */\ninterface FunctionTuning {\n /** Runtime to execute the function with. Defaults to `\"nodejs24\"`. */\n runtime?: FunctionRuntime;\n}\n/**\n * Per-branch tuning of Preview features. Only existing function slugs (those declared in\n * the static {@link PreviewInput.functions}) may be tuned — `Slug` is constrained to the\n * declared keys by {@link BranchTuningFn}.\n */\ninterface PreviewTuning<Slug extends string = string> {\n functions?: Partial<Record<Slug, FunctionTuning>>;\n}\n/**\n * The per-branch tuning object returned by the `branch` closure. It can adjust branch\n * lifecycle (`parent`, `ttl`, `protected`), Postgres compute settings, and per-function\n * deploy tuning — but **cannot** add/remove services or functions. That guarantee is what\n * keeps the static secret set (and therefore `NeonEnv`) exact.\n */\ninterface BranchTuning<Slug extends string = string> {\n /** Parent branch name used when creating a new branch. Not a Postgres setting. */\n parent?: string;\n /**\n * Branch time-to-live: how long after creation the branch should auto-expire. Applied\n * when creating a new branch and reconciled on existing branches (when `updateExisting`\n * is set). Accepts a {@link DurationString} (autocompletes common values) or a number of\n * seconds. Omit to keep the branch indefinitely.\n *\n * - {@link DurationString} — e.g. `\"7d\"`; autocompletes `\"1h\"`, `\"6h\"`, `\"12h\"`, `\"1d\"`,\n * `\"3d\"`, `\"7d\"`, `\"14d\"`, `\"30d\"`, and accepts any other `<integer><unit>` (units: `s`,\n * `m`, `h`, `d`, `w` — e.g. `\"12h\"`, `\"2w\"`). A **unit is required** — `\"7\"` is rejected;\n * for raw seconds pass a `number`.\n * - `number` — custom TTL in **seconds** (e.g. `3600`)\n * - `undefined` — no expiry; the branch persists until explicitly deleted\n *\n * The Neon API caps branch expiration at **30 days** from creation, so the resolved TTL must\n * be `> 0` and `<= 30d`; the suggestions stay within that limit and anything longer is\n * rejected at apply.\n *\n * @example \"1d\" // ephemeral preview branch: expires a day after creation\n * @example \"7d\" // one-week TTL\n * @example \"30d\" // the maximum the API allows\n * @example 3600 // 1 hour, expressed in seconds\n */\n ttl?: DurationField<TtlSuggestion>;\n /** Whether the selected branch should be protected. Undefined means \"leave as-is\". */\n protected?: boolean;\n postgres?: PostgresConfig;\n preview?: PreviewTuning<Slug>;\n}\n/** Extract the declared function slugs from a {@link PreviewInput} for closure typing. */\ntype FunctionSlugsOf<Preview extends PreviewInput | undefined> = Preview extends {\n functions: infer F;\n} ? Extract<keyof F, string> : string;\n/**\n * Signature of the `branch` closure. Generic over the static {@link PreviewInput} so the\n * `preview.functions` keys it may tune are constrained to the slugs actually declared.\n */\ntype BranchTuningFn<Preview extends PreviewInput | undefined = PreviewInput | undefined> = (branch: BranchTarget) => BranchTuning<FunctionSlugsOf<Preview>>;\n/**\n * A validated Neon branch policy — the value `defineConfig({ … })` returns and `neon.ts`\n * default-exports.\n *\n * Split into a **static** existential set (top-level `auth` / `dataApi` GA toggles plus the\n * beta `preview` block) and a **dynamic** per-branch `branch` closure for tuning. The\n * static half is what makes the secret set — and therefore `NeonEnv<typeof config>` and\n * `parseEnv` — exact; the closure can tune but never change what exists.\n *\n * Generic over the three static fields so the type system can read the exact toggle/slug\n * literals; the defaults make the bare `Config` a usable \"any policy\" type for runtime\n * function signatures.\n */\ninterface Config<Auth extends ServiceToggleInput | undefined = ServiceToggleInput | undefined, DataApi extends DataApiInput | undefined = DataApiInput | undefined, Preview extends PreviewInput | undefined = PreviewInput | undefined> {\n /** Neon Auth integration toggle (GA). Static — drives `NeonEnv.auth`. */\n auth?: Auth;\n /**\n * Neon Data API integration (GA). Static — drives `NeonEnv.dataApi`. A boolean/toggle, or\n * a {@link DataApiConfig} object selecting the auth provider (`\"neon\"` / `\"external\"`) and\n * runtime {@link DataApiSettings}. With `authProvider: \"neon\"` the policy must also enable\n * top-level `auth`.\n */\n dataApi?: DataApi;\n /** Beta (Preview) feature set: AI Gateway, functions, buckets. Static. */\n preview?: Preview;\n /** Per-branch tuning closure. Cannot change the static existential set. */\n branch?: BranchTuningFn<Preview>;\n}\n/**\n * A function with all deploy defaults applied. `resolveConfig` fills in `runtime` so\n * downstream diff/apply never has to re-derive it.\n */\ninterface ResolvedFunctionConfig {\n slug: string;\n name: string;\n source: string;\n env: Record<string, string>;\n /**\n * Packages the bundler leaves unresolved, passed through from\n * {@link FunctionDef.externalPackages}. Absent rather than empty when undeclared, so a\n * policy that never mentions it resolves to the same shape it always did.\n */\n externalPackages?: string[];\n runtime: FunctionRuntime;\n /**\n * Local-development settings, passed through untouched from {@link FunctionDef.dev}\n * (no defaults applied). Only consumed by `neon dev`; deploy ignores it.\n */\n dev?: FunctionDevConfig;\n}\n/** A bucket with its access level defaulted to `private`. */\ninterface ResolvedBucketConfig {\n name: string;\n access: BucketAccessLevel;\n}\n/**\n * Normalized {@link PreviewInput}. Only present on {@link ResolvedBranchConfig} when the\n * policy returned a `preview` block. `aiGatewayEnabled` follows the same\n * \"present-and-not-`false`\" semantics as `authEnabled` / `dataApiEnabled`.\n */\ninterface ResolvedPreviewConfig {\n functions: ResolvedFunctionConfig[];\n buckets: ResolvedBucketConfig[];\n aiGatewayEnabled: boolean;\n}\n/**\n * Normalized Data API integration. Present on {@link ResolvedBranchConfig} only when the\n * policy enables `dataApi`. `authProvider` always resolves (defaults to `\"neon\"`); the\n * external-IdP wiring is present only for `\"external\"`; `settings` carries the camelCase\n * runtime settings (reconciled as an update when they drift).\n */\ninterface ResolvedDataApiConfig {\n authProvider: DataApiAuthProvider;\n jwksUrl?: string;\n providerName?: string;\n jwtAudience?: string;\n settings?: DataApiSettings;\n}\ninterface ResolvedBranchConfig {\n parent?: string;\n ttlSeconds?: number;\n protected?: boolean;\n postgres?: PostgresConfig;\n authEnabled: boolean;\n dataApiEnabled: boolean;\n /**\n * Resolved Data API integration. Present iff {@link dataApiEnabled} is `true`. Carries the\n * create-time auth wiring and the updatable {@link DataApiSettings}.\n */\n dataApi?: ResolvedDataApiConfig;\n preview?: ResolvedPreviewConfig;\n}\n/**\n * One concrete change `pushConfig` made (or, in dry-run, would make) on the remote.\n */\ninterface AppliedChange {\n /**\n * `service` covers branch-scoped integrations driven by the branch policy (e.g.\n * Neon Auth, Data API).\n */\n kind: \"branch\" | \"service\";\n action: \"create\" | \"update\" | \"noop\";\n identifier: string;\n details?: Record<string, unknown>;\n}\n/**\n * A diff entry that conflicts with the desired config. `pushConfig` throws\n * {@link PushConflictError} on the first call when conflicts exist; pass\n * `updateExisting: true` to apply mutable drift (settings, `protected`, TTL, project\n * rename). Immutable fields (region, Postgres major version) are always conflicts —\n * recreate the project to change them.\n */\ninterface ConflictReport {\n kind: \"branch\";\n identifier: string;\n field: string;\n current: unknown;\n desired: unknown;\n reason: string;\n}\n/**\n * Result of a `pushConfig` invocation.\n */\ninterface PushResult {\n projectId: string;\n orgId?: string;\n branchId: string;\n branchName: string;\n /**\n * `true` when `pushConfig` was called with `{ dryRun: true }`. `applied` then records\n * what **would** be applied on a real push; no API mutations were performed.\n */\n dryRun: boolean;\n applied: AppliedChange[];\n conflicts: ConflictReport[];\n}\n//#endregion\nexport { AppliedChange, BranchTarget, BranchTuning, BranchTuningFn, BucketAccessLevel, BucketDef, ComputeSettings, ComputeUnit, Config, ConflictReport, CredentialPrincipalType, CredentialScope, DATA_API_AUTH_PROVIDERS, DataApiAuthProvider, DataApiConfig, DataApiExternalAuthConfig, DataApiInput, DataApiNeonAuthConfig, DataApiSettings, DurationString, DurationUnit, FunctionDef, FunctionDevConfig, FunctionRuntime, FunctionTuning, PostgresConfig, PreviewInput, PreviewTuning, PushResult, ResolvedBranchConfig, ResolvedBucketConfig, ResolvedDataApiConfig, ResolvedFunctionConfig, ResolvedPreviewConfig, ServiceEnabled, ServiceToggle, ServiceToggleInput };\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;A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;;;;;KAcHG,eAAAA;;;;;;KAMAC,uBAAAA;;KAEAC,iBAAAA;;;;;;UAMKC,SAAAA;;;;;WAKCD;;;;;;;;UAQDE,YAAAA;;cAEIpB;;cAEAe,eAAeD;;YAEjBC,eAAeI;;;;;;;;UAQjBE,cAAAA;;YAEET;;;;;;;UAOFU;cACIE,QAAQT,OAAOQ,MAAMF;;;;;;;;UAQzBI;;;;;;;;;;;;;;;;;;;;;;;;;QAyBF/B,cAAcD;;;aAGTU;YACDmB,cAAcC;;;KAGrBG,gCAAgCN,4BAA4BO;;IAE7DE,cAAcD;;;;;KAKbE,+BAA+BV,2BAA2BA,qCAAqCtB,iBAAiB2B,aAAaC,gBAAgBC;;;;;;;;;;;;;;UAcxII,oBAAoB/B,iCAAiCA,gDAAgDW,2BAA2BA,0CAA0CS,2BAA2BA;;SAEtMY;;;;;;;YAOGC;;YAEAN;;WAEDG,eAAeH;;;;;;UAMhBO,sBAAAA;;;;OAIHnB;;;;;;;WAOIH;;;;;QAKHC;;;UAGEsB,oBAAAA;;UAEAjB;;;;;;;UAOAkB,qBAAAA;aACGF;WACFC;;;;;;;;;UASDE,qBAAAA;gBACMhC;;;;aAIHC;;UAEHgC,oBAAAA;;;;aAIGnC;;;;;;;YAODkC;YACAD"}
@@ -15,8 +15,8 @@ function resolveContext(options) {
15
15
  const projectId = nonEmpty(options.projectId) ?? nonEmpty(env.NEON_PROJECT_ID) ?? file?.projectId;
16
16
  const branch = nonEmpty(options.branch) ?? nonEmpty(env.NEON_BRANCH) ?? nonEmpty(env.NEON_BRANCH_ID) ?? file?.branch;
17
17
  const missing = [];
18
- if (!projectId) missing.push("project id — pass `--project-id`, set `NEON_PROJECT_ID`, or add `projectId` to `.neon` (run `npx neonctl link`).");
19
- if (!branch) missing.push("branch — pass `--branch`, set `NEON_BRANCH`/`NEON_BRANCH_ID`, or add `branch` to `.neon` (run `npx neonctl link` / `neonctl checkout <branch>`).");
18
+ if (!projectId) missing.push("project id — pass `--project-id`, set `NEON_PROJECT_ID`, or add `projectId` to `.neon` (run `npx neon link`).");
19
+ if (!branch) missing.push("branch — pass `--branch`, set `NEON_BRANCH`/`NEON_BRANCH_ID`, or add `branch` to `.neon` (run `npx neon link` / `neon checkout <branch>`).");
20
20
  if (!projectId || !branch) return {
21
21
  ok: false,
22
22
  missing
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-context.js","names":[],"sources":["../../../src/lib/cli/resolve-context.ts"],"sourcesContent":["import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, resolve } from \"node:path\";\n\n/**\n * Resolved project + branch context for the `neon-env` CLI. The CLI owns this resolution\n * (flags → `NEON_*` env → `.neon[/project.json]` file) so the `@neon/env` library\n * functions can stay filesystem- and env-agnostic.\n */\nexport interface ResolvedContext {\n\tprojectId: string;\n\t/** Branch ref — a name (preferred for readability) or an id (`br-…`). */\n\tbranch: string;\n}\n\nexport interface ResolveContextOptions {\n\tprojectId?: string;\n\tbranch?: string;\n\tcwd: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\n/**\n * Resolve `projectId` and `branch` for a CLI invocation. Precedence (each wins over the\n * next): explicit flag → `NEON_*` env var → `.neon[/project.json]` walked up from `cwd`.\n *\n * Returns the resolved values plus a list of human-readable reasons for any field that\n * could not be resolved (so the caller can render one combined error).\n */\nexport function resolveContext(\n\toptions: ResolveContextOptions,\n): { ok: true; context: ResolvedContext } | { ok: false; missing: string[] } {\n\tconst env = options.env ?? process.env;\n\tconst file = findNeonFile(options.cwd);\n\n\tconst projectId =\n\t\tnonEmpty(options.projectId) ??\n\t\tnonEmpty(env.NEON_PROJECT_ID) ??\n\t\tfile?.projectId;\n\n\t// A branch ref — name (preferred) or id. `NEON_BRANCH` carries the name; `NEON_BRANCH_ID`\n\t// is the legacy id-only var. The `.neon` file pins `branch` (name) via `neonctl link`,\n\t// with legacy `branchId` still honored. fetchEnv resolves either form by name or id.\n\tconst branch =\n\t\tnonEmpty(options.branch) ??\n\t\tnonEmpty(env.NEON_BRANCH) ??\n\t\tnonEmpty(env.NEON_BRANCH_ID) ??\n\t\tfile?.branch;\n\n\tconst missing: string[] = [];\n\tif (!projectId) {\n\t\tmissing.push(\n\t\t\t\"project id — pass `--project-id`, set `NEON_PROJECT_ID`, or add `projectId` to `.neon` (run `npx neonctl link`).\",\n\t\t);\n\t}\n\tif (!branch) {\n\t\tmissing.push(\n\t\t\t\"branch — pass `--branch`, set `NEON_BRANCH`/`NEON_BRANCH_ID`, or add `branch` to `.neon` (run `npx neonctl link` / `neonctl checkout <branch>`).\",\n\t\t);\n\t}\n\tif (!projectId || !branch) return { ok: false, missing };\n\n\treturn {\n\t\tok: true,\n\t\tcontext: { projectId, branch },\n\t};\n}\n\ninterface NeonFile {\n\tprojectId?: string;\n\t/** Branch ref — name (preferred) or id. Reads `branch`, falling back to legacy `branchId`. */\n\tbranch?: string;\n}\n\n/**\n * Walk up from `cwd` looking for `.neon/project.json` (preferred) or `.neon` (neonctl\n * convention). Stops at the first `.git` directory or the home directory. Read-only.\n */\nfunction findNeonFile(cwd: string): NeonFile | null {\n\tlet current = resolve(cwd);\n\tconst stop = resolve(homedir());\n\tlet lastSeen: string | null = null;\n\n\twhile (true) {\n\t\tconst parsed =\n\t\t\treadNeonFileAt(resolve(current, \".neon\", \"project.json\")) ??\n\t\t\treadNeonFileAt(resolve(current, \".neon\"));\n\t\tif (parsed) return parsed;\n\n\t\tif (current === stop) return null;\n\t\tif (existsSync(resolve(current, \".git\"))) return null;\n\n\t\tconst parent = dirname(current);\n\t\tif (parent === current || parent === lastSeen) return null;\n\t\tlastSeen = current;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction readNeonFileAt(path: string): NeonFile | null {\n\tif (!isFile(path)) return null;\n\tlet raw: string;\n\ttry {\n\t\traw = readFileSync(path, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\treturn null;\n\tconst obj = parsed as Record<string, unknown>;\n\tconst out: NeonFile = {};\n\tif (typeof obj.projectId === \"string\" && obj.projectId !== \"\")\n\t\tout.projectId = obj.projectId;\n\t// Prefer the `branch` field (name or id, written by `neonctl link`); fall back to the\n\t// legacy id-only `branchId`.\n\tconst branch =\n\t\ttypeof obj.branch === \"string\" && obj.branch !== \"\"\n\t\t\t? obj.branch\n\t\t\t: typeof obj.branchId === \"string\" && obj.branchId !== \"\"\n\t\t\t\t? obj.branchId\n\t\t\t\t: undefined;\n\tif (branch) out.branch = branch;\n\treturn out;\n}\n\nfunction isFile(path: string): boolean {\n\ttry {\n\t\treturn statSync(path).isFile();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? undefined : trimmed;\n}\n"],"mappings":";;;;;;;;;;;AA6BA,SAAgB,eACf,SAC4E;CAC5E,MAAM,MAAM,QAAQ,OAAO,QAAQ;CACnC,MAAM,OAAO,aAAa,QAAQ,GAAG;CAErC,MAAM,YACL,SAAS,QAAQ,SAAS,KAC1B,SAAS,IAAI,eAAe,KAC5B,MAAM;CAKP,MAAM,SACL,SAAS,QAAQ,MAAM,KACvB,SAAS,IAAI,WAAW,KACxB,SAAS,IAAI,cAAc,KAC3B,MAAM;CAEP,MAAM,UAAoB,CAAC;CAC3B,IAAI,CAAC,WACJ,QAAQ,KACP,kHACD;CAED,IAAI,CAAC,QACJ,QAAQ,KACP,kJACD;CAED,IAAI,CAAC,aAAa,CAAC,QAAQ,OAAO;EAAE,IAAI;EAAO;CAAQ;CAEvD,OAAO;EACN,IAAI;EACJ,SAAS;GAAE;GAAW;EAAO;CAC9B;AACD;;;;;AAYA,SAAS,aAAa,KAA8B;CACnD,IAAI,UAAU,QAAQ,GAAG;CACzB,MA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ACrC"}
1
+ {"version":3,"file":"resolve-context.js","names":[],"sources":["../../../src/lib/cli/resolve-context.ts"],"sourcesContent":["import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, resolve } from \"node:path\";\n\n/**\n * Resolved project + branch context for the `neon-env` CLI. The CLI owns this resolution\n * (flags → `NEON_*` env → `.neon[/project.json]` file) so the `@neon/env` library\n * functions can stay filesystem- and env-agnostic.\n */\nexport interface ResolvedContext {\n\tprojectId: string;\n\t/** Branch ref — a name (preferred for readability) or an id (`br-…`). */\n\tbranch: string;\n}\n\nexport interface ResolveContextOptions {\n\tprojectId?: string;\n\tbranch?: string;\n\tcwd: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\n/**\n * Resolve `projectId` and `branch` for a CLI invocation. Precedence (each wins over the\n * next): explicit flag → `NEON_*` env var → `.neon[/project.json]` walked up from `cwd`.\n *\n * Returns the resolved values plus a list of human-readable reasons for any field that\n * could not be resolved (so the caller can render one combined error).\n */\nexport function resolveContext(\n\toptions: ResolveContextOptions,\n): { ok: true; context: ResolvedContext } | { ok: false; missing: string[] } {\n\tconst env = options.env ?? process.env;\n\tconst file = findNeonFile(options.cwd);\n\n\tconst projectId =\n\t\tnonEmpty(options.projectId) ??\n\t\tnonEmpty(env.NEON_PROJECT_ID) ??\n\t\tfile?.projectId;\n\n\t// A branch ref — name (preferred) or id. `NEON_BRANCH` carries the name; `NEON_BRANCH_ID`\n\t// is the legacy id-only var. The `.neon` file pins `branch` (name) via `neonctl link`,\n\t// with legacy `branchId` still honored. fetchEnv resolves either form by name or id.\n\tconst branch =\n\t\tnonEmpty(options.branch) ??\n\t\tnonEmpty(env.NEON_BRANCH) ??\n\t\tnonEmpty(env.NEON_BRANCH_ID) ??\n\t\tfile?.branch;\n\n\tconst missing: string[] = [];\n\tif (!projectId) {\n\t\tmissing.push(\n\t\t\t\"project id — pass `--project-id`, set `NEON_PROJECT_ID`, or add `projectId` to `.neon` (run `npx neon link`).\",\n\t\t);\n\t}\n\tif (!branch) {\n\t\tmissing.push(\n\t\t\t\"branch — pass `--branch`, set `NEON_BRANCH`/`NEON_BRANCH_ID`, or add `branch` to `.neon` (run `npx neon link` / `neon checkout <branch>`).\",\n\t\t);\n\t}\n\tif (!projectId || !branch) return { ok: false, missing };\n\n\treturn {\n\t\tok: true,\n\t\tcontext: { projectId, branch },\n\t};\n}\n\ninterface NeonFile {\n\tprojectId?: string;\n\t/** Branch ref — name (preferred) or id. Reads `branch`, falling back to legacy `branchId`. */\n\tbranch?: string;\n}\n\n/**\n * Walk up from `cwd` looking for `.neon/project.json` (preferred) or `.neon` (neonctl\n * convention). Stops at the first `.git` directory or the home directory. Read-only.\n */\nfunction findNeonFile(cwd: string): NeonFile | null {\n\tlet current = resolve(cwd);\n\tconst stop = resolve(homedir());\n\tlet lastSeen: string | null = null;\n\n\twhile (true) {\n\t\tconst parsed =\n\t\t\treadNeonFileAt(resolve(current, \".neon\", \"project.json\")) ??\n\t\t\treadNeonFileAt(resolve(current, \".neon\"));\n\t\tif (parsed) return parsed;\n\n\t\tif (current === stop) return null;\n\t\tif (existsSync(resolve(current, \".git\"))) return null;\n\n\t\tconst parent = dirname(current);\n\t\tif (parent === current || parent === lastSeen) return null;\n\t\tlastSeen = current;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction readNeonFileAt(path: string): NeonFile | null {\n\tif (!isFile(path)) return null;\n\tlet raw: string;\n\ttry {\n\t\traw = readFileSync(path, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\treturn null;\n\tconst obj = parsed as Record<string, unknown>;\n\tconst out: NeonFile = {};\n\tif (typeof obj.projectId === \"string\" && obj.projectId !== \"\")\n\t\tout.projectId = obj.projectId;\n\t// Prefer the `branch` field (name or id, written by `neonctl link`); fall back to the\n\t// legacy id-only `branchId`.\n\tconst branch =\n\t\ttypeof obj.branch === \"string\" && obj.branch !== \"\"\n\t\t\t? obj.branch\n\t\t\t: typeof obj.branchId === \"string\" && obj.branchId !== \"\"\n\t\t\t\t? obj.branchId\n\t\t\t\t: undefined;\n\tif (branch) out.branch = branch;\n\treturn out;\n}\n\nfunction isFile(path: string): boolean {\n\ttry {\n\t\treturn statSync(path).isFile();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? undefined : trimmed;\n}\n"],"mappings":";;;;;;;;;;;AA6BA,SAAgB,eACf,SAC4E;CAC5E,MAAM,MAAM,QAAQ,OAAO,QAAQ;CACnC,MAAM,OAAO,aAAa,QAAQ,GAAG;CAErC,MAAM,YACL,SAAS,QAAQ,SAAS,KAC1B,SAAS,IAAI,eAAe,KAC5B,MAAM;CAKP,MAAM,SACL,SAAS,QAAQ,MAAM,KACvB,SAAS,IAAI,WAAW,KACxB,SAAS,IAAI,cAAc,KAC3B,MAAM;CAEP,MAAM,UAAoB,CAAC;CAC3B,IAAI,CAAC,WACJ,QAAQ,KACP,+GACD;CAED,IAAI,CAAC,QACJ,QAAQ,KACP,4IACD;CAED,IAAI,CAAC,aAAa,CAAC,QAAQ,OAAO;EAAE,IAAI;EAAO;CAAQ;CAEvD,OAAO;EACN,IAAI;EACJ,SAAS;GAAE;GAAW;EAAO;CAC9B;AACD;;;;;AAYA,SAAS,aAAa,KAA8B;CACnD,IAAI,UAAU,QAAQ,GAAG;CACzB,MAAM,OAAO,QAAQ,QAAQ,CAAC;CAC9B,IAAI,WAA0B;CAE9B,OAAO,MAAM;EACZ,MAAM,SACL,eAAe,QAAQ,SAAS,SAAS,cAAc,CAAC,KACxD,eAAe,QAAQ,SAAS,OAAO,CAAC;EACzC,IAAI,QAAQ,OAAO;EAEnB,IAAI,YAAY,MAAM,OAAO;EAC7B,IAAI,WAAW,QAAQ,SAAS,MAAM,CAAC,GAAG,OAAO;EAEjD,MAAM,SAAS,QAAQ,OAAO;EAC9B,IAAI,WAAW,WAAW,WAAW,UAAU,OAAO;EACtD,WAAW;EACX,UAAU;CACX;AACD;AAEA,SAAS,eAAe,MAA+B;CACtD,IAAI,CAAC,OAAO,IAAI,GAAG,OAAO;CAC1B,IAAI;CACJ,IAAI;EACH,MAAM,aAAa,MAAM,OAAO;CACjC,QAAQ;EACP,OAAO;CACR;CACA,IAAI;CACJ,IAAI;EACH,SAAS,KAAK,MAAM,GAAG;CACxB,QAAQ;EACP,OAAO;CACR;CACA,IAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GACxE,OAAO;CACR,MAAM,MAAM;CACZ,MAAM,MAAgB,CAAC;CACvB,IAAI,OAAO,IAAI,cAAc,YAAY,IAAI,cAAc,IAC1D,IAAI,YAAY,IAAI;CAGrB,MAAM,SACL,OAAO,IAAI,WAAW,YAAY,IAAI,WAAW,KAC9C,IAAI,SACJ,OAAO,IAAI,aAAa,YAAY,IAAI,aAAa,KACpD,IAAI,WACJ,KAAA;CACL,IAAI,QAAQ,IAAI,SAAS;CACzB,OAAO;AACR;AAEA,SAAS,OAAO,MAAuB;CACtC,IAAI;EACH,OAAO,SAAS,IAAI,CAAC,CAAC,OAAO;CAC9B,QAAQ;EACP,OAAO;CACR;AACD;AAEA,SAAS,SAAS,OAA+C;CAChE,IAAI,OAAO,UAAU,UAAU,OAAO,KAAA;CACtC,MAAM,UAAU,MAAM,KAAK;CAC3B,OAAO,YAAY,KAAK,KAAA,IAAY;AACrC"}
package/dist/lib/env.js CHANGED
@@ -120,7 +120,7 @@ async function fetchEnvKeys(config, options, keys) {
120
120
  if (Object.keys(postgres).length > 0) result.postgres = postgres;
121
121
  if (wants(K.branch.name)) result.branch = { name: branch.name };
122
122
  if (wantsAuth) {
123
- if (!authSnapshot) throw new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy enables auth but no Neon Auth integration is enabled on branch ${branch.name} (${branch.id}).`, "Enable it via `apply(config, { projectId, branchId })` (or `npx neonctl …`), in the Neon Console — then re-run fetchEnv. Or return auth.enabled=false."].join(" "), { details: {
123
+ if (!authSnapshot) throw new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy enables auth but no Neon Auth integration is enabled on branch ${branch.name} (${branch.id}).`, "Enable it via `apply(config, { projectId, branchId })` (or `npx neon …`), in the Neon Console — then re-run fetchEnv. Or return auth.enabled=false."].join(" "), { details: {
124
124
  projectId,
125
125
  branchId: branch.id
126
126
  } });
@@ -1 +1 @@
1
- {"version":3,"file":"env.js","names":[],"sources":["../../src/lib/env.ts"],"sourcesContent":["import {\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\ttype ServiceToggleInput,\n} from \"@neon/config/v1\";\nimport { z } from \"zod\";\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/** The static `preview.functions` record of a config, or an empty record when absent. */\ntype PreviewFunctionsOf<C extends Config> =\n\tNonNullable<C[\"preview\"]> extends {\n\t\tfunctions: infer F;\n\t}\n\t\t? F\n\t\t: Record<never, never>;\n\n/** The declared function slugs of a config (record keys), as a string union. */\nexport type FunctionSlugOf<C extends Config> = Extract<\n\tkeyof PreviewFunctionsOf<C>,\n\tstring\n>;\n\n/**\n * Human-readable hint surfaced as the **expected type** of `parseEnv`'s `scope` argument when\n * the policy declares no functions at all. Without it the argument's expected type is the bare\n * `never` {@link FunctionSlugOf} yields, and TypeScript reports the opaque `Type '\"x\"' is not\n * assignable to type 'never'`; the literal turns that into a sentence naming the fix (and the\n * editor offers it as the single completion, so the empty completion list is explained rather\n * than just empty). Mirrors `NeonAuthRequiredHint` in `@neon/config`.\n */\n// Exported (type-only) for the type tests in `env.test-d.ts`; intentionally not re-exported\n// from `index.ts`, so it stays an internal implementation detail.\nexport type NoFunctionScopeHint =\n\t\"this policy declares no `preview.functions`, so there is no function scope to read. Declare the function in `neon.ts` first, or omit the scope to read the branch env\";\n\n/**\n * The expected type of `parseEnv`'s function-slug `scope` argument: the caller's inferred slug\n * `S` normally, and the {@link NoFunctionScopeHint} message when the policy declares no\n * functions. Keeping `S` (rather than `FunctionSlugOf<C>`) in the enabled branch is what makes\n * the returned `function` namespace exact — it stays the one function's env keys instead of\n * widening to every declared function's.\n */\ntype FunctionScopeField<C extends Config, S extends string> = [\n\tFunctionSlugOf<C>,\n] extends [never]\n\t? NoFunctionScopeHint\n\t: S;\n\n/** The declared env-var keys of one function `S`, as a string union. */\ntype FunctionEnvKeysOf<\n\tC extends Config,\n\tS extends string,\n> = S extends keyof PreviewFunctionsOf<C>\n\t? NonNullable<PreviewFunctionsOf<C>[S]> extends { env: infer E }\n\t\t? Extract<keyof E, string>\n\t\t: never\n\t: never;\n\n/**\n * The extra `function` namespace added to `parseEnv`'s result when called with a function\n * slug scope: the declared env-var keys for that function, each resolved to a `string`.\n */\nexport type NeonFunctionEnv<C extends Config, S extends string> = {\n\tfunction: Record<FunctionEnvKeysOf<C, S>, string>;\n};\n\n// ───────────────────────── parseEnv 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 neonctl …`), 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// ───────────────────────── parseEnv ─────────────────────────\n\n/**\n * Per-namespace zod schemas. Each defines exactly the OS-level keys parsed from\n * `process.env` for its namespace. Keep in sync with {@link NEON_ENV_VAR_KEYS}.\n *\n * `z.string().url()` would be tighter than `min(1)` but Postgres URIs that include\n * URL-illegal characters in the password (rare but legal in Neon's connection-string\n * format) fail the WHATWG `URL` parse, so we settle for \"non-empty string\".\n */\nconst postgresEnvSchema = z.object({\n\tDATABASE_URL: z\n\t\t.string({ message: \"DATABASE_URL is missing\" })\n\t\t.min(1, \"DATABASE_URL must not be empty\"),\n\tDATABASE_URL_UNPOOLED: z\n\t\t.string({ message: \"DATABASE_URL_UNPOOLED is missing\" })\n\t\t.min(1, \"DATABASE_URL_UNPOOLED must not be empty\"),\n});\n\nconst authEnvSchema = z.object({\n\tNEON_AUTH_BASE_URL: z\n\t\t.string({ message: \"NEON_AUTH_BASE_URL is missing\" })\n\t\t.min(1, \"NEON_AUTH_BASE_URL must not be empty\"),\n\tNEON_AUTH_JWKS_URL: z\n\t\t.string({ message: \"NEON_AUTH_JWKS_URL is missing\" })\n\t\t.min(1, \"NEON_AUTH_JWKS_URL must not be empty\"),\n});\n\nconst dataApiEnvSchema = z.object({\n\tNEON_DATA_API_URL: z\n\t\t.string({ message: \"NEON_DATA_API_URL is missing\" })\n\t\t.min(1, \"NEON_DATA_API_URL must not be empty\"),\n});\n\nconst storageEnvSchema = z.object({\n\tAWS_ACCESS_KEY_ID: z\n\t\t.string({ message: \"AWS_ACCESS_KEY_ID is missing\" })\n\t\t.min(1, \"AWS_ACCESS_KEY_ID must not be empty\"),\n\tAWS_SECRET_ACCESS_KEY: z\n\t\t.string({ message: \"AWS_SECRET_ACCESS_KEY is missing\" })\n\t\t.min(1, \"AWS_SECRET_ACCESS_KEY must not be empty\"),\n\tAWS_ENDPOINT_URL_S3: z\n\t\t.string({ message: \"AWS_ENDPOINT_URL_S3 is missing\" })\n\t\t.min(1, \"AWS_ENDPOINT_URL_S3 must not be empty\"),\n\tAWS_REGION: z\n\t\t.string({ message: \"AWS_REGION is missing\" })\n\t\t.min(1, \"AWS_REGION must not be empty\"),\n});\n\nconst aiGatewayEnvSchema = z.object({\n\tNEON_AI_GATEWAY_TOKEN: z\n\t\t.string({ message: \"NEON_AI_GATEWAY_TOKEN is missing\" })\n\t\t.min(1, \"NEON_AI_GATEWAY_TOKEN must not be empty\"),\n\tNEON_AI_GATEWAY_BASE_URL: z\n\t\t.string({ message: \"NEON_AI_GATEWAY_BASE_URL is missing\" })\n\t\t.min(1, \"NEON_AI_GATEWAY_BASE_URL must not be empty\"),\n});\n\n/** Whether a **static** policy declares object storage (`preview.buckets`). No network. */\nfunction configWantsStorage(config: Config): boolean {\n\treturn Object.keys(config.preview?.buckets ?? {}).length > 0;\n}\n\n/** Whether a **static** policy enables the AI Gateway (`preview.aiGateway`). No network. */\nfunction configWantsAiGateway(config: Config): boolean {\n\treturn isServiceEnabledInput(config.preview?.aiGateway);\n}\n\n/** Static-toggle helper mirroring `config`'s `isServiceEnabled` for the env reader. */\nfunction isServiceEnabledInput(\n\ttoggle: ServiceToggleInput | undefined,\n): boolean {\n\tif (toggle === undefined) return false;\n\tif (typeof toggle === \"boolean\") return toggle;\n\treturn toggle.enabled !== false;\n}\n\n/**\n * Synchronous, network-free counterpart to {@link fetchEnv}. Reads `process.env`, validates\n * the required Neon env vars with zod, and returns the same {@link NeonEnv} shape — so the\n * rest of your app touches `env.postgres.databaseUrl` instead of stringly-typed\n * `process.env.DATABASE_URL` lookups.\n *\n * Designed for the **\"env-vars-already-injected\"** path:\n * - You wrapped your dev command with `neon-env run -- <cmd>` or `neon dev`.\n * - Your platform (Vercel, Fly, Railway, …) injected the vars via its own integration.\n * - You are **inside a deployed Neon Function**, whose env was uploaded at `config apply`.\n *\n * Unlike the old API, `parseEnv` does **not** take a branch name: the secret set is now\n * static (top-level `config.auth` / `config.dataApi`), so it reads those directly without\n * evaluating the per-branch closure.\n *\n * The second argument is a **scope** or a **key filter**:\n * - omitted — *external* scope (app bootstrap, build scripts, your dev machine). Returns the\n * full `{ postgres, auth?, dataApi?, … }` the policy enables.\n * - a **function slug** (a key of `config.preview.functions`) — *function* scope: you are\n * running inside that function. Returns the same branch secrets **plus** a typed\n * `function` namespace with the function's declared env-var keys. The slug autocompletes\n * from the policy ({@link FunctionSlugOf}) and an undeclared one is a type error.\n * - an **array of OS-level env-var keys** (e.g. `[\"DATABASE_URL\", \"NEON_AUTH_BASE_URL\"]`) —\n * *filtered* mode: only those vars are required and returned, as a narrowed namespaced\n * shape. The keys autocomplete from the policy ({@link SelectableEnvKey}), so you can only\n * pick vars the policy actually enables. Use this when a process needs just a subset (a\n * Next.js app that reads `DATABASE_URL` but not `DATABASE_URL_UNPOOLED`, say) and you don't\n * want `parseEnv` to throw over vars you never use.\n *\n * Throws `PlatformError(EnvNotInjected)` listing every missing/invalid var when the env\n * isn't fully populated, with a fix hint pointing back at `neon dev` / `neon-env run`.\n *\n * ```ts\n * import config from \"../neon\";\n * import { parseEnv } from \"@neon/env\";\n *\n * // External (app / build):\n * const env = parseEnv(config);\n * const db = drizzle(neon(env.postgres.databaseUrl), { schema });\n *\n * // Inside the \"hello\" function:\n * const env = parseEnv(config, \"hello\");\n * env.function.resendApiKey; // typed from hello's declared env keys\n *\n * // Filtered: only enforce + return the pooled URL.\n * const { postgres } = parseEnv(config, [\"DATABASE_URL\"]);\n * postgres.databaseUrl; // string — `databaseUrlUnpooled` is absent\n * ```\n */\nexport function parseEnv<const C extends Config>(config: C): NeonEnv<C>;\n// Overload order is load-bearing for **editor autocomplete**, not for type checking: when the\n// argument is a half-typed string literal the call resolves against no signature, and the\n// editor takes its string-literal completions from the first candidate overload. With the\n// `keys` overload listed first, the expected type of `parseEnv(config, \"…\")` is read as\n// `readonly K[]` — an array has no literal completions, so typing a function slug offered\n// nothing. Keep the slug overload ahead of the array one: `env.completions.test.ts` asserts the\n// completions through the language service, and `env.test-d.ts` locks the order itself (the\n// last overload is observable as `Parameters<typeof parseEnv>`), so `tsc` fails on a reorder.\nexport function parseEnv<\n\tconst C extends Config,\n\tconst S extends FunctionSlugOf<C>,\n>(\n\tconfig: C,\n\tscope: FunctionScopeField<C, S>,\n): NeonEnv<C> & NeonFunctionEnv<C, S>;\nexport function parseEnv<\n\tconst C extends Config,\n\tconst K extends SelectableEnvKey<C>,\n>(config: C, keys: readonly K[]): FilteredNeonEnv<K>;\nexport function parseEnv(\n\tconfig: Config,\n\tscopeOrKeys?: string | readonly string[],\n): unknown {\n\tconst source = process.env;\n\tif (Array.isArray(scopeOrKeys)) {\n\t\treturn parseFilteredEnv(source, scopeOrKeys);\n\t}\n\t// `Array.isArray` doesn't narrow a `readonly string[]` out of the union, so re-derive the\n\t// function-slug scope from the remaining `string` shape explicitly.\n\tconst scope = typeof scopeOrKeys === \"string\" ? scopeOrKeys : undefined;\n\tconst issues: string[] = [];\n\tconst result: Record<string, unknown> = {};\n\n\tconst pg = postgresEnvSchema.safeParse({\n\t\tDATABASE_URL: source.DATABASE_URL,\n\t\tDATABASE_URL_UNPOOLED: source.DATABASE_URL_UNPOOLED,\n\t});\n\tif (pg.success) {\n\t\tresult.postgres = {\n\t\t\tdatabaseUrl: pg.data.DATABASE_URL,\n\t\t\tdatabaseUrlUnpooled: pg.data.DATABASE_URL_UNPOOLED,\n\t\t} satisfies NeonPostgresEnv;\n\t} else {\n\t\tfor (const issue of pg.error.issues) issues.push(issue.message);\n\t}\n\n\t// Branch identity is optional: the Functions runtime injects `NEON_BRANCH` on every\n\t// branch by default and `neon dev` / `neon-env run` / `env pull` emit it too, but older\n\t// runtimes and platform integrations may not, so a missing value is not an error — we\n\t// just omit the namespace rather than failing the whole parse.\n\tconst branchName = source[NEON_ENV_VAR_KEYS.branch.name];\n\tif (branchName !== undefined && branchName !== \"\") {\n\t\tresult.branch = { name: branchName } satisfies NeonBranchEnv;\n\t}\n\n\tif (isServiceEnabledInput(config.auth)) {\n\t\tconst auth = authEnvSchema.safeParse({\n\t\t\tNEON_AUTH_BASE_URL: source.NEON_AUTH_BASE_URL,\n\t\t\tNEON_AUTH_JWKS_URL: source.NEON_AUTH_JWKS_URL,\n\t\t});\n\t\tif (auth.success) {\n\t\t\tresult.auth = {\n\t\t\t\tbaseUrl: auth.data.NEON_AUTH_BASE_URL,\n\t\t\t\tjwksUrl: auth.data.NEON_AUTH_JWKS_URL,\n\t\t\t} satisfies NeonAuthEnv;\n\t\t} else {\n\t\t\tfor (const issue of auth.error.issues) issues.push(issue.message);\n\t\t}\n\t}\n\n\tif (isServiceEnabledInput(config.dataApi)) {\n\t\tconst dataApi = dataApiEnvSchema.safeParse({\n\t\t\tNEON_DATA_API_URL: source.NEON_DATA_API_URL,\n\t\t});\n\t\tif (dataApi.success) {\n\t\t\tresult.dataApi = {\n\t\t\t\turl: dataApi.data.NEON_DATA_API_URL,\n\t\t\t} satisfies NeonDataApiEnv;\n\t\t} else {\n\t\t\tfor (const issue of dataApi.error.issues)\n\t\t\t\tissues.push(issue.message);\n\t\t}\n\t}\n\n\tif (configWantsStorage(config)) {\n\t\tconst storage = storageEnvSchema.safeParse({\n\t\t\tAWS_ACCESS_KEY_ID: source.AWS_ACCESS_KEY_ID,\n\t\t\tAWS_SECRET_ACCESS_KEY: source.AWS_SECRET_ACCESS_KEY,\n\t\t\tAWS_ENDPOINT_URL_S3: source.AWS_ENDPOINT_URL_S3,\n\t\t\tAWS_REGION: source.AWS_REGION,\n\t\t});\n\t\tif (storage.success) {\n\t\t\tresult.storage = {\n\t\t\t\taccessKeyId: storage.data.AWS_ACCESS_KEY_ID,\n\t\t\t\tsecretAccessKey: storage.data.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tendpoint: storage.data.AWS_ENDPOINT_URL_S3,\n\t\t\t\tregion: storage.data.AWS_REGION,\n\t\t\t} satisfies NeonStorageEnv;\n\t\t} else {\n\t\t\tfor (const issue of storage.error.issues)\n\t\t\t\tissues.push(issue.message);\n\t\t}\n\t}\n\n\tif (configWantsAiGateway(config)) {\n\t\tconst aiGateway = aiGatewayEnvSchema.safeParse({\n\t\t\tNEON_AI_GATEWAY_TOKEN: source.NEON_AI_GATEWAY_TOKEN,\n\t\t\tNEON_AI_GATEWAY_BASE_URL: source.NEON_AI_GATEWAY_BASE_URL,\n\t\t});\n\t\tif (aiGateway.success) {\n\t\t\tresult.aiGateway = {\n\t\t\t\tapiKey: aiGateway.data.NEON_AI_GATEWAY_TOKEN,\n\t\t\t\tbaseUrl: aiGateway.data.NEON_AI_GATEWAY_BASE_URL,\n\t\t\t} satisfies NeonAiGatewayEnv;\n\t\t} else {\n\t\t\tfor (const issue of aiGateway.error.issues)\n\t\t\t\tissues.push(issue.message);\n\t\t}\n\t}\n\n\tif (scope !== undefined) {\n\t\tconst fn = config.preview?.functions?.[scope];\n\t\tif (!fn) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.EnvNotInjected,\n\t\t\t\t[\n\t\t\t\t\t`parseEnv: no function \"${scope}\" is declared in this policy's preview.functions.`,\n\t\t\t\t\t\"Pass a declared function slug (or omit the scope to read external env).\",\n\t\t\t\t].join(\"\\n\"),\n\t\t\t\t{ details: { scope } },\n\t\t\t);\n\t\t}\n\t\tconst envOut: Record<string, string> = {};\n\t\tfor (const key of Object.keys(fn.env ?? {})) {\n\t\t\tconst value = source[key];\n\t\t\t// Only a truly *unset* var is \"not injected\". Function env values carry no\n\t\t\t// non-empty constraint (unlike DATABASE_URL / NEON_AUTH_BASE_URL), so a\n\t\t\t// deliberately empty value is a present, valid value and is passed through.\n\t\t\tif (value === undefined) {\n\t\t\t\tissues.push(`${key} is missing (function \"${scope}\")`);\n\t\t\t} else {\n\t\t\t\tenvOut[key] = value;\n\t\t\t}\n\t\t}\n\t\tresult.function = envOut;\n\t}\n\n\tif (issues.length > 0) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.EnvNotInjected,\n\t\t\t[\n\t\t\t\t\"parseEnv: the required Neon env variables are not present in process.env.\",\n\t\t\t\t...issues.map((i) => ` - ${i}`),\n\t\t\t\t\"Inject them via one of:\",\n\t\t\t\t\" - `neon dev` / `neon-env run -- <your dev command>` (wraps the command with the vars injected)\",\n\t\t\t\t\" - your hosting platform's Neon integration (Vercel, Fly, Railway, …)\",\n\t\t\t\t\" - for the `function` namespace: deploy the function (`neon deploy` / `config apply`) so its env is uploaded.\",\n\t\t\t\t\"Or switch the call to `await fetchEnv(config, …)` if you're in a context that can do async I/O.\",\n\t\t\t].join(\"\\n\"),\n\t\t\t{ details: { missing: issues } },\n\t\t);\n\t}\n\n\treturn result;\n}\n\n/**\n * Runtime reverse map for filtered `parseEnv`: OS-level env-var key → `[namespace, property]`\n * in the {@link NeonEnv} shape. The compile-time mirror is {@link EnvKeysByNamespace} /\n * {@link EnvKeyToProp}; keep all three in sync. Only input vars appear (no output-only\n * aliases).\n */\nconst FILTERABLE_ENV_KEYS: Record<string, readonly [string, string]> = {\n\tDATABASE_URL: [\"postgres\", \"databaseUrl\"],\n\tDATABASE_URL_UNPOOLED: [\"postgres\", \"databaseUrlUnpooled\"],\n\tNEON_BRANCH: [\"branch\", \"name\"],\n\tNEON_AUTH_BASE_URL: [\"auth\", \"baseUrl\"],\n\tNEON_AUTH_JWKS_URL: [\"auth\", \"jwksUrl\"],\n\tNEON_DATA_API_URL: [\"dataApi\", \"url\"],\n\tAWS_ACCESS_KEY_ID: [\"storage\", \"accessKeyId\"],\n\tAWS_SECRET_ACCESS_KEY: [\"storage\", \"secretAccessKey\"],\n\tAWS_ENDPOINT_URL_S3: [\"storage\", \"endpoint\"],\n\tAWS_REGION: [\"storage\", \"region\"],\n\tNEON_AI_GATEWAY_TOKEN: [\"aiGateway\", \"apiKey\"],\n\tNEON_AI_GATEWAY_BASE_URL: [\"aiGateway\", \"baseUrl\"],\n};\n\n/**\n * Filtered counterpart to the {@link parseEnv} body: validate and return only the explicitly\n * selected OS-level env-var keys, projected back into the narrowed namespaced shape. Unlike\n * the full reader it never consults the policy — the selection alone decides what's required —\n * so vars the caller didn't ask for (e.g. `DATABASE_URL_UNPOOLED`) can be absent without\n * throwing. Mirrors the same non-empty constraint and {@link PlatformError} aggregation.\n */\nfunction parseFilteredEnv(\n\tsource: NodeJS.ProcessEnv,\n\tkeys: readonly string[],\n): Record<string, Record<string, string>> {\n\tconst issues: string[] = [];\n\tconst result: Record<string, Record<string, string>> = {};\n\tfor (const key of keys) {\n\t\t// Unknown keys are blocked at the type level; a runtime caller bypassing the types\n\t\t// gets a clear error rather than a silently-dropped selection.\n\t\tif (!Object.hasOwn(FILTERABLE_ENV_KEYS, key)) {\n\t\t\tissues.push(`${key} is not a selectable Neon env variable`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst value = source[key];\n\t\tif (value === undefined) {\n\t\t\tissues.push(`${key} is missing`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (value === \"\") {\n\t\t\tissues.push(`${key} must not be empty`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst [namespace, property] = FILTERABLE_ENV_KEYS[key];\n\t\tconst bucket = result[namespace] ?? {};\n\t\tbucket[property] = value;\n\t\tresult[namespace] = bucket;\n\t}\n\tif (issues.length > 0) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.EnvNotInjected,\n\t\t\t[\n\t\t\t\t\"parseEnv: the required Neon env variables are not present in process.env.\",\n\t\t\t\t...issues.map((i) => ` - ${i}`),\n\t\t\t\t\"Inject them via one of:\",\n\t\t\t\t\" - `neon dev` / `neon-env run -- <your dev command>` (wraps the command with the vars injected)\",\n\t\t\t\t\" - your hosting platform's Neon integration (Vercel, Fly, Railway, …)\",\n\t\t\t\t\"Or switch the call to `await fetchEnv(config, …)` if you're in a context that can do async I/O.\",\n\t\t\t].join(\"\\n\"),\n\t\t\t{ details: { missing: issues } },\n\t\t);\n\t}\n\treturn result;\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]>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,MAAM,0BAA0B;;;;;;AAOhC,MAAM,wBAAwB;;;;;;;;AAS9B,MAAM,0CAA+C,IAAI,IAAI;CAC5D;CACA;CACA;AACD,CAAC;AAED,MAAa,oBAAoB;;;;;;CAMhC,QAAQ,EACP,MAAM,cACP;CACA,UAAU;EACT,aAAa;EACb,qBAAqB;CACtB;CACA,MAAM;EACL,SAAS;EACT,SAAS;CACV;CACA,SAAS,EACR,KAAK,oBACN;;;;;;CAMA,SAAS;EACR,aAAa;EACb,iBAAiB;EACjB,UAAU;EACV,QAAQ;CACT;;;;;;;;CAQA,WAAW;EACV,QAAQ;EACR,SAAS;CACV;AACD;AA6aA,eAAsB,SACrB,QACA,SACmB;CACnB,OAAO,aAAa,QAAQ,SAAS,QAAQ,QAAQ,IAAI;AAC1D;;;;;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Content":["import {\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\ttype ServiceToggleInput,\n} from \"@neon/config/v1\";\nimport { z } from \"zod\";\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/** The static `preview.functions` record of a config, or an empty record when absent. */\ntype PreviewFunctionsOf<C extends Config> =\n\tNonNullable<C[\"preview\"]> extends {\n\t\tfunctions: infer F;\n\t}\n\t\t? F\n\t\t: Record<never, never>;\n\n/** The declared function slugs of a config (record keys), as a string union. */\nexport type FunctionSlugOf<C extends Config> = Extract<\n\tkeyof PreviewFunctionsOf<C>,\n\tstring\n>;\n\n/**\n * Human-readable hint surfaced as the **expected type** of `parseEnv`'s `scope` argument when\n * the policy declares no functions at all. Without it the argument's expected type is the bare\n * `never` {@link FunctionSlugOf} yields, and TypeScript reports the opaque `Type '\"x\"' is not\n * assignable to type 'never'`; the literal turns that into a sentence naming the fix (and the\n * editor offers it as the single completion, so the empty completion list is explained rather\n * than just empty). Mirrors `NeonAuthRequiredHint` in `@neon/config`.\n */\n// Exported (type-only) for the type tests in `env.test-d.ts`; intentionally not re-exported\n// from `index.ts`, so it stays an internal implementation detail.\nexport type NoFunctionScopeHint =\n\t\"this policy declares no `preview.functions`, so there is no function scope to read. Declare the function in `neon.ts` first, or omit the scope to read the branch env\";\n\n/**\n * The expected type of `parseEnv`'s function-slug `scope` argument: the caller's inferred slug\n * `S` normally, and the {@link NoFunctionScopeHint} message when the policy declares no\n * functions. Keeping `S` (rather than `FunctionSlugOf<C>`) in the enabled branch is what makes\n * the returned `function` namespace exact — it stays the one function's env keys instead of\n * widening to every declared function's.\n */\ntype FunctionScopeField<C extends Config, S extends string> = [\n\tFunctionSlugOf<C>,\n] extends [never]\n\t? NoFunctionScopeHint\n\t: S;\n\n/** The declared env-var keys of one function `S`, as a string union. */\ntype FunctionEnvKeysOf<\n\tC extends Config,\n\tS extends string,\n> = S extends keyof PreviewFunctionsOf<C>\n\t? NonNullable<PreviewFunctionsOf<C>[S]> extends { env: infer E }\n\t\t? Extract<keyof E, string>\n\t\t: never\n\t: never;\n\n/**\n * The extra `function` namespace added to `parseEnv`'s result when called with a function\n * slug scope: the declared env-var keys for that function, each resolved to a `string`.\n */\nexport type NeonFunctionEnv<C extends Config, S extends string> = {\n\tfunction: Record<FunctionEnvKeysOf<C, S>, string>;\n};\n\n// ───────────────────────── parseEnv 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// ───────────────────────── parseEnv ─────────────────────────\n\n/**\n * Per-namespace zod schemas. Each defines exactly the OS-level keys parsed from\n * `process.env` for its namespace. Keep in sync with {@link NEON_ENV_VAR_KEYS}.\n *\n * `z.string().url()` would be tighter than `min(1)` but Postgres URIs that include\n * URL-illegal characters in the password (rare but legal in Neon's connection-string\n * format) fail the WHATWG `URL` parse, so we settle for \"non-empty string\".\n */\nconst postgresEnvSchema = z.object({\n\tDATABASE_URL: z\n\t\t.string({ message: \"DATABASE_URL is missing\" })\n\t\t.min(1, \"DATABASE_URL must not be empty\"),\n\tDATABASE_URL_UNPOOLED: z\n\t\t.string({ message: \"DATABASE_URL_UNPOOLED is missing\" })\n\t\t.min(1, \"DATABASE_URL_UNPOOLED must not be empty\"),\n});\n\nconst authEnvSchema = z.object({\n\tNEON_AUTH_BASE_URL: z\n\t\t.string({ message: \"NEON_AUTH_BASE_URL is missing\" })\n\t\t.min(1, \"NEON_AUTH_BASE_URL must not be empty\"),\n\tNEON_AUTH_JWKS_URL: z\n\t\t.string({ message: \"NEON_AUTH_JWKS_URL is missing\" })\n\t\t.min(1, \"NEON_AUTH_JWKS_URL must not be empty\"),\n});\n\nconst dataApiEnvSchema = z.object({\n\tNEON_DATA_API_URL: z\n\t\t.string({ message: \"NEON_DATA_API_URL is missing\" })\n\t\t.min(1, \"NEON_DATA_API_URL must not be empty\"),\n});\n\nconst storageEnvSchema = z.object({\n\tAWS_ACCESS_KEY_ID: z\n\t\t.string({ message: \"AWS_ACCESS_KEY_ID is missing\" })\n\t\t.min(1, \"AWS_ACCESS_KEY_ID must not be empty\"),\n\tAWS_SECRET_ACCESS_KEY: z\n\t\t.string({ message: \"AWS_SECRET_ACCESS_KEY is missing\" })\n\t\t.min(1, \"AWS_SECRET_ACCESS_KEY must not be empty\"),\n\tAWS_ENDPOINT_URL_S3: z\n\t\t.string({ message: \"AWS_ENDPOINT_URL_S3 is missing\" })\n\t\t.min(1, \"AWS_ENDPOINT_URL_S3 must not be empty\"),\n\tAWS_REGION: z\n\t\t.string({ message: \"AWS_REGION is missing\" })\n\t\t.min(1, \"AWS_REGION must not be empty\"),\n});\n\nconst aiGatewayEnvSchema = z.object({\n\tNEON_AI_GATEWAY_TOKEN: z\n\t\t.string({ message: \"NEON_AI_GATEWAY_TOKEN is missing\" })\n\t\t.min(1, \"NEON_AI_GATEWAY_TOKEN must not be empty\"),\n\tNEON_AI_GATEWAY_BASE_URL: z\n\t\t.string({ message: \"NEON_AI_GATEWAY_BASE_URL is missing\" })\n\t\t.min(1, \"NEON_AI_GATEWAY_BASE_URL must not be empty\"),\n});\n\n/** Whether a **static** policy declares object storage (`preview.buckets`). No network. */\nfunction configWantsStorage(config: Config): boolean {\n\treturn Object.keys(config.preview?.buckets ?? {}).length > 0;\n}\n\n/** Whether a **static** policy enables the AI Gateway (`preview.aiGateway`). No network. */\nfunction configWantsAiGateway(config: Config): boolean {\n\treturn isServiceEnabledInput(config.preview?.aiGateway);\n}\n\n/** Static-toggle helper mirroring `config`'s `isServiceEnabled` for the env reader. */\nfunction isServiceEnabledInput(\n\ttoggle: ServiceToggleInput | undefined,\n): boolean {\n\tif (toggle === undefined) return false;\n\tif (typeof toggle === \"boolean\") return toggle;\n\treturn toggle.enabled !== false;\n}\n\n/**\n * Synchronous, network-free counterpart to {@link fetchEnv}. Reads `process.env`, validates\n * the required Neon env vars with zod, and returns the same {@link NeonEnv} shape — so the\n * rest of your app touches `env.postgres.databaseUrl` instead of stringly-typed\n * `process.env.DATABASE_URL` lookups.\n *\n * Designed for the **\"env-vars-already-injected\"** path:\n * - You wrapped your dev command with `neon-env run -- <cmd>` or `neon dev`.\n * - Your platform (Vercel, Fly, Railway, …) injected the vars via its own integration.\n * - You are **inside a deployed Neon Function**, whose env was uploaded at `config apply`.\n *\n * Unlike the old API, `parseEnv` does **not** take a branch name: the secret set is now\n * static (top-level `config.auth` / `config.dataApi`), so it reads those directly without\n * evaluating the per-branch closure.\n *\n * The second argument is a **scope** or a **key filter**:\n * - omitted — *external* scope (app bootstrap, build scripts, your dev machine). Returns the\n * full `{ postgres, auth?, dataApi?, … }` the policy enables.\n * - a **function slug** (a key of `config.preview.functions`) — *function* scope: you are\n * running inside that function. Returns the same branch secrets **plus** a typed\n * `function` namespace with the function's declared env-var keys. The slug autocompletes\n * from the policy ({@link FunctionSlugOf}) and an undeclared one is a type error.\n * - an **array of OS-level env-var keys** (e.g. `[\"DATABASE_URL\", \"NEON_AUTH_BASE_URL\"]`) —\n * *filtered* mode: only those vars are required and returned, as a narrowed namespaced\n * shape. The keys autocomplete from the policy ({@link SelectableEnvKey}), so you can only\n * pick vars the policy actually enables. Use this when a process needs just a subset (a\n * Next.js app that reads `DATABASE_URL` but not `DATABASE_URL_UNPOOLED`, say) and you don't\n * want `parseEnv` to throw over vars you never use.\n *\n * Throws `PlatformError(EnvNotInjected)` listing every missing/invalid var when the env\n * isn't fully populated, with a fix hint pointing back at `neon dev` / `neon-env run`.\n *\n * ```ts\n * import config from \"../neon\";\n * import { parseEnv } from \"@neon/env\";\n *\n * // External (app / build):\n * const env = parseEnv(config);\n * const db = drizzle(neon(env.postgres.databaseUrl), { schema });\n *\n * // Inside the \"hello\" function:\n * const env = parseEnv(config, \"hello\");\n * env.function.resendApiKey; // typed from hello's declared env keys\n *\n * // Filtered: only enforce + return the pooled URL.\n * const { postgres } = parseEnv(config, [\"DATABASE_URL\"]);\n * postgres.databaseUrl; // string — `databaseUrlUnpooled` is absent\n * ```\n */\nexport function parseEnv<const C extends Config>(config: C): NeonEnv<C>;\n// Overload order is load-bearing for **editor autocomplete**, not for type checking: when the\n// argument is a half-typed string literal the call resolves against no signature, and the\n// editor takes its string-literal completions from the first candidate overload. With the\n// `keys` overload listed first, the expected type of `parseEnv(config, \"…\")` is read as\n// `readonly K[]` — an array has no literal completions, so typing a function slug offered\n// nothing. Keep the slug overload ahead of the array one: `env.completions.test.ts` asserts the\n// completions through the language service, and `env.test-d.ts` locks the order itself (the\n// last overload is observable as `Parameters<typeof parseEnv>`), so `tsc` fails on a reorder.\nexport function parseEnv<\n\tconst C extends Config,\n\tconst S extends FunctionSlugOf<C>,\n>(\n\tconfig: C,\n\tscope: FunctionScopeField<C, S>,\n): NeonEnv<C> & NeonFunctionEnv<C, S>;\nexport function parseEnv<\n\tconst C extends Config,\n\tconst K extends SelectableEnvKey<C>,\n>(config: C, keys: readonly K[]): FilteredNeonEnv<K>;\nexport function parseEnv(\n\tconfig: Config,\n\tscopeOrKeys?: string | readonly string[],\n): unknown {\n\tconst source = process.env;\n\tif (Array.isArray(scopeOrKeys)) {\n\t\treturn parseFilteredEnv(source, scopeOrKeys);\n\t}\n\t// `Array.isArray` doesn't narrow a `readonly string[]` out of the union, so re-derive the\n\t// function-slug scope from the remaining `string` shape explicitly.\n\tconst scope = typeof scopeOrKeys === \"string\" ? scopeOrKeys : undefined;\n\tconst issues: string[] = [];\n\tconst result: Record<string, unknown> = {};\n\n\tconst pg = postgresEnvSchema.safeParse({\n\t\tDATABASE_URL: source.DATABASE_URL,\n\t\tDATABASE_URL_UNPOOLED: source.DATABASE_URL_UNPOOLED,\n\t});\n\tif (pg.success) {\n\t\tresult.postgres = {\n\t\t\tdatabaseUrl: pg.data.DATABASE_URL,\n\t\t\tdatabaseUrlUnpooled: pg.data.DATABASE_URL_UNPOOLED,\n\t\t} satisfies NeonPostgresEnv;\n\t} else {\n\t\tfor (const issue of pg.error.issues) issues.push(issue.message);\n\t}\n\n\t// Branch identity is optional: the Functions runtime injects `NEON_BRANCH` on every\n\t// branch by default and `neon dev` / `neon-env run` / `env pull` emit it too, but older\n\t// runtimes and platform integrations may not, so a missing value is not an error — we\n\t// just omit the namespace rather than failing the whole parse.\n\tconst branchName = source[NEON_ENV_VAR_KEYS.branch.name];\n\tif (branchName !== undefined && branchName !== \"\") {\n\t\tresult.branch = { name: branchName } satisfies NeonBranchEnv;\n\t}\n\n\tif (isServiceEnabledInput(config.auth)) {\n\t\tconst auth = authEnvSchema.safeParse({\n\t\t\tNEON_AUTH_BASE_URL: source.NEON_AUTH_BASE_URL,\n\t\t\tNEON_AUTH_JWKS_URL: source.NEON_AUTH_JWKS_URL,\n\t\t});\n\t\tif (auth.success) {\n\t\t\tresult.auth = {\n\t\t\t\tbaseUrl: auth.data.NEON_AUTH_BASE_URL,\n\t\t\t\tjwksUrl: auth.data.NEON_AUTH_JWKS_URL,\n\t\t\t} satisfies NeonAuthEnv;\n\t\t} else {\n\t\t\tfor (const issue of auth.error.issues) issues.push(issue.message);\n\t\t}\n\t}\n\n\tif (isServiceEnabledInput(config.dataApi)) {\n\t\tconst dataApi = dataApiEnvSchema.safeParse({\n\t\t\tNEON_DATA_API_URL: source.NEON_DATA_API_URL,\n\t\t});\n\t\tif (dataApi.success) {\n\t\t\tresult.dataApi = {\n\t\t\t\turl: dataApi.data.NEON_DATA_API_URL,\n\t\t\t} satisfies NeonDataApiEnv;\n\t\t} else {\n\t\t\tfor (const issue of dataApi.error.issues)\n\t\t\t\tissues.push(issue.message);\n\t\t}\n\t}\n\n\tif (configWantsStorage(config)) {\n\t\tconst storage = storageEnvSchema.safeParse({\n\t\t\tAWS_ACCESS_KEY_ID: source.AWS_ACCESS_KEY_ID,\n\t\t\tAWS_SECRET_ACCESS_KEY: source.AWS_SECRET_ACCESS_KEY,\n\t\t\tAWS_ENDPOINT_URL_S3: source.AWS_ENDPOINT_URL_S3,\n\t\t\tAWS_REGION: source.AWS_REGION,\n\t\t});\n\t\tif (storage.success) {\n\t\t\tresult.storage = {\n\t\t\t\taccessKeyId: storage.data.AWS_ACCESS_KEY_ID,\n\t\t\t\tsecretAccessKey: storage.data.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tendpoint: storage.data.AWS_ENDPOINT_URL_S3,\n\t\t\t\tregion: storage.data.AWS_REGION,\n\t\t\t} satisfies NeonStorageEnv;\n\t\t} else {\n\t\t\tfor (const issue of storage.error.issues)\n\t\t\t\tissues.push(issue.message);\n\t\t}\n\t}\n\n\tif (configWantsAiGateway(config)) {\n\t\tconst aiGateway = aiGatewayEnvSchema.safeParse({\n\t\t\tNEON_AI_GATEWAY_TOKEN: source.NEON_AI_GATEWAY_TOKEN,\n\t\t\tNEON_AI_GATEWAY_BASE_URL: source.NEON_AI_GATEWAY_BASE_URL,\n\t\t});\n\t\tif (aiGateway.success) {\n\t\t\tresult.aiGateway = {\n\t\t\t\tapiKey: aiGateway.data.NEON_AI_GATEWAY_TOKEN,\n\t\t\t\tbaseUrl: aiGateway.data.NEON_AI_GATEWAY_BASE_URL,\n\t\t\t} satisfies NeonAiGatewayEnv;\n\t\t} else {\n\t\t\tfor (const issue of aiGateway.error.issues)\n\t\t\t\tissues.push(issue.message);\n\t\t}\n\t}\n\n\tif (scope !== undefined) {\n\t\tconst fn = config.preview?.functions?.[scope];\n\t\tif (!fn) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.EnvNotInjected,\n\t\t\t\t[\n\t\t\t\t\t`parseEnv: no function \"${scope}\" is declared in this policy's preview.functions.`,\n\t\t\t\t\t\"Pass a declared function slug (or omit the scope to read external env).\",\n\t\t\t\t].join(\"\\n\"),\n\t\t\t\t{ details: { scope } },\n\t\t\t);\n\t\t}\n\t\tconst envOut: Record<string, string> = {};\n\t\tfor (const key of Object.keys(fn.env ?? {})) {\n\t\t\tconst value = source[key];\n\t\t\t// Only a truly *unset* var is \"not injected\". Function env values carry no\n\t\t\t// non-empty constraint (unlike DATABASE_URL / NEON_AUTH_BASE_URL), so a\n\t\t\t// deliberately empty value is a present, valid value and is passed through.\n\t\t\tif (value === undefined) {\n\t\t\t\tissues.push(`${key} is missing (function \"${scope}\")`);\n\t\t\t} else {\n\t\t\t\tenvOut[key] = value;\n\t\t\t}\n\t\t}\n\t\tresult.function = envOut;\n\t}\n\n\tif (issues.length > 0) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.EnvNotInjected,\n\t\t\t[\n\t\t\t\t\"parseEnv: the required Neon env variables are not present in process.env.\",\n\t\t\t\t...issues.map((i) => ` - ${i}`),\n\t\t\t\t\"Inject them via one of:\",\n\t\t\t\t\" - `neon dev` / `neon-env run -- <your dev command>` (wraps the command with the vars injected)\",\n\t\t\t\t\" - your hosting platform's Neon integration (Vercel, Fly, Railway, …)\",\n\t\t\t\t\" - for the `function` namespace: deploy the function (`neon deploy` / `config apply`) so its env is uploaded.\",\n\t\t\t\t\"Or switch the call to `await fetchEnv(config, …)` if you're in a context that can do async I/O.\",\n\t\t\t].join(\"\\n\"),\n\t\t\t{ details: { missing: issues } },\n\t\t);\n\t}\n\n\treturn result;\n}\n\n/**\n * Runtime reverse map for filtered `parseEnv`: OS-level env-var key → `[namespace, property]`\n * in the {@link NeonEnv} shape. The compile-time mirror is {@link EnvKeysByNamespace} /\n * {@link EnvKeyToProp}; keep all three in sync. Only input vars appear (no output-only\n * aliases).\n */\nconst FILTERABLE_ENV_KEYS: Record<string, readonly [string, string]> = {\n\tDATABASE_URL: [\"postgres\", \"databaseUrl\"],\n\tDATABASE_URL_UNPOOLED: [\"postgres\", \"databaseUrlUnpooled\"],\n\tNEON_BRANCH: [\"branch\", \"name\"],\n\tNEON_AUTH_BASE_URL: [\"auth\", \"baseUrl\"],\n\tNEON_AUTH_JWKS_URL: [\"auth\", \"jwksUrl\"],\n\tNEON_DATA_API_URL: [\"dataApi\", \"url\"],\n\tAWS_ACCESS_KEY_ID: [\"storage\", \"accessKeyId\"],\n\tAWS_SECRET_ACCESS_KEY: [\"storage\", \"secretAccessKey\"],\n\tAWS_ENDPOINT_URL_S3: [\"storage\", \"endpoint\"],\n\tAWS_REGION: [\"storage\", \"region\"],\n\tNEON_AI_GATEWAY_TOKEN: [\"aiGateway\", \"apiKey\"],\n\tNEON_AI_GATEWAY_BASE_URL: [\"aiGateway\", \"baseUrl\"],\n};\n\n/**\n * Filtered counterpart to the {@link parseEnv} body: validate and return only the explicitly\n * selected OS-level env-var keys, projected back into the narrowed namespaced shape. Unlike\n * the full reader it never consults the policy — the selection alone decides what's required —\n * so vars the caller didn't ask for (e.g. `DATABASE_URL_UNPOOLED`) can be absent without\n * throwing. Mirrors the same non-empty constraint and {@link PlatformError} aggregation.\n */\nfunction parseFilteredEnv(\n\tsource: NodeJS.ProcessEnv,\n\tkeys: readonly string[],\n): Record<string, Record<string, string>> {\n\tconst issues: string[] = [];\n\tconst result: Record<string, Record<string, string>> = {};\n\tfor (const key of keys) {\n\t\t// Unknown keys are blocked at the type level; a runtime caller bypassing the types\n\t\t// gets a clear error rather than a silently-dropped selection.\n\t\tif (!Object.hasOwn(FILTERABLE_ENV_KEYS, key)) {\n\t\t\tissues.push(`${key} is not a selectable Neon env variable`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst value = source[key];\n\t\tif (value === undefined) {\n\t\t\tissues.push(`${key} is missing`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (value === \"\") {\n\t\t\tissues.push(`${key} must not be empty`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst [namespace, property] = FILTERABLE_ENV_KEYS[key];\n\t\tconst bucket = result[namespace] ?? {};\n\t\tbucket[property] = value;\n\t\tresult[namespace] = bucket;\n\t}\n\tif (issues.length > 0) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.EnvNotInjected,\n\t\t\t[\n\t\t\t\t\"parseEnv: the required Neon env variables are not present in process.env.\",\n\t\t\t\t...issues.map((i) => ` - ${i}`),\n\t\t\t\t\"Inject them via one of:\",\n\t\t\t\t\" - `neon dev` / `neon-env run -- <your dev command>` (wraps the command with the vars injected)\",\n\t\t\t\t\" - your hosting platform's Neon integration (Vercel, Fly, Railway, …)\",\n\t\t\t\t\"Or switch the call to `await fetchEnv(config, …)` if you're in a context that can do async I/O.\",\n\t\t\t].join(\"\\n\"),\n\t\t\t{ details: { missing: issues } },\n\t\t);\n\t}\n\treturn result;\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]>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,MAAM,0BAA0B;;;;;;AAOhC,MAAM,wBAAwB;;;;;;;;AAS9B,MAAM,0CAA+C,IAAI,IAAI;CAC5D;CACA;CACA;AACD,CAAC;AAED,MAAa,oBAAoB;;;;;;CAMhC,QAAQ,EACP,MAAM,cACP;CACA,UAAU;EACT,aAAa;EACb,qBAAqB;CACtB;CACA,MAAM;EACL,SAAS;EACT,SAAS;CACV;CACA,SAAS,EACR,KAAK,oBACN;;;;;;CAMA,SAAS;EACR,aAAa;EACb,iBAAiB;EACjB,UAAU;EACV,QAAQ;CACT;;;;;;;;CAQA,WAAW;EACV,QAAQ;EACR,SAAS;CACV;AACD;AA6aA,eAAsB,SACrB,QACA,SACmB;CACnB,OAAO,aAAa,QAAQ,SAAS,QAAQ,QAAQ,IAAI;AAC1D;;;;;;;;;;AAWA,eAAsB,aACrB,QACA,SACA,MAC2B;CAC3B,MAAM,MAAM,QAAQ,OAAO,qBAAqB,OAAO;CACvD,MAAM,YAAY,QAAQ;CAC1B,MAAM,EAAE,QAAQ,YAAY,MAAM,oBAAoB,QAAQ,SAAS,GAAG;CAE1E,MAAM,YAAY,OAAO,IAAI,IAAY,IAAI,IAAI;CACjD,MAAM,SAAS,QACd,cAAc,QAAQ,UAAU,IAAI,GAAG;CAExC,MAAM,SAA0B,CAAC;CACjC,MAAM,CAAC,OAAO,aAAa,MAAM,QAAQ,IAAI,CAC5C,IAAI,gBAAgB,WAAW,OAAO,EAAE,GACxC,IAAI,oBAAoB,WAAW,OAAO,EAAE,CAC7C,CAAC;C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8B,CAAC;CACrC,MAAM,OAAO,KAAa,UAAoC;EAC7D,IAAI,UAAU,KAAA,GAAW,IAAI,OAAO;CACrC;CACA,MAAM,IAAI;CACV,IAAI,EAAE,SAAS,aAAa,IAAI,UAAU,WAAW;CACrD,IAAI,EAAE,SAAS,qBAAqB,IAAI,UAAU,mBAAmB;CACrE,IAAI,EAAE,OAAO,MAAM,IAAI,QAAQ,IAAI;CACnC,IAAI,EAAE,KAAK,SAAS,IAAI,MAAM,OAAO;CACrC,IAAI,EAAE,KAAK,SAAS,IAAI,MAAM,OAAO;CACrC,IAAI,EAAE,QAAQ,KAAK,IAAI,SAAS,GAAG;CACnC,IAAI,EAAE,QAAQ,aAAa,IAAI,SAAS,WAAW;CACnD,IAAI,EAAE,QAAQ,iBAAiB,IAAI,SAAS,eAAe;CAC3D,IAAI,EAAE,QAAQ,UAAU,IAAI,SAAS,QAAQ;CAC7C,IAAI,EAAE,QAAQ,QAAQ,IAAI,SAAS,MAAM;CAIzC,IAAI,EAAE,UAAU,QAAQ,IAAI,WAAW,MAAM;CAC7C,IAAI,EAAE,UAAU,SAAS,IAAI,WAAW,OAAO;CAC/C,OAAO;AACR"}
@@ -44,14 +44,17 @@ async function fetchEnvReusingSecrets(config, options) {
44
44
  storage: storageEnabled,
45
45
  aiGateway: gatewayEnabled
46
46
  });
47
- if (secretKeys.length === 0) return {
48
- vars: preferPersisted(toEntries(await fetchEnvKeys(config, fetchOptions, null)), source),
49
- credential: {
50
- issued: false,
51
- keys: [],
52
- revoked: []
53
- }
54
- };
47
+ if (secretKeys.length === 0) {
48
+ const fetched = await fetchEnvKeys(config, fetchOptions, null);
49
+ return {
50
+ vars: preferPersisted(toEntries(fetched), source),
51
+ credential: {
52
+ issued: false,
53
+ keys: [],
54
+ revoked: []
55
+ }
56
+ };
57
+ }
55
58
  const persisted = readPersistedSecrets(source);
56
59
  const complete = (!storageEnabled || Boolean(persisted.accessKeyId && persisted.secretAccessKey)) && (!gatewayEnabled || Boolean(persisted.apiToken));
57
60
  const named = persisted.accessKeyId !== "" || persisted.apiToken !== "" ? namedCredentials(await api.listCredentials(options.projectId, branch.id), persisted) : {
@@ -66,11 +69,12 @@ async function fetchEnvReusingSecrets(config, options) {
66
69
  const keep = reusable !== null && credentialScopesSatisfied(reusable.scopes, scopes);
67
70
  const allKeys = policyEnvKeys(desired);
68
71
  const fetchKeys = keep ? allKeys.filter((key) => !secretKeys.includes(key)) : allKeys;
69
- const vars = preferPersisted(toEntries(await fetchEnvKeys(config, {
72
+ const fetched = await fetchEnvKeys(config, {
70
73
  ...fetchOptions,
71
74
  branchId: branch.id,
72
75
  api
73
- }, fetchKeys)), source);
76
+ }, fetchKeys);
77
+ const vars = preferPersisted(toEntries(fetched), source);
74
78
  if (keep) {
75
79
  for (const key of secretKeys) {
76
80
  const value = source[key];
@@ -1 +1 @@
1
- {"version":3,"file":"reuse-secrets.js","names":[],"sources":["../../src/lib/reuse-secrets.ts"],"sourcesContent":["import {\n\ttype Config,\n\tcredentialScopesSatisfied,\n\ttype NeonCredentialMeta,\n} from \"@neon/config/v1\";\n\nimport {\n\tcreateApiFromOptions,\n\tcredentialEnvKeys,\n\tcredentialName,\n\ttype FetchEnvOptions,\n\tfetchEnvKeys,\n\tNEON_ENV_VAR_KEYS,\n\tpolicyEnvKeys,\n\tpreviewCredentialScopes,\n\tresolveBranchPolicy,\n\ttoEntries,\n} from \"./env.js\";\n\n/**\n * What happened to the branch credential during a {@link fetchEnvReusingSecrets} call.\n */\nexport interface CredentialOutcome {\n\t/**\n\t * `true` when a new credential was minted — because none was persisted, or because the\n\t * persisted secrets could not be verified against this branch. `false` when the persisted\n\t * secrets were verified and kept, and when the policy enables nothing credential-backed.\n\t */\n\tissued: boolean;\n\t/**\n\t * The env-var keys the branch credential's secrets surface under, given what the policy\n\t * enables. Empty when the policy enables neither object storage nor the AI Gateway.\n\t */\n\tkeys: string[];\n\t/**\n\t * `tokenId`s revoked because this call superseded them. Only ever credentials the persisted\n\t * secrets named *and* that this tool issued; empty otherwise.\n\t */\n\trevoked: string[];\n}\n\n/** A resolved branch env, ready to write to a dotenv file or inject into a process. */\nexport interface ReusedBranchEnv {\n\t/** Every Neon env var for the branch, as `{ KEY: value }`. */\n\tvars: Record<string, string>;\n\t/** What happened to the branch credential. */\n\tcredential: CredentialOutcome;\n}\n\n/** The branch credential's secrets as persisted in an env source. Empty string means absent. */\ninterface PersistedSecrets {\n\taccessKeyId: string;\n\tsecretAccessKey: string;\n\tapiToken: string;\n}\n\n/**\n * Resolve a branch's env while keeping one-time secrets the caller already holds.\n *\n * {@link fetchEnvKeys} — and the public `fetchEnv` — only ever *fetch*. The Neon API returns a\n * credential's `api_token` / `s3_secret_access_key` exactly once, at mint time, so \"fetching\"\n * them means minting a new credential; a plain `fetchEnv` on every `neon dev` start or `env\n * pull` would leave a live credential behind each time. This is the wrapper that avoids that:\n * it looks at what the caller already has, decides what is still usable, and asks `fetchEnv`\n * for only the rest.\n *\n * The check is a real verification, not a presence test. A persisted secret is kept only when\n * it names a credential that still exists on this branch, is not revoked or expired, and\n * carries every scope the policy needs. A `.env.example` placeholder, a credential revoked in\n * the console, one copied in from another branch, or one predating a newly-enabled feature all\n * fail that check and get replaced.\n *\n * None of this needs local bookkeeping, because the secrets carry their own credential id:\n * `AWS_ACCESS_KEY_ID` **is** the credential's `tokenId` (the storage gateway authenticates\n * against the full id), and the AI Gateway token is minted as `nt_live_<tokenIdShort>_<secret>`,\n * where `tokenIdShort` is what the credentials list reports. The env source being replaced is\n * the record of what the last call issued.\n *\n * ```ts\n * import { fetchEnvReusingSecrets } from \"@neon/env/runtime\";\n *\n * const { vars, credential } = await fetchEnvReusingSecrets(config, {\n * projectId,\n * branch: \"main\",\n * env: { ...process.env, ...readEnvFile(\".env\") },\n * });\n * if (credential.issued) console.log(`new values for ${credential.keys.join(\", \")}`);\n * ```\n */\nexport async function fetchEnvReusingSecrets<const C extends Config>(\n\tconfig: C,\n\toptions: FetchEnvOptions & {\n\t\t/**\n\t\t * Env source holding secrets a previous call persisted — `process.env` layered with a\n\t\t * `.env` file, typically. Defaults to `process.env`.\n\t\t */\n\t\tenv?: NodeJS.ProcessEnv;\n\t},\n): Promise<ReusedBranchEnv> {\n\tconst { env: source = process.env, ...fetchOptions } = options;\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst { branch, desired } = await resolveBranchPolicy(config, options, api);\n\n\tconst storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;\n\tconst gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;\n\tconst secretKeys = credentialEnvKeys({\n\t\tstorage: storageEnabled,\n\t\taiGateway: gatewayEnabled,\n\t});\n\n\t// Nothing credential-backed on this branch, so there is nothing to preserve and no\n\t// credential to spend: fetch everything and skip the credentials endpoint entirely.\n\tif (secretKeys.length === 0) {\n\t\tconst fetched = await fetchEnvKeys(config, fetchOptions, null);\n\t\treturn {\n\t\t\tvars: preferPersisted(toEntries(fetched), source),\n\t\t\tcredential: { issued: false, keys: [], revoked: [] },\n\t\t};\n\t}\n\n\tconst persisted = readPersistedSecrets(source);\n\tconst complete =\n\t\t(!storageEnabled ||\n\t\t\tBoolean(persisted.accessKeyId && persisted.secretAccessKey)) &&\n\t\t(!gatewayEnabled || Boolean(persisted.apiToken));\n\n\t// Look the persisted secrets up whenever there are any — not only when they're complete.\n\t// An incomplete set still names the credential a newly-enabled feature is about to\n\t// supersede (a storage-only credential on a branch that just gained the AI Gateway), and\n\t// that one should be revoked rather than left live.\n\tconst named =\n\t\tpersisted.accessKeyId !== \"\" || persisted.apiToken !== \"\"\n\t\t\t? namedCredentials(\n\t\t\t\t\tawait api.listCredentials(options.projectId, branch.id),\n\t\t\t\t\tpersisted,\n\t\t\t\t)\n\t\t\t: { storage: null, gateway: null };\n\n\tconst reusable = complete\n\t\t? reusableCredential(named, { storageEnabled, gatewayEnabled })\n\t\t: null;\n\tconst scopes = previewCredentialScopes(desired.preview);\n\tconst keep =\n\t\treusable !== null && credentialScopesSatisfied(reusable.scopes, scopes);\n\n\t// Ask for everything the policy produces, minus the secrets we're keeping — which is what\n\t// stops `fetchEnv` from minting a credential it doesn't need.\n\tconst allKeys = policyEnvKeys(desired);\n\tconst fetchKeys = keep\n\t\t? allKeys.filter((key) => !secretKeys.includes(key))\n\t\t: allKeys;\n\tconst fetched = await fetchEnvKeys(\n\t\tconfig,\n\t\t// Pass the resolved id so `fetchEnv` targets the same branch this call verified against,\n\t\t// even if `options.branch` was a name that has since been reused.\n\t\t{ ...fetchOptions, branchId: branch.id, api },\n\t\tfetchKeys,\n\t);\n\n\tconst vars = preferPersisted(toEntries(fetched), source);\n\tif (keep) {\n\t\tfor (const key of secretKeys) {\n\t\t\tconst value = source[key];\n\t\t\tif (value !== undefined) vars[key] = value;\n\t\t}\n\t\treturn {\n\t\t\tvars,\n\t\t\tcredential: { issued: false, keys: secretKeys, revoked: [] },\n\t\t};\n\t}\n\n\t// A replacement was minted, so revoke what it supersedes: the credentials the old secrets\n\t// named, minus any this tool did not issue. Their secrets lived nowhere but the env source\n\t// this call replaces, so revoking them strands nothing — and it keeps a branch from\n\t// accumulating a live credential per call. Everything else on the branch is left alone: it\n\t// may belong to a teammate, another checkout, or a deployed function, and nothing\n\t// observable distinguishes those from an orphan of our own.\n\t//\n\t// Revoked *after* the fetch, so a failed fetch leaves the caller's existing secrets working.\n\tconst ours = new Set<string>();\n\tfor (const meta of [named.storage, named.gateway]) {\n\t\tif (\n\t\t\tmeta !== null &&\n\t\t\tmeta.principalType === \"user\" &&\n\t\t\tmeta.name === credentialName(branch.name)\n\t\t) {\n\t\t\tours.add(meta.tokenId);\n\t\t}\n\t}\n\tfor (const tokenId of ours) {\n\t\tawait api.revokeCredential(options.projectId, branch.id, tokenId);\n\t}\n\n\treturn {\n\t\tvars,\n\t\tcredential: { issued: true, keys: secretKeys, revoked: [...ours] },\n\t};\n}\n\n/** Read the branch credential's secrets out of an env source. */\nfunction readPersistedSecrets(source: NodeJS.ProcessEnv): PersistedSecrets {\n\tconst storage = NEON_ENV_VAR_KEYS.storage;\n\tconst gateway = NEON_ENV_VAR_KEYS.aiGateway;\n\treturn {\n\t\taccessKeyId: source[storage.accessKeyId] ?? \"\",\n\t\tsecretAccessKey: source[storage.secretAccessKey] ?? \"\",\n\t\tapiToken: source[gateway.apiKey] ?? \"\",\n\t};\n}\n\n/**\n * Keep a persisted value rather than overwriting it with an empty fetched one.\n *\n * Neon Auth's `base_url` is the case that needs this: integrations created before the API\n * returned it answer with an empty string, and the persisted copy is the only one left. An\n * empty fetched value never carries more information than a non-empty persisted one, so\n * preferring the latter is safe for every var — and it keeps a pull from blanking a working\n * line in someone's `.env`.\n */\nfunction preferPersisted(\n\tvars: Record<string, string>,\n\tsource: NodeJS.ProcessEnv,\n): Record<string, string> {\n\tconst out = { ...vars };\n\tfor (const [key, value] of Object.entries(out)) {\n\t\tif (value !== \"\") continue;\n\t\tconst persisted = source[key];\n\t\tif (persisted !== undefined && persisted !== \"\") out[key] = persisted;\n\t}\n\treturn out;\n}\n\n/**\n * The credential id embedded in an AI Gateway token. The API mints them as\n * `nt_live_<tokenIdShort>_<secret>`, and `tokenIdShort` is the public identifier the credentials\n * list reports — so a persisted token names the credential that issued it. Returns `null` for\n * anything not in that shape (a `.env.example` placeholder, a hand-typed value), which callers\n * treat as unverifiable.\n */\nfunction gatewayTokenIdShort(apiToken: string): string | null {\n\treturn /^nt_live_([^_]+)_.+$/.exec(apiToken)?.[1] ?? null;\n}\n\n/** Whether an issued credential can still be used: not revoked, not past its expiry. */\nfunction isLiveCredential(meta: NeonCredentialMeta, now: number): boolean {\n\tif (meta.revokedAt !== undefined) return false;\n\tif (meta.expiresAt === undefined) return true;\n\tconst expiresAt = Date.parse(meta.expiresAt);\n\treturn Number.isNaN(expiresAt) || expiresAt > now;\n}\n\n/**\n * The live credentials the persisted secrets name — at most one per half. A half that names\n * nothing contributes nothing, which is what a placeholder, a credential revoked in the\n * console, and one copied in from another branch all look like from here.\n */\nfunction namedCredentials(\n\tlive: NeonCredentialMeta[],\n\tpersisted: PersistedSecrets,\n): { storage: NeonCredentialMeta | null; gateway: NeonCredentialMeta | null } {\n\tconst usable = live.filter((meta) => isLiveCredential(meta, Date.now()));\n\tconst shortId = persisted.apiToken\n\t\t? gatewayTokenIdShort(persisted.apiToken)\n\t\t: null;\n\treturn {\n\t\tstorage: persisted.accessKeyId\n\t\t\t? (usable.find((meta) => meta.tokenId === persisted.accessKeyId) ??\n\t\t\t\tnull)\n\t\t\t: null,\n\t\tgateway: shortId\n\t\t\t? (usable.find((meta) => meta.tokenIdShort === shortId) ?? null)\n\t\t\t: null,\n\t};\n}\n\n/**\n * The credential the persisted secrets can be *reused* as, or `null`.\n *\n * Strict on purpose: every half the policy enables has to name a live credential, and when both\n * features are enabled they must name the *same* one — they share a single credential, so\n * halves that disagree came from two different calls and neither can be trusted.\n */\nfunction reusableCredential(\n\tnamed: ReturnType<typeof namedCredentials>,\n\tenabled: { storageEnabled: boolean; gatewayEnabled: boolean },\n): NeonCredentialMeta | null {\n\tif (enabled.storageEnabled && enabled.gatewayEnabled) {\n\t\treturn named.storage &&\n\t\t\tnamed.gateway &&\n\t\t\tnamed.storage.tokenId === named.gateway.tokenId\n\t\t\t? named.storage\n\t\t\t: null;\n\t}\n\tif (enabled.storageEnabled) return named.storage;\n\tif (enabled.gatewayEnabled) return named.gateway;\n\treturn null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,eAAsB,uBACrB,QACA,SAO2B;CAC3B,MAAM,EAAE,KAAK,SAAS,QAAQ,KAAK,GAAG,iBAAiB;CACvD,MAAM,MAAM,QAAQ,OAAO,qBAAqB,OAAO;CACvD,MAAM,EAAE,QAAQ,YAAY,MAAM,oBAAoB,QAAQ,SAAS,GAAG;CAE1E,MAAM,kBAAkB,QAAQ,SAAS,QAAQ,UAAU,KAAK;CAChE,MAAM,iBAAiB,QAAQ,SAAS,oBAAoB;CAC5D,MAAM,aAAa,kBAAkB;EACpC,SAAS;EACT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AO,MAAM,SAAS,KAAK,YAAY,UAAU,WAAW,KAC9D,OACC;EACH,SAAS,UACL,OAAO,MAAM,SAAS,KAAK,iBAAiB,OAAO,KAAK,OACzD;CACJ;AACD;;;;;;;;AASA,SAAS,mBACR,OACA,SAC4B;CAC5B,IAAI,QAAQ,kBAAkB,QAAQ,gBACrC,OAAO,MAAM,WACZ,MAAM,WACN,MAAM,QAAQ,YAAY,MAAM,QAAQ,UACtC,MAAM,UACN;CAEJ,IAAI,QAAQ,gBAAgB,OAAO,MAAM;CACzC,IAAI,QAAQ,gBAAgB,OAAO,MAAM;CACzC,OAAO;AACR"}
1
+ {"version":3,"file":"reuse-secrets.js","names":[],"sources":["../../src/lib/reuse-secrets.ts"],"sourcesContent":["import {\n\ttype Config,\n\tcredentialScopesSatisfied,\n\ttype NeonCredentialMeta,\n} from \"@neon/config/v1\";\n\nimport {\n\tcreateApiFromOptions,\n\tcredentialEnvKeys,\n\tcredentialName,\n\ttype FetchEnvOptions,\n\tfetchEnvKeys,\n\tNEON_ENV_VAR_KEYS,\n\tpolicyEnvKeys,\n\tpreviewCredentialScopes,\n\tresolveBranchPolicy,\n\ttoEntries,\n} from \"./env.js\";\n\n/**\n * What happened to the branch credential during a {@link fetchEnvReusingSecrets} call.\n */\nexport interface CredentialOutcome {\n\t/**\n\t * `true` when a new credential was minted — because none was persisted, or because the\n\t * persisted secrets could not be verified against this branch. `false` when the persisted\n\t * secrets were verified and kept, and when the policy enables nothing credential-backed.\n\t */\n\tissued: boolean;\n\t/**\n\t * The env-var keys the branch credential's secrets surface under, given what the policy\n\t * enables. Empty when the policy enables neither object storage nor the AI Gateway.\n\t */\n\tkeys: string[];\n\t/**\n\t * `tokenId`s revoked because this call superseded them. Only ever credentials the persisted\n\t * secrets named *and* that this tool issued; empty otherwise.\n\t */\n\trevoked: string[];\n}\n\n/** A resolved branch env, ready to write to a dotenv file or inject into a process. */\nexport interface ReusedBranchEnv {\n\t/** Every Neon env var for the branch, as `{ KEY: value }`. */\n\tvars: Record<string, string>;\n\t/** What happened to the branch credential. */\n\tcredential: CredentialOutcome;\n}\n\n/** The branch credential's secrets as persisted in an env source. Empty string means absent. */\ninterface PersistedSecrets {\n\taccessKeyId: string;\n\tsecretAccessKey: string;\n\tapiToken: string;\n}\n\n/**\n * Resolve a branch's env while keeping one-time secrets the caller already holds.\n *\n * {@link fetchEnvKeys} — and the public `fetchEnv` — only ever *fetch*. The Neon API returns a\n * credential's `api_token` / `s3_secret_access_key` exactly once, at mint time, so \"fetching\"\n * them means minting a new credential; a plain `fetchEnv` on every `neon dev` start or `env\n * pull` would leave a live credential behind each time. This is the wrapper that avoids that:\n * it looks at what the caller already has, decides what is still usable, and asks `fetchEnv`\n * for only the rest.\n *\n * The check is a real verification, not a presence test. A persisted secret is kept only when\n * it names a credential that still exists on this branch, is not revoked or expired, and\n * carries every scope the policy needs. A `.env.example` placeholder, a credential revoked in\n * the console, one copied in from another branch, or one predating a newly-enabled feature all\n * fail that check and get replaced.\n *\n * None of this needs local bookkeeping, because the secrets carry their own credential id:\n * `AWS_ACCESS_KEY_ID` **is** the credential's `tokenId` (the storage gateway authenticates\n * against the full id), and the AI Gateway token is minted as `nt_live_<tokenIdShort>_<secret>`,\n * where `tokenIdShort` is what the credentials list reports. The env source being replaced is\n * the record of what the last call issued.\n *\n * ```ts\n * import { fetchEnvReusingSecrets } from \"@neon/env/runtime\";\n *\n * const { vars, credential } = await fetchEnvReusingSecrets(config, {\n * projectId,\n * branch: \"main\",\n * env: { ...process.env, ...readEnvFile(\".env\") },\n * });\n * if (credential.issued) console.log(`new values for ${credential.keys.join(\", \")}`);\n * ```\n */\nexport async function fetchEnvReusingSecrets<const C extends Config>(\n\tconfig: C,\n\toptions: FetchEnvOptions & {\n\t\t/**\n\t\t * Env source holding secrets a previous call persisted — `process.env` layered with a\n\t\t * `.env` file, typically. Defaults to `process.env`.\n\t\t */\n\t\tenv?: NodeJS.ProcessEnv;\n\t},\n): Promise<ReusedBranchEnv> {\n\tconst { env: source = process.env, ...fetchOptions } = options;\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst { branch, desired } = await resolveBranchPolicy(config, options, api);\n\n\tconst storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;\n\tconst gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;\n\tconst secretKeys = credentialEnvKeys({\n\t\tstorage: storageEnabled,\n\t\taiGateway: gatewayEnabled,\n\t});\n\n\t// Nothing credential-backed on this branch, so there is nothing to preserve and no\n\t// credential to spend: fetch everything and skip the credentials endpoint entirely.\n\tif (secretKeys.length === 0) {\n\t\tconst fetched = await fetchEnvKeys(config, fetchOptions, null);\n\t\treturn {\n\t\t\tvars: preferPersisted(toEntries(fetched), source),\n\t\t\tcredential: { issued: false, keys: [], revoked: [] },\n\t\t};\n\t}\n\n\tconst persisted = readPersistedSecrets(source);\n\tconst complete =\n\t\t(!storageEnabled ||\n\t\t\tBoolean(persisted.accessKeyId && persisted.secretAccessKey)) &&\n\t\t(!gatewayEnabled || Boolean(persisted.apiToken));\n\n\t// Look the persisted secrets up whenever there are any — not only when they're complete.\n\t// An incomplete set still names the credential a newly-enabled feature is about to\n\t// supersede (a storage-only credential on a branch that just gained the AI Gateway), and\n\t// that one should be revoked rather than left live.\n\tconst named =\n\t\tpersisted.accessKeyId !== \"\" || persisted.apiToken !== \"\"\n\t\t\t? namedCredentials(\n\t\t\t\t\tawait api.listCredentials(options.projectId, branch.id),\n\t\t\t\t\tpersisted,\n\t\t\t\t)\n\t\t\t: { storage: null, gateway: null };\n\n\tconst reusable = complete\n\t\t? reusableCredential(named, { storageEnabled, gatewayEnabled })\n\t\t: null;\n\tconst scopes = previewCredentialScopes(desired.preview);\n\tconst keep =\n\t\treusable !== null && credentialScopesSatisfied(reusable.scopes, scopes);\n\n\t// Ask for everything the policy produces, minus the secrets we're keeping — which is what\n\t// stops `fetchEnv` from minting a credential it doesn't need.\n\tconst allKeys = policyEnvKeys(desired);\n\tconst fetchKeys = keep\n\t\t? allKeys.filter((key) => !secretKeys.includes(key))\n\t\t: allKeys;\n\tconst fetched = await fetchEnvKeys(\n\t\tconfig,\n\t\t// Pass the resolved id so `fetchEnv` targets the same branch this call verified against,\n\t\t// even if `options.branch` was a name that has since been reused.\n\t\t{ ...fetchOptions, branchId: branch.id, api },\n\t\tfetchKeys,\n\t);\n\n\tconst vars = preferPersisted(toEntries(fetched), source);\n\tif (keep) {\n\t\tfor (const key of secretKeys) {\n\t\t\tconst value = source[key];\n\t\t\tif (value !== undefined) vars[key] = value;\n\t\t}\n\t\treturn {\n\t\t\tvars,\n\t\t\tcredential: { issued: false, keys: secretKeys, revoked: [] },\n\t\t};\n\t}\n\n\t// A replacement was minted, so revoke what it supersedes: the credentials the old secrets\n\t// named, minus any this tool did not issue. Their secrets lived nowhere but the env source\n\t// this call replaces, so revoking them strands nothing — and it keeps a branch from\n\t// accumulating a live credential per call. Everything else on the branch is left alone: it\n\t// may belong to a teammate, another checkout, or a deployed function, and nothing\n\t// observable distinguishes those from an orphan of our own.\n\t//\n\t// Revoked *after* the fetch, so a failed fetch leaves the caller's existing secrets working.\n\tconst ours = new Set<string>();\n\tfor (const meta of [named.storage, named.gateway]) {\n\t\tif (\n\t\t\tmeta !== null &&\n\t\t\tmeta.principalType === \"user\" &&\n\t\t\tmeta.name === credentialName(branch.name)\n\t\t) {\n\t\t\tours.add(meta.tokenId);\n\t\t}\n\t}\n\tfor (const tokenId of ours) {\n\t\tawait api.revokeCredential(options.projectId, branch.id, tokenId);\n\t}\n\n\treturn {\n\t\tvars,\n\t\tcredential: { issued: true, keys: secretKeys, revoked: [...ours] },\n\t};\n}\n\n/** Read the branch credential's secrets out of an env source. */\nfunction readPersistedSecrets(source: NodeJS.ProcessEnv): PersistedSecrets {\n\tconst storage = NEON_ENV_VAR_KEYS.storage;\n\tconst gateway = NEON_ENV_VAR_KEYS.aiGateway;\n\treturn {\n\t\taccessKeyId: source[storage.accessKeyId] ?? \"\",\n\t\tsecretAccessKey: source[storage.secretAccessKey] ?? \"\",\n\t\tapiToken: source[gateway.apiKey] ?? \"\",\n\t};\n}\n\n/**\n * Keep a persisted value rather than overwriting it with an empty fetched one.\n *\n * Neon Auth's `base_url` is the case that needs this: integrations created before the API\n * returned it answer with an empty string, and the persisted copy is the only one left. An\n * empty fetched value never carries more information than a non-empty persisted one, so\n * preferring the latter is safe for every var — and it keeps a pull from blanking a working\n * line in someone's `.env`.\n */\nfunction preferPersisted(\n\tvars: Record<string, string>,\n\tsource: NodeJS.ProcessEnv,\n): Record<string, string> {\n\tconst out = { ...vars };\n\tfor (const [key, value] of Object.entries(out)) {\n\t\tif (value !== \"\") continue;\n\t\tconst persisted = source[key];\n\t\tif (persisted !== undefined && persisted !== \"\") out[key] = persisted;\n\t}\n\treturn out;\n}\n\n/**\n * The credential id embedded in an AI Gateway token. The API mints them as\n * `nt_live_<tokenIdShort>_<secret>`, and `tokenIdShort` is the public identifier the credentials\n * list reports — so a persisted token names the credential that issued it. Returns `null` for\n * anything not in that shape (a `.env.example` placeholder, a hand-typed value), which callers\n * treat as unverifiable.\n */\nfunction gatewayTokenIdShort(apiToken: string): string | null {\n\treturn /^nt_live_([^_]+)_.+$/.exec(apiToken)?.[1] ?? null;\n}\n\n/** Whether an issued credential can still be used: not revoked, not past its expiry. */\nfunction isLiveCredential(meta: NeonCredentialMeta, now: number): boolean {\n\tif (meta.revokedAt !== undefined) return false;\n\tif (meta.expiresAt === undefined) return true;\n\tconst expiresAt = Date.parse(meta.expiresAt);\n\treturn Number.isNaN(expiresAt) || expiresAt > now;\n}\n\n/**\n * The live credentials the persisted secrets name — at most one per half. A half that names\n * nothing contributes nothing, which is what a placeholder, a credential revoked in the\n * console, and one copied in from another branch all look like from here.\n */\nfunction namedCredentials(\n\tlive: NeonCredentialMeta[],\n\tpersisted: PersistedSecrets,\n): { storage: NeonCredentialMeta | null; gateway: NeonCredentialMeta | null } {\n\tconst usable = live.filter((meta) => isLiveCredential(meta, Date.now()));\n\tconst shortId = persisted.apiToken\n\t\t? gatewayTokenIdShort(persisted.apiToken)\n\t\t: null;\n\treturn {\n\t\tstorage: persisted.accessKeyId\n\t\t\t? (usable.find((meta) => meta.tokenId === persisted.accessKeyId) ??\n\t\t\t\tnull)\n\t\t\t: null,\n\t\tgateway: shortId\n\t\t\t? (usable.find((meta) => meta.tokenIdShort === shortId) ?? null)\n\t\t\t: null,\n\t};\n}\n\n/**\n * The credential the persisted secrets can be *reused* as, or `null`.\n *\n * Strict on purpose: every half the policy enables has to name a live credential, and when both\n * features are enabled they must name the *same* one — they share a single credential, so\n * halves that disagree came from two different calls and neither can be trusted.\n */\nfunction reusableCredential(\n\tnamed: ReturnType<typeof namedCredentials>,\n\tenabled: { storageEnabled: boolean; gatewayEnabled: boolean },\n): NeonCredentialMeta | null {\n\tif (enabled.storageEnabled && enabled.gatewayEnabled) {\n\t\treturn named.storage &&\n\t\t\tnamed.gateway &&\n\t\t\tnamed.storage.tokenId === named.gateway.tokenId\n\t\t\t? named.storage\n\t\t\t: null;\n\t}\n\tif (enabled.storageEnabled) return named.storage;\n\tif (enabled.gatewayEnabled) return named.gateway;\n\treturn null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,eAAsB,uBACrB,QACA,SAO2B;CAC3B,MAAM,EAAE,KAAK,SAAS,QAAQ,KAAK,GAAG,iBAAiB;CACvD,MAAM,MAAM,QAAQ,OAAO,qBAAqB,OAAO;CACvD,MAAM,EAAE,QAAQ,YAAY,MAAM,oBAAoB,QAAQ,SAAS,GAAG;CAE1E,MAAM,kBAAkB,QAAQ,SAAS,QAAQ,UAAU,KAAK;CAChE,MAAM,iBAAiB,QAAQ,SAAS,oBAAoB;CAC5D,MAAM,aAAa,kBAAkB;EACpC,SAAS;EACT,WAAW;CACZ,CAAC;CAID,IAAI,WAAW,WAAW,GAAG;EAC5B,MAAM,UAAU,MAAM,aAAa,QAAQ,cAAc,IAAI;EAC7D,OAAO;GACN,MAAM,gBAAgB,UAAU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K,iBAAiB,OAAO,KAAK,OACzD;CACJ;AACD;;;;;;;;AASA,SAAS,mBACR,OACA,SAC4B;CAC5B,IAAI,QAAQ,kBAAkB,QAAQ,gBACrC,OAAO,MAAM,WACZ,MAAM,WACN,MAAM,QAAQ,YAAY,MAAM,QAAQ,UACtC,MAAM,UACN;CAEJ,IAAI,QAAQ,gBAAgB,OAAO,MAAM;CACzC,IAAI,QAAQ,gBAAgB,OAAO,MAAM;CACzC,OAAO;AACR"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neondatabase/env",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "Resolve and inject Neon connection strings for the branch selected by your neon.ts policy. fetchEnv / parseEnv plus a `neon-env` CLI with `run` and `export`.",
5
5
  "keywords": [
6
6
  "neon",
@@ -50,13 +50,13 @@
50
50
  "tsdown": "^0.14.1",
51
51
  "typescript": "^5.9.0",
52
52
  "vitest": "^3.0.9",
53
- "@neon/e2e-harness": "0.0.0",
54
- "@neon/sdk": "1.5.0"
53
+ "@neon/sdk": "1.5.0",
54
+ "@neon/e2e-harness": "0.0.0"
55
55
  },
56
56
  "dependencies": {
57
57
  "zod": "^4.4.3",
58
58
  "yargs": "^18.0.0",
59
- "@neon/config": "0.14.0"
59
+ "@neon/config": "0.14.1"
60
60
  },
61
61
  "engines": {
62
62
  "node": ">=20.19.0"