neon 8.23.4 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +8 -7
  2. package/dist/_chunks/{checkout-OEE3GTc_.js → checkout-B_gbS0nD.js} +3 -3
  3. package/dist/_chunks/{claim-C-9or54_.js → claim-BVEwQ65H.js} +1 -1
  4. package/dist/_chunks/{config-DPuP7ywm.js → config-BClSMzco.js} +1 -1
  5. package/dist/_chunks/{deploy-CpF33Ij-.js → deploy-CJ22hy3i.js} +1 -1
  6. package/dist/_chunks/{dev-BE5TL7ZH.js → dev-CSoQfCuS.js} +19 -20
  7. package/dist/_chunks/{env-CIFMBEon.js → env-CFBmcKyo.js} +18 -45
  8. package/dist/_chunks/{env-C4-EYFmE.js → env-DxcO3oJk.js} +21 -23
  9. package/dist/_chunks/{env-JgoSsmyt.js → env-EJU-0InB.js} +49 -110
  10. package/dist/_chunks/{git-R8RebFpF.js → git-C6XPViK5.js} +2 -2
  11. package/dist/_chunks/{link-PLk7-vwB.js → link-n40BxbmK.js} +2 -2
  12. package/dist/_chunks/{status-BjaHpnTV.js → status-TDYLPWRO.js} +1 -1
  13. package/dist/commands/checkout.js +1 -1
  14. package/dist/commands/claim.js +1 -1
  15. package/dist/commands/config.js +1 -1
  16. package/dist/commands/deploy.js +1 -1
  17. package/dist/commands/dev.js +1 -1
  18. package/dist/commands/env.js +1 -1
  19. package/dist/commands/env_output.js +4 -4
  20. package/dist/commands/functions_new.js +1 -1
  21. package/dist/commands/git.js +1 -1
  22. package/dist/commands/index.js +9 -9
  23. package/dist/commands/link.js +1 -1
  24. package/dist/commands/status.js +1 -1
  25. package/dist/commands/subscribe.js +1 -1
  26. package/dist/dev/env.js +1 -1
  27. package/dist/env_services.js +30 -23
  28. package/dist/errors.js +2 -1
  29. package/dist/init/auth.js +1 -1
  30. package/dist/init/choices.js +8 -6
  31. package/dist/init/deploy.js +1 -1
  32. package/dist/init/link.js +1 -1
  33. package/dist/init/run.js +3 -3
  34. package/dist/utils/hooks.js +9 -4
  35. package/package.json +6 -6
package/README.md CHANGED
@@ -601,9 +601,8 @@ neon env pull -e DATABASE_URL,NEON_AUTH_BASE_URL
601
601
  # The selectors compose as a union: all Auth vars plus DATABASE_URL
602
602
  neon env pull -s auth -e DATABASE_URL
603
603
 
604
- # Function invocation URLs
604
+ # The variables functionBaseUrl("<slug>") from @neon/env reads
605
605
  neon env pull -s functions
606
- neon env pull -e NEON_FUNCTION_HELLO_BASE_URL
607
606
  ```
608
607
 
609
608
  Every services flag in the CLI takes those three spellings, the same value syntax, and the same service names — see [`config init --services`](#getting-a-neonts-config-init).
@@ -613,15 +612,17 @@ Every services flag in the CLI takes those three spellings, the same value synta
613
612
  | `postgres` | `DATABASE_URL`, `DATABASE_URL_UNPOOLED` |
614
613
  | `auth` | `NEON_AUTH_BASE_URL`, `NEON_AUTH_JWKS_URL` |
615
614
  | `data-api` | `NEON_DATA_API_URL` |
616
- | `functions` | `NEON_FUNCTION_<SLUG>_BASE_URL` for each deployed function |
615
+ | `functions` | `NEON_FUNCTION_HOST_SUFFIX` |
617
616
  | `object-storage` | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_ENDPOINT_URL_S3`, `AWS_REGION` |
618
617
  | `ai-gateway` | `NEON_AI_GATEWAY_TOKEN`, `NEON_AI_GATEWAY_BASE_URL` |
619
618
 
620
- `-e, --env` accepts any variable in the table plus `NEON_BRANCH`, or `NEON_FUNCTION_<SLUG>_BASE_URL` where `<SLUG>` is the function slug uppercased. It is case-sensitive and rejects unknown names rather than silently widening the pull. `NEON_BRANCH` is written by unscoped and service-scoped pulls because it is branch identity, not a service; an env-only pull writes it only when you select it.
619
+ `-e, --env` accepts any variable in the table plus `NEON_BRANCH` and `NEON_BRANCH_ID`. It is case-sensitive and rejects unknown names rather than silently widening the pull. `NEON_BRANCH` and `NEON_BRANCH_ID` are written by unscoped and service-scoped pulls because they are branch identity, not a service; an env-only pull writes them only when you select them.
621
620
 
622
- `--env` never narrows `--service`: `neon env pull -s postgres -e DATABASE_URL` still pulls the complete Postgres bundle (`DATABASE_URL`, `DATABASE_URL_UNPOOLED`, and `NEON_BRANCH`). The two selectors always form a union.
621
+ `NEON_BRANCH_ID` and `NEON_FUNCTION_HOST_SUFFIX` are what `functionBaseUrl("<slug>")` from `@neon/env` builds a function's URL from, and what the Functions runtime injects into every deployed function. An unscoped pull writes both whether or not `neon.ts` declares functions. Earlier releases wrote one `NEON_FUNCTION_<SLUG>_BASE_URL` per function instead; an unscoped or `-s functions` pull removes those lines, and `-e NEON_FUNCTION_<SLUG>_BASE_URL` fails with a pointer to `functionBaseUrl`.
623
622
 
624
- **A scoped pull is scoped in both directions.** An unscoped `env pull` owns the Neon-named variables: pointing a directory at a branch without Neon Auth prunes the stale `NEON_AUTH_*` lines, and a branch without those functions prunes stale `NEON_FUNCTION_*_BASE_URL` lines. `--service` narrows that to the services you named, while `--env` narrows it to the exact keys you named, so `env pull -e DATABASE_URL` never touches `DATABASE_URL_UNPOOLED`. (`AWS_*` is never pruned by any pull: those names collide with credentials you may set yourself, so `env pull` only ever writes them.)
623
+ `--env` never narrows `--service`: `neon env pull -s postgres -e DATABASE_URL` still pulls the complete Postgres bundle (`DATABASE_URL`, `DATABASE_URL_UNPOOLED`, `NEON_BRANCH`, and `NEON_BRANCH_ID`). The two selectors always form a union.
624
+
625
+ **A scoped pull is scoped in both directions.** An unscoped `env pull` owns the Neon-named variables: pointing a directory at a branch without Neon Auth prunes the stale `NEON_AUTH_*` lines. `--service` narrows that to the services you named, while `--env` narrows it to the exact keys you named, so `env pull -e DATABASE_URL` never touches `DATABASE_URL_UNPOOLED`. (`AWS_*` is never pruned by any pull: those names collide with credentials you may set yourself, so `env pull` only ever writes them.)
625
626
 
626
627
  **A scoped pull also never revokes a credential.** Where an unscoped pull revokes the credential it replaces, a scoped one leaves the old one live — it can't tell which other variables still use it. It says so when it happens; revoke it in the Neon Console if nothing does.
627
628
 
@@ -639,7 +640,7 @@ Console), or drop auth from --service.
639
640
 
640
641
  If you'd rather not keep env vars on disk, inject them at runtime instead with `neon-env run -- <your dev command>` (from `@neon/env`) or `neon dev`, and pass `--no-env-pull` to `link` / `checkout`.
641
642
 
642
- **`neon dev` resolves the same set, by the same rules** — including the AI Gateway on a branch with no `neon.ts`. A function running locally gets the same Postgres / Auth / Data API / storage / AI Gateway vars a deploy would inject. Each `NEON_FUNCTION_<SLUG>_BASE_URL` this process is serving is rewritten to `http://localhost:<port>`: every neon.ts function, or the matching slug when `--source` names one. `neon env pull` and `neon-env run` write the production URL (`https://<branchId>-<slug>.compute.…`).
643
+ **`neon dev` resolves the same set, by the same rules** — including the AI Gateway on a branch with no `neon.ts`. A function running locally gets the same Postgres / Auth / Data API / storage / AI Gateway vars a deploy would inject. `dev` also sets `NEON_DEV_FUNCTION_PORTS`, a JSON map of the slugs this process is serving to their ports (every neon.ts function, or the matching slug when `--source` names one), so `functionBaseUrl("<slug>")` returns `http://localhost:<port>` for those and the deployed URL on the linked branch for any other slug.
643
644
 
644
645
  Before `neon.ts` is evaluated, `dev` loads the project directory's `.env`, then `.env.local`, which overrides it, into the environment, so Function env values written as `process.env.X!` resolve the same way they do for `neon deploy --env`. A variable already set in the shell wins over both. Local Functions inherit every loaded variable, including keys `neon.ts` doesn't declare; the deployed runtime gets only declared and Neon-injected env. `--env <file>` loads only that file, resolved from the current directory, matching `neon deploy --env`:
645
646
 
@@ -11,9 +11,9 @@ import { looksLikeBranchId } from "../utils/formats.js";
11
11
  import { fillSingleProject, listAllProjectBranches } from "../utils/enrichers.js";
12
12
  import { buildCheckoutEvent, readGitContext } from "../utils/git.js";
13
13
  import { buildHookBranch, loadHookConfig, resolveHookEnv, runCheckoutAfterHook, runCheckoutBeforeHook, runCreateAfterHook, runCreateBeforeHook } from "../utils/hooks.js";
14
- import { n as autoPullEnvAfterPin } from "./env-C4-EYFmE.js";
15
- import { a as applyPolicyOnCreate, f as envFlag, l as createBranchFromPolicyOnCheckout } from "./config-DPuP7ywm.js";
16
- import { i as handler$1 } from "./link-PLk7-vwB.js";
14
+ import { n as autoPullEnvAfterPin } from "./env-DxcO3oJk.js";
15
+ import { a as applyPolicyOnCreate, f as envFlag, l as createBranchFromPolicyOnCheckout } from "./config-BClSMzco.js";
16
+ import { i as handler$1 } from "./link-n40BxbmK.js";
17
17
  import chalk from "chalk";
18
18
  import prompts from "prompts";
19
19
  // src/commands/checkout.ts
@@ -12,7 +12,7 @@ import { projectConfigPath } from "../project.js";
12
12
  import { resolveEnvFilePath } from "../env_file.js";
13
13
  import { writer } from "../writer.js";
14
14
  import { noPassthrough } from "../utils/flags.js";
