neon 8.11.0 → 8.11.2

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 (106) hide show
  1. package/README.md +1 -1
  2. package/dist/_chunks/api-GbEaBZJ5.js +388 -0
  3. package/dist/_chunks/api_keys-CNnnugbQ.js +281 -0
  4. package/dist/_chunks/ask-DVwy0eUL.js +155 -0
  5. package/dist/_chunks/auth-CIUtXByB.js +495 -0
  6. package/dist/_chunks/bootstrap-wPZWa1sT.js +499 -0
  7. package/dist/_chunks/branches-BNa1xX1L.js +460 -0
  8. package/dist/_chunks/bucket-BCdryTkD.js +409 -0
  9. package/dist/_chunks/checkout-CXIOydqZ.js +348 -0
  10. package/dist/_chunks/claim-DqAvAvDm.js +473 -0
  11. package/dist/_chunks/config-BH_qRHiG.js +1113 -0
  12. package/dist/_chunks/connection_string-DB4awPzZ.js +154 -0
  13. package/dist/_chunks/credentials-BSjE9fRR.js +146 -0
  14. package/dist/_chunks/data_api-Djxj5ZQD.js +263 -0
  15. package/dist/_chunks/databases-Dok4wru7.js +84 -0
  16. package/dist/_chunks/deploy-D7B0Xfjg.js +33 -0
  17. package/dist/_chunks/dev-CSvxAecE.js +945 -0
  18. package/dist/_chunks/diff-DhxxbdQE.js +178 -0
  19. package/dist/_chunks/docs-CrVybkTP.js +197 -0
  20. package/dist/_chunks/env-5HS5qQGd.js +284 -0
  21. package/dist/_chunks/feedback-CMayyTa8.js +88 -0
  22. package/dist/_chunks/functions-Q0zuvtnk.js +464 -0
  23. package/dist/_chunks/git-H32TNt6M.js +356 -0
  24. package/dist/_chunks/init-BkA6RilG.js +111 -0
  25. package/dist/_chunks/inspect-g0wekylj.js +90 -0
  26. package/dist/_chunks/ip_allow-5lLFvIuE.js +106 -0
  27. package/dist/_chunks/link-BgtkOBws.js +936 -0
  28. package/dist/_chunks/logs-DWkpjzIH.js +291 -0
  29. package/dist/_chunks/mcp-Bo-7TKc7.js +253 -0
  30. package/dist/_chunks/neon_auth-CBs1_3qu.js +822 -0
  31. package/dist/_chunks/open-CX3BT3Tp.js +33 -0
  32. package/dist/_chunks/operations-D4I-AxVs.js +37 -0
  33. package/dist/_chunks/orgs-xGfANwHQ.js +52 -0
  34. package/dist/_chunks/plugins-DqD7BDO1.js +169 -0
  35. package/dist/_chunks/profile-yXOiKk9R.js +672 -0
  36. package/dist/_chunks/projects-BwI2Uo0z.js +439 -0
  37. package/dist/_chunks/psql-BM-doe8e.js +64 -0
  38. package/dist/_chunks/realtime-BRqIyGR-.js +79 -0
  39. package/dist/_chunks/roles-B4w3YT_7.js +79 -0
  40. package/dist/_chunks/set_context-DbrwoImy.js +38 -0
  41. package/dist/_chunks/skills-DyiBXKS3.js +255 -0
  42. package/dist/_chunks/snapshots-RJBzW8GM.js +338 -0
  43. package/dist/_chunks/status-DV8Z2kw3.js +44 -0
  44. package/dist/_chunks/triggers-BrRo1z4b.js +302 -0
  45. package/dist/_chunks/user-dlOGXbX9.js +60 -0
  46. package/dist/_chunks/vpc_endpoints-CNb0YfMo.js +105 -0
  47. package/dist/auth_recovery.js +1 -1
  48. package/dist/commands/api.js +1 -388
  49. package/dist/commands/api_keys.js +1 -281
  50. package/dist/commands/ask.js +1 -155
  51. package/dist/commands/auth.js +1 -495
  52. package/dist/commands/bootstrap.js +1 -499
  53. package/dist/commands/branches.js +1 -460
  54. package/dist/commands/bucket.js +1 -409
  55. package/dist/commands/checkout.js +1 -348
  56. package/dist/commands/claim.js +1 -473
  57. package/dist/commands/config.js +1 -1113
  58. package/dist/commands/connection_string.js +1 -154
  59. package/dist/commands/credentials.js +1 -146
  60. package/dist/commands/data_api.js +1 -263
  61. package/dist/commands/databases.js +1 -84
  62. package/dist/commands/deploy.js +1 -33
  63. package/dist/commands/dev.js +1 -945
  64. package/dist/commands/diff.js +1 -178
  65. package/dist/commands/docs.js +1 -197
  66. package/dist/commands/env.js +1 -284
  67. package/dist/commands/feedback.js +1 -88
  68. package/dist/commands/functions.js +1 -464
  69. package/dist/commands/functions_new.js +6 -6
  70. package/dist/commands/git.js +1 -356
  71. package/dist/commands/index.js +45 -45
  72. package/dist/commands/init.js +1 -111
  73. package/dist/commands/inspect.js +1 -90
  74. package/dist/commands/ip_allow.js +1 -106
  75. package/dist/commands/link.js +1 -936
  76. package/dist/commands/logs.js +1 -291
  77. package/dist/commands/mcp.js +1 -253
  78. package/dist/commands/neon_auth.js +1 -822
  79. package/dist/commands/open.js +1 -33
  80. package/dist/commands/operations.js +1 -37
  81. package/dist/commands/orgs.js +1 -52
  82. package/dist/commands/plugins.js +1 -169
  83. package/dist/commands/profile.js +1 -672
  84. package/dist/commands/projects.js +1 -439
  85. package/dist/commands/psql.js +1 -64
  86. package/dist/commands/realtime.js +1 -79
  87. package/dist/commands/roles.js +1 -79
  88. package/dist/commands/set_context.js +1 -38
  89. package/dist/commands/skills.js +1 -255
  90. package/dist/commands/snapshots.js +1 -338
  91. package/dist/commands/status.js +1 -44
  92. package/dist/commands/subscribe.js +1 -1
  93. package/dist/commands/triggers.js +1 -302
  94. package/dist/commands/user.js +1 -60
  95. package/dist/commands/vpc_endpoints.js +1 -105
  96. package/dist/functions/registry.js +29 -151
  97. package/dist/functions/source.js +42 -2
  98. package/dist/index.js +1 -1
  99. package/dist/init/auth.js +3 -3
  100. package/dist/init/link.js +2 -2
  101. package/dist/init/run.js +3 -3
  102. package/dist/init/tooling.js +3 -3
  103. package/dist/mcp/mint.js +1 -1
  104. package/dist/test_utils/registry.js +1 -2
  105. package/dist/utils/package_manager.js +1 -0
  106. package/package.json +4 -2