15
- import { c as pull } from "./env-C4-EYFmE.js";
15
+ import { c as pull } from "./env-DxcO3oJk.js";
16
16
  import { existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
17
17
  import open from "open";
18
18
  import prompts from "prompts";
@@ -26,7 +26,7 @@ import { readGitContext } from "../utils/git.js";
26
26
  import { resolveHookEnv, runDeployAfterHook, runDeployBeforeHook } from "../utils/hooks.js";
27
27
  import { pickServicesInteractively } from "../utils/service_picker.js";
28
28
  import { zipBundle } from "../utils/zip.js";
29
- import { n as autoPullEnvAfterPin } from "./env-C4-EYFmE.js";
29
+ import { n as autoPullEnvAfterPin } from "./env-DxcO3oJk.js";
30
30
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
31
31
  import { dirname, join, relative, resolve } from "node:path";
32
32
  import chalk from "chalk";
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.js";
2
2
  import { fillSingleProject } from "../utils/enrichers.js";
3
- import { f as envFlag, i as applyFlags, p as envPullFlag, r as applyCmd } from "./config-DPuP7ywm.js";
3
+ import { f as envFlag, i as applyFlags, p as envPullFlag, r as applyCmd } from "./config-BClSMzco.js";
4
4
  import { DEPLOY_COMMANDS_EPILOGUE } from "../commands/deploy_help.js";
5
5
  // src/commands/deploy.ts
6
6
  var deploy_exports = /* @__PURE__ */ __exportAll({
@@ -3,11 +3,11 @@ import { log } from "../log.js";
3
3
  import { isClaimableEnvTarget } from "../claimable/state.js";
4
4
  import { getCliName } from "../utils/cli_name.js";
5
5
  import { defaultDevEnvFiles, readEnvFile, resolveEnvFilePath } from "../env_file.js";
6
- import { l as functionBaseUrlKey } from "./env-JgoSsmyt.js";
6
+ import { t as NEON_DEV_FUNCTION_PORTS } from "./env-EJU-0InB.js";
7
7
  import { branchIdResolve } from "../utils/enrichers.js";
8
8
  import { bundleEntry } from "../utils/esbuild.js";
9
- import { a as resolveDevEnv } from "./env-CIFMBEon.js";
10
- import { f as envFlag } from "./config-DPuP7ywm.js";
9
+ import { a as resolveDevEnv } from "./env-CFBmcKyo.js";
10
+ import { f as envFlag } from "./config-BClSMzco.js";
11
11
  import { findConfigFunctionBySource, resolveFunctionsFromConfig } from "../dev/functions.js";
12
12
  import { resolveWatchInputs } from "../dev/inputs.js";
13
13
  import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -31,7 +31,7 @@ var dev_exports = /* @__PURE__ */ __exportAll({
31
31
  formatEnvSummary: () => formatEnvSummary,
32
32
  handler: () => handler,
33
33
  loadDevEnvFiles: () => loadDevEnvFiles,
34
- localFunctionUrlEnv: () => localFunctionUrlEnv,
34
+ localFunctionPortsEnv: () => localFunctionPortsEnv,
35
35
  planFunctionsToUnits: () => planFunctionsToUnits,
36
36
  reportDevCredential: () => reportDevCredential,
37
37
  sourceFunctionUrlOverlay: () => sourceFunctionUrlOverlay
@@ -55,10 +55,10 @@ const builder = (argv) => argv.usage("$0 dev [--source <path>] [options]").examp
55
55
  "object storage and the AI Gateway where the branch has them. A neon.ts in",
56
56
  "this directory decides instead, exactly as it does for `env pull`.",
57
57
  "",
58
- "NEON_FUNCTION_<SLUG>_BASE_URL from `env pull` / `neon-env run` is the production",
59
- "invocation URL. `dev` rewrites it to `http://localhost:<port>` for each function",
60
- "this process is serving (every neon.ts function, or the matching slug when",
61
- "`--source` names one).",
58
+ "`functionBaseUrl(\"<slug>\")` from @neon/env returns `http://localhost:<port>` for",
59
+ "each function this process is serving (every neon.ts function, or the matching",
60
+ "slug when `--source` names one), through NEON_DEV_FUNCTION_PORTS, and the",
61
+ "deployed URL on the linked branch for any other slug.",
62
62
  "",
63
63
  "Before neon.ts is evaluated, `dev` loads the project's .env, then .env.local,",
64
64
  "which overrides it, into the environment, so Function env values that read",
@@ -267,7 +267,7 @@ const planFunctionsToUnits = async (functions, neonEnv, searchBase, keepPorts =
267
267
  port
268
268
  };
269
269
  });
270
- const overlay = localFunctionUrlEnv(assigned.map(({ fn, port }) => ({
270
+ const overlay = localFunctionPortsEnv(assigned.map(({ fn, port }) => ({
271
271
  slug: fn.slug,
272
272
  port
273
273
  })));
@@ -281,14 +281,10 @@ const planFunctionsToUnits = async (functions, neonEnv, searchBase, keepPorts =
281
281
  }, overlay));
282
282
  };
283
283
  /**
284
- * Local invocation URLs for functions `neon dev` is serving, so siblings call each
285
- * other on localhost instead of the production compute host.
284
+ * The ports of the functions `neon dev` is serving, which `functionBaseUrl` reads so
285
+ * siblings call each other on localhost instead of the deployed compute host.
286
286
  */
287
- const localFunctionUrlEnv = (functions) => {
288
- const out = {};
289
- for (const fn of functions) out[functionBaseUrlKey(fn.slug)] = `http://localhost:${fn.port}`;
290
- return out;
291
- };
287
+ const localFunctionPortsEnv = (functions) => ({ [NEON_DEV_FUNCTION_PORTS]: JSON.stringify(Object.fromEntries(functions.map((fn) => [fn.slug, fn.port]))) });
292
288
  /**
293
289
  * `--source` serves one file. If that file is a neon.ts function, rewrite only that
294
290
  * slug to localhost — this process is not listening for the others.
@@ -301,7 +297,7 @@ const sourceFunctionUrlOverlay = async (match, cliPort, shellEnv = process.env)
301
297
  };
302
298
  const port = portSpec.mode === "explicit" ? portSpec.port : match.port ?? await pickFreePort(portSpec.from);
303
299
  return {
304
- overlay: localFunctionUrlEnv([{
300
+ overlay: localFunctionPortsEnv([{
305
301
  slug: match.slug,
306
302
  port
307
303
  }]),
@@ -421,11 +417,14 @@ const plannedToUnit = (fn, branchEnv, port, overlay = {}) => {
421
417
  * Build a child's env. Neon vars layer over the inherited environment (so the branch's
422
418
  * DATABASE_URL wins over a stale inherited value); a function that loads its own `.env`
423
419
  * at runtime still overrides them. The port spec is encoded for the runtime via
424
- * NEON_DEV_PORT (explicit) or NEON_DEV_PORT_BASE (search).
420
+ * NEON_DEV_PORT (explicit) or NEON_DEV_PORT_BASE (search). An inherited
421
+ * NEON_DEV_FUNCTION_PORTS names another process's ports, so only this one's applies.
425
422
  */
426
423
  const buildChildEnv = (neonEnv, port) => {
424
+ const inherited = { ...process.env };
425
+ delete inherited[NEON_DEV_FUNCTION_PORTS];
427
426
  const env = {
428
- ...process.env,
427
+ ...inherited,
429
428
  ...neonEnv
430
429
  };
431
430
  delete env.NEON_DEV_PORT;
@@ -941,4 +940,4 @@ const resolveRuntimePath = () => {
941
940
  if (!existsSync(candidate)) throw new Error(`Could not locate the dev runtime at ${candidate}`);
942
941
  return candidate;
943
942
  };
944
- export { devBundleDir as a, diffUnits as c, handler as d, loadDevEnvFiles as f, sourceFunctionUrlOverlay as g, reportDevCredential as h, describe as i, formatEnvFiles as l, planFunctionsToUnits as m, captureShellEnv as n, devEnvContext as o, localFunctionUrlEnv as p, command as r, dev_exports as s, builder as t, formatEnvSummary as u };
943
+ export { devBundleDir as a, diffUnits as c, handler as d, loadDevEnvFiles as f, sourceFunctionUrlOverlay as g, reportDevCredential as h, describe as i, formatEnvFiles as l, planFunctionsToUnits as m, captureShellEnv as n, devEnvContext as o, localFunctionPortsEnv as p, command as r, dev_exports as s, builder as t, formatEnvSummary as u };
@@ -2,7 +2,7 @@ import { log } from "../log.js";
2
2
  import { getCliName } from "../utils/cli_name.js";
3
3
  import { declaredNeonServices } from "../config_services.js";
4
4
  import { loadProjectConfig } from "../project.js";
5
- import { a as defaultAiGatewayCredential, c as fetchEnvKeysState, d as isLiveCredential, h as toEntries, i as credentialName, l as functionBaseUrlKey, m as resolveBranchPolicy, n as createApiFromOptions, o as defaultStorageCredential, p as policyEnvKeys, r as credentialEnvKeys, t as NEON_ENV_VAR_KEYS, u as isFunctionBaseUrlKey } from "./env-JgoSsmyt.js";
5
+ import { a as credentialName, d as policyEnvKeys, f as resolveBranchPolicy, i as credentialEnvKeys, l as fetchEnvKeysState, n as NEON_ENV_VAR_KEYS, o as defaultAiGatewayCredential, p as toEntries, r as createApiFromOptions, s as defaultStorageCredential, u as isLiveCredential } from "./env-EJU-0InB.js";
6
6
  import { ENV_PULL_SERVICES, envKeysForSelection, serviceForEnvKey, servicesForEnvKeys } from "../env_services.js";
7
7
  import { formatInstallCommand, resolvePackageManager } from "../utils/package_manager.js";
8
8
  import { StagingOnlyError } from "../utils/staging.js";
@@ -48,7 +48,7 @@ async function fetchEnvReusingSecrets(config, options) {
48
48
  const { branch, desired } = await resolveBranchPolicy(config, options, api, resolvedBranch);
49
49
  const allPolicyKeys = policyEnvKeys(desired);
50
50
  const requested = requestedKeys ? new Set(requestedKeys) : null;
51
- const selectedPolicyKeys = requested === null ? allPolicyKeys : [...allPolicyKeys.filter((key) => requested.has(key)), ...[...requested].filter(isFunctionBaseUrlKey).sort()];
51
+ const selectedPolicyKeys = requested === null ? allPolicyKeys : [...allPolicyKeys.filter((key) => requested.has(key)), ...Object.values(NEON_ENV_VAR_KEYS.branch).filter((key) => requested.has(key) && !allPolicyKeys.includes(key))];
52
52
  const selected = new Set(selectedPolicyKeys);
53
53
  const K = NEON_ENV_VAR_KEYS;
54
54
  const storageCredentialSelected = (desired.preview?.buckets.length ?? 0) > 0 && (selected.has(K.storage.accessKeyId) || selected.has(K.storage.secretAccessKey));
@@ -70,8 +70,7 @@ async function fetchEnvReusingSecrets(config, options) {
70
70
  fresh: [],
71
71
  revoked: [],
72
72
  superseded: []
73
- },
74
- ...fetched.functionUrlsUnavailable ? { functionUrlsUnavailable: true } : {}
73
+ }
75
74
  };
76
75
  }
77
76
  const persisted = readPersistedSecrets(source);
@@ -103,7 +102,6 @@ async function fetchEnvReusingSecrets(config, options) {
103
102
  desired
104
103
  });
105
104
  const vars = preferPersisted(toEntries(fetched.env), source);
106
- const unavailable = fetched.functionUrlsUnavailable ? { functionUrlsUnavailable: true } : {};
107
105
  for (const key of keptSecretKeys) {
108
106
  const value = source[key];
109
107
  if (value !== void 0) vars[key] = value;
@@ -116,8 +114,7 @@ async function fetchEnvReusingSecrets(config, options) {
116
114
  fresh: [],
117
115
  revoked: [],
118
116
  superseded: []
119
- },
120
- ...unavailable
117
+ }
121
118
  };
122
119
  const ours = /* @__PURE__ */ new Set();
123
120
  for (const meta of [storageCredentialManaged && !keepStorage ? named.storage : null, gatewayCredentialManaged && !keepGateway ? named.gateway : null]) if (meta !== null && meta.principalType === "user" && meta.name === credentialName(branch.name)) ours.add(meta.tokenId);
@@ -130,8 +127,7 @@ async function fetchEnvReusingSecrets(config, options) {
130
127
  fresh: secretKeys.filter((key) => !keptSecretKeys.includes(key)),
131
128
  revoked: revokeSuperseded ? [...ours] : [],
132
129
  superseded: revokeSuperseded ? [] : [...ours]
133
- },
134
- ...unavailable
130
+ }
135
131
  };
136
132
  }
137
133
  /** Read the branch credential's secrets out of an env source. */
@@ -378,16 +374,13 @@ const resolveClaimableNeonEnvVars = async (ctx) => {
378
374
  * 1. a `neon.ts` policy is found -> the policy is the source of truth. We first
379
375
  * check it against the branch's live state (`plan`); if it declares a resource
380
376
  * the branch is missing, we stop with a {@link DevEnvMismatchError} pointing at
381
- * `neonctl deploy`. Function declarations are excluded from that check: their
382
- * invocation URLs are derived from the branch connection host, so an undeployed
383
- * function still gets `NEON_FUNCTION_*_BASE_URL`. Otherwise `fetchEnv` evaluates
377
+ * `neonctl deploy`. Function declarations are excluded from that check: local env
378
+ * does not depend on whether a function is deployed. Otherwise `fetchEnv` evaluates
384
379
  * the policy.
385
380
  * 2. no `neon.ts`, but a project + branch are known -> `pullConfig` reads the
386
381
  * branch's live state (Auth / Data API / Realtime enablement plus any object-storage
387
382
  * buckets) into a config, then `fetchEnv` resolves what is actually enabled —
388
- * so a branch with a bucket gets its `AWS_*` storage vars pulled with no policy.
389
- * Function invocation URLs are listed live (`functionUrls: "all-live"`) because
390
- * `pullConfig` cannot round-trip them into `functions`. With
383
+ * so a branch with a bucket gets its `AWS_*` storage vars pulled with no policy. With
391
384
  * {@link DevEnvContext.implyAiGateway}, the AI Gateway is added on top, since
392
385
  * `pullConfig` cannot read it back.
393
386
  * 3. otherwise -> throw {@link MissingBranchContextError}.
@@ -422,10 +415,7 @@ const resolveNeonEnvVars = async (ctx) => {
422
415
  protected: pulled.branch.protected,
423
416
  ...pulled.branch.expiresAt ? { expiresAt: pulled.branch.expiresAt } : {}
424
417
  };
425
- if (!ctx.implyAiGateway) return await fetchAndProject(pulled.config, ctx, {
426
- functionUrls: "all-live",
427
- resolvedBranch
428
- });
418
+ if (!ctx.implyAiGateway) return await fetchAndProject(pulled.config, ctx, { resolvedBranch });
429
419
  return await resolveWithImpliedGateway(pulled.config, ctx, {
430
420
  projectId: ctx.projectId,
431
421
  branchId: ctx.branchId,
@@ -466,15 +456,9 @@ const withAiGateway = (config) => ({
466
456
  */
467
457
  const resolveWithImpliedGateway = async (config, ctx, branch) => {
468
458
  const unreachable = await credentialsUnreachable(ctx, branch);
469
- if (unreachable === null) return await fetchAndProject(withAiGateway(config), ctx, {
470
- functionUrls: "all-live",
471
- resolvedBranch: branch.resolvedBranch
472
- });
459
+ if (unreachable === null) return await fetchAndProject(withAiGateway(config), ctx, { resolvedBranch: branch.resolvedBranch });
473
460
  log.warning(`Could not reach the AI Gateway's credentials, so %s were not resolved. Everything else was. Either this project does not have the AI Gateway, or the call failed — \`${getCliName()} env pull -s ai-gateway\` will say which.\nDetails: %s`, [NEON_ENV_VAR_KEYS.aiGateway.apiKey, NEON_ENV_VAR_KEYS.aiGateway.baseUrl].join(" and "), unreachable);
474
- const pulled = await fetchAndProject(config, ctx, {
475
- functionUrls: "all-live",
476
- resolvedBranch: branch.resolvedBranch
477
- });
461
+ const pulled = await fetchAndProject(config, ctx, { resolvedBranch: branch.resolvedBranch });
478
462
  return {
479
463
  ...pulled,
480
464
  skipped: [...pulled.skipped ?? [], "ai-gateway"]
@@ -514,18 +498,13 @@ const resolveSelectedServices = async (ctx, directServices, envKeys) => {
514
498
  const api = apiFor(ctx);
515
499
  const has = (service) => services.includes(service);
516
500
  const checkAiGateway = has("ai-gateway") && !selectedKeys.includes(NEON_ENV_VAR_KEYS.aiGateway.apiKey);
517
- const [auth, dataApiEnabled, realtime, buckets, aiGatewayAvailable, functions] = await Promise.all([
501
+ const [auth, dataApiEnabled, realtime, buckets, aiGatewayAvailable] = await Promise.all([
518
502
  has("auth") ? api.getNeonAuth(projectId, branchId) : null,
519
503
  has("data-api") ? readDataApiEnabled(api, projectId, branchId) : null,
520
504
  has("realtime") ? readRealtime(api, projectId, branchId) : null,
521
505
  has("object-storage") ? api.listBranchBuckets(projectId, branchId) : null,
522
- checkAiGateway ? readAiGatewayAvailable(api, projectId, branchId) : null,
523
- directServices.includes("functions") ? api.listBranchFunctions(projectId, branchId) : null
506
+ checkAiGateway ? readAiGatewayAvailable(api, projectId, branchId) : null
524
507
  ]);
525
- const callableFunctions = (functions ?? []).filter((fn) => fn.invocationUrl !== "");
526
- if (directServices.includes("functions") && callableFunctions.length === 0) throw new ServiceNotOnBranchError(`--service functions: branch ${branchId} has no deployed functions, so there are no NEON_FUNCTION_*_BASE_URL vars to pull. Deploy a function first (\`${getCliName()} deploy\`, or in the Neon Console), or drop functions from --service.`);
527
- const functionKeys = directServices.includes("functions") ? callableFunctions.map((fn) => functionBaseUrlKey(fn.slug)).sort((left, right) => left.localeCompare(right)) : [];
528
- const fetchKeys = [.../* @__PURE__ */ new Set([...selectedKeys, ...functionKeys])];
529
508
  const config = configForServices(services, branchId, {
530
509
  authEnabled: auth !== null,
531
510
  dataApiEnabled,
@@ -537,12 +516,8 @@ const resolveSelectedServices = async (ctx, directServices, envKeys) => {
537
516
  envKeys
538
517
  });
539
518
  return await fetchAndProject(config, ctx, {
540
- keys: fetchKeys,
541
- revokeSuperseded: false,
542
- ...directServices.includes("functions") ? {
543
- functionUrls: "all-live",
544
- listedFunctions: callableFunctions
545
- } : {}
519
+ keys: selectedKeys,
520
+ revokeSuperseded: false
546
521
  });
547
522
  };
548
523
  /**
@@ -703,14 +678,12 @@ const fetchAndProject = async (config, ctx, opts = {}) => {
703
678
  ...ctx.env ? { env: ctx.env } : {},
704
679
  ...opts.keys ? { keys: opts.keys } : {},
705
680
  ...opts.revokeSuperseded === false ? { revokeSuperseded: false } : {},
706
- ...opts.functionUrls ? { functionUrls: opts.functionUrls } : {},
707
- ...opts.listedFunctions ? { listedFunctions: opts.listedFunctions } : {},
708
- ...opts.resolvedBranch ? { resolvedBranch: opts.resolvedBranch } : {}
681
+ ...opts.resolvedBranch ? { resolvedBranch: opts.resolvedBranch } : {},
682
+ functionHostSuffix: "always"
709
683
  });
710
684
  return {
711
685
  vars: result.vars,
712
- credential: result.credential,
713
- ...result.functionUrlsUnavailable ? { skipped: ["functions"] } : {}
686
+ credential: result.credential
714
687
  };
715
688
  };
716
689
  /**
@@ -5,10 +5,10 @@ import { isClaimableEnvTarget } from "../claimable/state.js";
5
5
  import { getCliName } from "../utils/cli_name.js";
6
6
  import { deprecatedServiceMessage, parseServices, servicesFlagValue, servicesOption } from "../neon_services.js";
7
7
  import { mergeEnvFile, readEnvFile, resolveEnvFilePath } from "../env_file.js";
8
- import { t as NEON_ENV_VAR_KEYS, u as isFunctionBaseUrlKey } from "./env-JgoSsmyt.js";
9
- import { ENV_PULL_KEY_HELP, ENV_PULL_SERVICES, envKeysForSelection, envPullFlagValue, ownedEnvServiceKeys, parseEnvPullKeys } from "../env_services.js";
8
+ import { n as NEON_ENV_VAR_KEYS } from "./env-EJU-0InB.js";
9
+ import { ENV_PULL_KEY_HELP, ENV_PULL_SERVICES, envKeysForSelection, envPullFlagValue, isLegacyFunctionBaseUrlKey, ownedEnvServiceKeys, parseEnvPullKeys } from "../env_services.js";
10
10
  import { fillSingleProject, resolveBranchRef } from "../utils/enrichers.js";
11
- import { i as dropClaimableUnsupported, o as resolveNeonEnvVars } from "./env-CIFMBEon.js";
11
+ import { i as dropClaimableUnsupported, o as resolveNeonEnvVars } from "./env-CFBmcKyo.js";
12
12
  import { warnAiGateway } from "../utils/ai_gateway_notice.js";
13
13
  import { formatPulledEnv, pulledBranch } from "../commands/env_output.js";
14
14
  import { existsSync } from "node:fs";
@@ -66,8 +66,7 @@ const builder = (argv) => argv.usage("$0 env <sub-command> [options]").options({
66
66
  "What gets pulled, in precedence order:",
67
67
  " 1. --service / --env, when given — their union, ignoring neon.ts.",
68
68
  " 2. neon.ts, when the project directory (next to .neon, or cwd",
69
- " without one) has one — including derived function URLs (the",
70
- " function does not have to be deployed).",
69
+ " without one) has one.",
71
70
  " 3. Otherwise everything the branch has, plus the AI Gateway —",
72
71
  " which pulls the default AI Gateway credential.",
73
72
  "",
@@ -82,7 +81,7 @@ const builder = (argv) => argv.usage("$0 env <sub-command> [options]").options({
82
81
  "The pull bundled into link / checkout / config apply follows 2 and 3",
83
82
  "without the AI Gateway, so it never writes a gateway token you did",
84
83
  "not ask for. Run `env pull` to add it."
85
- ].join("\n")).example("$0 env pull", "Write the linked branch's Neon vars into .env.local (or .env if present)").example("$0 env pull --branch preview --file .env.preview", "Pull a specific branch into a specific file").example("$0 env pull -s ai-gateway -s postgres", "Pull only the AI Gateway and Postgres variables").example("$0 env pull -e DATABASE_URL", "Pull only the pooled Postgres connection string").example("$0 env pull -s auth -e DATABASE_URL", "Pull all Auth variables plus DATABASE_URL").example("$0 env pull -s functions", "Pull NEON_FUNCTION_<SLUG>_BASE_URL for every deployed function").example("$0 env pull -e NEON_FUNCTION_HELLO_BASE_URL", "Write that function's production invocation URL (no deploy required)").strict(), async (args) => {
84
+ ].join("\n")).example("$0 env pull", "Write the linked branch's Neon vars into .env.local (or .env if present)").example("$0 env pull --branch preview --file .env.preview", "Pull a specific branch into a specific file").example("$0 env pull -s ai-gateway -s postgres", "Pull only the AI Gateway and Postgres variables").example("$0 env pull -e DATABASE_URL", "Pull only the pooled Postgres connection string").example("$0 env pull -s auth -e DATABASE_URL", "Pull all Auth variables plus DATABASE_URL").example("$0 env pull -s functions", "Pull NEON_BRANCH_ID and NEON_FUNCTION_HOST_SUFFIX, which functionBaseUrl(\"<slug>\") from @neon/env reads").strict(), async (args) => {
86
85
  const rawServices = servicesFlagValue(args.service);
87
86
  const rawEnvKeys = envPullFlagValue(args.env);
88
87
  const services = rawServices ? parseServices(rawServices, {
@@ -118,6 +117,8 @@ const NEON_VAR_NAMES = Object.values(NEON_ENV_VAR_KEYS).flatMap((group) => Objec
118
117
  */
119
118
  const NEON_OWNED_ENV_KEYS = [
120
119
  ...Object.values(NEON_ENV_VAR_KEYS.postgres),
120
+ NEON_ENV_VAR_KEYS.branch.id,
121
+ NEON_ENV_VAR_KEYS.branch.functionHostSuffix,
121
122
  ...Object.values(NEON_ENV_VAR_KEYS.auth),
122
123
  ...Object.values(NEON_ENV_VAR_KEYS.dataApi),
123
124
  ...Object.values(NEON_ENV_VAR_KEYS.realtime),
@@ -162,12 +163,12 @@ const pull = async (props, opts = {}) => {
162
163
  ...props.apiHost ? { apiHost: props.apiHost } : {},
163
164
  ...props.runtimeApi ? { api: props.runtimeApi } : {}
164
165
  });
165
- const neonVars = pickSelectedVars(pickNeonVars(vars), selectedKeys, props.services !== void 0 ? selectionServices : void 0);
166
+ const neonVars = pickSelectedVars(pickNeonVars(vars), selectedKeys);
166
167
  if (Object.keys(neonVars).length === 0) {
167
168
  if (!(dropped !== null && dropped.services.length === 0 && dropped.envKeys.length === 0 && dropped.skipped.length > 0)) log.info(`No Neon env variables to pull from ${namedBranch ? pulledBranch(namedBranch) : "this branch"}: no DATABASE_URL or enabled Auth / Data API.`);
168
169
  return { status: "empty" };
169
170
  }
170
- const { written, removed } = mergeEnvFile(targetPath, neonVars, { managedKeys: managedKeysFor(selectedKeys, unreachedButCurrent(skipped, existingEnv, branchId), existingEnv, props.services !== void 0 ? selectionServices : void 0, props.envKeys !== void 0 ? selectionEnvKeys : void 0) });
171
+ const { written, removed } = mergeEnvFile(targetPath, neonVars, { managedKeys: managedKeysFor(selectedKeys, unreachedButCurrent(skipped, existingEnv, branchId), existingEnv, props.services !== void 0 ? selectionServices : void 0) });
171
172
  process.stderr.write(formatPulledEnv({
172
173
  status: "written",
173
174
  written,
@@ -195,18 +196,17 @@ const pull = async (props, opts = {}) => {
195
196
  ...skipped && skipped.length > 0 ? { skipped } : {}
196
197
  };
197
198
  };
198
- /** Prevents scoped or unavailable services from pruning values they did not resolve. */
199
- const managedKeysFor = (selectedKeys, unreached, existingEnv, services, envKeys) => {
200
- const existingFunctionKeys = Object.keys(existingEnv).filter(isFunctionBaseUrlKey);
201
- const namedFunctionKeys = (envKeys ?? []).filter(isFunctionBaseUrlKey);
202
- const ownedFunctionKeys = selectedKeys === void 0 || (services?.includes("functions") ?? false) ? existingFunctionKeys : namedFunctionKeys;
203
- const owned = selectedKeys ? [...NEON_OWNED_ENV_KEYS.filter((key) => selectedKeys.includes(key)), ...ownedFunctionKeys] : [...NEON_OWNED_ENV_KEYS, ...ownedFunctionKeys];
199
+ /**
200
+ * Prevents scoped or unavailable services from pruning values they did not resolve. A pull
201
+ * that covers functions also prunes the `NEON_FUNCTION_<SLUG>_BASE_URL` lines earlier
202
+ * releases wrote, since nothing reads or refreshes them anymore.
203
+ */
204
+ const managedKeysFor = (selectedKeys, unreached, existingEnv, services) => {
205
+ const legacyFunctionKeys = selectedKeys === void 0 || (services?.includes("functions") ?? false) ? Object.keys(existingEnv).filter(isLegacyFunctionBaseUrlKey) : [];
206
+ const owned = [...selectedKeys ? NEON_OWNED_ENV_KEYS.filter((key) => selectedKeys.includes(key)) : NEON_OWNED_ENV_KEYS, ...legacyFunctionKeys];
204
207
  if (unreached.length === 0) return owned;
205
208
  const keep = new Set(ownedEnvServiceKeys(unreached));
206
- return owned.filter((key) => {
207
- if (unreached.includes("functions") && isFunctionBaseUrlKey(key)) return false;
208
- return !keep.has(key);
209
- });
209
+ return owned.filter((key) => !keep.has(key));
210
210
  };
211
211
  /**
212
212
  * Endpoint failure is not evidence that existing values are stale; the gateway host check
@@ -219,7 +219,6 @@ const unreachedButCurrent = (skipped, existingEnv, branchId) => {
219
219
  const baseUrl = existingEnv[NEON_ENV_VAR_KEYS.aiGateway.baseUrl];
220
220
  if (baseUrl !== void 0 && isBranchGatewayUrl(baseUrl, branchId)) keep.push("ai-gateway");
221
221
  }
222
- if (skipped.includes("functions")) keep.push("functions");
223
222
  return keep;
224
223
  };
225
224
  /**
@@ -237,11 +236,10 @@ const isBranchGatewayUrl = (baseUrl, branchId) => URL.canParse(baseUrl) && new U
237
236
  * supporting values that were not selected (the direct connection URI derives the AI Gateway
238
237
  * host, for example); those must not land in the target file.
239
238
  */
240
- const pickSelectedVars = (vars, selectedKeys, services) => {
239
+ const pickSelectedVars = (vars, selectedKeys) => {
241
240
  if (!selectedKeys) return vars;
242
241
  const wanted = new Set(selectedKeys);
243
- const keepFunctionUrls = services?.includes("functions") ?? false;
244
- return Object.fromEntries(Object.entries(vars).filter(([key]) => wanted.has(key) || keepFunctionUrls && isFunctionBaseUrlKey(key)));
242
+ return Object.fromEntries(Object.entries(vars).filter(([key]) => wanted.has(key)));
245
243
  };
246
244
  /**
247
245
  * Pull a freshly-pinned branch's Neon env vars into a local `.env`, bundled into `link` and
@@ -276,7 +274,7 @@ Run \`${getCliName()} env pull\` once resolved (e.g. \`${getCliName()} deploy\`
276
274
  */
277
275
  const pickNeonVars = (vars) => {
278
276
  const out = {};
279
- for (const [name, value] of Object.entries(vars)) if (NEON_VAR_NAMES.some((key) => key === name) || isFunctionBaseUrlKey(name)) out[name] = value;
277
+ for (const [name, value] of Object.entries(vars)) if (NEON_VAR_NAMES.some((key) => key === name)) out[name] = value;
280
278
  return out;
281
279
  };
282
280
  export { describe as a, pull as c, command as i, autoPullEnvAfterPin as n, env_exports as o, builder as r, handler as s, ENV_PULL_SKIPPED_HINT as t };
@@ -1,5 +1,5 @@
1
1
  import { n as defaultConnectionRole, t as NEON_DEFAULT_OWNER_ROLE } from "./roles-Bd9r8_pX.js";
2
- import { ErrorCode, PlatformError, createNeonApiFromOptions, deriveCredentialScopes, isPlatformError, resolveConfig } from "@neon/config/v1";
2
+ import { ErrorCode, PlatformError, createNeonApiFromOptions, deriveCredentialScopes, resolveConfig } from "@neon/config/v1";
3
3
  // ../../internals/env-core/dist/env.js
4
4
  /**
5
5
  * The Neon env core — resolving a branch's env from the Neon API, and projecting it into
@@ -28,13 +28,27 @@ import { ErrorCode, PlatformError, createNeonApiFromOptions, deriveCredentialSco
28
28
  * user added a second database next to `neondb`) auto-picks without asking.
29
29
  */
30
30
  const NEON_DEFAULT_DATABASE = "neondb";
31
+ /**
32
+ * Set only by `neon dev`: a JSON object mapping each function it serves to its localhost port,
33
+ * which `functionBaseUrl` prefers over the deployed hostname.
34
+ */
35
+ const NEON_DEV_FUNCTION_PORTS = "NEON_DEV_FUNCTION_PORTS";
31
36
  const NEON_ENV_VAR_KEYS = {
32
37
  /**
33
38
  * Branch identity. `NEON_BRANCH` carries the branch **name** and is injected into the
34
39
  * Neon Functions runtime on every branch (including the default) by default. `env pull` /
35
40
  * `neon dev` / `neon-env run` emit it too so local dev mirrors the deployed runtime.
36
41
  */
37
- branch: { name: "NEON_BRANCH" },
42
+ branch: {
43
+ name: "NEON_BRANCH",
44
+ id: "NEON_BRANCH_ID",
45
+ /**
46
+ * Shared by every function on the branch, with a leading dot
47
+ * (`.compute.c-2.us-east-2.aws.neon.tech`). A function's host is
48
+ * `<NEON_BRANCH_ID>-<slug><NEON_FUNCTION_HOST_SUFFIX>`.
49
+ */
50
+ functionHostSuffix: "NEON_FUNCTION_HOST_SUFFIX"
51
+ },
38
52
  postgres: {
39
53
  databaseUrl: "DATABASE_URL",
40
54
  databaseUrlUnpooled: "DATABASE_URL_UNPOOLED"
@@ -71,19 +85,6 @@ const NEON_ENV_VAR_KEYS = {
71
85
  baseUrl: "NEON_AI_GATEWAY_BASE_URL"
72
86
  }
73
87
  };
74
- const FUNCTION_SLUG = /^[a-z0-9]{1,20}$/;
75
- const FUNCTION_BASE_URL_KEY = /^NEON_FUNCTION_([A-Z0-9]{1,20})_BASE_URL$/;
76
- function functionBaseUrlKey(slug) {
77
- if (!FUNCTION_SLUG.test(slug)) throw new Error(`functionBaseUrlKey: ${JSON.stringify(slug)} is not a function slug ([a-z0-9]{1,20}).`);
78
- return `NEON_FUNCTION_${slug.toUpperCase()}_BASE_URL`;
79
- }
80
- function parseFunctionBaseUrlKey(key) {
81
- const match = FUNCTION_BASE_URL_KEY.exec(key);
82
- return match ? match[1].toLowerCase() : null;
83
- }
84
- function isFunctionBaseUrlKey(key) {
85
- return parseFunctionBaseUrlKey(key) !== null;
86
- }
87
88
  /**
88
89
  * Starts a read now and keeps an unread rejection from crashing the process; the caller
89
90
  * awaits it (and sees the error) when its turn comes. The read is called synchronously and
@@ -185,24 +186,13 @@ async function fetchEnvKeysState(config, options, keys, policy) {
185
186
  const wantsDataApi = desired.dataApiEnabled && wants(K.dataApi.url);
186
187
  const wantsRealtime = desired.realtimePolicy === "enabled" && (wants(K.realtime.url) || wants(K.realtime.secret));
187
188
  const gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;
188
- const functionUrlMode = options.functionUrls ?? "policy";
189
- const declaredSlugs = (desired.preview?.functions ?? []).map((fn) => fn.slug);
190
- const selectedFunctionKeys = selection === null ? [] : [...selection].filter(isFunctionBaseUrlKey);
191
- const constructSlugs = functionUrlSlugsToConstruct({
192
- functionUrlMode,
193
- selection,
194
- declaredSlugs,
195
- selectedFunctionKeys,
196
- wants
197
- });
198
- const wantsAnyFunctionUrl = selection === null || selectedFunctionKeys.length > 0;
189
+ const wantsFunctionHostSuffix = wants(K.branch.functionHostSuffix) && (selection !== null || options.functionHostSuffix === "always" || (desired.preview?.functions.length ?? 0) > 0);
199
190
  const storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;
200
191
  const wantsStorage = storageEnabled && (wants(K.storage.accessKeyId) || wants(K.storage.secretAccessKey) || wants(K.storage.endpoint) || wants(K.storage.region));
201
- const functionsRead = functionUrlMode === "all-live" && wantsAnyFunctionUrl && options.listedFunctions === void 0 ? listFunctionInvocationUrls(api, projectId, branch.id) : null;
202
- functionsRead?.catch(() => void 0);
203
- const storageRead = wantsStorage ? started(() => api.getProjectBranchStorage(projectId, branch.id)) : null;
204
- const needsUnpooled = wantsUnpooled || gatewayEnabled && wants(K.aiGateway.baseUrl) || constructSlugs.length > 0;
192
+ const needsUnpooled = wantsUnpooled || gatewayEnabled && wants(K.aiGateway.baseUrl);
205
193
  const needsConnectionTarget = wantsPooled || needsUnpooled;
194
+ const storageRead = wantsStorage ? started(() => api.getProjectBranchStorage(projectId, branch.id)) : null;
195
+ const endpointsRead = wantsFunctionHostSuffix && !needsConnectionTarget ? started(() => api.listEndpoints(projectId)) : null;
206
196
  const needsDatabase = needsConnectionTarget || wantsDataApi;
207
197
  const [roles, databases] = await Promise.all([needsConnectionTarget ? api.listBranchRoles(projectId, branch.id) : Promise.resolve([]), needsDatabase ? api.listBranchDatabases(projectId, branch.id) : Promise.resolve([])]);
208
198
  const databaseName = needsDatabase ? pickDatabaseName(databases, branch, options.databaseName) : null;
@@ -228,7 +218,16 @@ async function fetchEnvKeysState(config, options, keys, policy) {
228
218
  if (wantsPooled) postgres.databaseUrl = requiredValue(pooled, "pooled connection URI response").uri;
229
219
  if (wantsUnpooled) postgres.databaseUrlUnpooled = requiredValue(unpooled, "direct connection URI response").uri;
230
220
  if (Object.keys(postgres).length > 0) result.postgres = postgres;
231
- if (wants(K.branch.name)) result.branch = { name: branch.name };
221
+ if (wants(K.branch.name) || wants(K.branch.id) || wantsFunctionHostSuffix) {
222
+ const branchEnv = {};
223
+ if (wants(K.branch.name)) branchEnv.name = branch.name;
224
+ if (wants(K.branch.id)) branchEnv.id = branch.id;
225
+ if (wantsFunctionHostSuffix) {
226
+ const connectionUri = unpooled?.uri ?? pooled?.uri;
227
+ branchEnv.functionHostSuffix = functionHostSuffix(connectionUri !== void 0 ? new URL(connectionUri).hostname : branchComputeHost(await requiredValue(endpointsRead, "branch endpoint list"), branch));
228
+ }
229
+ result.branch = branchEnv;
230
+ }
232
231
  if (wantsAuth) {
233
232
  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: {
234
233
  projectId,
@@ -301,66 +300,7 @@ async function fetchEnvKeysState(config, options, keys, policy) {
301
300
  result.aiGateway = gateway;
302
301
  }
303
302
  }
304
- const functions = {};
305
- let functionUrlsUnavailable = false;
306
- if (functionUrlMode === "all-live" && wantsAnyFunctionUrl) {
307
- const listed = options.listedFunctions === void 0 ? await requiredValue(functionsRead, "function listing") : listedFromSnapshots(options.listedFunctions);
308
- if (listed.status === "unavailable") {
309
- if (selection === null) functionUrlsUnavailable = true;
310
- } else for (const fn of listed.functions) {
311
- if (!wants(functionBaseUrlKey(fn.slug))) continue;
312
- functions[fn.slug] = { baseUrl: asEnvBaseUrl(fn.invocationUrl) };
313
- }
314
- }
315
- const missingConstructSlugs = constructSlugs.filter((slug) => functions[slug] === void 0);
316
- if (missingConstructSlugs.length > 0) {
317
- const uri = requiredValue(unpooled, "direct connection URI for function invocation URLs").uri;
318
- for (const slug of missingConstructSlugs) functions[slug] = { baseUrl: functionInvocationUrl(branch.id, slug, uri) };
319
- }
320
- assertSelectedFunctionUrls(selectedFunctionKeys, functions);
321
- if (Object.keys(functions).length > 0) result.functions = functions;
322
- return {
323
- env: result,
324
- functionUrlsUnavailable
325
- };
326
- }
327
- function functionUrlSlugsToConstruct(args) {
328
- const slugs = [];
329
- if (args.functionUrlMode === "policy" && args.selection === null) {
330
- for (const slug of args.declaredSlugs) if (args.wants(functionBaseUrlKey(slug))) slugs.push(slug);
331
- return slugs;
332
- }
333
- for (const key of args.selectedFunctionKeys) {
334
- const slug = parseFunctionBaseUrlKey(key);
335
- if (slug !== null) slugs.push(slug);
336
- }
337
- return slugs;
338
- }
339
- function listedFromSnapshots(snapshots) {
340
- return {
341
- status: "ok",
342
- functions: snapshots.filter((fn) => fn.invocationUrl !== "").map((fn) => ({
343
- slug: fn.slug,
344
- invocationUrl: fn.invocationUrl
345
- })).sort((left, right) => left.slug.localeCompare(right.slug))
346
- };
347
- }
348
- function assertSelectedFunctionUrls(keys, functions) {
349
- for (const key of keys) {
350
- const slug = parseFunctionBaseUrlKey(key);
351
- if (slug === null || functions[slug] === void 0) throw new Error(`fetchEnv: missing ${key}.`);
352
- }
353
- }
354
- async function listFunctionInvocationUrls(api, projectId, branchId) {
355
- try {
356
- return listedFromSnapshots(await api.listBranchFunctions(projectId, branchId));
357
- } catch (error) {
358
- if (isPlatformError(error) && error.code === ErrorCode.FeatureUnavailable) return {
359
- status: "unavailable",
360
- error
361
- };
362
- throw error;
363
- }
303
+ return { env: result };
364
304
  }
365
305
  /**
366
306
  * Resolve the target branch and evaluate the policy against it — the first thing any
@@ -425,6 +365,8 @@ function policyEnvKeys(desired) {
425
365
  K.postgres.databaseUrl,
426
366
  K.postgres.databaseUrlUnpooled,
427
367
  K.branch.name,
368
+ K.branch.id,
369
+ ...(desired.preview?.functions.length ?? 0) > 0 ? [K.branch.functionHostSuffix] : [],
428
370
  ...desired.authEnabled ? [K.auth.baseUrl, K.auth.jwksUrl] : [],
429
371
  ...desired.dataApiEnabled ? [K.dataApi.url] : [],
430
372
  ...desired.realtimePolicy === "enabled" ? [K.realtime.url, K.realtime.secret] : [],
@@ -539,24 +481,20 @@ function aiGatewayHost(branchId, connectionUri) {
539
481
  return `${branchId}-api.ai.${connectionHostSuffix(connectionUri)}`;
540
482
  }
541
483
  /**
542
- * The API's `invocation_url` ends with `/` so paths concatenate onto it. Neon `*_BASE_URL`
543
- * vars are origin-only (`NEON_AUTH_BASE_URL`, `NEON_AI_GATEWAY_BASE_URL`).
484
+ * `NEON_FUNCTION_HOST_SUFFIX` from a compute host: the endpoint label is replaced by
485
+ * `compute`, as the Functions runtime does (`.compute.c-2.us-east-2.aws.neon.tech`).
544
486
  */
545
- function asEnvBaseUrl(url) {
546
- let parsed;
547
- try {
548
- parsed = new URL(url);
549
- } catch {
550
- throw new Error(`fetchEnv: function invocation URL is not a URL: ${JSON.stringify(url)}`);
551
- }
552
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`fetchEnv: function invocation URL must be http(s): ${JSON.stringify(url)}`);
553
- return parsed.origin;
554
- }
555
- /** Derived from the connection URI so undeployed functions have a cell-routed URL. */
556
- function functionInvocationUrl(branchId, slug, connectionUri) {
557
- const suffix = connectionHostSuffix(connectionUri);
558
- if (suffix === "") throw new Error(`fetchEnv: cannot derive the invocation URL for function "${slug}": the direct connection URI has no host suffix.`);
559
- return `https://${branchId}-${slug}.compute.${suffix}`;
487
+ function functionHostSuffix(computeHost) {
488
+ const suffix = computeHost.split(".").slice(1).join(".");
489
+ if (suffix === "") throw new Error(`fetchEnv: cannot derive NEON_FUNCTION_HOST_SUFFIX from compute host ${JSON.stringify(computeHost)}.`);
490
+ return `.compute.${suffix}`;
491
+ }
492
+ /** The branch's read-write compute host, else its first compute host. */
493
+ function branchComputeHost(endpoints, branch) {
494
+ const own = endpoints.filter((endpoint) => endpoint.branchId === branch.id);
495
+ const endpoint = own.find((candidate) => candidate.type === "read_write") ?? own[0];
496
+ if (!endpoint?.host) throw new PlatformError(ErrorCode.NotFound, `fetchEnv: branch ${branch.name} (${branch.id}) has no compute endpoint, so NEON_FUNCTION_HOST_SUFFIX cannot be derived. Add a compute to the branch, then re-run.`, { details: { branchId: branch.id } });
497
+ return endpoint.host;
560
498
  }
561
499
  /** The AI Gateway's bare base URL (`NEON_AI_GATEWAY_BASE_URL`) on the branch gateway host. */
562
500
  function aiGatewayBaseUrl(branchId, connectionUri) {
@@ -637,6 +575,8 @@ function toEntries(env) {
637
575
  put(K.postgres.databaseUrl, env.postgres?.databaseUrl);
638
576
  put(K.postgres.databaseUrlUnpooled, env.postgres?.databaseUrlUnpooled);
639
577
  put(K.branch.name, env.branch?.name);
578
+ put(K.branch.id, env.branch?.id);
579
+ put(K.branch.functionHostSuffix, env.branch?.functionHostSuffix);
640
580
  put(K.auth.baseUrl, env.auth?.baseUrl);
641
581
  put(K.auth.jwksUrl, env.auth?.jwksUrl);
642
582
  put(K.dataApi.url, env.dataApi?.url);
@@ -648,7 +588,6 @@ function toEntries(env) {
648
588
  put(K.storage.region, env.storage?.region);
649
589
  put(K.aiGateway.apiKey, env.aiGateway?.apiKey);
650
590
  put(K.aiGateway.baseUrl, env.aiGateway?.baseUrl);
651
- if (env.functions) for (const slug of Object.keys(env.functions).sort()) put(functionBaseUrlKey(slug), env.functions[slug]?.baseUrl);
652
591
  return out;
653
592
  }
654
- export { defaultAiGatewayCredential as a, fetchEnvKeysState as c, isLiveCredential as d, parseFunctionBaseUrlKey as f, toEntries as h, credentialName as i, functionBaseUrlKey as l, resolveBranchPolicy as m, createApiFromOptions as n, defaultStorageCredential as o, policyEnvKeys as p, credentialEnvKeys as r, fetchEnvKeys as s, NEON_ENV_VAR_KEYS as t, isFunctionBaseUrlKey as u };
593
+ export { credentialName as a, fetchEnvKeys as c, policyEnvKeys as d, resolveBranchPolicy as f, credentialEnvKeys as i, fetchEnvKeysState as l, NEON_ENV_VAR_KEYS as n, defaultAiGatewayCredential as o, toEntries as p, createApiFromOptions as r, defaultStorageCredential as s, NEON_DEV_FUNCTION_PORTS as t, isLiveCredential as u };
@@ -5,8 +5,8 @@ import { CONTEXT_FILE, contextBranch, gitBranchMap, gitBranchMapping, isUnfollow
5
5
  import { writer } from "../writer.js";
6
6
  import { neonSafeBranchName } from "../utils/branch_name.js";
7
7
  import { currentGitBranch, gitPull, gitRepoRoot, hasUpstream, installPostCheckoutHook, isGitRepo, isManagedHook, localGitBranches, postCheckoutHookPath, readGitContext, removePostCheckoutHook } from "../utils/git.js";
8
- import { o as quoteFlagValue } from "./link-PLk7-vwB.js";
9
- import { o as handler$1 } from "./checkout-OEE3GTc_.js";
8
+ import { o as quoteFlagValue } from "./link-n40BxbmK.js";
9
+ import { o as handler$1 } from "./checkout-B_gbS0nD.js";
10
10
  import { existsSync } from "node:fs";
11
11
  import { join } from "node:path";
12
12
  import chalk from "chalk";
@@ -13,8 +13,8 @@ import { writer } from "../writer.js";
13
13
  import { createBranch, pickBranchInteractively } from "../utils/branch_picker.js";
14
14
  import { looksLikeBranchId } from "../utils/formats.js";
15
15
  import { listAllProjectBranches } from "../utils/enrichers.js";
16
- import { n as autoPullEnvAfterPin } from "./env-C4-EYFmE.js";
17
- import { h as initCmd } from "./config-DPuP7ywm.js";
16
+ import { n as autoPullEnvAfterPin } from "./env-DxcO3oJk.js";
17
+ import { h as initCmd } from "./config-BClSMzco.js";
18
18
  import { formatLinkSummary } from "../commands/link_output.js";
19
19
  import { r as REGIONS } from "./projects-a3X4OFEJ.js";
20
20
  import prompts from "prompts";
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.js";
2
2
  import { fillSingleProject } from "../utils/enrichers.js";
3
- import { y as status } from "./config-DPuP7ywm.js";
3
+ import { y as status } from "./config-BClSMzco.js";
4
4
  // src/commands/status.ts
5
5
  var status_exports = /* @__PURE__ */ __exportAll({
6
6
  builder: () => builder,
@@ -1 +1 @@
1
- export { t as builder, r as command, i as describe, a as formatCheckoutPolicyFailure, o as handler } from "../_chunks/checkout-OEE3GTc_.js";
1
+ export { t as builder, r as command, i as describe, a as formatCheckoutPolicyFailure, o as handler } from "../_chunks/checkout-B_gbS0nD.js";
@@ -1 +1 @@
1
- export { t as CLAIM_CREATE_FIELDS, n as CLAIM_LIST_FIELDS, r as aliases, i as builder, a as claimCreateFields, s as claimableCapabilities, c as command, l as create, u as describe, d as handler } from "../_chunks/claim-C-9or54_.js";
1
+ export { t as CLAIM_CREATE_FIELDS, n as CLAIM_LIST_FIELDS, r as aliases, i as builder, a as claimCreateFields, s as claimableCapabilities, c as command, l as create, u as describe, d as handler } from "../_chunks/claim-BVEwQ65H.js";
@@ -1 +1 @@
1
- export { t as ConfigInstallFailed, n as addCmd, r as applyCmd, i as applyFlags, a as applyPolicyOnCreate, o as builder, s as command, l as createBranchFromPolicyOnCheckout, u as describe, d as ensureConfigPackages, f as envFlag, p as envPullFlag, m as handler, h as initCmd, g as installCommandFrom, _ as missingDependencies, v as planCmd, y as status } from "../_chunks/config-DPuP7ywm.js";
1
+ export { t as ConfigInstallFailed, n as addCmd, r as applyCmd, i as applyFlags, a as applyPolicyOnCreate, o as builder, s as command, l as createBranchFromPolicyOnCheckout, u as describe, d as ensureConfigPackages, f as envFlag, p as envPullFlag, m as handler, h as initCmd, g as installCommandFrom, _ as missingDependencies, v as planCmd, y as status } from "../_chunks/config-BClSMzco.js";
@@ -1 +1 @@
1
- export { t as builder, n as command, i as describe, a as handler } from "../_chunks/deploy-CpF33Ij-.js";
1
+ export { t as builder, n as command, i as describe, a as handler } from "../_chunks/deploy-CJ22hy3i.js";
@@ -1 +1 @@
1
- export { t as builder, n as captureShellEnv, r as command, i as describe, a as devBundleDir, o as devEnvContext, c as diffUnits, l as formatEnvFiles, u as formatEnvSummary, d as handler, f as loadDevEnvFiles, p as localFunctionUrlEnv, m as planFunctionsToUnits, h as reportDevCredential, g as sourceFunctionUrlOverlay } from "../_chunks/dev-BE5TL7ZH.js";
1
+ export { t as builder, n as captureShellEnv, r as command, i as describe, a as devBundleDir, o as devEnvContext, c as diffUnits, l as formatEnvFiles, u as formatEnvSummary, d as handler, f as loadDevEnvFiles, p as localFunctionPortsEnv, m as planFunctionsToUnits, h as reportDevCredential, g as sourceFunctionUrlOverlay } from "../_chunks/dev-CSoQfCuS.js";
@@ -1 +1 @@
1
- export { t as ENV_PULL_SKIPPED_HINT, n as autoPullEnvAfterPin, r as builder, i as command, a as describe, s as handler, c as pull } from "../_chunks/env-C4-EYFmE.js";
1
+ export { t as ENV_PULL_SKIPPED_HINT, n as autoPullEnvAfterPin, r as builder, i as command, a as describe, s as handler, c as pull } from "../_chunks/env-DxcO3oJk.js";
@@ -1,6 +1,5 @@
1
1
  import { NEON_SERVICES, NEON_SERVICE_LABELS } from "../neon_services.js";
2
- import { u as isFunctionBaseUrlKey } from "../_chunks/env-JgoSsmyt.js";
3
- import { BRANCH_ENV_KEY, ENV_PULL_KEYS, serviceForEnvKey } from "../env_services.js";
2
+ import { BRANCH_ENV_KEYS, ENV_PULL_KEYS, isLegacyFunctionBaseUrlKey, serviceForEnvKey } from "../env_services.js";
4
3
  import { isAbsolute, relative } from "node:path";
5
4
  import { homedir } from "node:os";
6
5
  import chalk from "chalk";
@@ -24,8 +23,8 @@ const GROUP_ORDER = [
24
23
  OTHER_GROUP
25
24
  ];
26
25
  const groupOf = (key) => {
27
- if (key === BRANCH_ENV_KEY) return BRANCH_GROUP;
28
- if (isFunctionBaseUrlKey(key)) return NEON_SERVICE_LABELS.functions;
26
+ if (BRANCH_ENV_KEYS.includes(key)) return BRANCH_GROUP;
27
+ if (isLegacyFunctionBaseUrlKey(key)) return NEON_SERVICE_LABELS.functions;
29
28
  const pullKey = ENV_PULL_KEYS.find((candidate) => candidate === key);
30
29
  const service = pullKey ? serviceForEnvKey(pullKey) : null;
31
30
  return service ? NEON_SERVICE_LABELS[service] : OTHER_GROUP;
@@ -57,6 +56,7 @@ const formatPulledEnv = (outcome, cwd, branch) => {
57
56
  lines.push(row(group, keys.map((key) => fresh.has(key) ? `${key}*` : key).join(", ")));
58
57
  }
59
58
  if (outcome.removed.length > 0) lines.push(row("Removed", `${outcome.removed.join(", ")} (not produced by this pull)`));
59
+ if (outcome.removed.some(isLegacyFunctionBaseUrlKey)) lines.push(row("", "Use functionBaseUrl(\"<slug>\") from @neon/env instead."));
60
60
  if (fresh.size > 0) lines.push(" * new credential value");
61
61
  const credential = outcome.credential;
62
62
  if (credential?.issued && credential.revoked.length > 0) lines.push(`Revoked the credential it replaced (${credential.revoked.join(", ")}).`);
@@ -8,7 +8,7 @@ import { writer } from "../writer.js";
8
8
  import { formatInitDone, printInitDone } from "../init/chrome.js";
9
9
  import { FUNCTION_SLUG_PATTERN, deriveFunctionSlug } from "../utils/function_slug.js";
10
10
  import { displayPath } from "./env_output.js";
11
- import { _ as missingDependencies, d as ensureConfigPackages, g as installCommandFrom } from "../_chunks/config-DPuP7ywm.js";
11
+ import { _ as missingDependencies, d as ensureConfigPackages, g as installCommandFrom } from "../_chunks/config-BClSMzco.js";
12
12
  import { recommendedOperations } from "../functions/registry.js";
13
13
  import { collidingFiles, operationsFromFlags, planConfigRegistration, planEnvExample, planScaffold, writeScaffold } from "../functions/scaffold.js";
14
14
  import { describeRegistrySource, openRegistry } from "../functions/source.js";
@@ -1 +1 @@
1
- export { t as aliases, n as builder, r as cleanup, i as command, a as describe, s as handler, c as install, l as partitionBranchesToPrune, u as status, d as sync, f as uninstall } from "../_chunks/git-R8RebFpF.js";
1
+ export { t as aliases, n as builder, r as cleanup, i as command, a as describe, s as handler, c as install, l as partitionBranchesToPrune, u as status, d as sync, f as uninstall } from "../_chunks/git-C6XPViK5.js";
@@ -2,29 +2,29 @@ import { r as auth_exports } from "../_chunks/auth-rup6nemJ.js";
2
2
  import { t as api_exports } from "../_chunks/api-1MKsfpY3.js";
3
3
  import { n as api_keys_exports } from "../_chunks/api_keys-CTFHd5m_.js";
4
4
  import { n as ask_exports } from "../_chunks/ask-Xlek1Pxh.js";
5
- import { o as env_exports } from "../_chunks/env-C4-EYFmE.js";
6
- import { c as config_exports } from "../_chunks/config-DPuP7ywm.js";
5
+ import { o as env_exports } from "../_chunks/env-DxcO3oJk.js";
6
+ import { c as config_exports } from "../_chunks/config-BClSMzco.js";
7
7
  import { u as projects_exports } from "../_chunks/projects-a3X4OFEJ.js";
8
- import { a as link_exports } from "../_chunks/link-PLk7-vwB.js";
8
+ import { a as link_exports } from "../_chunks/link-n40BxbmK.js";
9
9
  import { o as mcp_exports } from "../_chunks/mcp-SvqWzHnT.js";
10
10
  import { c as plugins_exports } from "../_chunks/plugins-BwUZQ6Ic.js";
11
11
  import { l as skills_exports } from "../_chunks/skills-Bv8oKKwE.js";
12
12
  import { t as bootstrap_exports } from "../_chunks/bootstrap-B73qVB39.js";
13
13
  import { r as branches_exports } from "../_chunks/branches-Bp-5z1lM.js";
14
14
  import { n as bucket_exports } from "../_chunks/bucket-D06bvDSa.js";
15
- import { n as checkout_exports } from "../_chunks/checkout-OEE3GTc_.js";
16
- import { o as claim_exports } from "../_chunks/claim-C-9or54_.js";
15
+ import { n as checkout_exports } from "../_chunks/checkout-B_gbS0nD.js";
16
+ import { o as claim_exports } from "../_chunks/claim-BVEwQ65H.js";
17
17
  import { o as connection_string_exports } from "../_chunks/connection_string-6WhV4WFx.js";
18
18
  import { a as credentials_exports } from "../_chunks/credentials-BMBNmW0t.js";
19
19
  import { r as data_api_exports } from "../_chunks/data_api-CHDwvMTG.js";
20
20
  import { s as databases_exports } from "../_chunks/databases-B-qY303S.js";
21
- import { r as deploy_exports } from "../_chunks/deploy-CpF33Ij-.js";
22
- import { s as dev_exports } from "../_chunks/dev-BE5TL7ZH.js";
21
+ import { r as deploy_exports } from "../_chunks/deploy-CJ22hy3i.js";
22
+ import { s as dev_exports } from "../_chunks/dev-CSoQfCuS.js";
23
23
  import { i as diff_exports } from "../_chunks/diff-dnxneH0u.js";
24
24
  import { c as docs_exports } from "../_chunks/docs-BpLiSTmm.js";
25
25
  import { o as feedback_exports } from "../_chunks/feedback-mQmdTRFn.js";
26
26
  import { o as functions_exports } from "../_chunks/functions-PHaU-kRb.js";
27
- import { o as git_exports } from "../_chunks/git-R8RebFpF.js";
27
+ import { o as git_exports } from "../_chunks/git-C6XPViK5.js";
28
28
  import { a as init_exports } from "../_chunks/init-D2fClHtC.js";
29
29
  import { o as inspect_exports } from "../_chunks/inspect-yFAb61qo.js";
30
30
  import { a as ip_allow_exports } from "../_chunks/ip_allow-DBdxNEUa.js";
@@ -40,7 +40,7 @@ import { o as profile_exports } from "../_chunks/profile-CArcjyS4.js";
40
40
  import { s as realtime_exports } from "../_chunks/realtime-BwtzYf5a.js";
41
41
  import { a as set_context_exports } from "../_chunks/set_context-ompB6d2D.js";
42
42
  import { s as snapshots_exports } from "../_chunks/snapshots-DxNhjcco.js";
43
- import { a as status_exports } from "../_chunks/status-BjaHpnTV.js";
43
+ import { a as status_exports } from "../_chunks/status-TDYLPWRO.js";
44
44
  import { d as triggers_exports } from "../_chunks/triggers-BfvyeJUC.js";
45
45
  import { s as user_exports } from "../_chunks/user-D9mC430O.js";
46
46
  import { i as vpc_endpoints_exports } from "../_chunks/vpc_endpoints-C-Y4WK2M.js";
@@ -1 +1 @@
1
- export { t as builder, n as command, r as describe, i as handler, o as quoteFlagValue, s as runLink, c as shouldOfferConfigInit } from "../_chunks/link-PLk7-vwB.js";
1
+ export { t as builder, n as command, r as describe, i as handler, o as quoteFlagValue, s as runLink, c as shouldOfferConfigInit } from "../_chunks/link-n40BxbmK.js";
@@ -1 +1 @@
1
- export { t as builder, n as command, r as describe, i as handler } from "../_chunks/status-BjaHpnTV.js";
1
+ export { t as builder, n as command, r as describe, i as handler } from "../_chunks/status-TDYLPWRO.js";
@@ -1,6 +1,6 @@
1
1
  import { writer } from "../writer.js";
2
2
  import { branchIdFromProps } from "../utils/enrichers.js";
3
- import { o as resolveNeonEnvVars } from "../_chunks/env-CIFMBEon.js";
3
+ import { o as resolveNeonEnvVars } from "../_chunks/env-CFBmcKyo.js";
4
4
  import YAML from "yaml";
5
5
  // src/commands/subscribe.ts
6
6
  const builder = (argv) => argv.usage("$0 realtime subscribe \"<query>\" [options]").positional("query", {
package/dist/dev/env.js CHANGED
@@ -1 +1 @@
1
- export { t as DevEnvMismatchError, n as MissingBranchContextError, r as ServiceNotOnBranchError, i as dropClaimableUnsupported, a as resolveDevEnv, o as resolveNeonEnvVars } from "../_chunks/env-CIFMBEon.js";
1
+ export { t as DevEnvMismatchError, n as MissingBranchContextError, r as ServiceNotOnBranchError, i as dropClaimableUnsupported, a as resolveDevEnv, o as resolveNeonEnvVars } from "../_chunks/env-CFBmcKyo.js";
@@ -1,17 +1,25 @@
1
1
  import { NEON_SERVICES } from "./neon_services.js";
2
- import { f as parseFunctionBaseUrlKey, t as NEON_ENV_VAR_KEYS, u as isFunctionBaseUrlKey } from "./_chunks/env-JgoSsmyt.js";
2
+ import { n as NEON_ENV_VAR_KEYS } from "./_chunks/env-EJU-0InB.js";
3
3
  // src/env_services.ts
4
4
  const ENV_PULL_SERVICES = NEON_SERVICES;
5
5
  const ENV_PULL_KEYS = [
6
6
  ...Object.values(NEON_ENV_VAR_KEYS.postgres),
7
7
  NEON_ENV_VAR_KEYS.branch.name,
8
+ NEON_ENV_VAR_KEYS.branch.id,
9
+ NEON_ENV_VAR_KEYS.branch.functionHostSuffix,
8
10
  ...Object.values(NEON_ENV_VAR_KEYS.auth),
9
11
  ...Object.values(NEON_ENV_VAR_KEYS.dataApi),
10
12
  ...Object.values(NEON_ENV_VAR_KEYS.realtime),
11
13
  ...Object.values(NEON_ENV_VAR_KEYS.storage),
12
14
  ...Object.values(NEON_ENV_VAR_KEYS.aiGateway)
13
15
  ];
14
- const ENV_PULL_KEY_HELP = `${ENV_PULL_KEYS.join(", ")}, or NEON_FUNCTION_<SLUG>_BASE_URL`;
16
+ const ENV_PULL_KEY_HELP = ENV_PULL_KEYS.join(", ");
17
+ /**
18
+ * The per-function URL vars earlier releases wrote (`NEON_FUNCTION_<SLUG>_BASE_URL`), replaced
19
+ * by `NEON_BRANCH_ID` + `NEON_FUNCTION_HOST_SUFFIX`. Recognized only to prune them from a
20
+ * pulled file and to point `--env` callers at `functionBaseUrl`.
21
+ */
22
+ const isLegacyFunctionBaseUrlKey = (key) => /^NEON_FUNCTION_[A-Z0-9]{1,20}_BASE_URL$/.test(key);
15
23
  /** The OS-level env vars each service contributes to a pulled `.env`. */
16
24
  const SERVICE_ENV_KEYS = {
17
25
  postgres: Object.values(NEON_ENV_VAR_KEYS.postgres),
@@ -20,29 +28,29 @@ const SERVICE_ENV_KEYS = {
20
28
  realtime: Object.values(NEON_ENV_VAR_KEYS.realtime),
21
29
  "object-storage": Object.values(NEON_ENV_VAR_KEYS.storage),
22
30
  "ai-gateway": Object.values(NEON_ENV_VAR_KEYS.aiGateway),
23
- functions: []
31
+ functions: [NEON_ENV_VAR_KEYS.branch.functionHostSuffix]
24
32
  };
25
33
  /**
26
34
  * The subset of {@link SERVICE_ENV_KEYS} a pull *owns*, and so may prune from the target file
27
35
  * when the branch no longer has it. Object storage is deliberately absent: it is emitted under
28
36
  * the third-party `AWS_*` names, which collide with credentials a user may set by hand, so
29
- * `env pull` only ever writes them. Function URL keys cannot live here because slugs are
30
- * discovered at runtime.
37
+ * `env pull` only ever writes them.
31
38
  */
32
39
  const SERVICE_OWNED_ENV_KEYS = {
33
40
  ...SERVICE_ENV_KEYS,
34
- "object-storage": [],
35
- functions: []
41
+ "object-storage": []
36
42
  };
37
43
  /**
38
- * Branch identity. Not a service — every branch has a name — so a scoped pull refreshes it
39
- * alongside whatever services were selected.
44
+ * Branch identity. Not a service — every branch has a name and an id — so a scoped pull
45
+ * refreshes it alongside whatever services were selected.
40
46
  */
41
- const BRANCH_ENV_KEY = NEON_ENV_VAR_KEYS.branch.name;
47
+ const BRANCH_ENV_KEYS = [NEON_ENV_VAR_KEYS.branch.name, NEON_ENV_VAR_KEYS.branch.id];
42
48
  const ENV_KEY_SERVICE = {
43
49
  DATABASE_URL: "postgres",
44
50
  DATABASE_URL_UNPOOLED: "postgres",
45
51
  NEON_BRANCH: null,
52
+ NEON_BRANCH_ID: null,
53
+ NEON_FUNCTION_HOST_SUFFIX: "functions",
46
54
  NEON_AUTH_BASE_URL: "auth",
47
55
  NEON_AUTH_JWKS_URL: "auth",
48
56
  NEON_DATA_API_URL: "data-api",
@@ -55,12 +63,12 @@ const ENV_KEY_SERVICE = {
55
63
  NEON_AI_GATEWAY_TOKEN: "ai-gateway",
56
64
  NEON_AI_GATEWAY_BASE_URL: "ai-gateway"
57
65
  };
58
- const serviceForEnvKey = (key) => isFunctionBaseUrlKey(key) ? "functions" : ENV_KEY_SERVICE[key];
66
+ const serviceForEnvKey = (key) => ENV_KEY_SERVICE[key];
59
67
  /** Services that must be resolved to produce the selected env keys. */
60
68
  const servicesForEnvKeys = (keys) => ENV_PULL_SERVICES.filter((service) => keys.some((key) => serviceForEnvKey(key) === service));
61
69
  /** Every env var the selected services contribute, plus branch identity. */
62
70
  const envServiceKeys = (services) => {
63
- const keys = /* @__PURE__ */ new Set([BRANCH_ENV_KEY]);
71
+ const keys = new Set(BRANCH_ENV_KEYS);
64
72
  for (const service of services) for (const key of SERVICE_ENV_KEYS[service]) keys.add(key);
65
73
  return keys;
66
74
  };
@@ -68,34 +76,34 @@ const envServiceKeys = (services) => {
68
76
  * The env vars a pull scoped to `services` may prune. Narrower than the unscoped set on
69
77
  * purpose: `env pull -s ai-gateway` says nothing about `DATABASE_URL`, so it must leave it
70
78
  * alone rather than treat its absence from this pull as "the branch no longer has it".
71
- * Function URL keys cannot live here because slugs are discovered at runtime.
72
79
  */
73
80
  const ownedEnvServiceKeys = (services) => services.flatMap((service) => SERVICE_OWNED_ENV_KEYS[service]);
74
81
  const envKeysForSelection = (services, envKeys) => {
75
82
  const selected = services.length > 0 ? envServiceKeys(services) : /* @__PURE__ */ new Set();
76
83
  for (const key of envKeys) selected.add(key);
77
84
  if (selected.has(NEON_ENV_VAR_KEYS.storage.accessKeyId) !== selected.has(NEON_ENV_VAR_KEYS.storage.secretAccessKey)) throw new Error("AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be selected together: they are two halves of one newly issued object-storage credential. Add the missing key to --env, or use --service object-storage.");
78
- const staticKeys = ENV_PULL_KEYS.filter((key) => selected.has(key));
79
- const functionKeys = [...selected].filter(isFunctionBaseUrlKey).sort((left, right) => left.localeCompare(right));
80
- return [...staticKeys, ...functionKeys];
85
+ return ENV_PULL_KEYS.filter((key) => selected.has(key));
81
86
  };
82
87
  /** Parse repeated or comma-separated `--env` values into canonical env-key order. */
83
88
  const parseEnvPullKeys = (raw, flag) => {
84
89
  const names = raw.flatMap((value) => value.split(",")).map((name) => name.trim()).filter((name) => name !== "");
85
90
  const supported = `Supported values: ${ENV_PULL_KEY_HELP}.`;
86
91
  if (names.length === 0) throw new Error(`${flag} needs at least one env variable. ${supported}`);
87
- const unknown = names.filter((name) => !ENV_PULL_KEYS.some((key) => key === name) && !isFunctionBaseUrlKey(name));
92
+ const legacy = names.filter(isLegacyFunctionBaseUrlKey);
93
+ if (legacy.length > 0) {
94
+ const slug = (legacy[0] ?? "").slice(14, -9).toLowerCase();
95
+ throw new Error(`${legacy.join(", ")} ${legacy.length === 1 ? "is" : "are"} no longer pulled. Pull NEON_BRANCH_ID and NEON_FUNCTION_HOST_SUFFIX with \`--service functions\`, then build the URL with \`functionBaseUrl("${slug}")\` from @neon/env.`);
96
+ }
97
+ const unknown = names.filter((name) => !ENV_PULL_KEYS.some((key) => key === name));
88
98
  if (unknown.length > 0) {
89
99
  const displayNames = unknown.map(redactUnknownEnvValue);
90
100
  const suggestions = [...new Set(unknown.map(suggestEnvPullKey).filter((key) => key !== null))];
91
101
  const suggestion = suggestions.length > 0 ? ` Did you mean ${suggestions.join(" or ")}?` : "";
92
102
  throw new Error(`Unknown env variable${unknown.length === 1 ? "" : "s"} ${displayNames.join(", ")}.${suggestion} ${supported}`);
93
103
  }
94
- const staticKeys = ENV_PULL_KEYS.filter((key) => names.includes(key));
95
- const functionKeys = [...new Set(names.filter(isFunctionBaseUrlKey))].sort((left, right) => left.localeCompare(right));
96
- return [...staticKeys, ...functionKeys];
104
+ return ENV_PULL_KEYS.filter((key) => names.includes(key));
97
105
  };
98
- const isKnownEnvPullKey = (key) => ENV_PULL_KEYS.some((supportedKey) => supportedKey === key) || isFunctionBaseUrlKey(key);
106
+ const isKnownEnvPullKey = (key) => ENV_PULL_KEYS.some((supportedKey) => supportedKey === key);
99
107
  const redactUnknownEnvValue = (value) => {
100
108
  const separator = value.indexOf("=");
101
109
  if (separator !== -1) {
@@ -106,7 +114,6 @@ const redactUnknownEnvValue = (value) => {
106
114
  };
107
115
  const suggestEnvPullKey = (value) => {
108
116
  if (value.includes("=")) return null;
109
- if (parseFunctionBaseUrlKey(value) !== null) return null;
110
117
  const closest = ENV_PULL_KEYS.map((key) => [key, editDistance(value, key)]).sort((a, b) => a[1] - b[1])[0];
111
118
  return closest && closest[1] <= 2 ? closest[0] : null;
112
119
  };
@@ -121,4 +128,4 @@ const editDistance = (left, right) => {
121
128
  };
122
129
  /** Narrow yargs' array option value without accepting any other runtime shape. */
123
130
  const envPullFlagValue = (value) => Array.isArray(value) ? value.map(String) : void 0;
124
- export { BRANCH_ENV_KEY, ENV_PULL_KEYS, ENV_PULL_KEY_HELP, ENV_PULL_SERVICES, envKeysForSelection, envPullFlagValue, envServiceKeys, ownedEnvServiceKeys, parseEnvPullKeys, serviceForEnvKey, servicesForEnvKeys };
131
+ export { BRANCH_ENV_KEYS, ENV_PULL_KEYS, ENV_PULL_KEY_HELP, ENV_PULL_SERVICES, envKeysForSelection, envPullFlagValue, envServiceKeys, isLegacyFunctionBaseUrlKey, ownedEnvServiceKeys, parseEnvPullKeys, serviceForEnvKey, servicesForEnvKeys };
package/dist/errors.js CHANGED
@@ -19,7 +19,8 @@ const ERROR_MATCHERS = [
19
19
  [/^(Failed to install Neon agent skills|skills CLI failed)/, "SKILLS_CLI_FAILED"],
20
20
  [/^Cannot install the Neon plugin for /, "AGENT_COMMAND_UNAVAILABLE"],
21
21
  [/^(Failed to install the Neon plugin for: |plugins CLI (failed|timed out))/, "PLUGINS_CLI_FAILED"],
22
- [/^Could not install the Neon dependencies/, "DEPENDENCY_INSTALL_FAILED"]
22
+ [/^Could not install the Neon dependencies/, "DEPENDENCY_INSTALL_FAILED"],
23
+ [/ (is|are) no longer pulled\. Pull NEON_BRANCH_ID /, "LEGACY_FUNCTION_ENV_KEY"]
23
24
  ];
24
25
  const matchErrorCode = (message) => {
25
26
  if (!message) return "UNKNOWN_ERROR";
package/dist/init/auth.js CHANGED
@@ -4,7 +4,7 @@ import "../config.js";
4
4
  import "../auth.js";
5
5
  import { c as ensureAuth, l as existingApiClient } from "../_chunks/auth-rup6nemJ.js";
6
6
  import { recoverFrom401 } from "../auth_recovery.js";
7
- import { c as pull } from "../_chunks/env-C4-EYFmE.js";
7
+ import { c as pull } from "../_chunks/env-DxcO3oJk.js";
8
8
  import { c as setupNeonMcp } from "../_chunks/mcp-SvqWzHnT.js";
9
9
  // src/init/auth.ts
10
10
  const isUnauthorized = (error) => isNeonApiError(error) && error.status === 401;
@@ -1,5 +1,3 @@
1
- import { FUNCTION_SLUG } from "../config_template.js";
2
- import { l as functionBaseUrlKey } from "../_chunks/env-JgoSsmyt.js";
3
1
  // src/init/choices.ts
4
2
  const INIT_CONFIG_SERVICES_CONFLICT = "--no-config cannot be combined with --services.";
5
3
  const resolveInitConfigChoice = (input) => {
@@ -25,8 +23,8 @@ const configPlanFromResolution = (resolution, accepted) => {
25
23
  };
26
24
  /**
27
25
  * A neon.ts policy pull fails while the branch lacks a declared service. These two need
28
- * no `deploy`: the AI Gateway exists on every branch, and function URLs derive from the
29
- * branch host.
26
+ * no `deploy`: the AI Gateway exists on every branch, and the function host suffix derives
27
+ * from the branch's compute host.
30
28
  */
31
29
  const DEPLOY_FREE_SERVICES = /* @__PURE__ */ new Set(["ai-gateway", "functions"]);
32
30
  const needsDeploy = (declared) => declared.some((service) => !DEPLOY_FREE_SERVICES.has(service));
@@ -37,8 +35,12 @@ const initEnvPullAfterConfig = (input) => {
37
35
  if (!needsDeploy(input.declared)) return { kind: "policy" };
38
36
  return {
39
37
  kind: "services",
40
- services: input.declared.includes("ai-gateway") ? ["postgres", "ai-gateway"] : ["postgres"],
41
- envKeys: input.declared.includes("functions") ? [functionBaseUrlKey(FUNCTION_SLUG)] : []
38
+ services: [
39
+ "postgres",
40
+ ...input.declared.includes("ai-gateway") ? ["ai-gateway"] : [],
41
+ ...input.declared.includes("functions") ? ["functions"] : []
42
+ ],
43
+ envKeys: []
42
44
  };
43
45
  };
44
46
  export { INIT_CONFIG_SERVICES_CONFLICT, configPlanFromResolution, initEnvPullAfterConfig, resolveInitConfigChoice };
@@ -4,7 +4,7 @@ import { c as ensureAuth } from "../_chunks/auth-rup6nemJ.js";
4
4
  import { recoverFrom401 } from "../auth_recovery.js";
5
5
  import { loadProjectConfig } from "../project.js";
6
6
  import { loadEnvFileIntoProcess } from "../env_file.js";
7
- import { r as applyCmd } from "../_chunks/config-DPuP7ywm.js";
7
+ import { r as applyCmd } from "../_chunks/config-BClSMzco.js";
8
8
  import { authContext } from "./auth.js";
9
9
  import { existsSync } from "node:fs";
10
10
  // src/init/deploy.ts
package/dist/init/link.js CHANGED
@@ -4,7 +4,7 @@ import "../config.js";
4
4
  import "../auth.js";
5
5
  import { c as ensureAuth } from "../_chunks/auth-rup6nemJ.js";
6
6
  import { recoverFrom401 } from "../auth_recovery.js";
7
- import { s as runLink } from "../_chunks/link-PLk7-vwB.js";
7
+ import { s as runLink } from "../_chunks/link-n40BxbmK.js";
8
8
  // src/init/link.ts
9
9
  const isUnauthorized = (error) => isNeonApiError(error) && error.status === 401;
10
10
  const authenticationFailed = () => /* @__PURE__ */ new Error("Authentication failed.");
package/dist/init/run.js CHANGED
@@ -14,8 +14,8 @@ import { getAgentDisplayName } from "../mcp/agents.js";
14
14
  import { missingPluginsCommands, pluginsCommandProblemText, pluginsInstallableAgents, unusablePluginsCommands } from "../plugins/targets.js";
15
15
  import { AGENTS_NOT_INSTALLED, CANCELLED_BODY, CLAIMABLE_ACCOUNT_FLAGS, CLAIMABLE_ALREADY_LINKED, CLAIMABLE_MCP_API_KEY, CLAIMABLE_NO_LINK, MCP_API_KEY_NEEDS_AUTH, MCP_SCOPED_NEEDS_PROJECT, NON_TTY_LINK_NEEDS_AUTH, NO_AGENTS_FALLBACK_STATUS, PROGRESS, PROJECT_PINNED_OFFLINE, claimableNext, claimableThenServicesNext, configInitNext, envPullFailedNext, existingConfigNext, installFailedNext, mcpAfterLinkNext, mcpConfigLocationSkipped, mcpConfigLocationUnavailable, mcpKeyFailedNext, namedAgentsUnavailable, newConfigNext, offlinePinNext, skippedLinkNext, toolingFailedNext, unattendedUnauthedNext } from "./copy.js";
16
16
  import { agentsRowValue, configRowValue, formatInitDone, headingForKind, printInitBanner, printInitDone, printInitProgress, projectRowValue, shouldPrintInitBanner } from "./chrome.js";
17
- import { h as initCmd, t as ConfigInstallFailed } from "../_chunks/config-DPuP7ywm.js";
18
- import { o as quoteFlagValue, s as runLink } from "../_chunks/link-PLk7-vwB.js";
17
+ import { h as initCmd, t as ConfigInstallFailed } from "../_chunks/config-BClSMzco.js";
18
+ import { o as quoteFlagValue, s as runLink } from "../_chunks/link-n40BxbmK.js";
19
19
  import { runAuthenticatedLink } from "./link.js";
20
20
  import { mcpInstallableAgents } from "../mcp/targets.js";
21
21
  import { skillsInstallableAgents } from "../skills/targets.js";
@@ -25,7 +25,7 @@ import { pullInitEnv, resolveInitConfigApi } from "./auth.js";
25
25
  import { InitCancelled, raceSigint, restoreCursor } from "./cancelled.js";
26
26
  import { pickAgentSetupInteractively, pickInitAgentsInteractively, pickInitConfigInteractively, pickInitMcpAuthInteractively, pickInitMcpConfigLocationInteractively, pickInitModeInteractively, pickInitPackageManagerInteractively, pickInitProjectSetupInteractively, pickInitServicesInteractively, pickInitSkillsInteractively } from "./wizard.js";
27
27
  import { runToolingSteps, toolingStepCommandText } from "./tooling.js";
28
- import { l as create } from "../_chunks/claim-C-9or54_.js";
28
+ import { l as create } from "../_chunks/claim-BVEwQ65H.js";
29
29
  import { INIT_CONFIG_SERVICES_CONFLICT, configPlanFromResolution, initEnvPullAfterConfig, resolveInitConfigChoice } from "./choices.js";
30
30
  import { detectInitEnvironment } from "./detect.js";
31
31
  import { createInitFunnel, emitInitStart, finishInitFunnel, initStartProperties, recordInitError, recordInitExit } from "./funnel.js";
@@ -1,6 +1,6 @@
1
1
  import { log } from "../log.js";
2
2
  import { loadProjectConfig } from "../project.js";
3
- import { s as fetchEnvKeys } from "../_chunks/env-JgoSsmyt.js";
3
+ import { c as fetchEnvKeys } from "../_chunks/env-EJU-0InB.js";
4
4
  import { runHook } from "@neon/config-runtime";
5
5
  // src/utils/hooks.ts
6
6
  /**
@@ -170,7 +170,11 @@ const shapeHookEnv = (resolved) => ({
170
170
  databaseUrl: resolved.postgres?.databaseUrl ?? "",
171
171
  databaseUrlUnpooled: resolved.postgres?.databaseUrlUnpooled ?? ""
172
172
  },
173
- ...resolved.branch?.name ? { branch: { name: resolved.branch.name } } : {},
173
+ ...resolved.branch?.name ? { branch: {
174
+ name: resolved.branch.name,
175
+ ...resolved.branch.id ? { id: resolved.branch.id } : {},
176
+ ...resolved.branch.functionHostSuffix ? { functionHostSuffix: resolved.branch.functionHostSuffix } : {}
177
+ } } : {},
174
178
  ...resolved.auth?.baseUrl !== void 0 && resolved.auth.jwksUrl !== void 0 ? { auth: {
175
179
  baseUrl: resolved.auth.baseUrl,
176
180
  jwksUrl: resolved.auth.jwksUrl
@@ -185,8 +189,7 @@ const shapeHookEnv = (resolved) => ({
185
189
  ...resolved.aiGateway?.apiKey !== void 0 && resolved.aiGateway.baseUrl !== void 0 ? { aiGateway: {
186
190
  apiKey: resolved.aiGateway.apiKey,
187
191
  baseUrl: resolved.aiGateway.baseUrl
188
- } } : {},
189
- ...resolved.functions ? { functions: Object.fromEntries(Object.entries(resolved.functions).map(([slug, fn]) => [slug, { baseUrl: fn.baseUrl }])) } : {}
192
+ } } : {}
190
193
  });
191
194
  /** Re-derive the OS-level env vars from a {@link HookEnv} for shell-hook injection. */
192
195
  const hookEnvToProcessEnv = (env) => {
@@ -195,6 +198,8 @@ const hookEnvToProcessEnv = (env) => {
195
198
  DATABASE_URL_UNPOOLED: env.postgres.databaseUrlUnpooled
196
199
  };
197
200
  if (env.branch?.name) out.NEON_BRANCH = env.branch.name;
201
+ if (env.branch?.id) out.NEON_BRANCH_ID = env.branch.id;
202
+ if (env.branch?.functionHostSuffix) out.NEON_FUNCTION_HOST_SUFFIX = env.branch.functionHostSuffix;
198
203
  if (env.auth) {
199
204
  out.NEON_AUTH_BASE_URL = env.auth.baseUrl;
200
205
  out.NEON_AUTH_JWKS_URL = env.auth.jwksUrl;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neon",
3
- "version": "8.23.4",
3
+ "version": "9.0.0",
4
4
  "description": "CLI tool for Neon, the cloud backend primitives built around Lakebase Postgres",
5
5
  "keywords": [
6
6
  "neon",
@@ -73,9 +73,9 @@
73
73
  "yaml": "^2.9.0",
74
74
  "yargs": "17.7.2",
75
75
  "yoctocolors": "^2.1.2",
76
- "@neon/config-runtime": "1.11.7",
76
+ "@neon/config-runtime": "1.11.8",
77
+ "@neon/config": "1.12.0",
77
78
  "@neon/realtime": "0.2.0",
78
- "@neon/config": "1.11.3",
79
79
  "@neon/sdk": "7.10.0"
80
80
  },
81
81
  "optionalDependencies": {
@@ -113,10 +113,10 @@
113
113
  "typescript": "^5.9.0",
114
114
  "vitest": "^3.0.9",
115
115
  "@neon-internals/cli-core": "0.0.0",
116
- "@neon-internals/env-core": "0.0.45",
117
- "@neon/env": "1.6.15",
116
+ "@neon-internals/env-core": "0.0.46",
117
+ "@neon/e2e-harness": "0.0.0",
118
118
  "@neon/functions": "0.11.0",
119
- "@neon/e2e-harness": "0.0.0"
119
+ "@neon/env": "2.0.0"
120
120
  },
121
121
  "publishConfig": {
122
122
  "access": "public",