@@ -0,0 +1,178 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
+ import { log } from "../log.js";
3
+ import { isNeonApiError } from "../api.js";
4
+ import { writer } from "../writer.js";
5
+ import { looksLikeBranchId } from "../utils/formats.js";
6
+ import { fillSingleProject, listAllProjectBranches } from "../utils/enrichers.js";
7
+ import { renderDatabaseSchemaDiff, renderSchemaDiffReport } from "../utils/git_diff.js";
8
+ import chalk from "chalk";
9
+ //#region src/commands/diff.ts
10
+ var diff_exports = /* @__PURE__ */ __exportAll({
11
+ builder: () => builder,
12
+ command: () => command,
13
+ describe: () => describe,
14
+ handler: () => handler
15
+ });
16
+ const command = "diff [compare-branch]";
17
+ const describe = "Show a git-style schema diff between the current branch and another branch";
18
+ const builder = (argv) => argv.usage("$0 diff [compare-branch] [options]").positional("compare-branch", {
19
+ describe: "Branch name or id to compare against (the reference / '---' side). Defaults to the current branch's parent.",
20
+ type: "string"
21
+ }).options({
22
+ "project-id": {
23
+ describe: "Project ID",
24
+ type: "string"
25
+ },
26
+ branch: {
27
+ alias: "b",
28
+ describe: "The branch to review (the '+++' side). Defaults to the branch pinned in the local context (.neon).",
29
+ type: "string"
30
+ },
31
+ database: {
32
+ alias: "db",
33
+ describe: "Limit the diff to a single database. Defaults to every database on the current branch.",
34
+ type: "string"
35
+ }
36
+ }).middleware(fillSingleProject).middleware((args) => {
37
+ const compareBranch = args["compare-branch"];
38
+ if (typeof compareBranch === "string") args.compareBranch = compareBranch;
39
+ }).example([
40
+ ["$0 diff main", "Diff the current branch's schema against the main branch"],
41
+ ["$0 diff", "Diff the current branch's schema against its parent branch"],
42
+ ["$0 diff main --branch feature/checkout", "Diff an explicit branch against main (ignoring the .neon context)"],
43
+ ["$0 diff main --db neondb", "Diff only the neondb database against main"]
44
+ ]);
45
+ const handler = async (props) => {
46
+ const branches = await listAllProjectBranches(props.apiClient, props.projectId);
47
+ const after = resolveAfterBranch(branches, props.branch);
48
+ const before = resolveBeforeBranch(branches, after, props.compareBranch);
49
+ if (before.branchId === after.branchId) throw new Error(`Nothing to compare: both sides resolve to branch ${after.branchName} (${after.branchId}).`);
50
+ const databases = await resolveDatabases(props, after);
51
+ const diffs = [];
52
+ for (const database of databases) {
53
+ const [beforeSql, afterSql] = await Promise.all([fetchSchemaSql(props, before.branchId, database), fetchSchemaSql(props, after.branchId, database)]);
54
+ diffs.push({
55
+ database,
56
+ before: {
57
+ ...before,
58
+ sql: beforeSql
59
+ },
60
+ after: {
61
+ ...after,
62
+ sql: afterSql
63
+ }
64
+ });
65
+ }
66
+ if (props.output === "json" || props.output === "yaml") {
67
+ writeStructured(props, diffs);
68
+ return;
69
+ }
70
+ log.info("%s Comparing schema %s → %s", chalk.dim("→"), chalk.red(`${before.branchName}`), chalk.green(`${after.branchName}`));
71
+ const { hasChanges, text } = renderSchemaDiffReport(diffs, { color: props.color !== false });
72
+ if (!hasChanges) {
73
+ log.info("No schema differences between %s and %s.", before.branchName, after.branchName);
74
+ return;
75
+ }
76
+ writer(props).text(`${text}\n`);
77
+ };
78
+ /**
79
+ * Resolve the branch under review (`+++` side). Prefers the explicit
80
+ * `branch`/`--branch` value (name or `br-…` id), falling back to the project's
81
+ * default branch. An unknown `br-…` id is trusted as-is (it may be too new to
82
+ * appear in the listing); an unknown *name* is a hard error.
83
+ */
84
+ const resolveAfterBranch = (branches, ref) => {
85
+ if (ref) return resolveRef(branches, ref);
86
+ const def = branches.find((b) => b.default);
87
+ if (!def) throw new Error("No branch specified and no default branch found. Pass --branch <name|id>.");
88
+ return {
89
+ branchId: def.id,
90
+ branchName: def.name ?? def.id
91
+ };
92
+ };
93
+ /**
94
+ * Resolve the reference branch (`---` side). Uses the `compare-branch`
95
+ * positional when given, otherwise the parent of the branch under review — so a
96
+ * bare `neon diff` answers "what did I change since branching?".
97
+ */
98
+ const resolveBeforeBranch = (branches, after, ref) => {
99
+ if (ref) return resolveRef(branches, ref);
100
+ const parentId = branches.find((b) => b.id === after.branchId)?.parent_id;
101
+ if (!parentId) throw new Error(`Branch "${after.branchName}" has no parent to compare against. Pass a branch to compare with, e.g. \`neon diff main\`.`);
102
+ return {
103
+ branchId: parentId,
104
+ branchName: branches.find((b) => b.id === parentId)?.name ?? parentId
105
+ };
106
+ };
107
+ /** Resolve a branch reference (name or `br-…` id) against the fetched listing. */
108
+ const resolveRef = (branches, ref) => {
109
+ const found = looksLikeBranchId(ref) ? branches.find((b) => b.id === ref) : branches.find((b) => b.name === ref);
110
+ if (found) return {
111
+ branchId: found.id,
112
+ branchName: found.name ?? found.id
113
+ };
114
+ if (looksLikeBranchId(ref)) return {
115
+ branchId: ref,
116
+ branchName: ref
117
+ };
118
+ throw new Error(`Branch ${ref} not found.\nAvailable branches: ${branches.map((b) => b.name).join(", ")}`);
119
+ };
120
+ /**
121
+ * The databases to diff: the one passed via `--database` (validated against the
122
+ * branch under review), or every database on that branch when none is given.
123
+ */
124
+ const resolveDatabases = async (props, after) => {
125
+ const databases = (await props.apiClient.listProjectBranchDatabases(props.projectId, after.branchId)).data.databases;
126
+ if (props.database !== void 0) {
127
+ if (!databases.find((d) => d.name === props.database)) throw new Error(`Database "${props.database}" not found on branch ${after.branchName}. Available: ${databases.map((d) => d.name).join(", ")}`);
128
+ return [props.database];
129
+ }
130
+ if (databases.length === 0) throw new Error(`No databases found on branch ${after.branchName} (${after.branchId}).`);
131
+ return databases.map((d) => d.name);
132
+ };
133
+ /**
134
+ * Fetch a branch database's `CREATE …` SQL. A database absent from the branch
135
+ * (404) yields an empty schema, so the diff shows it as fully added/removed
136
+ * rather than failing — the natural outcome when a database exists on only one
137
+ * side of the comparison.
138
+ */
139
+ const fetchSchemaSql = async (props, branchId, database) => {
140
+ try {
141
+ const { data } = await props.apiClient.getProjectBranchSchema({
142
+ projectId: props.projectId,
143
+ branchId,
144
+ db_name: database
145
+ });
146
+ return data.sql ?? "";
147
+ } catch (err) {
148
+ if (isNeonApiError(err) && err.status === 404) {
149
+ log.debug("diff: database %s not found on branch %s; treating schema as empty", database, branchId);
150
+ return "";
151
+ }
152
+ throw err;
153
+ }
154
+ };
155
+ /** Machine-readable output for `--output json|yaml`: one entry per database. */
156
+ const writeStructured = (props, diffs) => {
157
+ const report = diffs.map((diff) => {
158
+ const rendered = renderDatabaseSchemaDiff(diff, { color: false });
159
+ return {
160
+ database: diff.database,
161
+ base_branch: diff.before.branchName,
162
+ base_branch_id: diff.before.branchId,
163
+ compare_branch: diff.after.branchName,
164
+ compare_branch_id: diff.after.branchId,
165
+ has_changes: rendered.hasChanges,
166
+ diff: rendered.text
167
+ };
168
+ });
169
+ writer(props).end(report, { fields: [
170
+ "database",
171
+ "base_branch",
172
+ "compare_branch",
173
+ "has_changes",
174
+ "diff"
175
+ ] });
176
+ };
177
+ //#endregion
178
+ export { handler as a, diff_exports as i, command as n, describe as r, builder as t };
@@ -0,0 +1,197 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
+ import { getCliAgent, isCi } from "../env.js";
3
+ import pkg_default from "../pkg.js";
4
+ import { isNetworkError } from "../errors.js";
5
+ import { resolveOutputWidth, stripAnsi, truncateTo } from "../human_table.js";
6
+ import { writer } from "../writer.js";
7
+ import { single } from "../utils/flags.js";
8
+ import chalk from "chalk";
9
+ //#region src/commands/docs.ts
10
+ var docs_exports = /* @__PURE__ */ __exportAll({
11
+ DEFAULT_SITE_SEARCH_URL: () => DEFAULT_SITE_SEARCH_URL,
12
+ MAX_LIMIT: () => 40,
13
+ MAX_QUERY_LENGTH: () => 500,
14
+ SITE_SEARCH_CATEGORIES: () => SITE_SEARCH_CATEGORIES,
15
+ builder: () => builder,
16
+ command: () => command,
17
+ describe: () => describe,
18
+ formatSearchResults: () => formatSearchResults,
19
+ parseSearchHits: () => parseSearchHits,
20
+ resolveSiteSearchUrl: () => resolveSiteSearchUrl,
21
+ siteSearchHeaders: () => siteSearchHeaders
22
+ });
23
+ const DEFAULT_SITE_SEARCH_URL = "https://br-frosty-cell-a5smzg39-assistant.compute.c-1.us-east-2.aws.neon.tech/site-search";
24
+ const SITE_SEARCH_CATEGORIES = [
25
+ "docs",
26
+ "api",
27
+ "postgresql",
28
+ "guides",
29
+ "faqs",
30
+ "blog",
31
+ "changelog"
32
+ ];
33
+ const MAX_QUERY_LENGTH = 500;
34
+ const MAX_LIMIT = 40;
35
+ const DEFAULT_LIMIT = 10;
36
+ const SEARCH_TIMEOUT_MS = 1e4;
37
+ const command = "docs";
38
+ const describe = "Search neon.com docs, guides, and more";
39
+ const SEARCH_DESCRIBE = "Search neon.com: docs, API reference, PostgreSQL tutorial, guides, FAQs, changelog, and blog";
40
+ const builder = (argv) => argv.usage("$0 docs <sub-command> [options]").command("search <query>", SEARCH_DESCRIBE, (yargs) => yargs.positional("query", {
41
+ describe: "What to search for",
42
+ type: "string"
43
+ }).options({
44
+ category: {
45
+ describe: "Only return pages in these categories (repeatable)",
46
+ type: "string",
47
+ array: true,
48
+ choices: SITE_SEARCH_CATEGORIES
49
+ },
50
+ limit: {
51
+ describe: `Maximum number of results (1-40)`,
52
+ type: "number",
53
+ default: DEFAULT_LIMIT
54
+ },
55
+ url: {
56
+ describe: "Override the site search URL",
57
+ type: "string",
58
+ hidden: true,
59
+ coerce: single("url")
60
+ }
61
+ }).strict().check((args) => {
62
+ const query = typeof args.query === "string" ? args.query.trim() : "";
63
+ if (query === "") throw new Error("<query> needs a value");
64
+ if (query.length > 500) throw new Error(`<query> must be 500 characters or fewer`);
65
+ const limit = args.limit;
66
+ if (!Number.isInteger(limit) || limit < 1 || limit > 40) throw new Error(`--limit must be a whole number from 1 to 40`);
67
+ return true;
68
+ }).example("$0 docs search \"reset a branch\"", SEARCH_DESCRIBE).example("$0 docs search \"create branch\" --category api --category docs", "Search only the API reference and the docs"), (args) => search(args));
69
+ function resolveSiteSearchUrl(opts) {
70
+ const fromFlag = opts.url?.trim();
71
+ if (fromFlag) return fromFlag;
72
+ const fromEnv = opts.envUrl?.trim();
73
+ if (fromEnv) return fromEnv;
74
+ return DEFAULT_SITE_SEARCH_URL;
75
+ }
76
+ const search = async (props) => {
77
+ const query = props.query.trim();
78
+ const hits = await searchSite({
79
+ url: resolveSiteSearchUrl({
80
+ url: props.url,
81
+ envUrl: process.env.NEON_SITE_SEARCH_URL
82
+ }),
83
+ query,
84
+ limit: props.limit,
85
+ categories: props.category ? [...new Set(props.category)] : void 0,
86
+ headers: siteSearchHeaders({
87
+ analytics: props.analytics,
88
+ agent: getCliAgent(process.env),
89
+ version: pkg_default.version
90
+ })
91
+ });
92
+ const emptyMessage = `No results for "${query}".`;
93
+ if (props.output === "json" || props.output === "yaml") {
94
+ writer(props).end(hits, {
95
+ fields: [
96
+ "title",
97
+ "heading",
98
+ "url"
99
+ ],
100
+ emptyMessage
101
+ });
102
+ return;
103
+ }
104
+ const text = formatSearchResults(hits, {
105
+ emptyMessage,
106
+ width: resolveOutputWidth(process.stdout, void 0, {
107
+ stdout: process.stdout,
108
+ envColumns: process.env.COLUMNS
109
+ })
110
+ });
111
+ process.stdout.write(process.env.NO_COLOR || isCi() ? stripAnsi(text) : text);
112
+ };
113
+ function formatSearchResults(hits, opts) {
114
+ if (hits.length === 0) return `\n${opts.emptyMessage}\n`;
115
+ return hits.map((hit) => {
116
+ const section = sectionOf(hit).split(" > ").filter(Boolean);
117
+ const line = [hit.title, ...section].join(" › ");
118
+ const shown = opts.width === void 0 ? line : truncateTo(line, opts.width);
119
+ return `${chalk.bold(shown)}\n ${chalk.cyan(hit.url)}\n`;
120
+ }).join("\n");
121
+ }
122
+ function sectionOf(hit) {
123
+ const parts = hit.heading.split(" > ");
124
+ return (parts[0] === hit.title ? parts.slice(1) : parts).join(" > ");
125
+ }
126
+ function siteSearchHeaders(opts) {
127
+ return {
128
+ "Content-Type": "application/json",
129
+ "User-Agent": `neon/${opts.version}`,
130
+ "x-caller-source": "cli",
131
+ ...opts.agent ? { "x-caller-client": encodeURIComponent(opts.agent) } : {},
132
+ ...opts.analytics ? {} : { "x-caller-analytics": "off" }
133
+ };
134
+ }
135
+ function isTimeout(error) {
136
+ return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
137
+ }
138
+ async function searchSite(opts) {
139
+ const signal = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
140
+ try {
141
+ const response = await fetch(opts.url, {
142
+ method: "POST",
143
+ headers: opts.headers,
144
+ body: JSON.stringify({
145
+ query: opts.query,
146
+ limit: opts.limit,
147
+ ...opts.categories ? { categories: opts.categories } : {}
148
+ }),
149
+ signal
150
+ });
151
+ const raw = await response.text();
152
+ if (!response.ok) throw new Error(searchErrorMessage(raw, response.status));
153
+ return parseSearchHits(raw);
154
+ } catch (error) {
155
+ if (isTimeout(error)) throw new Error("Neon site search did not respond in time.");
156
+ if (isNetworkError(error)) throw new Error("Could not reach Neon site search. Check your internet connection and try again.");
157
+ throw error;
158
+ }
159
+ }
160
+ function parseJson(raw) {
161
+ try {
162
+ return JSON.parse(raw);
163
+ } catch {
164
+ return;
165
+ }
166
+ }
167
+ function searchErrorMessage(raw, status) {
168
+ const body = parseJson(raw);
169
+ if (status < 500 && typeof body === "object" && body !== null && "error" in body && typeof body.error === "string" && body.error.trim() !== "") return body.error;
170
+ return `Neon site search failed (HTTP ${status}).`;
171
+ }
172
+ const UNEXPECTED_RESPONSE = "Neon site search returned an unexpected response.";
173
+ function stringField(fields, key) {
174
+ const field = fields[key];
175
+ if (typeof field !== "string") throw new Error(UNEXPECTED_RESPONSE);
176
+ return field;
177
+ }
178
+ function parseSearchHits(raw) {
179
+ const body = parseJson(raw);
180
+ if (typeof body !== "object" || body === null || !("hits" in body) || !Array.isArray(body.hits)) throw new Error(UNEXPECTED_RESPONSE);
181
+ return body.hits.map((hit) => {
182
+ if (typeof hit !== "object" || hit === null) throw new Error(UNEXPECTED_RESPONSE);
183
+ const fields = Object.fromEntries(Object.entries(hit));
184
+ const breadcrumb = fields.breadcrumb;
185
+ if (!Array.isArray(breadcrumb) || !breadcrumb.every((part) => typeof part === "string")) throw new Error(UNEXPECTED_RESPONSE);
186
+ return {
187
+ title: stringField(fields, "title"),
188
+ url: stringField(fields, "url"),
189
+ category: stringField(fields, "category"),
190
+ breadcrumb,
191
+ heading: stringField(fields, "heading"),
192
+ excerpt: stringField(fields, "excerpt")
193
+ };
194
+ });
195
+ }
196
+ //#endregion
197
+ export { builder as a, docs_exports as c, resolveSiteSearchUrl as d, siteSearchHeaders as f, SITE_SEARCH_CATEGORIES as i, formatSearchResults as l, MAX_LIMIT as n, command as o, MAX_QUERY_LENGTH as r, describe as s, DEFAULT_SITE_SEARCH_URL as t, parseSearchHits as u };
@@ -0,0 +1,284 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
+ import { log } from "../log.js";
3
+ import { ensureGitignored } from "../context.js";
4
+ import { isClaimableEnvTarget } from "../claimable/state.js";
5
+ import { getCliName } from "../utils/cli_name.js";
6
+ import { deprecatedServiceMessage, parseServices, servicesFlagValue, servicesOption } from "../neon_services.js";
7
+ import { mergeEnvFile, readEnvFile, resolveEnvFilePath } from "../env_file.js";
8
+ import { t as NEON_ENV_VAR_KEYS, u as isFunctionBaseUrlKey } from "./env-BpP3Dqpe.js";
9
+ import { ENV_PULL_KEY_HELP, ENV_PULL_SERVICES, envKeysForSelection, envPullFlagValue, ownedEnvServiceKeys, parseEnvPullKeys } from "../env_services.js";
10
+ import { fillSingleProject, resolveBranchRef } from "../utils/enrichers.js";
11
+ import { warnAiGateway } from "../utils/ai_gateway_notice.js";
12
+ import { i as dropClaimableUnsupported, o as resolveNeonEnvVars } from "./env-BNm69Qh8.js";
13
+ import { formatPulledEnv, pulledBranch } from "../commands/env_output.js";
14
+ import { existsSync } from "node:fs";
15
+ import chalk from "chalk";
16
+ //#region src/commands/env.ts
17
+ var env_exports = /* @__PURE__ */ __exportAll({
18
+ ENV_PULL_SKIPPED_HINT: () => ENV_PULL_SKIPPED_HINT,
19
+ autoPullEnvAfterPin: () => autoPullEnvAfterPin,
20
+ builder: () => builder,
21
+ command: () => "env",
22
+ describe: () => describe,
23
+ handler: () => handler,
24
+ pull: () => pull
25
+ });
26
+ const command = "env";
27
+ const describe = "Manage a branch's Neon env variables locally";
28
+ /**
29
+ * Shown (to stderr) when `link` / `checkout` skip the bundled env pull because the user passed
30
+ * `--no-env-pull`. Names the two ways to get the branch's vars without an on-disk file written
31
+ * eagerly: an explicit `neonctl env pull`, or runtime injection via `neon-env run`.
32
+ */
33
+ const ENV_PULL_SKIPPED_HINT = `Skipped env pull (--no-env-pull). Run \`${getCliName()} env pull\` to write this branch’s env vars (DATABASE_URL, …) into a local .env, or inject them at runtime with \`neon-env run -- <your dev command>\`.`;
34
+ const builder = (argv) => argv.usage("$0 env <sub-command> [options]").options({
35
+ "project-id": {
36
+ describe: "Project ID",
37
+ type: "string"
38
+ },
39
+ branch: {
40
+ describe: "Branch ID or name",
41
+ type: "string"
42
+ }
43
+ }).middleware(fillSingleProject).command("pull", "Write the branch's Neon env variables to a local .env file", (yargs) => yargs.usage("$0 env pull [options]").options({
44
+ file: {
45
+ describe: "Target .env file to write, relative to cwd. Defaults to an existing .env, otherwise .env.local, in the project directory (next to .neon, or cwd without one). Only Neon variables are updated; other lines are preserved.",
46
+ type: "string"
47
+ },
48
+ service: servicesOption({
49
+ key: "service",
50
+ allowed: ENV_PULL_SERVICES,
51
+ describe: "Pull only these services' variables",
52
+ also: "Overrides neon.ts, and prunes only within the services you name. Combines with --env as a union."
53
+ }),
54
+ env: {
55
+ alias: "e",
56
+ describe: `Pull only these individual variables: ${ENV_PULL_KEY_HELP}. Repeat the flag or comma-separate. Overrides neon.ts. Combines with --service as a union; it never narrows a service bundle.`,
57
+ type: "array",
58
+ string: true
59
+ },
60
+ config: {
61
+ describe: "Path to a neon.ts policy (defaults to the neon.ts next to .neon, or in cwd without one)",
62
+ type: "string"
63
+ }
64
+ }).epilogue([
65
+ "",
66
+ "What gets pulled, in precedence order:",
67
+ " 1. --service / --env, when given — their union, ignoring neon.ts.",
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).",
71
+ " 3. Otherwise everything the branch has, plus the AI Gateway —",
72
+ " which pulls the default AI Gateway credential.",
73
+ "",
74
+ "On an unclaimed Claimable Neon project, neon.ts is still the source",
75
+ "of truth when it only declares Postgres, Auth, and the Data API.",
76
+ "A neon.ts that declares Realtime, AI Gateway, Functions, or Object Storage",
77
+ "fails: those cannot be used until the project is claimed. Without",
78
+ "a neon.ts, a bare pull writes provisioned Postgres, Auth, and Data",
79
+ "API. Naming unsupported services with --service / --env warns",
80
+ "and writes nothing for them.",
81
+ "",
82
+ "The pull bundled into link / checkout / config apply follows 2 and 3",
83
+ "without the AI Gateway, so it never writes a gateway token you did",
84
+ "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) => {
86
+ const rawServices = servicesFlagValue(args.service);
87
+ const rawEnvKeys = envPullFlagValue(args.env);
88
+ const services = rawServices ? parseServices(rawServices, {
89
+ allowed: ENV_PULL_SERVICES,
90
+ flag: "--service",
91
+ onDeprecated: (used, canonical) => log.warning(deprecatedServiceMessage(used, canonical))
92
+ }) : void 0;
93
+ const envKeys = rawEnvKeys ? parseEnvPullKeys(rawEnvKeys, "--env") : void 0;
94
+ await pull({
95
+ ...args,
96
+ ...services ? { services } : {},
97
+ ...envKeys ? { envKeys } : {}
98
+ }, {
99
+ announce: true,
100
+ implyAiGateway: rawServices === void 0 && rawEnvKeys === void 0
101
+ });
102
+ });
103
+ const handler = (args) => args;
104
+ /** Every OS-level env var name `@neon/env` can emit, used only for reporting. */
105
+ const NEON_VAR_NAMES = Object.values(NEON_ENV_VAR_KEYS).flatMap((group) => Object.values(group));
106
+ /**
107
+ * The Neon env vars `env pull` *owns*, so it removes any that the branch no longer has when
108
+ * it reconciles the local `.env` (see {@link pull}). Scoped to the unambiguously Neon-named
109
+ * vars — the `NEON_*` aliases plus `DATABASE_URL[_UNPOOLED]` — so switching a working
110
+ * directory to a project/branch without Auth / the Data API / Realtime drops the now-stale
111
+ * `NEON_AUTH_*` / `NEON_DATA_API_*` / `NEON_REALTIME_*` lines instead of leaving credentials for features that
112
+ * aren't enabled.
113
+ *
114
+ * Deliberately **excludes** the storage vars Neon projects onto third-party SDK names
115
+ * (`AWS_*`): those collide with credentials a user may set by hand, so `env pull` only ever
116
+ * writes them, never prunes them. The AI Gateway is emitted solely under its Neon-branded
117
+ * vars (`NEON_AI_GATEWAY_*`), which are owned and pruned.
118
+ */
119
+ const NEON_OWNED_ENV_KEYS = [
120
+ ...Object.values(NEON_ENV_VAR_KEYS.postgres),
121
+ ...Object.values(NEON_ENV_VAR_KEYS.auth),
122
+ ...Object.values(NEON_ENV_VAR_KEYS.dataApi),
123
+ ...Object.values(NEON_ENV_VAR_KEYS.realtime),
124
+ ...Object.values(NEON_ENV_VAR_KEYS.aiGateway)
125
+ ];
126
+ const pull = async (props, opts = {}) => {
127
+ const cwd = props.cwd ?? process.cwd();
128
+ const claimable = isClaimableEnvTarget({
129
+ apiHost: props.apiHost,
130
+ contextFile: props.contextFile,
131
+ configDir: props.configDir ?? ""
132
+ });
133
+ const dropped = claimable && (props.services !== void 0 || props.envKeys !== void 0) ? dropClaimableUnsupported(props.services ?? [], props.envKeys ?? []) : null;
134
+ const selectionServices = dropped ? dropped.services : props.services ?? [];
135
+ const selectionEnvKeys = dropped ? dropped.envKeys : props.envKeys ?? [];
136
+ const selectedKeys = props.services !== void 0 || props.envKeys !== void 0 ? envKeysForSelection(selectionServices, selectionEnvKeys) : void 0;
137
+ const branch = opts.branch ?? await resolveBranchRef(props);
138
+ const namedBranch = opts.announce ? branch : void 0;
139
+ const branchId = branch.branchId;
140
+ const location = {
141
+ cwd,
142
+ contextFile: props.contextFile
143
+ };
144
+ const targetPath = resolveEnvFilePath(location, props.file);
145
+ const fileExisted = existsSync(targetPath);
146
+ const existingEnv = fileExisted ? readEnvFile(targetPath) : {};
147
+ const { vars, credential, skipped } = await resolveNeonEnvVars({
148
+ ...location,
149
+ projectId: props.projectId,
150
+ branchId,
151
+ env: {
152
+ ...process.env,
153
+ ...existingEnv
154
+ },
155
+ ...props.services !== void 0 ? { services: props.services } : {},
156
+ ...props.envKeys !== void 0 ? { envKeys: props.envKeys } : {},
157
+ ...opts.implyAiGateway ? { implyAiGateway: true } : {},
158
+ omitUnsetFunctionEnv: true,
159
+ ...claimable ? { claimable: true } : {},
160
+ ...props.config ? { config: props.config } : {},
161
+ ...props.apiKey ? { apiKey: props.apiKey } : {},
162
+ ...props.apiHost ? { apiHost: props.apiHost } : {},
163
+ ...props.runtimeApi ? { api: props.runtimeApi } : {}
164
+ });
165
+ const neonVars = pickSelectedVars(pickNeonVars(vars), selectedKeys, props.services !== void 0 ? selectionServices : void 0);
166
+ if (Object.keys(neonVars).length === 0) {
167
+ 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
+ return { status: "empty" };
169
+ }
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
+ process.stderr.write(formatPulledEnv({
172
+ status: "written",
173
+ written,
174
+ removed,
175
+ file: targetPath,
176
+ ...credential && credential.keys.length > 0 ? { credential } : {}
177
+ }, cwd, namedBranch));
178
+ if (!fileExisted) ensureGitignored(targetPath);
179
+ const gatewayBaseUrl = neonVars.NEON_AI_GATEWAY_BASE_URL;
180
+ const gatewayToken = neonVars.NEON_AI_GATEWAY_TOKEN;
181
+ if (gatewayBaseUrl && gatewayToken) await warnAiGateway({
182
+ apiClient: props.apiClient,
183
+ projectId: props.projectId,
184
+ branchId,
185
+ gateway: {
186
+ baseUrl: gatewayBaseUrl,
187
+ token: gatewayToken
188
+ }
189
+ });
190
+ return {
191
+ status: "written",
192
+ written,
193
+ removed,
194
+ file: targetPath,
195
+ ...credential && credential.keys.length > 0 ? { credential } : {},
196
+ ...skipped && skipped.length > 0 ? { skipped } : {}
197
+ };
198
+ };
199
+ /** Prevents scoped or unavailable services from pruning values they did not resolve. */
200
+ const managedKeysFor = (selectedKeys, unreached, existingEnv, services, envKeys) => {
201
+ const existingFunctionKeys = Object.keys(existingEnv).filter(isFunctionBaseUrlKey);
202
+ const namedFunctionKeys = (envKeys ?? []).filter(isFunctionBaseUrlKey);
203
+ const ownedFunctionKeys = selectedKeys === void 0 || (services?.includes("functions") ?? false) ? existingFunctionKeys : namedFunctionKeys;
204
+ const owned = selectedKeys ? [...NEON_OWNED_ENV_KEYS.filter((key) => selectedKeys.includes(key)), ...ownedFunctionKeys] : [...NEON_OWNED_ENV_KEYS, ...ownedFunctionKeys];
205
+ if (unreached.length === 0) return owned;
206
+ const keep = new Set(ownedEnvServiceKeys(unreached));
207
+ return owned.filter((key) => {
208
+ if (unreached.includes("functions") && isFunctionBaseUrlKey(key)) return false;
209
+ return !keep.has(key);
210
+ });
211
+ };
212
+ /**
213
+ * Endpoint failure is not evidence that existing values are stale; the gateway host check
214
+ * avoids preserving credentials for a different branch.
215
+ */
216
+ const unreachedButCurrent = (skipped, existingEnv, branchId) => {
217
+ if (!skipped) return [];
218
+ const keep = [];
219
+ if (skipped.includes("ai-gateway")) {
220
+ const baseUrl = existingEnv[NEON_ENV_VAR_KEYS.aiGateway.baseUrl];
221
+ if (baseUrl !== void 0 && isBranchGatewayUrl(baseUrl, branchId)) keep.push("ai-gateway");
222
+ }
223
+ if (skipped.includes("functions")) keep.push("functions");
224
+ return keep;
225
+ };
226
+ /**
227
+ * Whether a persisted `NEON_AI_GATEWAY_BASE_URL` addresses `branchId`'s gateway.
228
+ *
229
+ * Checks the parsed **hostname** against the shape `@neon/env` builds
230
+ * (`<branchId>-api.ai.<host suffix>`), not the raw string: a prefix comparison is satisfied
231
+ * by a URL whose userinfo carries the branch id (`https://<branchId>-api.ai.@other-host/`)
232
+ * while the request actually goes elsewhere. An unparseable value is not this branch's
233
+ * gateway either, which is an answer rather than a swallowed failure.
234
+ */
235
+ const isBranchGatewayUrl = (baseUrl, branchId) => URL.canParse(baseUrl) && new URL(baseUrl).hostname.startsWith(`${branchId}-api.ai.`);
236
+ /**
237
+ * Narrow the resolved vars to the explicit service/key union. `fetchEnv` may resolve
238
+ * supporting values that were not selected (the direct connection URI derives the AI Gateway
239
+ * host, for example); those must not land in the target file.
240
+ */
241
+ const pickSelectedVars = (vars, selectedKeys, services) => {
242
+ if (!selectedKeys) return vars;
243
+ const wanted = new Set(selectedKeys);
244
+ const keepFunctionUrls = services?.includes("functions") ?? false;
245
+ return Object.fromEntries(Object.entries(vars).filter(([key]) => wanted.has(key) || keepFunctionUrls && isFunctionBaseUrlKey(key)));
246
+ };
247
+ /**
248
+ * Pull a freshly-pinned branch's Neon env vars into a local `.env`, bundled into `link` and
249
+ * `checkout` so the branch-first loop is just *link + checkout* — `env pull` runs for you.
250
+ *
251
+ * On by default; `--no-env-pull` opts out (e.g. when env is injected at runtime via
252
+ * `neon-env run` / `neon dev`, or to keep secrets out of the working tree). The pin is the
253
+ * command's primary effect and has already succeeded by the time this runs, so a pull failure
254
+ * degrades to a warning rather than failing the command.
255
+ */
256
+ const autoPullEnvAfterPin = async (props, branch) => {
257
+ if (!props.envPull) {
258
+ log.info(chalk.dim(ENV_PULL_SKIPPED_HINT));
259
+ return { status: "skipped" };
260
+ }
261
+ try {
262
+ return await pull(props, branch ? { branch } : {});
263
+ } catch (err) {
264
+ const message = err instanceof Error ? err.message : String(err);
265
+ log.warning(`Branch pinned, but pulling its Neon env vars failed: %s
266
+ Run \`${getCliName()} env pull\` once resolved (e.g. \`${getCliName()} deploy\` if a declared service is missing), or inject them at runtime with \`neon-env run -- <your dev command>\`.`, message);
267
+ return {
268
+ status: "failed",
269
+ message
270
+ };
271
+ }
272
+ };
273
+ /**
274
+ * Keep only the recognized Neon variables from the resolved set, so a stray inherited
275
+ * value never lands in the user's `.env` file. (Today `resolveNeonEnvVars` only emits Neon
276
+ * vars, but filtering keeps the contract explicit and future-proof.)
277
+ */
278
+ const pickNeonVars = (vars) => {
279
+ const out = {};
280
+ for (const [name, value] of Object.entries(vars)) if (NEON_VAR_NAMES.some((key) => key === name) || isFunctionBaseUrlKey(name)) out[name] = value;
281
+ return out;
282
+ };
283
+ //#endregion
284
+ 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 };