@neondatabase/env 0.3.2 → 0.5.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.
- package/dist/cli.js.map +1 -1
- package/dist/config/dist/lib/neon-api.d.ts +101 -19
- package/dist/config/dist/lib/neon-api.d.ts.map +1 -1
- package/dist/config/dist/lib/types.d.ts +22 -16
- package/dist/config/dist/lib/types.d.ts.map +1 -1
- package/dist/config/dist/v1.d.ts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/lib/cli/commands.js.map +1 -1
- package/dist/lib/cli/resolve-context.js.map +1 -1
- package/dist/lib/env.d.ts +92 -1
- package/dist/lib/env.d.ts.map +1 -1
- package/dist/lib/env.js +203 -2
- package/dist/lib/env.js.map +1 -1
- package/dist/v1.d.ts +2 -2
- package/package.json +2 -2
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport {\n\ttype CommandResult,\n\trunEnvExport,\n\trunEnvRun,\n} from \"./lib/cli/commands.js\";\n\nconst pkgVersion = readPackageVersion();\n\nconst argv = yargs(hideBin(process.argv))\n\t.scriptName(\"neon-env\")\n\t.usage(\"$0 <command> [options]\")\n\t.parserConfiguration({ \"populate--\": true })\n\t.option(\"debug\", {\n\t\ttype: \"boolean\",\n\t\tdefault: false,\n\t\tdescribe:\n\t\t\t\"Print stack traces and structured error details when something fails\",\n\t})\n\t.command(\n\t\t\"run\",\n\t\t\"Run a command with Neon env vars (from your neon.ts policy) injected into its environment. Use `--` to separate the command: `neon-env run -- npm run dev`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Override the .neon/project.json branchId / NEON_BRANCH_ID\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t}),\n\t)\n\t.command(\n\t\t\"export\",\n\t\t\"Print the branch's Neon env vars (from your neon.ts policy) to stdout, as dotenv lines or JSON. Useful for piping into other env tools, e.g. `neon-env export --format json`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"format\", {\n\t\t\t\t\tchoices: [\"dotenv\", \"json\"] as const,\n\t\t\t\t\tdefault: \"dotenv\",\n\t\t\t\t\tdescribe: \"Output format: dotenv (KEY=value lines) or json\",\n\t\t\t\t})\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Override the .neon/project.json branchId / NEON_BRANCH_ID\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t}),\n\t)\n\t.demandCommand(1, \"Run `neon-env --help` to see the available commands.\")\n\t.strict()\n\t.help()\n\t.version(pkgVersion)\n\t.parseSync();\n\nconst command = String(argv._[0]);\nconst cwd = process.cwd();\n\nlet result: CommandResult;\nswitch (command) {\n\tcase \"run\": {\n\t\tconst passthrough = Array.isArray(argv[\"--\"])\n\t\t\t? argv[\"--\"].map(String)\n\t\t\t: [];\n\t\tresult = await runEnvRun(\n\t\t\t{\n\t\t\t\tcommand: passthrough,\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tcase \"export\": {\n\t\tresult = await runEnvExport(\n\t\t\t{\n\t\t\t\tformat: argv.format === \"json\" ? \"json\" : \"dotenv\",\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tresult = {\n\t\t\texitCode: 1,\n\t\t\tstdout: \"\",\n\t\t\tstderr: `Unknown command: ${command}\\n`,\n\t\t};\n}\n\nif (result.stdout) process.stdout.write(result.stdout);\nif (result.stderr) process.stderr.write(result.stderr);\nif (argv.debug && result.exitCode !== 0 && result.debugInfo) {\n\tprocess.stderr.write(`\\n--- debug ---\\n${result.debugInfo}\\n`);\n}\nprocess.exit(result.exitCode);\n\nfunction readPackageVersion(): string {\n\t// The built CLI lives at `dist/cli.js`, so `package.json` is one directory up. When\n\t// running from source (tsx, vitest), the file lives at `src/cli.ts` and `package.json`\n\t// is again one directory up. Single resolution covers both layouts.\n\ttry {\n\t\tconst pkgUrl = new URL(\"../package.json\", import.meta.url);\n\t\tconst raw = readFileSync(fileURLToPath(pkgUrl), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as { version?: unknown };\n\t\treturn typeof parsed.version === \"string\" ? parsed.version : \"0.0.0\";\n\t} catch {\n\t\treturn \"0.0.0\";\n\t}\n}\n"],"mappings":";;;;;;;AAYA,MAAM,aAAa,mBAAmB;AAEtC,MAAM,OAAO,MAAM,QAAQ,QAAQ,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport {\n\ttype CommandResult,\n\trunEnvExport,\n\trunEnvRun,\n} from \"./lib/cli/commands.js\";\n\nconst pkgVersion = readPackageVersion();\n\nconst argv = yargs(hideBin(process.argv))\n\t.scriptName(\"neon-env\")\n\t.usage(\"$0 <command> [options]\")\n\t.parserConfiguration({ \"populate--\": true })\n\t.option(\"debug\", {\n\t\ttype: \"boolean\",\n\t\tdefault: false,\n\t\tdescribe:\n\t\t\t\"Print stack traces and structured error details when something fails\",\n\t})\n\t.command(\n\t\t\"run\",\n\t\t\"Run a command with Neon env vars (from your neon.ts policy) injected into its environment. Use `--` to separate the command: `neon-env run -- npm run dev`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Override the .neon/project.json branchId / NEON_BRANCH_ID\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t}),\n\t)\n\t.command(\n\t\t\"export\",\n\t\t\"Print the branch's Neon env vars (from your neon.ts policy) to stdout, as dotenv lines or JSON. Useful for piping into other env tools, e.g. `neon-env export --format json`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"format\", {\n\t\t\t\t\tchoices: [\"dotenv\", \"json\"] as const,\n\t\t\t\t\tdefault: \"dotenv\",\n\t\t\t\t\tdescribe: \"Output format: dotenv (KEY=value lines) or json\",\n\t\t\t\t})\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Override the .neon/project.json branchId / NEON_BRANCH_ID\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t}),\n\t)\n\t.demandCommand(1, \"Run `neon-env --help` to see the available commands.\")\n\t.strict()\n\t.help()\n\t.version(pkgVersion)\n\t.parseSync();\n\nconst command = String(argv._[0]);\nconst cwd = process.cwd();\n\nlet result: CommandResult;\nswitch (command) {\n\tcase \"run\": {\n\t\tconst passthrough = Array.isArray(argv[\"--\"])\n\t\t\t? argv[\"--\"].map(String)\n\t\t\t: [];\n\t\tresult = await runEnvRun(\n\t\t\t{\n\t\t\t\tcommand: passthrough,\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tcase \"export\": {\n\t\tresult = await runEnvExport(\n\t\t\t{\n\t\t\t\tformat: argv.format === \"json\" ? \"json\" : \"dotenv\",\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tresult = {\n\t\t\texitCode: 1,\n\t\t\tstdout: \"\",\n\t\t\tstderr: `Unknown command: ${command}\\n`,\n\t\t};\n}\n\nif (result.stdout) process.stdout.write(result.stdout);\nif (result.stderr) process.stderr.write(result.stderr);\nif (argv.debug && result.exitCode !== 0 && result.debugInfo) {\n\tprocess.stderr.write(`\\n--- debug ---\\n${result.debugInfo}\\n`);\n}\nprocess.exit(result.exitCode);\n\nfunction readPackageVersion(): string {\n\t// The built CLI lives at `dist/cli.js`, so `package.json` is one directory up. When\n\t// running from source (tsx, vitest), the file lives at `src/cli.ts` and `package.json`\n\t// is again one directory up. Single resolution covers both layouts.\n\ttry {\n\t\tconst pkgUrl = new URL(\"../package.json\", import.meta.url);\n\t\tconst raw = readFileSync(fileURLToPath(pkgUrl), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as { version?: unknown };\n\t\treturn typeof parsed.version === \"string\" ? parsed.version : \"0.0.0\";\n\t} catch {\n\t\treturn \"0.0.0\";\n\t}\n}\n"],"mappings":";;;;;;;AAYA,MAAM,aAAa,mBAAmB;AAEtC,MAAM,OAAO,MAAM,QAAQ,QAAQ,IAAI,CAAC,CAAC,CACvC,WAAW,UAAU,CAAC,CACtB,MAAM,wBAAwB,CAAC,CAC/B,oBAAoB,EAAE,cAAc,KAAK,CAAC,CAAC,CAC3C,OAAO,SAAS;CAChB,MAAM;CACN,SAAS;CACT,UACC;AACF,CAAC,CAAC,CACD,QACA,OACA,gKACC,MACA,EACE,OAAO,UAAU;CACjB,MAAM;CACN,UACC;AACF,CAAC,CAAC,CACD,OAAO,cAAc;CACrB,MAAM;CACN,UAAU;AACX,CAAC,CAAC,CACD,OAAO,UAAU;CACjB,MAAM;CACN,UACC;AACF,CAAC,CAAC,CACD,OAAO,WAAW;CAClB,MAAM;CACN,UAAU;AACX,CAAC,CACJ,CAAC,CACA,QACA,UACA,kLACC,MACA,EACE,OAAO,UAAU;CACjB,SAAS,CAAC,UAAU,MAAM;CAC1B,SAAS;CAC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Ae,WAC5B,EAAE,QAAQ,KAAK,WAAW,IAC1B,CAAC;EACL,GACA,EAAE,IAAI,CACP;EACA;CAED,SACC,SAAS;EACR,UAAU;EACV,QAAQ;EACR,QAAQ,oBAAoB,QAAQ;CACrC;AACF;AAEA,IAAI,OAAO,QAAQ,QAAQ,OAAO,MAAM,OAAO,MAAM;AACrD,IAAI,OAAO,QAAQ,QAAQ,OAAO,MAAM,OAAO,MAAM;AACrD,IAAI,KAAK,SAAS,OAAO,aAAa,KAAK,OAAO,WACjD,QAAQ,OAAO,MAAM,oBAAoB,OAAO,UAAU,GAAG;AAE9D,QAAQ,KAAK,OAAO,QAAQ;AAE5B,SAAS,qBAA6B;CAIrC,IAAI;EAEH,MAAM,MAAM,aAAa,cAAc,IADpB,IAAI,mBAAmB,OAAO,KAAK,GACV,CAAC,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,OAAO,OAAO,OAAO,YAAY,WAAW,OAAO,UAAU;CAC9D,QAAQ;EACP,OAAO;CACR;AACD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BucketAccessLevel, ComputeSettings, FunctionRuntime } from "./types.js";
|
|
1
|
+
import { BucketAccessLevel, ComputeSettings, CredentialPrincipalType, CredentialScope, FunctionRuntime } from "./types.js";
|
|
2
2
|
|
|
3
3
|
//#region ../config/dist/lib/neon-api.d.ts
|
|
4
4
|
|
|
@@ -110,6 +110,22 @@ interface NeonBucketSnapshot {
|
|
|
110
110
|
name: string;
|
|
111
111
|
accessLevel: BucketAccessLevel;
|
|
112
112
|
}
|
|
113
|
+
/**
|
|
114
|
+
* S3-compatible connection details for a branch's object storage (Preview) — the
|
|
115
|
+
* `BranchStorage` shape from `GET /projects/{id}/branches/{id}/storage`. Non-secret: it
|
|
116
|
+
* carries the endpoint/region/addressing the S3 SDK needs, while the access keys come from
|
|
117
|
+
* a minted {@link NeonCredentialSecret}. `forcePathStyle` is always `true` today (Neon's
|
|
118
|
+
* wildcard TLS cert puts the branch id in the subdomain, so the bucket must travel in the
|
|
119
|
+
* path).
|
|
120
|
+
*/
|
|
121
|
+
interface NeonBranchStorageSnapshot {
|
|
122
|
+
/** S3-compatible endpoint URL, e.g. `https://br-….storage.<suffix>`. */
|
|
123
|
+
s3Endpoint: string;
|
|
124
|
+
/** AWS region string, normalized server-side (e.g. `us-east-2`, `us-east-1`). */
|
|
125
|
+
region: string;
|
|
126
|
+
/** Whether the S3 client must use path-style addressing (always `true` today). */
|
|
127
|
+
forcePathStyle: boolean;
|
|
128
|
+
}
|
|
113
129
|
/**
|
|
114
130
|
* Input for creating a bucket on a branch.
|
|
115
131
|
*/
|
|
@@ -151,6 +167,61 @@ interface NeonFunctionDeploymentSnapshot {
|
|
|
151
167
|
id: number;
|
|
152
168
|
status: "pending" | "building" | "completed" | "failed";
|
|
153
169
|
}
|
|
170
|
+
/**
|
|
171
|
+
* Input for {@link NeonApi.createCredential}. Mirrors the Neon API `CreateCredentialRequest`
|
|
172
|
+
* (`POST .../credentials`, `x-stability-level: beta`):
|
|
173
|
+
*
|
|
174
|
+
* - `scopes` — 1–16 capabilities the credential may exercise (derived from the policy's
|
|
175
|
+
* enabled Preview features, never hand-authored).
|
|
176
|
+
* - `principalType` — `user` (developer/app) or `function` (a deployed function).
|
|
177
|
+
* - `functionId` — required when `principalType === "function"`.
|
|
178
|
+
* - `name` — optional free-form label echoed back on the response.
|
|
179
|
+
*/
|
|
180
|
+
interface CreateCredentialInput {
|
|
181
|
+
scopes: CredentialScope[];
|
|
182
|
+
principalType: CredentialPrincipalType;
|
|
183
|
+
functionId?: string;
|
|
184
|
+
name?: string;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* The secret-bearing result of {@link NeonApi.createCredential} — the Neon API
|
|
188
|
+
* `CreateCredentialResponse`. `apiToken` and `s3SecretAccessKey` are returned **exactly
|
|
189
|
+
* once** (they are not stored server-side), so the caller must persist them immediately;
|
|
190
|
+
* they can never be re-fetched (the list endpoint returns metadata only). `tokenIdShort`
|
|
191
|
+
* is the public identifier embedded in `apiToken` (`nt_live_<tokenIdShort>_…`) and doubles
|
|
192
|
+
* as the S3 access-key id.
|
|
193
|
+
*/
|
|
194
|
+
interface NeonCredentialSecret {
|
|
195
|
+
tokenId: string;
|
|
196
|
+
tokenIdShort: string;
|
|
197
|
+
name?: string;
|
|
198
|
+
/** Bearer token (`nt_live_…`); returned once. Used for AI Gateway / Functions invoke. */
|
|
199
|
+
apiToken: string;
|
|
200
|
+
/** 64-char hex S3 secret access key; returned once. Paired with `tokenIdShort` as the access-key id. */
|
|
201
|
+
s3SecretAccessKey: string;
|
|
202
|
+
scopes: CredentialScope[];
|
|
203
|
+
branchId: string;
|
|
204
|
+
createdAt: string;
|
|
205
|
+
/** When the credential expires; absent means it never expires. */
|
|
206
|
+
expiresAt?: string;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Secret-free metadata for an issued credential — the Neon API `CredentialMeta` returned by
|
|
210
|
+
* {@link NeonApi.listCredentials}. Never includes `apiToken` / `s3SecretAccessKey`.
|
|
211
|
+
*/
|
|
212
|
+
interface NeonCredentialMeta {
|
|
213
|
+
tokenId: string;
|
|
214
|
+
tokenIdShort: string;
|
|
215
|
+
name?: string;
|
|
216
|
+
scopes: CredentialScope[];
|
|
217
|
+
principalType: CredentialPrincipalType;
|
|
218
|
+
functionId?: string;
|
|
219
|
+
branchId?: string;
|
|
220
|
+
createdAt: string;
|
|
221
|
+
lastUsedAt?: string;
|
|
222
|
+
revokedAt?: string;
|
|
223
|
+
expiresAt?: string;
|
|
224
|
+
}
|
|
154
225
|
/**
|
|
155
226
|
* Parameters accepted by {@link NeonApi.getConnectionUri}. `branchId` and `endpointId`
|
|
156
227
|
* are optional — when omitted, the API uses the project's default branch and that
|
|
@@ -230,34 +301,45 @@ interface NeonApi {
|
|
|
230
301
|
createBranchBucket(projectId: string, branchId: string, input: CreateBucketInput): Promise<NeonBucketSnapshot>;
|
|
231
302
|
/** Delete a bucket from a branch. */
|
|
232
303
|
deleteBranchBucket(projectId: string, branchId: string, bucketName: string): Promise<void>;
|
|
233
|
-
/** List functions on a branch. */
|
|
234
|
-
listBranchFunctions(projectId: string, branchId: string): Promise<NeonFunctionSnapshot[]>;
|
|
235
304
|
/**
|
|
236
|
-
*
|
|
237
|
-
*
|
|
305
|
+
* Fetch the branch's S3-compatible object-storage connection details (endpoint, region,
|
|
306
|
+
* path-style). Returns `null` when storage is not enabled for the branch (the API's 404
|
|
307
|
+
* `BranchStorageNotEnabled`). Used by `fetchEnv` to populate the `AWS_*` storage env
|
|
308
|
+
* alongside the minted credential's access keys.
|
|
238
309
|
*/
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
}): Promise<NeonFunctionSnapshot>;
|
|
310
|
+
getProjectBranchStorage(projectId: string, branchId: string): Promise<NeonBranchStorageSnapshot | null>;
|
|
311
|
+
/** List functions on a branch. */
|
|
312
|
+
listBranchFunctions(projectId: string, branchId: string): Promise<NeonFunctionSnapshot[]>;
|
|
243
313
|
/** Delete a function (by slug) from a branch. */
|
|
244
314
|
deleteBranchFunction(projectId: string, branchId: string, slug: string): Promise<void>;
|
|
245
315
|
/**
|
|
246
|
-
* Deploy a built bundle to a function
|
|
247
|
-
*
|
|
316
|
+
* Deploy a built bundle to a function, creating the function if it does not yet exist —
|
|
317
|
+
* Neon has no separate create endpoint, so the first deployment to a slug creates the
|
|
318
|
+
* function. The newest deployment becomes active. The `bundle` is built (esbuild + zip)
|
|
319
|
+
* by the caller and passed in as bytes.
|
|
248
320
|
*/
|
|
249
321
|
deployBranchFunction(projectId: string, branchId: string, slug: string, input: DeployFunctionInput): Promise<NeonFunctionDeploymentSnapshot>;
|
|
250
322
|
/**
|
|
251
|
-
*
|
|
252
|
-
*
|
|
323
|
+
* Mint a new scoped service credential on a branch (`POST .../credentials`). The
|
|
324
|
+
* returned {@link NeonCredentialSecret} carries `apiToken` + `s3SecretAccessKey`
|
|
325
|
+
* **once** — persist them immediately. Used by `fetchEnv` / `env pull` to issue the
|
|
326
|
+
* unified credential for the branch's enabled Preview features (object storage, AI
|
|
327
|
+
* Gateway, Functions).
|
|
328
|
+
*/
|
|
329
|
+
createCredential(projectId: string, branchId: string, input: CreateCredentialInput): Promise<NeonCredentialSecret>;
|
|
330
|
+
/**
|
|
331
|
+
* List the secret-free metadata for credentials issued on a branch
|
|
332
|
+
* (`GET .../credentials`). Used to report issued credentials (e.g. `config status`)
|
|
333
|
+
* and to verify a persisted credential still exists / isn't revoked.
|
|
334
|
+
*/
|
|
335
|
+
listCredentials(projectId: string, branchId: string): Promise<NeonCredentialMeta[]>;
|
|
336
|
+
/**
|
|
337
|
+
* Revoke (soft-delete) a credential by its `tokenId` (`DELETE .../credentials/{id}`).
|
|
338
|
+
* Idempotent.
|
|
253
339
|
*/
|
|
254
|
-
|
|
255
|
-
/** Enable the AI Gateway on a branch. Idempotent. */
|
|
256
|
-
enableAiGateway(projectId: string, branchId: string): Promise<void>;
|
|
257
|
-
/** Disable the AI Gateway on a branch. Idempotent. */
|
|
258
|
-
disableAiGateway(projectId: string, branchId: string): Promise<void>;
|
|
340
|
+
revokeCredential(projectId: string, branchId: string, tokenId: string): Promise<void>;
|
|
259
341
|
}
|
|
260
342
|
//#endregion
|
|
261
343
|
//#endregion
|
|
262
|
-
export { CreateBranchInput, CreateBucketInput, CreateProjectInput, DeployFunctionInput, GetConnectionUriInput, NeonApi, NeonAuthSnapshot, NeonBranchSnapshot, NeonBucketSnapshot, NeonDataApiSnapshot, NeonDatabaseSnapshot, NeonEndpointSnapshot, NeonFunctionDeploymentSnapshot, NeonFunctionSnapshot, NeonProjectSnapshot, NeonRoleSnapshot, UpdateBranchInput };
|
|
344
|
+
export { CreateBranchInput, CreateBucketInput, CreateCredentialInput, CreateProjectInput, DeployFunctionInput, GetConnectionUriInput, NeonApi, NeonAuthSnapshot, NeonBranchSnapshot, NeonBranchStorageSnapshot, NeonBucketSnapshot, NeonCredentialMeta, NeonCredentialSecret, NeonDataApiSnapshot, NeonDatabaseSnapshot, NeonEndpointSnapshot, NeonFunctionDeploymentSnapshot, NeonFunctionSnapshot, NeonProjectSnapshot, NeonRoleSnapshot, UpdateBranchInput };
|
|
263
345
|
//# sourceMappingURL=neon-api.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"neon-api.d.ts","names":["BucketAccessLevel","ComputeSettings","FunctionRuntime","NeonProjectSnapshot","NeonBranchSnapshot","NeonEndpointSnapshot","CreateProjectInput","CreateBranchInput","UpdateBranchInput","NeonRoleSnapshot","NeonDatabaseSnapshot","NeonAuthSnapshot","NeonDataApiSnapshot","NeonBucketSnapshot","CreateBucketInput","NeonFunctionSnapshot","DeployFunctionInput","Uint8Array","Record","NeonFunctionDeploymentSnapshot","GetConnectionUriInput","NeonApi","Promise"],"sources":["../../../../../config/dist/lib/neon-api.d.ts"],"sourcesContent":["import { BucketAccessLevel, ComputeSettings, FunctionRuntime } from \"./types.js\";\n\n//#region src/lib/neon-api.d.ts\n\n/**\n * Snapshot of a Neon project field set we care about. Maps onto a subset of the upstream\n * `@neondatabase/api-client` `Project` type. We do **not** widen this to the full upstream\n * shape — keeping the surface narrow makes the in-memory fake practical to maintain.\n */\ninterface NeonProjectSnapshot {\n id: string;\n name: string;\n regionId: string;\n pgVersion: number;\n orgId?: string;\n defaultEndpointSettings?: ComputeSettings;\n}\ninterface NeonBranchSnapshot {\n id: string;\n name: string;\n parentId?: string;\n isDefault: boolean;\n /** Whether the branch is marked protected on Neon. */\n protected: boolean;\n expiresAt?: string;\n}\ninterface NeonEndpointSnapshot {\n id: string;\n branchId: string;\n type: \"read_only\" | \"read_write\";\n autoscalingLimitMinCu: ComputeSettings[\"autoscalingLimitMinCu\"];\n autoscalingLimitMaxCu: ComputeSettings[\"autoscalingLimitMaxCu\"];\n suspendTimeout: ComputeSettings[\"suspendTimeout\"];\n}\ninterface CreateProjectInput {\n name: string;\n regionId: string;\n pgVersion?: number;\n orgId?: string;\n defaultEndpointSettings?: ComputeSettings;\n /**\n * Optional name for the project's auto-created default branch. When omitted, Neon\n * uses its own default (`main`).\n */\n defaultBranchName?: string;\n}\ninterface CreateBranchInput {\n name: string;\n parentId?: string;\n expiresAt?: string;\n /** When `true`, the branch is created with the `protected` flag set on Neon. */\n protected?: boolean;\n computeSettings?: ComputeSettings;\n}\ninterface UpdateBranchInput {\n name?: string;\n expiresAt?: string | null;\n /** When set, toggles the branch's `protected` flag on Neon. */\n protected?: boolean;\n}\n/**\n * A role on a Neon branch (e.g. `neondb_owner`). Passwords are never returned by\n * {@link NeonApi.listBranchRoles}; use {@link NeonApi.getConnectionUri} to fetch a URI\n * with the role's password baked in.\n */\ninterface NeonRoleSnapshot {\n name: string;\n branchId: string;\n /** Whether the role is system-protected (cannot be deleted). */\n protected: boolean;\n}\n/**\n * A database on a Neon branch (e.g. `neondb`).\n */\ninterface NeonDatabaseSnapshot {\n name: string;\n branchId: string;\n /** The role that owns the database (one role can own multiple databases). */\n ownerName: string;\n}\n/**\n * Bits of a Neon Auth integration. The key fields are optional because the Neon API only\n * includes them on create / rotate responses; `GET /auth` returns the public fields.\n */\ninterface NeonAuthSnapshot {\n /** The Neon Auth project id (`auth_provider_project_id` on the Neon API). */\n projectId: string;\n /** Public client key (`pub_client_key`), only present on create / rotate responses. */\n publishableClientKey?: string;\n /** Secret server key (`secret_server_key`), only present on create / rotate responses. */\n secretServerKey?: string;\n /** JWKS URL for verifying tokens issued by Neon Auth. */\n jwksUrl: string;\n /** Optional base URL of the Neon Auth deployment. */\n baseUrl?: string;\n}\n/**\n * Public, fetchable bits of a Neon Data API integration on a specific branch.\n */\ninterface NeonDataApiSnapshot {\n /** REST endpoint URL. */\n url: string;\n}\n/**\n * A branchable object-storage bucket (Preview). Backed by the Neon Platform\n * branchable-storage service.\n */\ninterface NeonBucketSnapshot {\n name: string;\n accessLevel: BucketAccessLevel;\n}\n/**\n * Input for creating a bucket on a branch.\n */\ninterface CreateBucketInput {\n name: string;\n accessLevel?: BucketAccessLevel;\n}\n/**\n * A Neon Function on a branch (Preview). Mirrors the subset of the Functions API we model:\n * the immutable `slug`, the display `name`, and the active deployment id when one exists.\n */\ninterface NeonFunctionSnapshot {\n /** Opaque, stable function identifier. */\n id: string;\n /** Branch-unique slug (the invocation path segment). Immutable. */\n slug: string;\n /** Free-form display name. */\n name: string;\n /** URL at which the function is invoked. */\n invocationUrl: string;\n /** Id (platform version number) of the active deployment, when any code is deployed. */\n activeDeploymentId?: number;\n}\n/**\n * Input for deploying code to a function. `bundle` is the already-built ZIP archive of the\n * function source — building it (esbuild + zip) is an imperative step performed by the\n * caller, not by the {@link NeonApi} adapter.\n */\ninterface DeployFunctionInput {\n bundle: Uint8Array;\n runtime: FunctionRuntime;\n environment: Record<string, string>;\n}\n/**\n * A function deployment (Preview).\n */\ninterface NeonFunctionDeploymentSnapshot {\n /** The deployment id (monotonic per function). */\n id: number;\n status: \"pending\" | \"building\" | \"completed\" | \"failed\";\n}\n/**\n * Parameters accepted by {@link NeonApi.getConnectionUri}. `branchId` and `endpointId`\n * are optional — when omitted, the API uses the project's default branch and that\n * branch's read-write endpoint, respectively.\n */\ninterface GetConnectionUriInput {\n branchId?: string;\n endpointId?: string;\n databaseName: string;\n roleName: string;\n /** When `true`, returns the pooled (PgBouncer) URI instead of the direct URI. */\n pooled?: boolean;\n}\n/**\n * Narrow façade over the Neon management API. `pullConfig`, `pushConfig`, and `fetchEnv`\n * depend on this interface — *not* on `@neondatabase/api-client` directly — which lets us\n * inject a real in-memory fake during tests without resorting to module mocks.\n */\ninterface NeonApi {\n listProjects(filter: {\n orgId?: string;\n }): Promise<NeonProjectSnapshot[]>;\n getProject(projectId: string): Promise<NeonProjectSnapshot>;\n createProject(input: CreateProjectInput): Promise<NeonProjectSnapshot>;\n updateProject(projectId: string, input: {\n name?: string;\n defaultEndpointSettings?: ComputeSettings;\n }): Promise<NeonProjectSnapshot>;\n listBranches(projectId: string): Promise<NeonBranchSnapshot[]>;\n createBranch(projectId: string, input: CreateBranchInput): Promise<{\n branch: NeonBranchSnapshot;\n endpoints: NeonEndpointSnapshot[];\n }>;\n updateBranch(projectId: string, branchId: string, input: UpdateBranchInput): Promise<NeonBranchSnapshot>;\n listEndpoints(projectId: string): Promise<NeonEndpointSnapshot[]>;\n updateEndpoint(projectId: string, endpointId: string, settings: ComputeSettings): Promise<NeonEndpointSnapshot>;\n /** List roles on a branch. Used by {@link fetchEnv} to auto-pick the role when only one exists. */\n listBranchRoles(projectId: string, branchId: string): Promise<NeonRoleSnapshot[]>;\n /** List databases on a branch. Used by {@link fetchEnv} to auto-pick the database when only one exists. */\n listBranchDatabases(projectId: string, branchId: string): Promise<NeonDatabaseSnapshot[]>;\n /**\n * Fetch a Postgres connection URI for the given role + database on a branch.\n * Returns the same string the Neon Console shows under \"Connection Details\".\n */\n getConnectionUri(projectId: string, input: GetConnectionUriInput): Promise<{\n uri: string;\n }>;\n /**\n * Fetch the Neon Auth integration attached to a specific branch. Returns `null` when\n * no integration is enabled — used by `fetchEnv` to decide whether the `env.auth`\n * namespace can be populated.\n */\n getNeonAuth(projectId: string, branchId: string): Promise<NeonAuthSnapshot | null>;\n /**\n * Enable the Neon Auth integration on a specific branch. Idempotent: if an integration\n * is already enabled, the existing snapshot is returned unchanged. Used by\n * `pushConfig` and `branch` to honour branch policy `auth: {}` / `auth.enabled: true`.\n */\n enableNeonAuth(projectId: string, branchId: string, input?: {\n databaseName?: string;\n }): Promise<NeonAuthSnapshot>;\n /**\n * Fetch the Neon Data API integration attached to a specific branch + database.\n * Returns `null` when no integration is enabled — used by `fetchEnv` to decide\n * whether the `env.dataApi` namespace can be populated.\n */\n getNeonDataApi(projectId: string, branchId: string, databaseName: string): Promise<NeonDataApiSnapshot | null>;\n /**\n * Enable the Neon Data API integration on a specific branch + database. Idempotent:\n * if an integration is already enabled, the existing snapshot is returned unchanged.\n * Used by `pushConfig` and `branch` to honour branch policy `dataApi: {}` / `dataApi.enabled: true`.\n */\n enableProjectBranchDataApi(projectId: string, branchId: string, databaseName: string): Promise<NeonDataApiSnapshot>;\n /** List branchable object-storage buckets visible on a branch. */\n listBranchBuckets(projectId: string, branchId: string): Promise<NeonBucketSnapshot[]>;\n /** Create a bucket on a branch. Used by `pushConfig` to honour `preview.buckets`. */\n createBranchBucket(projectId: string, branchId: string, input: CreateBucketInput): Promise<NeonBucketSnapshot>;\n /** Delete a bucket from a branch. */\n deleteBranchBucket(projectId: string, branchId: string, bucketName: string): Promise<void>;\n /** List functions on a branch. */\n listBranchFunctions(projectId: string, branchId: string): Promise<NeonFunctionSnapshot[]>;\n /**\n * Create a function on a branch. The function has no deployment until code is deployed\n * to it with {@link deployBranchFunction}.\n */\n createBranchFunction(projectId: string, branchId: string, input: {\n slug: string;\n name: string;\n }): Promise<NeonFunctionSnapshot>;\n /** Delete a function (by slug) from a branch. */\n deleteBranchFunction(projectId: string, branchId: string, slug: string): Promise<void>;\n /**\n * Deploy a built bundle to a function. The newest deployment becomes active. The\n * `bundle` is built (esbuild + zip) by the caller and passed in as bytes.\n */\n deployBranchFunction(projectId: string, branchId: string, slug: string, input: DeployFunctionInput): Promise<NeonFunctionDeploymentSnapshot>;\n /**\n * Whether the AI Gateway is enabled on a branch. Toggle-style, like Neon Auth / Data\n * API: used by both `fetchEnv` (to decide visibility) and `pushConfig` (to diff intent).\n */\n getAiGatewayEnabled(projectId: string, branchId: string): Promise<boolean>;\n /** Enable the AI Gateway on a branch. Idempotent. */\n enableAiGateway(projectId: string, branchId: string): Promise<void>;\n /** Disable the AI Gateway on a branch. Idempotent. */\n disableAiGateway(projectId: string, branchId: string): Promise<void>;\n}\n//#endregion\nexport { CreateBranchInput, CreateBucketInput, CreateProjectInput, DeployFunctionInput, GetConnectionUriInput, NeonApi, NeonAuthSnapshot, NeonBranchSnapshot, NeonBucketSnapshot, NeonDataApiSnapshot, NeonDatabaseSnapshot, NeonEndpointSnapshot, NeonFunctionDeploymentSnapshot, NeonFunctionSnapshot, NeonProjectSnapshot, NeonRole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A,GAAAA,IAAAA;;WAEIA,CAAAA,EAAAA,OAAAA;;;;;;;UA9HlDb,gBAAAA,CAyJ2EG;QAARU,MAAAA;UAMoBV,EAAAA,MAAAA;;WAE/BC,EAAAA,OAAAA;;;;;UAxJxDH,oBAAAA,CA4JqEY;QAEXP,MAAAA;UAARO,EAAAA,MAAAA;;WAQtDA,EAAAA,MAAAA;;;;;;UA5JIX,gBAAAA,CA0K8CW;;EAEQ,SAAA,EAAA,MAAA;;;;;;;;;;;;;UA7JtDV,mBAAAA;;;;;;;;UAQAC,kBAAAA;;eAEKb;;;;;UAKLc,iBAAAA;;gBAEMd;;;;;;UAMNe,oBAAAA;;;;;;;;;;;;;;;;;UAiBAC,mBAAAA;UACAC;WACCf;eACIgB;;;;;UAKLC,8BAAAA;;;;;;;;;;UAUAC,qBAAAA;;;;;;;;;;;;;UAaAC,OAAAA;;;MAGJC,QAAQnB;iCACmBmB,QAAQnB;uBAClBG,qBAAqBgB,QAAQnB;;;8BAGtBF;MACxBqB,QAAQnB;mCACqBmB,QAAQlB;yCACFG,oBAAoBe;YACjDlB;eACGC;;2DAE4CG,oBAAoBc,QAAQlB;oCACnDkB,QAAQjB;kEACsBJ,kBAAkBqB,QAAQjB;;wDAEpCiB,QAAQb;;4DAEJa,QAAQZ;;;;;6CAKvBU,wBAAwBE;;;;;;;;oDAQjBA,QAAQX;;;;;;;;MAQtDW,QAAQX;;;;;;6EAM+DW,QAAQV;;;;;;yFAMIU,QAAQV;;0DAEvCU,QAAQT;;iEAEDC,oBAAoBQ,QAAQT;;+EAEdS;;4DAEnBA,QAAQP;;;;;;;;MAQ9DO,QAAQP;;2EAE6DO;;;;;iFAKMN,sBAAsBM,QAAQH;;;;;4DAKnDG;;wDAEJA;;yDAECA"}
|
|
1
|
+
{"version":3,"file":"neon-api.d.ts","names":["BucketAccessLevel","ComputeSettings","CredentialPrincipalType","CredentialScope","FunctionRuntime","NeonProjectSnapshot","NeonBranchSnapshot","NeonEndpointSnapshot","CreateProjectInput","CreateBranchInput","UpdateBranchInput","NeonRoleSnapshot","NeonDatabaseSnapshot","NeonAuthSnapshot","NeonDataApiSnapshot","NeonBucketSnapshot","NeonBranchStorageSnapshot","CreateBucketInput","NeonFunctionSnapshot","DeployFunctionInput","Uint8Array","Record","NeonFunctionDeploymentSnapshot","CreateCredentialInput","NeonCredentialSecret","NeonCredentialMeta","GetConnectionUriInput","NeonApi","Promise"],"sources":["../../../../../config/dist/lib/neon-api.d.ts"],"sourcesContent":["import { BucketAccessLevel, ComputeSettings, CredentialPrincipalType, CredentialScope, FunctionRuntime } from \"./types.js\";\n\n//#region src/lib/neon-api.d.ts\n\n/**\n * Snapshot of a Neon project field set we care about. Maps onto a subset of the upstream\n * `@neondatabase/api-client` `Project` type. We do **not** widen this to the full upstream\n * shape — keeping the surface narrow makes the in-memory fake practical to maintain.\n */\ninterface NeonProjectSnapshot {\n id: string;\n name: string;\n regionId: string;\n pgVersion: number;\n orgId?: string;\n defaultEndpointSettings?: ComputeSettings;\n}\ninterface NeonBranchSnapshot {\n id: string;\n name: string;\n parentId?: string;\n isDefault: boolean;\n /** Whether the branch is marked protected on Neon. */\n protected: boolean;\n expiresAt?: string;\n}\ninterface NeonEndpointSnapshot {\n id: string;\n branchId: string;\n type: \"read_only\" | \"read_write\";\n autoscalingLimitMinCu: ComputeSettings[\"autoscalingLimitMinCu\"];\n autoscalingLimitMaxCu: ComputeSettings[\"autoscalingLimitMaxCu\"];\n suspendTimeout: ComputeSettings[\"suspendTimeout\"];\n}\ninterface CreateProjectInput {\n name: string;\n regionId: string;\n pgVersion?: number;\n orgId?: string;\n defaultEndpointSettings?: ComputeSettings;\n /**\n * Optional name for the project's auto-created default branch. When omitted, Neon\n * uses its own default (`main`).\n */\n defaultBranchName?: string;\n}\ninterface CreateBranchInput {\n name: string;\n parentId?: string;\n expiresAt?: string;\n /** When `true`, the branch is created with the `protected` flag set on Neon. */\n protected?: boolean;\n computeSettings?: ComputeSettings;\n}\ninterface UpdateBranchInput {\n name?: string;\n expiresAt?: string | null;\n /** When set, toggles the branch's `protected` flag on Neon. */\n protected?: boolean;\n}\n/**\n * A role on a Neon branch (e.g. `neondb_owner`). Passwords are never returned by\n * {@link NeonApi.listBranchRoles}; use {@link NeonApi.getConnectionUri} to fetch a URI\n * with the role's password baked in.\n */\ninterface NeonRoleSnapshot {\n name: string;\n branchId: string;\n /** Whether the role is system-protected (cannot be deleted). */\n protected: boolean;\n}\n/**\n * A database on a Neon branch (e.g. `neondb`).\n */\ninterface NeonDatabaseSnapshot {\n name: string;\n branchId: string;\n /** The role that owns the database (one role can own multiple databases). */\n ownerName: string;\n}\n/**\n * Bits of a Neon Auth integration. The key fields are optional because the Neon API only\n * includes them on create / rotate responses; `GET /auth` returns the public fields.\n */\ninterface NeonAuthSnapshot {\n /** The Neon Auth project id (`auth_provider_project_id` on the Neon API). */\n projectId: string;\n /** Public client key (`pub_client_key`), only present on create / rotate responses. */\n publishableClientKey?: string;\n /** Secret server key (`secret_server_key`), only present on create / rotate responses. */\n secretServerKey?: string;\n /** JWKS URL for verifying tokens issued by Neon Auth. */\n jwksUrl: string;\n /** Optional base URL of the Neon Auth deployment. */\n baseUrl?: string;\n}\n/**\n * Public, fetchable bits of a Neon Data API integration on a specific branch.\n */\ninterface NeonDataApiSnapshot {\n /** REST endpoint URL. */\n url: string;\n}\n/**\n * A branchable object-storage bucket (Preview). Backed by the Neon Platform\n * branchable-storage service.\n */\ninterface NeonBucketSnapshot {\n name: string;\n accessLevel: BucketAccessLevel;\n}\n/**\n * S3-compatible connection details for a branch's object storage (Preview) — the\n * `BranchStorage` shape from `GET /projects/{id}/branches/{id}/storage`. Non-secret: it\n * carries the endpoint/region/addressing the S3 SDK needs, while the access keys come from\n * a minted {@link NeonCredentialSecret}. `forcePathStyle` is always `true` today (Neon's\n * wildcard TLS cert puts the branch id in the subdomain, so the bucket must travel in the\n * path).\n */\ninterface NeonBranchStorageSnapshot {\n /** S3-compatible endpoint URL, e.g. `https://br-….storage.<suffix>`. */\n s3Endpoint: string;\n /** AWS region string, normalized server-side (e.g. `us-east-2`, `us-east-1`). */\n region: string;\n /** Whether the S3 client must use path-style addressing (always `true` today). */\n forcePathStyle: boolean;\n}\n/**\n * Input for creating a bucket on a branch.\n */\ninterface CreateBucketInput {\n name: string;\n accessLevel?: BucketAccessLevel;\n}\n/**\n * A Neon Function on a branch (Preview). Mirrors the subset of the Functions API we model:\n * the immutable `slug`, the display `name`, and the active deployment id when one exists.\n */\ninterface NeonFunctionSnapshot {\n /** Opaque, stable function identifier. */\n id: string;\n /** Branch-unique slug (the invocation path segment). Immutable. */\n slug: string;\n /** Free-form display name. */\n name: string;\n /** URL at which the function is invoked. */\n invocationUrl: string;\n /** Id (platform version number) of the active deployment, when any code is deployed. */\n activeDeploymentId?: number;\n}\n/**\n * Input for deploying code to a function. `bundle` is the already-built ZIP archive of the\n * function source — building it (esbuild + zip) is an imperative step performed by the\n * caller, not by the {@link NeonApi} adapter.\n */\ninterface DeployFunctionInput {\n bundle: Uint8Array;\n runtime: FunctionRuntime;\n environment: Record<string, string>;\n}\n/**\n * A function deployment (Preview).\n */\ninterface NeonFunctionDeploymentSnapshot {\n /** The deployment id (monotonic per function). */\n id: number;\n status: \"pending\" | \"building\" | \"completed\" | \"failed\";\n}\n/**\n * Input for {@link NeonApi.createCredential}. Mirrors the Neon API `CreateCredentialRequest`\n * (`POST .../credentials`, `x-stability-level: beta`):\n *\n * - `scopes` — 1–16 capabilities the credential may exercise (derived from the policy's\n * enabled Preview features, never hand-authored).\n * - `principalType` — `user` (developer/app) or `function` (a deployed function).\n * - `functionId` — required when `principalType === \"function\"`.\n * - `name` — optional free-form label echoed back on the response.\n */\ninterface CreateCredentialInput {\n scopes: CredentialScope[];\n principalType: CredentialPrincipalType;\n functionId?: string;\n name?: string;\n}\n/**\n * The secret-bearing result of {@link NeonApi.createCredential} — the Neon API\n * `CreateCredentialResponse`. `apiToken` and `s3SecretAccessKey` are returned **exactly\n * once** (they are not stored server-side), so the caller must persist them immediately;\n * they can never be re-fetched (the list endpoint returns metadata only). `tokenIdShort`\n * is the public identifier embedded in `apiToken` (`nt_live_<tokenIdShort>_…`) and doubles\n * as the S3 access-key id.\n */\ninterface NeonCredentialSecret {\n tokenId: string;\n tokenIdShort: string;\n name?: string;\n /** Bearer token (`nt_live_…`); returned once. Used for AI Gateway / Functions invoke. */\n apiToken: string;\n /** 64-char hex S3 secret access key; returned once. Paired with `tokenIdShort` as the access-key id. */\n s3SecretAccessKey: string;\n scopes: CredentialScope[];\n branchId: string;\n createdAt: string;\n /** When the credential expires; absent means it never expires. */\n expiresAt?: string;\n}\n/**\n * Secret-free metadata for an issued credential — the Neon API `CredentialMeta` returned by\n * {@link NeonApi.listCredentials}. Never includes `apiToken` / `s3SecretAccessKey`.\n */\ninterface NeonCredentialMeta {\n tokenId: string;\n tokenIdShort: string;\n name?: string;\n scopes: CredentialScope[];\n principalType: CredentialPrincipalType;\n functionId?: string;\n branchId?: string;\n createdAt: string;\n lastUsedAt?: string;\n revokedAt?: string;\n expiresAt?: string;\n}\n/**\n * Parameters accepted by {@link NeonApi.getConnectionUri}. `branchId` and `endpointId`\n * are optional — when omitted, the API uses the project's default branch and that\n * branch's read-write endpoint, respectively.\n */\ninterface GetConnectionUriInput {\n branchId?: string;\n endpointId?: string;\n databaseName: string;\n roleName: string;\n /** When `true`, returns the pooled (PgBouncer) URI instead of the direct URI. */\n pooled?: boolean;\n}\n/**\n * Narrow façade over the Neon management API. `pullConfig`, `pushConfig`, and `fetchEnv`\n * depend on this interface — *not* on `@neondatabase/api-client` directly — which lets us\n * inject a real in-memory fake during tests without resorting to module mocks.\n */\ninterface NeonApi {\n listProjects(filter: {\n orgId?: string;\n }): Promise<NeonProjectSnapshot[]>;\n getProject(projectId: string): Promise<NeonProjectSnapshot>;\n createProject(input: CreateProjectInput): Promise<NeonProjectSnapshot>;\n updateProject(projectId: string, input: {\n name?: string;\n defaultEndpointSettings?: ComputeSettings;\n }): Promise<NeonProjectSnapshot>;\n listBranches(projectId: string): Promise<NeonBranchSnapshot[]>;\n createBranch(projectId: string, input: CreateBranchInput): Promise<{\n branch: NeonBranchSnapshot;\n endpoints: NeonEndpointSnapshot[];\n }>;\n updateBranch(projectId: string, branchId: string, input: UpdateBranchInput): Promise<NeonBranchSnapshot>;\n listEndpoints(projectId: string): Promise<NeonEndpointSnapshot[]>;\n updateEndpoint(projectId: string, endpointId: string, settings: ComputeSettings): Promise<NeonEndpointSnapshot>;\n /** List roles on a branch. Used by {@link fetchEnv} to auto-pick the role when only one exists. */\n listBranchRoles(projectId: string, branchId: string): Promise<NeonRoleSnapshot[]>;\n /** List databases on a branch. Used by {@link fetchEnv} to auto-pick the database when only one exists. */\n listBranchDatabases(projectId: string, branchId: string): Promise<NeonDatabaseSnapshot[]>;\n /**\n * Fetch a Postgres connection URI for the given role + database on a branch.\n * Returns the same string the Neon Console shows under \"Connection Details\".\n */\n getConnectionUri(projectId: string, input: GetConnectionUriInput): Promise<{\n uri: string;\n }>;\n /**\n * Fetch the Neon Auth integration attached to a specific branch. Returns `null` when\n * no integration is enabled — used by `fetchEnv` to decide whether the `env.auth`\n * namespace can be populated.\n */\n getNeonAuth(projectId: string, branchId: string): Promise<NeonAuthSnapshot | null>;\n /**\n * Enable the Neon Auth integration on a specific branch. Idempotent: if an integration\n * is already enabled, the existing snapshot is returned unchanged. Used by\n * `pushConfig` and `branch` to honour branch policy `auth: {}` / `auth.enabled: true`.\n */\n enableNeonAuth(projectId: string, branchId: string, input?: {\n databaseName?: string;\n }): Promise<NeonAuthSnapshot>;\n /**\n * Fetch the Neon Data API integration attached to a specific branch + database.\n * Returns `null` when no integration is enabled — used by `fetchEnv` to decide\n * whether the `env.dataApi` namespace can be populated.\n */\n getNeonDataApi(projectId: string, branchId: string, databaseName: string): Promise<NeonDataApiSnapshot | null>;\n /**\n * Enable the Neon Data API integration on a specific branch + database. Idempotent:\n * if an integration is already enabled, the existing snapshot is returned unchanged.\n * Used by `pushConfig` and `branch` to honour branch policy `dataApi: {}` / `dataApi.enabled: true`.\n */\n enableProjectBranchDataApi(projectId: string, branchId: string, databaseName: string): Promise<NeonDataApiSnapshot>;\n /** List branchable object-storage buckets visible on a branch. */\n listBranchBuckets(projectId: string, branchId: string): Promise<NeonBucketSnapshot[]>;\n /** Create a bucket on a branch. Used by `pushConfig` to honour `preview.buckets`. */\n createBranchBucket(projectId: string, branchId: string, input: CreateBucketInput): Promise<NeonBucketSnapshot>;\n /** Delete a bucket from a branch. */\n deleteBranchBucket(projectId: string, branchId: string, bucketName: string): Promise<void>;\n /**\n * Fetch the branch's S3-compatible object-storage connection details (endpoint, region,\n * path-style). Returns `null` when storage is not enabled for the branch (the API's 404\n * `BranchStorageNotEnabled`). Used by `fetchEnv` to populate the `AWS_*` storage env\n * alongside the minted credential's access keys.\n */\n getProjectBranchStorage(projectId: string, branchId: string): Promise<NeonBranchStorageSnapshot | null>;\n /** List functions on a branch. */\n listBranchFunctions(projectId: string, branchId: string): Promise<NeonFunctionSnapshot[]>;\n /** Delete a function (by slug) from a branch. */\n deleteBranchFunction(projectId: string, branchId: string, slug: string): Promise<void>;\n /**\n * Deploy a built bundle to a function, creating the function if it does not yet exist —\n * Neon has no separate create endpoint, so the first deployment to a slug creates the\n * function. The newest deployment becomes active. The `bundle` is built (esbuild + zip)\n * by the caller and passed in as bytes.\n */\n deployBranchFunction(projectId: string, branchId: string, slug: string, input: DeployFunctionInput): Promise<NeonFunctionDeploymentSnapshot>;\n /**\n * Mint a new scoped service credential on a branch (`POST .../credentials`). The\n * returned {@link NeonCredentialSecret} carries `apiToken` + `s3SecretAccessKey`\n * **once** — persist them immediately. Used by `fetchEnv` / `env pull` to issue the\n * unified credential for the branch's enabled Preview features (object storage, AI\n * Gateway, Functions).\n */\n createCredential(projectId: string, branchId: string, input: CreateCredentialInput): Promise<NeonCredentialSecret>;\n /**\n * List the secret-free metadata for credentials issued on a branch\n * (`GET .../credentials`). Used to report issued credentials (e.g. `config status`)\n * and to verify a persisted credential still exists / isn't revoked.\n */\n listCredentials(projectId: string, branchId: string): Promise<NeonCredentialMeta[]>;\n /**\n * Revoke (soft-delete) a credential by its `tokenId` (`DELETE .../credentials/{id}`).\n * Idempotent.\n */\n revokeCredential(projectId: string, branchId: string, tokenId: string): Promise<void>;\n}\n//#endregion\nexport { CreateBranchInput, CreateBucketInput, CreateCredentialInput, CreateProjectInput, DeployFunctionInput, GetConnectionUriInput, NeonApi, NeonAuthSnapshot, NeonBranchSnapshot, NeonBranchStorageSnapshot, NeonBucketSnapshot, NeonCredentialMeta, NeonCredentialSecret, NeonDataApiSnapshot, NeonDatabaseSnapshot, NeonEndpointSnapshot, NeonFunctionDeploymentSnapshot, NeonFunctionSnapshot, NeonProjectSnapshot, NeonRoleSnapshot, UpdateBranchInput };\n//# sourceMappingURL=neon-api.d.ts.map"],"mappings":";;;;;AAe2C;AAEf;;;;UARlBK,mBAAAA,CAuBQJ;EAAe,EAAA,EAAA,MAAA;EAAA,IAEvBO,EAAAA,MAAAA;EAKiC,QAOjCC,EAAAA,MAAAA;EAMyB,SAEzBC,EAAAA,MAAAA;EAAiB,KAWjBC,CAAAA,EAAAA,MAAAA;EAAgB,uBAShBC,CAAAA,EA3DkBX,eA2DE;AAAA;AAUJ,UAnEhBK,kBAAAA,CAkFmB;EAAA,EAQnBS,EAAAA,MAAAA;EAEsB,IAUtBC,EAAAA,MAAAA;EAAyB,QAWzBC,CAAAA,EAAAA,MAAAA;EAEuB,SAMvBC,EAAAA,OAAAA;EAAoB;EAiBD,SAAA,EAAA,OAAA;WACnBE,CAAAA,EAAAA,MAAAA;;UAlIAb,oBAAAA,CAoIKc;EAAM,EAAA,EAAA,MAAA;EAAA,QAKXC,EAAAA,MAAAA;EAA8B,IAe9BC,EAAAA,WAAAA,GAAAA,YAAqB;EAAA,qBAAA,EApJNtB,eAoJM,CAAA,uBAAA,CAAA;uBACrBE,EApJeF,eAoJfE,CAAAA,uBAAAA,CAAAA;gBACOD,EApJCD,eAoJDC,CA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;;;UAYPsB,oBAAAA;;;;;;;;UAQArB;;;;;;;;;;UAUAsB,kBAAAA;;;;UAIAtB;iBACOD;;;;;;;;;;;;;UAaPwB,qBAAAA;;;;;;;;;;;;;UAaAC,OAAAA;;;MAGJC,QAAQvB;iCACmBuB,QAAQvB;uBAClBG,qBAAqBoB,QAAQvB;;;8BAGtBJ;MACxB2B,QAAQvB;mCACqBuB,QAAQtB;yCACFG,oBAAoBmB;YACjDtB;eACGC;;2DAE4CG,oBAAoBkB,QAAQtB;oCACnDsB,QAAQrB;kEACsBN,kBAAkB2B,QAAQrB;;wDAEpCqB,QAAQjB;;4DAEJiB,QAAQhB;;;;;6CAKvBc,wBAAwBE;;;;;;;;oDAQjBA,QAAQf;;;;;;;;MAQtDe,QAAQf;;;;;;6EAM+De,QAAQd;;;;;;yFAMIc,QAAQd;;0DAEvCc,QAAQb;;iEAEDE,oBAAoBW,QAAQb;;+EAEda;;;;;;;gEAOfA,QAAQZ;;4DAEZY,QAAQV;;2EAEOU;;;;;;;iFAOMT,sBAAsBS,QAAQN;;;;;;;;+DAQhDC,wBAAwBK,QAAQJ;;;;;;wDAMvCI,QAAQH;;;;;0EAKUG"}
|
|
@@ -138,26 +138,13 @@ type FunctionRuntime = "nodejs24";
|
|
|
138
138
|
/**
|
|
139
139
|
* Local-development settings for a function, used by `neon dev` when it serves every
|
|
140
140
|
* function declared in `neon.ts` (i.e. invoked with no `--source`). Never affects deploy.
|
|
141
|
-
*
|
|
142
|
-
* `port` and `portless` are independent:
|
|
143
|
-
*
|
|
144
|
-
* - `portless: true` — wrap this function's local server with `portless <slug> …` so it gets
|
|
145
|
-
* a stable `slug.localhost` URL. Portless assigns the port itself (it injects `PORT`), so
|
|
146
|
-
* `port` is ignored in this mode.
|
|
147
|
-
* - otherwise — serve directly. `port`, when set, is bound exactly (and `neon dev` fails
|
|
148
|
-
* loudly if it is taken); when omitted a free port is found automatically.
|
|
149
141
|
*/
|
|
150
142
|
interface FunctionDevConfig {
|
|
151
143
|
/**
|
|
152
|
-
* Port the local server binds. Bound exactly (
|
|
153
|
-
*
|
|
144
|
+
* Port the local server binds. Bound exactly (and `neon dev` fails loudly if it is taken)
|
|
145
|
+
* when set; a free port is found automatically when omitted.
|
|
154
146
|
*/
|
|
155
147
|
port?: number;
|
|
156
|
-
/**
|
|
157
|
-
* Expose this function via `portless` (a stable `slug.localhost` URL). Requires the
|
|
158
|
-
* `portless` binary on PATH. Portless assigns the port, so `port` is ignored here.
|
|
159
|
-
*/
|
|
160
|
-
portless?: boolean;
|
|
161
148
|
}
|
|
162
149
|
/**
|
|
163
150
|
* Static definition of a Neon Function (Preview feature). Declares that the function
|
|
@@ -205,6 +192,25 @@ interface FunctionDef {
|
|
|
205
192
|
*/
|
|
206
193
|
dev?: FunctionDevConfig;
|
|
207
194
|
}
|
|
195
|
+
/**
|
|
196
|
+
* A single capability a branch-scoped service credential may exercise (Preview). A
|
|
197
|
+
* credential is granted a set of these and may only perform the listed actions. Mirrors
|
|
198
|
+
* the Neon API `CredentialScope` enum (`x-stability-level: beta`):
|
|
199
|
+
*
|
|
200
|
+
* - `storage:read` / `storage:write` — object-storage (bucket) access via the S3 key.
|
|
201
|
+
* - `ai_gateway:invoke` — call the AI Gateway with the bearer `api_token`.
|
|
202
|
+
* - `functions:invoke` — invoke Neon Functions with the bearer `api_token`.
|
|
203
|
+
*
|
|
204
|
+
* The set a policy needs is derived from its enabled Preview features (see
|
|
205
|
+
* {@link deriveCredentialScopes}); it is never authored by hand.
|
|
206
|
+
*/
|
|
207
|
+
type CredentialScope = "storage:read" | "storage:write" | "ai_gateway:invoke" | "functions:invoke";
|
|
208
|
+
/**
|
|
209
|
+
* Who a credential acts as. `user` is the developer/app principal minted for local dev and
|
|
210
|
+
* app bootstrap (`fetchEnv` / `env pull`); `function` is a deployed-function principal
|
|
211
|
+
* (carries a `function_id`). The env tooling only mints `user` credentials today.
|
|
212
|
+
*/
|
|
213
|
+
type CredentialPrincipalType = "user" | "function";
|
|
208
214
|
/** Anonymous-access level for a branchable object-storage bucket. */
|
|
209
215
|
type BucketAccessLevel = "private" | "public_read";
|
|
210
216
|
/**
|
|
@@ -325,5 +331,5 @@ interface Config<Auth extends ServiceToggleInput | undefined = ServiceToggleInpu
|
|
|
325
331
|
* downstream diff/apply never has to re-derive it.
|
|
326
332
|
*/
|
|
327
333
|
//#endregion
|
|
328
|
-
export { BranchTarget, BranchTuning, BranchTuningFn, BucketAccessLevel, BucketDef, ComputeSettings, ComputeUnit, Config, DurationString, DurationUnit, FunctionDef, FunctionDevConfig, FunctionRuntime, FunctionTuning, PostgresConfig, PreviewInput, PreviewTuning, ServiceToggle, ServiceToggleInput };
|
|
334
|
+
export { BranchTarget, BranchTuning, BranchTuningFn, BucketAccessLevel, BucketDef, ComputeSettings, ComputeUnit, Config, CredentialPrincipalType, CredentialScope, DurationString, DurationUnit, FunctionDef, FunctionDevConfig, FunctionRuntime, FunctionTuning, PostgresConfig, PreviewInput, PreviewTuning, ServiceToggle, ServiceToggleInput };
|
|
329
335
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":["ComputeUnit","DurationUnit","DurationString","SuspendTimeoutSuggestion","TtlSuggestion","DurationField","Suggestions","NonNullable","ComputeSettings","BranchTarget","ServiceToggle","ServiceToggleInput","PostgresConfig","FunctionRuntime","FunctionDevConfig","FunctionDef","Record","BucketAccessLevel","BucketDef","PreviewInput","FunctionTuning","PreviewTuning","Slug","Partial","BranchTuning","FunctionSlugsOf","Preview","F","Extract","BranchTuningFn","Config","Auth","DataApi","ResolvedFunctionConfig","ResolvedBucketConfig","ResolvedPreviewConfig","ResolvedBranchConfig","AppliedChange","ConflictReport","PushResult"],"sources":["../../../../../config/dist/lib/types.d.ts"],"sourcesContent":["//#region src/lib/types.d.ts\n/**\n * Valid Neon Compute Unit values.\n * Most plans support 0.25, 0.5, 1, 2, 4, 8. Higher values may be available on Business plans.\n */\ntype ComputeUnit = 0.25 | 0.5 | 1 | 2 | 4 | 8;\n/** Time units accepted in a {@link DurationString}: seconds, minutes, hours, days, weeks. */\ntype DurationUnit = \"s\" | \"m\" | \"h\" | \"d\" | \"w\";\n/**\n * A Neon duration string: a positive integer **followed by a unit** — `s` (seconds),\n * `m` (minutes), `h` (hours), `d` (days), or `w` (weeks). Used by\n * {@link ComputeSettings.suspendTimeout} and {@link BranchTuning.ttl}.\n *\n * A **unit is required**: a bare numeric string like `\"7\"` is rejected at the type level. To\n * express a raw number of seconds, pass a `number` (`300`) — not a string (`\"300\"`). This\n * removes the old ambiguity where `\"7\"` silently meant 7 *seconds* instead of, say, `\"7d\"`.\n *\n * @example \"5m\" // 5 minutes\n * @example \"1h\" // 1 hour\n * @example \"7d\" // 7 days\n */\ntype DurationString = `${number}${DurationUnit}`;\n/**\n * Autocomplete suggestions for {@link ComputeSettings.suspendTimeout}. Every value sits inside\n * the Neon API's allowed scale-to-zero band: **60s–604800s** (1 minute – 1 week). This is *not*\n * a closed set — the field also accepts any other {@link DurationString} or a `number` of\n * seconds; out-of-range values type-check but are rejected at apply time.\n */\ntype SuspendTimeoutSuggestion = \"1m\" | \"5m\" | \"15m\" | \"30m\" | \"1h\" | \"6h\" | \"12h\" | \"1d\" | \"7d\";\n/**\n * Autocomplete suggestions for {@link BranchTuning.ttl}. Every value sits within the Neon API's\n * branch-expiration limit (**max 30 days** from creation; the Console's own presets are 1h / 1d\n * / 7d). This is *not* a closed set — the field also accepts any other {@link DurationString} or\n * a `number` of seconds; values over 30 days are rejected at apply time.\n */\ntype TtlSuggestion = \"1h\" | \"6h\" | \"12h\" | \"1d\" | \"3d\" | \"7d\" | \"14d\" | \"30d\";\n/**\n * Compose a field's duration type: its curated autocomplete `Suggestions` plus the open\n * `DurationString` template (so any `<integer><unit>` string still type-checks) and a `number`\n * of seconds. Intersecting the template arm with `NonNullable<unknown>` stops TypeScript from\n * collapsing the literal suggestions into the template, which is what preserves the autocomplete.\n */\ntype DurationField<Suggestions extends DurationString> = Suggestions | (DurationString & NonNullable<unknown>) | number;\n/**\n * Compute settings applied to the read/write endpoint of a branch.\n *\n * Mirrors the subset of {@link https://api-docs.neon.tech/reference/getting-started-with-neon-api Neon endpoint}\n * fields that we expose as IaC primitives. Anything left undefined falls back to the project's\n * `default_endpoint_settings` (which themselves fall back to Neon platform defaults).\n */\ninterface ComputeSettings {\n /**\n * Minimum number of Compute Units. Set to 0.25 for true scale-to-zero.\n * @example 0.25 // scale-to-zero\n * @example 1 // always-on with 1 CU minimum\n */\n autoscalingLimitMinCu?: ComputeUnit;\n /**\n * Maximum number of Compute Units for autoscaling.\n * @example 2\n * @example 8\n */\n autoscalingLimitMaxCu?: ComputeUnit;\n /**\n * How long an idle compute waits before suspending (Neon's scale-to-zero). Accepts a\n * {@link DurationString} (autocompletes common values), a number of seconds, or `false`.\n *\n * - `false` — never suspend (always-on compute)\n * - {@link DurationString} — e.g. `\"5m\"`; autocompletes the in-range values `\"1m\"`, `\"5m\"`,\n * `\"15m\"`, `\"30m\"`, `\"1h\"`, `\"6h\"`, `\"12h\"`, `\"1d\"`, `\"7d\"`, and accepts any other\n * `<integer><unit>` (units: `s`, `m`, `h`, `d`, `w`). A **unit is required** — for raw\n * seconds pass a `number`, not a string.\n * - `number` — custom timeout in **seconds**, must be in `60`–`604800` (1 minute to 1 week)\n * - `undefined` — use the Neon platform default (currently 300s / 5 minutes)\n *\n * Whichever form you use, the resolved timeout must fall in `60`–`604800` seconds (the Neon\n * API limit); the suggestions are all within that band, anything else is checked at apply.\n *\n * @example false // never suspend (always-on)\n * @example \"5m\" // suspend after 5 minutes idle\n * @example \"1h\" // suspend after 1 hour idle\n * @example 300 // 5 minutes, expressed in seconds\n */\n suspendTimeout?: false | DurationField<SuspendTimeoutSuggestion>;\n}\n/**\n * Read-only descriptor of the branch a {@link Config} policy is being evaluated for — the\n * `branch` argument passed to your `defineConfig((branch) => …)` callback. It describes\n * **which** branch this invocation decides for; it is not a live branch handle and must not\n * be mutated. Switch on its fields and return the desired {@link BranchConfig}.\n */\ninterface BranchTarget {\n /** Branch name being evaluated. For `branch dev`, this is the generated branch name. */\n name: string;\n /** Neon branch id when the branch already exists. Undefined during pre-create eval. */\n id?: string;\n /** Whether this branch already exists on Neon. */\n exists: boolean;\n /** Parent branch id from Neon when known. */\n parentId?: string;\n /** Whether Neon marks this branch as the project default. */\n isDefault?: boolean;\n /** Whether Neon currently marks this branch protected. */\n isProtected?: boolean;\n /** Current expiration timestamp from Neon, when set. */\n expiresAt?: string;\n}\n/**\n * Object form of a branch-scoped service toggle. `{}` or `{ enabled: true }` enables it;\n * `{ enabled: false }` opts out. Used as the object half of {@link ServiceToggleInput}.\n */\ninterface ServiceToggle {\n /** Defaults to `true` when the service namespace is present. Set `false` to opt out. */\n enabled?: boolean;\n}\n/**\n * How a branch-scoped service (Neon Auth, Data API, AI Gateway) is toggled in a policy.\n *\n * - `true` / `{}` / `{ enabled: true }` — enabled.\n * - `false` / `{ enabled: false }` — disabled.\n * - omitted (`undefined`) — not part of the policy at all.\n *\n * These toggles are **static** (they live in the top-level `defineConfig({ … })` object,\n * not in the per-branch `branch` closure) so the secret set they imply can be derived at\n * the type level — that's what makes `NeonEnv<typeof config>` exact.\n */\ntype ServiceToggleInput = boolean | ServiceToggle;\ninterface PostgresConfig {\n computeSettings?: ComputeSettings;\n}\n/**\n * Supported function runtimes. Mirrors the Neon Functions deploy API `runtime` enum.\n * Only `nodejs24` exists today; kept as a union so adding runtimes later is a\n * non-breaking, type-checked change.\n */\ntype FunctionRuntime = \"nodejs24\";\n/**\n * Local-development settings for a function, used by `neon dev` when it serves every\n * function declared in `neon.ts` (i.e. invoked with no `--source`). Never affects deploy.\n *\n * `port` and `portless` are independent:\n *\n * - `portless: true` — wrap this function's local server with `portless <slug> …` so it gets\n * a stable `slug.localhost` URL. Portless assigns the port itself (it injects `PORT`), so\n * `port` is ignored in this mode.\n * - otherwise — serve directly. `port`, when set, is bound exactly (and `neon dev` fails\n * loudly if it is taken); when omitted a free port is found automatically.\n */\ninterface FunctionDevConfig {\n /**\n * Port the local server binds. Bound exactly (fails if taken) when set; a free port is\n * found when omitted. Ignored when `portless` is true (portless assigns the port).\n */\n port?: number;\n /**\n * Expose this function via `portless` (a stable `slug.localhost` URL). Requires the\n * `portless` binary on PATH. Portless assigns the port, so `port` is ignored here.\n */\n portless?: boolean;\n}\n/**\n * Static definition of a Neon Function (Preview feature). Declares that the function\n * **exists** on every branch; its branch-unique slug is the **record key** in\n * {@link PreviewInput.functions} (not a field here), so slugs are statically enumerable,\n * cannot duplicate, and the `branch` closure can only tune slugs that are declared here.\n *\n * A function is invoked like a Cloudflare/Vercel handler — its source module\n * `export default { fetch }` or `export async function handler(req): Response`. The\n * `source` path is bundled (esbuild) and uploaded as a deployment; the newest deployment\n * becomes active.\n *\n * Runtime tuning is **not** here — it varies per branch and lives in the `branch` closure\n * (see {@link FunctionTuning}). Memory is fixed by the platform policy for now and is not\n * user-configurable.\n */\ninterface FunctionDef {\n /** Free-form display name. @example \"Hello World\" */\n name: string;\n /**\n * Path to the function's entry module, **relative to `neon.ts`** (or absolute). The\n * module's default export (`{ fetch }`) or `handler` export is the function entry. This\n * path is resolved against the loaded `neon.ts` location and bundled with esbuild at\n * deploy time.\n *\n * We require a string path rather than an imported handler because a JS function value\n * carries no reference back to its source file, so esbuild has nothing to bundle from.\n * @example \"./functions/hello-world.ts\"\n */\n source: string;\n /**\n * Environment variables injected into the deployed function, keyed by the var name the\n * function reads at runtime. The **keys** are static (preserved at the type level so\n * `parseEnv(config, \"<slug>\").function.<key>` is typed); the **values** are arbitrary\n * strings evaluated when `neon.ts` is loaded (typically `process.env.X`) and uploaded\n * at `config apply`. Every value must be a defined string — a `process.env.X` that is\n * `undefined` (unset) errors at validation time rather than silently shipping\n * `undefined`.\n * @example { resendApiKey: process.env.RESEND_API_KEY ?? \"\" }\n */\n env?: Record<string, string>;\n /**\n * Local-development settings used by `neon dev` when serving every function from\n * `neon.ts`. Ignored at deploy time. See {@link FunctionDevConfig}.\n */\n dev?: FunctionDevConfig;\n}\n/** Anonymous-access level for a branchable object-storage bucket. */\ntype BucketAccessLevel = \"private\" | \"public_read\";\n/**\n * Static definition of a branchable object-storage bucket (Preview feature). The bucket's\n * name is the **record key** in {@link PreviewInput.buckets}, so names are statically\n * enumerable and cannot duplicate.\n */\ninterface BucketDef {\n /**\n * Anonymous access level. `private` (default) requires authenticated reads/writes;\n * `public_read` allows anonymous GetObject/HeadObject.\n */\n access?: BucketAccessLevel;\n}\n/**\n * Static, branch-scoped **Preview** features. Grouped under `preview` to signal they are\n * backed by Neon `x-stability-level: beta` endpoints and may change before GA. Everything\n * here is existential (it determines what exists on the branch); per-branch tuning lives in\n * the `branch` closure.\n */\ninterface PreviewInput {\n /** Enable/disable the AI Gateway on the branch (toggle, like auth / dataApi). */\n aiGateway?: ServiceToggleInput;\n /** Functions to deploy, keyed by branch-unique slug (`^[a-z0-9]{1,20}$`). */\n functions?: Record<string, FunctionDef>;\n /** Object-storage buckets to create, keyed by bucket name. */\n buckets?: Record<string, BucketDef>;\n}\n/**\n * Per-branch deploy tuning for a single function. Returned (per slug) by the `branch`\n * closure. Deliberately **cannot** change the function's existence, source, name, env\n * **keys**, or memory — only runtime selection is currently configurable — so the static\n * secret/function set stays sound.\n */\ninterface FunctionTuning {\n /** Runtime to execute the function with. Defaults to `\"nodejs24\"`. */\n runtime?: FunctionRuntime;\n}\n/**\n * Per-branch tuning of Preview features. Only existing function slugs (those declared in\n * the static {@link PreviewInput.functions}) may be tuned — `Slug` is constrained to the\n * declared keys by {@link BranchTuningFn}.\n */\ninterface PreviewTuning<Slug extends string = string> {\n functions?: Partial<Record<Slug, FunctionTuning>>;\n}\n/**\n * The per-branch tuning object returned by the `branch` closure. It can adjust branch\n * lifecycle (`parent`, `ttl`, `protected`), Postgres compute settings, and per-function\n * deploy tuning — but **cannot** add/remove services or functions. That guarantee is what\n * keeps the static secret set (and therefore `NeonEnv`) exact.\n */\ninterface BranchTuning<Slug extends string = string> {\n /** Parent branch name used when creating a new branch. Not a Postgres setting. */\n parent?: string;\n /**\n * Branch time-to-live: how long after creation the branch should auto-expire. Applied\n * when creating a new branch and reconciled on existing branches (when `updateExisting`\n * is set). Accepts a {@link DurationString} (autocompletes common values) or a number of\n * seconds. Omit to keep the branch indefinitely.\n *\n * - {@link DurationString} — e.g. `\"7d\"`; autocompletes `\"1h\"`, `\"6h\"`, `\"12h\"`, `\"1d\"`,\n * `\"3d\"`, `\"7d\"`, `\"14d\"`, `\"30d\"`, and accepts any other `<integer><unit>` (units: `s`,\n * `m`, `h`, `d`, `w` — e.g. `\"12h\"`, `\"2w\"`). A **unit is required** — `\"7\"` is rejected;\n * for raw seconds pass a `number`.\n * - `number` — custom TTL in **seconds** (e.g. `3600`)\n * - `undefined` — no expiry; the branch persists until explicitly deleted\n *\n * The Neon API caps branch expiration at **30 days** from creation, so the resolved TTL must\n * be `> 0` and `<= 30d`; the suggestions stay within that limit and anything longer is\n * rejected at apply.\n *\n * @example \"1d\" // ephemeral preview branch: expires a day after creation\n * @example \"7d\" // one-week TTL\n * @example \"30d\" // the maximum the API allows\n * @example 3600 // 1 hour, expressed in seconds\n */\n ttl?: DurationField<TtlSuggestion>;\n /** Whether the selected branch should be protected. Undefined means \"leave as-is\". */\n protected?: boolean;\n postgres?: PostgresConfig;\n preview?: PreviewTuning<Slug>;\n}\n/** Extract the declared function slugs from a {@link PreviewInput} for closure typing. */\ntype FunctionSlugsOf<Preview extends PreviewInput | undefined> = Preview extends {\n functions: infer F;\n} ? Extract<keyof F, string> : string;\n/**\n * Signature of the `branch` closure. Generic over the static {@link PreviewInput} so the\n * `preview.functions` keys it may tune are constrained to the slugs actually declared.\n */\ntype BranchTuningFn<Preview extends PreviewInput | undefined = PreviewInput | undefined> = (branch: BranchTarget) => BranchTuning<FunctionSlugsOf<Preview>>;\n/**\n * A validated Neon branch policy — the value `defineConfig({ … })` returns and `neon.ts`\n * default-exports.\n *\n * Split into a **static** existential set (top-level `auth` / `dataApi` GA toggles plus the\n * beta `preview` block) and a **dynamic** per-branch `branch` closure for tuning. The\n * static half is what makes the secret set — and therefore `NeonEnv<typeof config>` and\n * `parseEnv` — exact; the closure can tune but never change what exists.\n *\n * Generic over the three static fields so the type system can read the exact toggle/slug\n * literals; the defaults make the bare `Config` a usable \"any policy\" type for runtime\n * function signatures.\n */\ninterface Config<Auth extends ServiceToggleInput | undefined = ServiceToggleInput | undefined, DataApi extends ServiceToggleInput | undefined = ServiceToggleInput | undefined, Preview extends PreviewInput | undefined = PreviewInput | undefined> {\n /** Neon Auth integration toggle (GA). Static — drives `NeonEnv.auth`. */\n auth?: Auth;\n /** Neon Data API integration toggle (GA). Static — drives `NeonEnv.dataApi`. */\n dataApi?: DataApi;\n /** Beta (Preview) feature set: AI Gateway, functions, buckets. Static. */\n preview?: Preview;\n /** Per-branch tuning closure. Cannot change the static existential set. */\n branch?: BranchTuningFn<Preview>;\n}\n/**\n * A function with all deploy defaults applied. `resolveConfig` fills in `runtime` so\n * downstream diff/apply never has to re-derive it.\n */\ninterface ResolvedFunctionConfig {\n slug: string;\n name: string;\n source: string;\n env: Record<string, string>;\n runtime: FunctionRuntime;\n /**\n * Local-development settings, passed through untouched from {@link FunctionDef.dev}\n * (no defaults applied). Only consumed by `neon dev`; deploy ignores it.\n */\n dev?: FunctionDevConfig;\n}\n/** A bucket with its access level defaulted to `private`. */\ninterface ResolvedBucketConfig {\n name: string;\n access: BucketAccessLevel;\n}\n/**\n * Normalized {@link PreviewInput}. Only present on {@link ResolvedBranchConfig} when the\n * policy returned a `preview` block. `aiGatewayEnabled` follows the same\n * \"present-and-not-`false`\" semantics as `authEnabled` / `dataApiEnabled`.\n */\ninterface ResolvedPreviewConfig {\n functions: ResolvedFunctionConfig[];\n buckets: ResolvedBucketConfig[];\n aiGatewayEnabled: boolean;\n}\ninterface ResolvedBranchConfig {\n parent?: string;\n ttlSeconds?: number;\n protected?: boolean;\n postgres?: PostgresConfig;\n authEnabled: boolean;\n dataApiEnabled: boolean;\n preview?: ResolvedPreviewConfig;\n}\n/**\n * One concrete change `pushConfig` made (or, in dry-run, would make) on the remote.\n */\ninterface AppliedChange {\n /**\n * `service` covers branch-scoped integrations driven by the branch policy (e.g.\n * Neon Auth, Data API).\n */\n kind: \"branch\" | \"service\";\n action: \"create\" | \"update\" | \"noop\";\n identifier: string;\n details?: Record<string, unknown>;\n}\n/**\n * A diff entry that conflicts with the desired config. `pushConfig` throws\n * {@link PushConflictError} on the first call when conflicts exist; pass\n * `updateExisting: true` to apply mutable drift (settings, `protected`, TTL, project\n * rename). Immutable fields (region, Postgres major version) are always conflicts —\n * recreate the project to change them.\n */\ninterface ConflictReport {\n kind: \"branch\";\n identifier: string;\n field: string;\n current: unknown;\n desired: unknown;\n reason: string;\n}\n/**\n * Result of a `pushConfig` invocation.\n */\ninterface PushResult {\n projectId: string;\n orgId?: string;\n branchId: string;\n branchName: string;\n /**\n * `true` when `pushConfig` was called with `{ dryRun: true }`. `applied` then records\n * what **would** be applied on a real push; no API mutations were performed.\n */\n dryRun: boolean;\n applied: AppliedChange[];\n conflicts: ConflictReport[];\n}\n//#endregion\nexport { AppliedChange, BranchTarget, BranchTuning, BranchTuningFn, BucketAccessLevel, BucketDef, ComputeSettings, ComputeUnit, Config, ConflictReport, DurationString, DurationUnit, FunctionDef, FunctionDevConfig, FunctionRuntime, FunctionTuning, PostgresConfig, PreviewInput, PreviewTuning, PushResult, ResolvedBranchConfig, ResolvedBucketConfig, ResolvedFunctionConfig, ResolvedPreviewConfig, ServiceToggle, ServiceToggleInput };\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;AAKgB;AAEC;AAc6B;AAOjB,KAvBxBA,WAAAA,GA8BAI,IAAa,GAAA,GAAA,GAAA,CAAA,GAAA,CAAA,GAAA,CAAA,GAAA,CAAA;AAAA;KA5BbH,YAAAA,GAmCa,GAAA,GAAA,GAAA,GAAA,GAAA,GAAA,GAAA,GAAA,GAAA;;;;;AAAkF;AAAA;;;;;;AAy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jBC,eAAeE;;;;;;;;UAQjBE,cAAAA;;YAEEP;;;;;;;UAOFQ;cACIE,QAAQP,OAAOM,MAAMF;;;;;;;;UAQzBI;;;;;;;;;;;;;;;;;;;;;;;;;QAyBFnB,cAAcD;;;aAGTQ;YACDS,cAAcC;;;KAGrBG,gCAAgCN,4BAA4BO;;IAE7DE,cAAcD;;;;;KAKbE,+BAA+BV,2BAA2BA,qCAAqCV,iBAAiBe,aAAaC,gBAAgBC;;;;;;;;;;;;;;UAcxII,oBAAoBnB,iCAAiCA,gDAAgDA,iCAAiCA,gDAAgDQ,2BAA2BA;;SAElNY;;YAEGC;;YAEAN;;WAEDG,eAAeH"}
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":["ComputeUnit","DurationUnit","DurationString","SuspendTimeoutSuggestion","TtlSuggestion","DurationField","Suggestions","NonNullable","ComputeSettings","BranchTarget","ServiceToggle","ServiceToggleInput","PostgresConfig","FunctionRuntime","FunctionDevConfig","FunctionDef","Record","CredentialScope","CredentialPrincipalType","BucketAccessLevel","BucketDef","PreviewInput","FunctionTuning","PreviewTuning","Slug","Partial","BranchTuning","FunctionSlugsOf","Preview","F","Extract","BranchTuningFn","Config","Auth","DataApi","ResolvedFunctionConfig","ResolvedBucketConfig","ResolvedPreviewConfig","ResolvedBranchConfig","AppliedChange","ConflictReport","PushResult"],"sources":["../../../../../config/dist/lib/types.d.ts"],"sourcesContent":["//#region src/lib/types.d.ts\n/**\n * Valid Neon Compute Unit values.\n * Most plans support 0.25, 0.5, 1, 2, 4, 8. Higher values may be available on Business plans.\n */\ntype ComputeUnit = 0.25 | 0.5 | 1 | 2 | 4 | 8;\n/** Time units accepted in a {@link DurationString}: seconds, minutes, hours, days, weeks. */\ntype DurationUnit = \"s\" | \"m\" | \"h\" | \"d\" | \"w\";\n/**\n * A Neon duration string: a positive integer **followed by a unit** — `s` (seconds),\n * `m` (minutes), `h` (hours), `d` (days), or `w` (weeks). Used by\n * {@link ComputeSettings.suspendTimeout} and {@link BranchTuning.ttl}.\n *\n * A **unit is required**: a bare numeric string like `\"7\"` is rejected at the type level. To\n * express a raw number of seconds, pass a `number` (`300`) — not a string (`\"300\"`). This\n * removes the old ambiguity where `\"7\"` silently meant 7 *seconds* instead of, say, `\"7d\"`.\n *\n * @example \"5m\" // 5 minutes\n * @example \"1h\" // 1 hour\n * @example \"7d\" // 7 days\n */\ntype DurationString = `${number}${DurationUnit}`;\n/**\n * Autocomplete suggestions for {@link ComputeSettings.suspendTimeout}. Every value sits inside\n * the Neon API's allowed scale-to-zero band: **60s–604800s** (1 minute – 1 week). This is *not*\n * a closed set — the field also accepts any other {@link DurationString} or a `number` of\n * seconds; out-of-range values type-check but are rejected at apply time.\n */\ntype SuspendTimeoutSuggestion = \"1m\" | \"5m\" | \"15m\" | \"30m\" | \"1h\" | \"6h\" | \"12h\" | \"1d\" | \"7d\";\n/**\n * Autocomplete suggestions for {@link BranchTuning.ttl}. Every value sits within the Neon API's\n * branch-expiration limit (**max 30 days** from creation; the Console's own presets are 1h / 1d\n * / 7d). This is *not* a closed set — the field also accepts any other {@link DurationString} or\n * a `number` of seconds; values over 30 days are rejected at apply time.\n */\ntype TtlSuggestion = \"1h\" | \"6h\" | \"12h\" | \"1d\" | \"3d\" | \"7d\" | \"14d\" | \"30d\";\n/**\n * Compose a field's duration type: its curated autocomplete `Suggestions` plus the open\n * `DurationString` template (so any `<integer><unit>` string still type-checks) and a `number`\n * of seconds. Intersecting the template arm with `NonNullable<unknown>` stops TypeScript from\n * collapsing the literal suggestions into the template, which is what preserves the autocomplete.\n */\ntype DurationField<Suggestions extends DurationString> = Suggestions | (DurationString & NonNullable<unknown>) | number;\n/**\n * Compute settings applied to the read/write endpoint of a branch.\n *\n * Mirrors the subset of {@link https://api-docs.neon.tech/reference/getting-started-with-neon-api Neon endpoint}\n * fields that we expose as IaC primitives. Anything left undefined falls back to the project's\n * `default_endpoint_settings` (which themselves fall back to Neon platform defaults).\n */\ninterface ComputeSettings {\n /**\n * Minimum number of Compute Units. Set to 0.25 for true scale-to-zero.\n * @example 0.25 // scale-to-zero\n * @example 1 // always-on with 1 CU minimum\n */\n autoscalingLimitMinCu?: ComputeUnit;\n /**\n * Maximum number of Compute Units for autoscaling.\n * @example 2\n * @example 8\n */\n autoscalingLimitMaxCu?: ComputeUnit;\n /**\n * How long an idle compute waits before suspending (Neon's scale-to-zero). Accepts a\n * {@link DurationString} (autocompletes common values), a number of seconds, or `false`.\n *\n * - `false` — never suspend (always-on compute)\n * - {@link DurationString} — e.g. `\"5m\"`; autocompletes the in-range values `\"1m\"`, `\"5m\"`,\n * `\"15m\"`, `\"30m\"`, `\"1h\"`, `\"6h\"`, `\"12h\"`, `\"1d\"`, `\"7d\"`, and accepts any other\n * `<integer><unit>` (units: `s`, `m`, `h`, `d`, `w`). A **unit is required** — for raw\n * seconds pass a `number`, not a string.\n * - `number` — custom timeout in **seconds**, must be in `60`–`604800` (1 minute to 1 week)\n * - `undefined` — use the Neon platform default (currently 300s / 5 minutes)\n *\n * Whichever form you use, the resolved timeout must fall in `60`–`604800` seconds (the Neon\n * API limit); the suggestions are all within that band, anything else is checked at apply.\n *\n * @example false // never suspend (always-on)\n * @example \"5m\" // suspend after 5 minutes idle\n * @example \"1h\" // suspend after 1 hour idle\n * @example 300 // 5 minutes, expressed in seconds\n */\n suspendTimeout?: false | DurationField<SuspendTimeoutSuggestion>;\n}\n/**\n * Read-only descriptor of the branch a {@link Config} policy is being evaluated for — the\n * `branch` argument passed to your `defineConfig((branch) => …)` callback. It describes\n * **which** branch this invocation decides for; it is not a live branch handle and must not\n * be mutated. Switch on its fields and return the desired {@link BranchConfig}.\n */\ninterface BranchTarget {\n /** Branch name being evaluated. For `branch dev`, this is the generated branch name. */\n name: string;\n /** Neon branch id when the branch already exists. Undefined during pre-create eval. */\n id?: string;\n /** Whether this branch already exists on Neon. */\n exists: boolean;\n /** Parent branch id from Neon when known. */\n parentId?: string;\n /** Whether Neon marks this branch as the project default. */\n isDefault?: boolean;\n /** Whether Neon currently marks this branch protected. */\n isProtected?: boolean;\n /** Current expiration timestamp from Neon, when set. */\n expiresAt?: string;\n}\n/**\n * Object form of a branch-scoped service toggle. `{}` or `{ enabled: true }` enables it;\n * `{ enabled: false }` opts out. Used as the object half of {@link ServiceToggleInput}.\n */\ninterface ServiceToggle {\n /** Defaults to `true` when the service namespace is present. Set `false` to opt out. */\n enabled?: boolean;\n}\n/**\n * How a branch-scoped service (Neon Auth, Data API, AI Gateway) is toggled in a policy.\n *\n * - `true` / `{}` / `{ enabled: true }` — enabled.\n * - `false` / `{ enabled: false }` — disabled.\n * - omitted (`undefined`) — not part of the policy at all.\n *\n * These toggles are **static** (they live in the top-level `defineConfig({ … })` object,\n * not in the per-branch `branch` closure) so the secret set they imply can be derived at\n * the type level — that's what makes `NeonEnv<typeof config>` exact.\n */\ntype ServiceToggleInput = boolean | ServiceToggle;\ninterface PostgresConfig {\n computeSettings?: ComputeSettings;\n}\n/**\n * Supported function runtimes. Mirrors the Neon Functions deploy API `runtime` enum.\n * Only `nodejs24` exists today; kept as a union so adding runtimes later is a\n * non-breaking, type-checked change.\n */\ntype FunctionRuntime = \"nodejs24\";\n/**\n * Local-development settings for a function, used by `neon dev` when it serves every\n * function declared in `neon.ts` (i.e. invoked with no `--source`). Never affects deploy.\n */\ninterface FunctionDevConfig {\n /**\n * Port the local server binds. Bound exactly (and `neon dev` fails loudly if it is taken)\n * when set; a free port is found automatically when omitted.\n */\n port?: number;\n}\n/**\n * Static definition of a Neon Function (Preview feature). Declares that the function\n * **exists** on every branch; its branch-unique slug is the **record key** in\n * {@link PreviewInput.functions} (not a field here), so slugs are statically enumerable,\n * cannot duplicate, and the `branch` closure can only tune slugs that are declared here.\n *\n * A function is invoked like a Cloudflare/Vercel handler — its source module\n * `export default { fetch }` or `export async function handler(req): Response`. The\n * `source` path is bundled (esbuild) and uploaded as a deployment; the newest deployment\n * becomes active.\n *\n * Runtime tuning is **not** here — it varies per branch and lives in the `branch` closure\n * (see {@link FunctionTuning}). Memory is fixed by the platform policy for now and is not\n * user-configurable.\n */\ninterface FunctionDef {\n /** Free-form display name. @example \"Hello World\" */\n name: string;\n /**\n * Path to the function's entry module, **relative to `neon.ts`** (or absolute). The\n * module's default export (`{ fetch }`) or `handler` export is the function entry. This\n * path is resolved against the loaded `neon.ts` location and bundled with esbuild at\n * deploy time.\n *\n * We require a string path rather than an imported handler because a JS function value\n * carries no reference back to its source file, so esbuild has nothing to bundle from.\n * @example \"./functions/hello-world.ts\"\n */\n source: string;\n /**\n * Environment variables injected into the deployed function, keyed by the var name the\n * function reads at runtime. The **keys** are static (preserved at the type level so\n * `parseEnv(config, \"<slug>\").function.<key>` is typed); the **values** are arbitrary\n * strings evaluated when `neon.ts` is loaded (typically `process.env.X`) and uploaded\n * at `config apply`. Every value must be a defined string — a `process.env.X` that is\n * `undefined` (unset) errors at validation time rather than silently shipping\n * `undefined`.\n * @example { resendApiKey: process.env.RESEND_API_KEY ?? \"\" }\n */\n env?: Record<string, string>;\n /**\n * Local-development settings used by `neon dev` when serving every function from\n * `neon.ts`. Ignored at deploy time. See {@link FunctionDevConfig}.\n */\n dev?: FunctionDevConfig;\n}\n/**\n * A single capability a branch-scoped service credential may exercise (Preview). A\n * credential is granted a set of these and may only perform the listed actions. Mirrors\n * the Neon API `CredentialScope` enum (`x-stability-level: beta`):\n *\n * - `storage:read` / `storage:write` — object-storage (bucket) access via the S3 key.\n * - `ai_gateway:invoke` — call the AI Gateway with the bearer `api_token`.\n * - `functions:invoke` — invoke Neon Functions with the bearer `api_token`.\n *\n * The set a policy needs is derived from its enabled Preview features (see\n * {@link deriveCredentialScopes}); it is never authored by hand.\n */\ntype CredentialScope = \"storage:read\" | \"storage:write\" | \"ai_gateway:invoke\" | \"functions:invoke\";\n/**\n * Who a credential acts as. `user` is the developer/app principal minted for local dev and\n * app bootstrap (`fetchEnv` / `env pull`); `function` is a deployed-function principal\n * (carries a `function_id`). The env tooling only mints `user` credentials today.\n */\ntype CredentialPrincipalType = \"user\" | \"function\";\n/** Anonymous-access level for a branchable object-storage bucket. */\ntype BucketAccessLevel = \"private\" | \"public_read\";\n/**\n * Static definition of a branchable object-storage bucket (Preview feature). The bucket's\n * name is the **record key** in {@link PreviewInput.buckets}, so names are statically\n * enumerable and cannot duplicate.\n */\ninterface BucketDef {\n /**\n * Anonymous access level. `private` (default) requires authenticated reads/writes;\n * `public_read` allows anonymous GetObject/HeadObject.\n */\n access?: BucketAccessLevel;\n}\n/**\n * Static, branch-scoped **Preview** features. Grouped under `preview` to signal they are\n * backed by Neon `x-stability-level: beta` endpoints and may change before GA. Everything\n * here is existential (it determines what exists on the branch); per-branch tuning lives in\n * the `branch` closure.\n */\ninterface PreviewInput {\n /** Enable/disable the AI Gateway on the branch (toggle, like auth / dataApi). */\n aiGateway?: ServiceToggleInput;\n /** Functions to deploy, keyed by branch-unique slug (`^[a-z0-9]{1,20}$`). */\n functions?: Record<string, FunctionDef>;\n /** Object-storage buckets to create, keyed by bucket name. */\n buckets?: Record<string, BucketDef>;\n}\n/**\n * Per-branch deploy tuning for a single function. Returned (per slug) by the `branch`\n * closure. Deliberately **cannot** change the function's existence, source, name, env\n * **keys**, or memory — only runtime selection is currently configurable — so the static\n * secret/function set stays sound.\n */\ninterface FunctionTuning {\n /** Runtime to execute the function with. Defaults to `\"nodejs24\"`. */\n runtime?: FunctionRuntime;\n}\n/**\n * Per-branch tuning of Preview features. Only existing function slugs (those declared in\n * the static {@link PreviewInput.functions}) may be tuned — `Slug` is constrained to the\n * declared keys by {@link BranchTuningFn}.\n */\ninterface PreviewTuning<Slug extends string = string> {\n functions?: Partial<Record<Slug, FunctionTuning>>;\n}\n/**\n * The per-branch tuning object returned by the `branch` closure. It can adjust branch\n * lifecycle (`parent`, `ttl`, `protected`), Postgres compute settings, and per-function\n * deploy tuning — but **cannot** add/remove services or functions. That guarantee is what\n * keeps the static secret set (and therefore `NeonEnv`) exact.\n */\ninterface BranchTuning<Slug extends string = string> {\n /** Parent branch name used when creating a new branch. Not a Postgres setting. */\n parent?: string;\n /**\n * Branch time-to-live: how long after creation the branch should auto-expire. Applied\n * when creating a new branch and reconciled on existing branches (when `updateExisting`\n * is set). Accepts a {@link DurationString} (autocompletes common values) or a number of\n * seconds. Omit to keep the branch indefinitely.\n *\n * - {@link DurationString} — e.g. `\"7d\"`; autocompletes `\"1h\"`, `\"6h\"`, `\"12h\"`, `\"1d\"`,\n * `\"3d\"`, `\"7d\"`, `\"14d\"`, `\"30d\"`, and accepts any other `<integer><unit>` (units: `s`,\n * `m`, `h`, `d`, `w` — e.g. `\"12h\"`, `\"2w\"`). A **unit is required** — `\"7\"` is rejected;\n * for raw seconds pass a `number`.\n * - `number` — custom TTL in **seconds** (e.g. `3600`)\n * - `undefined` — no expiry; the branch persists until explicitly deleted\n *\n * The Neon API caps branch expiration at **30 days** from creation, so the resolved TTL must\n * be `> 0` and `<= 30d`; the suggestions stay within that limit and anything longer is\n * rejected at apply.\n *\n * @example \"1d\" // ephemeral preview branch: expires a day after creation\n * @example \"7d\" // one-week TTL\n * @example \"30d\" // the maximum the API allows\n * @example 3600 // 1 hour, expressed in seconds\n */\n ttl?: DurationField<TtlSuggestion>;\n /** Whether the selected branch should be protected. Undefined means \"leave as-is\". */\n protected?: boolean;\n postgres?: PostgresConfig;\n preview?: PreviewTuning<Slug>;\n}\n/** Extract the declared function slugs from a {@link PreviewInput} for closure typing. */\ntype FunctionSlugsOf<Preview extends PreviewInput | undefined> = Preview extends {\n functions: infer F;\n} ? Extract<keyof F, string> : string;\n/**\n * Signature of the `branch` closure. Generic over the static {@link PreviewInput} so the\n * `preview.functions` keys it may tune are constrained to the slugs actually declared.\n */\ntype BranchTuningFn<Preview extends PreviewInput | undefined = PreviewInput | undefined> = (branch: BranchTarget) => BranchTuning<FunctionSlugsOf<Preview>>;\n/**\n * A validated Neon branch policy — the value `defineConfig({ … })` returns and `neon.ts`\n * default-exports.\n *\n * Split into a **static** existential set (top-level `auth` / `dataApi` GA toggles plus the\n * beta `preview` block) and a **dynamic** per-branch `branch` closure for tuning. The\n * static half is what makes the secret set — and therefore `NeonEnv<typeof config>` and\n * `parseEnv` — exact; the closure can tune but never change what exists.\n *\n * Generic over the three static fields so the type system can read the exact toggle/slug\n * literals; the defaults make the bare `Config` a usable \"any policy\" type for runtime\n * function signatures.\n */\ninterface Config<Auth extends ServiceToggleInput | undefined = ServiceToggleInput | undefined, DataApi extends ServiceToggleInput | undefined = ServiceToggleInput | undefined, Preview extends PreviewInput | undefined = PreviewInput | undefined> {\n /** Neon Auth integration toggle (GA). Static — drives `NeonEnv.auth`. */\n auth?: Auth;\n /** Neon Data API integration toggle (GA). Static — drives `NeonEnv.dataApi`. */\n dataApi?: DataApi;\n /** Beta (Preview) feature set: AI Gateway, functions, buckets. Static. */\n preview?: Preview;\n /** Per-branch tuning closure. Cannot change the static existential set. */\n branch?: BranchTuningFn<Preview>;\n}\n/**\n * A function with all deploy defaults applied. `resolveConfig` fills in `runtime` so\n * downstream diff/apply never has to re-derive it.\n */\ninterface ResolvedFunctionConfig {\n slug: string;\n name: string;\n source: string;\n env: Record<string, string>;\n runtime: FunctionRuntime;\n /**\n * Local-development settings, passed through untouched from {@link FunctionDef.dev}\n * (no defaults applied). Only consumed by `neon dev`; deploy ignores it.\n */\n dev?: FunctionDevConfig;\n}\n/** A bucket with its access level defaulted to `private`. */\ninterface ResolvedBucketConfig {\n name: string;\n access: BucketAccessLevel;\n}\n/**\n * Normalized {@link PreviewInput}. Only present on {@link ResolvedBranchConfig} when the\n * policy returned a `preview` block. `aiGatewayEnabled` follows the same\n * \"present-and-not-`false`\" semantics as `authEnabled` / `dataApiEnabled`.\n */\ninterface ResolvedPreviewConfig {\n functions: ResolvedFunctionConfig[];\n buckets: ResolvedBucketConfig[];\n aiGatewayEnabled: boolean;\n}\ninterface ResolvedBranchConfig {\n parent?: string;\n ttlSeconds?: number;\n protected?: boolean;\n postgres?: PostgresConfig;\n authEnabled: boolean;\n dataApiEnabled: boolean;\n preview?: ResolvedPreviewConfig;\n}\n/**\n * One concrete change `pushConfig` made (or, in dry-run, would make) on the remote.\n */\ninterface AppliedChange {\n /**\n * `service` covers branch-scoped integrations driven by the branch policy (e.g.\n * Neon Auth, Data API).\n */\n kind: \"branch\" | \"service\";\n action: \"create\" | \"update\" | \"noop\";\n identifier: string;\n details?: Record<string, unknown>;\n}\n/**\n * A diff entry that conflicts with the desired config. `pushConfig` throws\n * {@link PushConflictError} on the first call when conflicts exist; pass\n * `updateExisting: true` to apply mutable drift (settings, `protected`, TTL, project\n * rename). Immutable fields (region, Postgres major version) are always conflicts —\n * recreate the project to change them.\n */\ninterface ConflictReport {\n kind: \"branch\";\n identifier: string;\n field: string;\n current: unknown;\n desired: unknown;\n reason: string;\n}\n/**\n * Result of a `pushConfig` invocation.\n */\ninterface PushResult {\n projectId: string;\n orgId?: string;\n branchId: string;\n branchName: string;\n /**\n * `true` when `pushConfig` was called with `{ dryRun: true }`. `applied` then records\n * what **would** be applied on a real push; no API mutations were performed.\n */\n dryRun: boolean;\n applied: AppliedChange[];\n conflicts: ConflictReport[];\n}\n//#endregion\nexport { AppliedChange, BranchTarget, BranchTuning, BranchTuningFn, BucketAccessLevel, BucketDef, ComputeSettings, ComputeUnit, Config, ConflictReport, CredentialPrincipalType, CredentialScope, DurationString, DurationUnit, FunctionDef, FunctionDevConfig, FunctionRuntime, FunctionTuning, PostgresConfig, PreviewInput, PreviewTuning, PushResult, ResolvedBranchConfig, ResolvedBucketConfig, ResolvedFunctionConfig, ResolvedPreviewConfig, ServiceToggle, ServiceToggleInput };\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;AAKgB;AAEC;AAc6B;AAOjB,KAvBxBA,WAAAA,GA8BAI,IAAa,GAAA,GAAA,GAAA,CAAA,GAAA,CAAA,GAAA,CAAA,GAAA,CAAA;AAAA;KA5BbH,YAAAA,GAmCa,GAAA,GAAA,GAAA,GAAA,GAAA,GAAA,GAAA,GAAA,GAAA;;;;;AAAkF;AAAA;;;;;;AAyC5D;A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cAEIV;;cAEAK,eAAeD;;YAEjBC,eAAeI;;;;;;;;UAQjBE,cAAAA;;YAEET;;;;;;;UAOFU;cACIE,QAAQT,OAAOQ,MAAMF;;;;;;;;UAQzBI;;;;;;;;;;;;;;;;;;;;;;;;;QAyBFrB,cAAcD;;;aAGTQ;YACDW,cAAcC;;;KAGrBG,gCAAgCN,4BAA4BO;;IAE7DE,cAAcD;;;;;KAKbE,+BAA+BV,2BAA2BA,qCAAqCZ,iBAAiBiB,aAAaC,gBAAgBC;;;;;;;;;;;;;;UAcxII,oBAAoBrB,iCAAiCA,gDAAgDA,iCAAiCA,gDAAgDU,2BAA2BA;;SAElNY;;YAEGC;;YAEAN;;WAEDG,eAAeH"}
|
package/dist/config/dist/v1.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BranchTarget, BranchTuning, BranchTuningFn, BucketAccessLevel, BucketDef, ComputeSettings, ComputeUnit, Config, DurationString, DurationUnit, FunctionDef, FunctionDevConfig, FunctionRuntime, FunctionTuning, PostgresConfig, PreviewInput, PreviewTuning, ServiceToggle, ServiceToggleInput } from "./lib/types.js";
|
|
2
|
-
import { CreateBranchInput, CreateBucketInput, CreateProjectInput, DeployFunctionInput, GetConnectionUriInput, NeonApi, NeonAuthSnapshot, NeonBranchSnapshot, NeonBucketSnapshot, NeonDataApiSnapshot, NeonDatabaseSnapshot, NeonEndpointSnapshot, NeonFunctionDeploymentSnapshot, NeonFunctionSnapshot, NeonProjectSnapshot, NeonRoleSnapshot, UpdateBranchInput } from "./lib/neon-api.js";
|
|
1
|
+
import { BranchTarget, BranchTuning, BranchTuningFn, BucketAccessLevel, BucketDef, ComputeSettings, ComputeUnit, Config, CredentialPrincipalType, CredentialScope, DurationString, DurationUnit, FunctionDef, FunctionDevConfig, FunctionRuntime, FunctionTuning, PostgresConfig, PreviewInput, PreviewTuning, ServiceToggle, ServiceToggleInput } from "./lib/types.js";
|
|
2
|
+
import { CreateBranchInput, CreateBucketInput, CreateCredentialInput, CreateProjectInput, DeployFunctionInput, GetConnectionUriInput, NeonApi, NeonAuthSnapshot, NeonBranchSnapshot, NeonBranchStorageSnapshot, NeonBucketSnapshot, NeonCredentialMeta, NeonCredentialSecret, NeonDataApiSnapshot, NeonDatabaseSnapshot, NeonEndpointSnapshot, NeonFunctionDeploymentSnapshot, NeonFunctionSnapshot, NeonProjectSnapshot, NeonRoleSnapshot, UpdateBranchInput } from "./lib/neon-api.js";
|
|
3
3
|
import "zod";
|
|
4
4
|
export {};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { FetchEnvOptions, FunctionSlugOf, NEON_ENV_VAR_KEYS, NeonAuthEnv, NeonDataApiEnv, NeonEnv, NeonFunctionEnv, NeonPostgresEnv, fetchEnv, parseEnv, toEntries } from "./lib/env.js";
|
|
2
|
-
export { FetchEnvOptions, FunctionSlugOf, NEON_ENV_VAR_KEYS, NeonAuthEnv, NeonDataApiEnv, NeonEnv, NeonFunctionEnv, NeonPostgresEnv, fetchEnv, parseEnv, toEntries };
|
|
1
|
+
import { FetchEnvOptions, FunctionSlugOf, NEON_ENV_VAR_KEYS, NeonAiGatewayEnv, NeonAuthEnv, NeonDataApiEnv, NeonEnv, NeonFunctionEnv, NeonPostgresEnv, NeonStorageEnv, fetchEnv, parseEnv, toEntries } from "./lib/env.js";
|
|
2
|
+
export { FetchEnvOptions, FunctionSlugOf, NEON_ENV_VAR_KEYS, NeonAiGatewayEnv, NeonAuthEnv, NeonDataApiEnv, NeonEnv, NeonFunctionEnv, NeonPostgresEnv, NeonStorageEnv, fetchEnv, parseEnv, toEntries };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commands.js","names":[],"sources":["../../../src/lib/cli/commands.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport {\n\tConfigLoadError,\n\tErrorCode,\n\tloadConfigFromFile,\n\tMissingContextError,\n\ttype NeonApi,\n\tPlatformError,\n} from \"@neondatabase/config/v1\";\nimport { fetchEnv, toEntries } from \"../env.js\";\nimport { resolveContext } from \"./resolve-context.js\";\n\n/** File `env run` reads to layer one-time auth keys. Matches the Vercel/Next.js convention. */\nconst DEFAULT_ENV_FILE = \".env.local\";\n\n/**\n * Cross-cutting environment a CLI command is allowed to touch. Injected so tests can drive\n * the handler with a custom NeonApi and a controlled `cwd` without spawning child\n * processes.\n */\nexport interface CommandEnv {\n\tcwd: string;\n\t/**\n\t * When set, used directly as the NeonApi. When omitted, the real adapter is built from\n\t * `options.apiKey ?? NEON_API_KEY` inside `fetchEnv`.\n\t */\n\tapi?: NeonApi;\n}\n\nexport interface CommandResult {\n\t/** Process exit code. `0` for success, non-zero for failure. */\n\texitCode: number;\n\t/** Text intended for stdout. */\n\tstdout: string;\n\t/** Text intended for stderr (human-readable status / error messages). */\n\tstderr: string;\n\t/** Optional structured debug payload — printed only when `--debug` is passed. */\n\tdebugInfo?: string;\n}\n\n/**\n * Inputs needed to resolve a branch and fetch its env, shared by `run` and `export`: an\n * optional explicit `neon.ts` path, project/branch overrides, and an API key (otherwise\n * resolved from `.neon` / `NEON_*` env by the CLI and `NEON_API_KEY` by `fetchEnv`).\n */\nexport interface EnvResolveOptions {\n\tconfigPath?: string;\n\tprojectId?: string;\n\tbranch?: string;\n\tapiKey?: string;\n}\n\nexport interface EnvRunCommandOptions extends EnvResolveOptions {\n\t/** The user command to spawn (after `--`). The first element is the executable. */\n\tcommand: string[];\n}\n\n/**\n * Implementation of `neon-env run -- <cmd...>`. Loads `neon.ts`, fetches the env from\n * Neon, then spawns the user-supplied command with the env vars injected on top of the\n * inherited `process.env`. Stdio is inherited so interactive dev servers keep working.\n * The parent process exits with the child's exit code.\n */\nexport async function runEnvRun(\n\toptions: EnvRunCommandOptions,\n\tctx: CommandEnv,\n): Promise<CommandResult> {\n\tif (options.command.length === 0) {\n\t\treturn failure(\n\t\t\t[\n\t\t\t\t\"`env run` requires a command to spawn.\",\n\t\t\t\t\"Usage: neon-env run -- <command> [args...]\",\n\t\t\t\t\"Example: neon-env run -- npm run dev\",\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n\n\t// The CLI owns project/branch resolution (flags → NEON_* env → .neon file) so the\n\t// library functions stay filesystem/env-agnostic.\n\tconst resolved = resolveContext({\n\t\tcwd: ctx.cwd,\n\t\t...(options.projectId ? { projectId: options.projectId } : {}),\n\t\t...(options.branch ? { branch: options.branch } : {}),\n\t});\n\tif (!resolved.ok) {\n\t\treturn failure(\n\t\t\t[\n\t\t\t\t\"`env run` could not resolve the Neon project and branch:\",\n\t\t\t\t...resolved.missing.map((m) => ` - ${m}`),\n\t\t\t].join(\"\\n\"),\n\t\t\t3,\n\t\t);\n\t}\n\n\tlet injected: Record<string, string>;\n\ttry {\n\t\tconst env = await loadConfigAndFetchEnv(options, ctx, resolved.context);\n\t\tinjected = toEntries(env);\n\t} catch (err) {\n\t\treturn handleError(err);\n\t}\n\n\tconst [executable, ...args] = options.command;\n\tconst exitCode = await spawnAndWait(executable, args, {\n\t\tcwd: ctx.cwd,\n\t\tenv: { ...process.env, ...injected },\n\t});\n\treturn { exitCode, stdout: \"\", stderr: \"\" };\n}\n\nexport interface EnvExportCommandOptions extends EnvResolveOptions {\n\t/** Output format. `dotenv` (KEY=value lines) by default; `json` for tooling / bulk loaders. */\n\tformat?: \"dotenv\" | \"json\";\n}\n\n/**\n * Implementation of `neon-env export`. Resolves the branch's Neon env the same way `run`\n * does (neon.ts policy + linked branch), then writes it to stdout — as dotenv lines or JSON —\n * instead of spawning a process, so other env tools can consume it. For example, varlock can\n * bulk-load it with `@setValuesBulk(exec(\"neon-env export --format json\"), format=json)`.\n */\nexport async function runEnvExport(\n\toptions: EnvExportCommandOptions,\n\tctx: CommandEnv,\n): Promise<CommandResult> {\n\tconst resolved = resolveContext({\n\t\tcwd: ctx.cwd,\n\t\t...(options.projectId ? { projectId: options.projectId } : {}),\n\t\t...(options.branch ? { branch: options.branch } : {}),\n\t});\n\tif (!resolved.ok) {\n\t\treturn failure(\n\t\t\t[\n\t\t\t\t\"`env export` could not resolve the Neon project and branch:\",\n\t\t\t\t...resolved.missing.map((m) => ` - ${m}`),\n\t\t\t].join(\"\\n\"),\n\t\t\t3,\n\t\t);\n\t}\n\n\tlet entries: Record<string, string>;\n\ttry {\n\t\tconst env = await loadConfigAndFetchEnv(options, ctx, resolved.context);\n\t\tentries = toEntries(env);\n\t} catch (err) {\n\t\treturn handleError(err);\n\t}\n\n\tconst stdout =\n\t\toptions.format === \"json\"\n\t\t\t? `${JSON.stringify(entries, null, 2)}\\n`\n\t\t\t: toDotenv(entries);\n\treturn { exitCode: 0, stdout, stderr: \"\" };\n}\n\n/** Render an env map as dotenv `KEY=value` lines, quoting values that need it. */\nfunction toDotenv(entries: Record<string, string>): string {\n\tconst lines = Object.entries(entries).map(([key, value]) =>\n\t\tformatDotenvLine(key, value),\n\t);\n\treturn lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\";\n}\n\n/**\n * Render a single `KEY=value` dotenv line, double-quoting (and escaping) values that contain\n * whitespace, `#`, quotes, or `=` so connection strings round-trip through dotenv parsers.\n */\nfunction formatDotenvLine(key: string, value: string): string {\n\tif (!/[\\s#\"'=]/.test(value)) return `${key}=${value}`;\n\tconst escaped = value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n\treturn `${key}=\"${escaped}\"`;\n}\n\n/**\n * Load `neon.ts`, then call `fetchEnv` with the explicitly-resolved project + branch.\n * Layers any one-time Auth keys from `.env.local` (next to the config file) into the env\n * source so re-runs keep round-tripping values the Neon API only returns once at\n * integration-creation time.\n */\nasync function loadConfigAndFetchEnv(\n\toptions: EnvResolveOptions,\n\tctx: CommandEnv,\n\tresolved: { projectId: string; branchId: string },\n): Promise<Awaited<ReturnType<typeof fetchEnv>>> {\n\tconst { config, resolvedPath } = await loadConfigFromFile({\n\t\t...(options.configPath ? { path: options.configPath } : {}),\n\t\tcwd: ctx.cwd,\n\t});\n\tconst envFileSource = join(dirname(resolvedPath), DEFAULT_ENV_FILE);\n\tconst fileEnv = existsSync(envFileSource)\n\t\t? parseEnvFile(readFileSync(envFileSource, \"utf-8\"))\n\t\t: {};\n\treturn fetchEnv(config, {\n\t\tprojectId: resolved.projectId,\n\t\tbranchId: resolved.branchId,\n\t\tenv: { ...process.env, ...fileEnv },\n\t\t...(ctx.api ? { api: ctx.api } : {}),\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t});\n}\n\n/**\n * Spawn a child process with stdio inherited so dev servers stay interactive. Resolves\n * with the child's exit code (treating signal terminations as code 1 so the CLI surfaces\n * a non-zero exit consistently).\n */\nfunction spawnAndWait(\n\tcommand: string,\n\targs: string[],\n\toptions: { cwd: string; env: Record<string, string | undefined> },\n): Promise<number> {\n\treturn new Promise((resolve) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd: options.cwd,\n\t\t\tenv: options.env,\n\t\t\tstdio: \"inherit\",\n\t\t});\n\t\tchild.on(\"error\", (err) => {\n\t\t\tprocess.stderr.write(\n\t\t\t\t`neon-env run: failed to spawn '${command}': ${err.message}\\n`,\n\t\t\t);\n\t\t\tresolve(1);\n\t\t});\n\t\tchild.on(\"exit\", (code, signal) => {\n\t\t\tif (typeof code === \"number\") {\n\t\t\t\tresolve(code);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (signal) {\n\t\t\t\tprocess.stderr.write(\n\t\t\t\t\t`neon-env run: child terminated by signal ${signal}\\n`,\n\t\t\t\t);\n\t\t\t\tresolve(1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve(1);\n\t\t});\n\t});\n}\n\nfunction parseEnvFile(body: string): NodeJS.ProcessEnv {\n\tconst out: NodeJS.ProcessEnv = {};\n\tfor (const line of body.split(\"\\n\")) {\n\t\tconst parsed = parseEnvLine(line);\n\t\tif (parsed) out[parsed.key] = parsed.value;\n\t}\n\treturn out;\n}\n\nfunction parseEnvLine(line: string): { key: string; value: string } | null {\n\tconst match = line.match(\n\t\t/^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*)$/,\n\t);\n\tconst key = match?.[1];\n\tconst rawValue = match?.[2];\n\tif (key === undefined || rawValue === undefined) return null;\n\treturn { key, value: unescapeEnvValue(rawValue.trim()) };\n}\n\nfunction unescapeEnvValue(value: string): string {\n\tif (value.length >= 2 && value.startsWith('\"') && value.endsWith('\"')) {\n\t\treturn value.slice(1, -1).replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\");\n\t}\n\tif (value.length >= 2 && value.startsWith(\"'\") && value.endsWith(\"'\")) {\n\t\treturn value.slice(1, -1);\n\t}\n\treturn value;\n}\n\n/**\n * Stable exit code per `PlatformError` code. Mirrors the table in the config package so\n * shell pipelines can branch on the specific failure mode without parsing free text.\n */\nconst EXIT_CODE_BY_PLATFORM_ERROR_CODE: Readonly<Record<string, number>> = {\n\t[ErrorCode.MissingApiKey]: 1,\n\t[ErrorCode.Unauthorized]: 6,\n\t[ErrorCode.Forbidden]: 7,\n\t[ErrorCode.NotFound]: 8,\n\t[ErrorCode.RateLimited]: 9,\n\t[ErrorCode.NetworkError]: 10,\n\t[ErrorCode.ServerError]: 11,\n\t[ErrorCode.Locked]: 11,\n\t[ErrorCode.InternalError]: 99,\n};\n\nfunction handleError(err: unknown): CommandResult {\n\tif (err instanceof MissingContextError)\n\t\treturn errorResult(err, `Missing context: ${err.message}`, 3);\n\tif (err instanceof ConfigLoadError)\n\t\treturn errorResult(err, `Failed to load config: ${err.message}`, 4);\n\tif (err instanceof PlatformError) {\n\t\tconst exitCode = EXIT_CODE_BY_PLATFORM_ERROR_CODE[err.code];\n\t\tif (exitCode !== undefined)\n\t\t\treturn errorResult(err, err.message, exitCode);\n\t\treturn errorResult(err, `[${err.code}] ${err.message}`, 5);\n\t}\n\tif (err instanceof Error) return errorResult(err, err.message, 1);\n\treturn failure(String(err), 1);\n}\n\nfunction errorResult(\n\terr: unknown,\n\tmessage: string,\n\texitCode: number,\n): CommandResult {\n\tconst result: CommandResult = {\n\t\texitCode,\n\t\tstdout: \"\",\n\t\tstderr: `${message}\\n`,\n\t};\n\tconst debug = buildDebugInfo(err);\n\tif (debug) result.debugInfo = debug;\n\treturn result;\n}\n\nfunction buildDebugInfo(err: unknown): string | undefined {\n\tif (!(err instanceof Error)) return undefined;\n\tconst lines: string[] = [];\n\tif (err instanceof PlatformError) {\n\t\tlines.push(`code : ${err.code}`);\n\t\tif (Object.keys(err.details).length > 0) {\n\t\t\tlines.push(`details : ${JSON.stringify(err.details, null, 2)}`);\n\t\t}\n\t}\n\tif (err.cause instanceof Error) {\n\t\tlines.push(`cause : ${err.cause.name}: ${err.cause.message}`);\n\t}\n\tif (err.stack) {\n\t\tlines.push(err.stack);\n\t}\n\treturn lines.length > 0 ? lines.join(\"\\n\") : undefined;\n}\n\nfunction failure(message: string, exitCode = 1): CommandResult {\n\treturn { exitCode, stdout: \"\", stderr: `${message}\\n` };\n}\n"],"mappings":";;;;;;;;AAeA,MAAM,mBAAmB;;;;;;;AAkDzB,eAAsB,UACrB,SACA,KACyB;CACzB,IAAI,QAAQ,QAAQ,WAAW,GAC9B,OAAO,QACN;EACC;EACA;EACA;CACD,EAAE,KAAK,IAAI,CACZ;CAKD,MAAM,WAAW,eAAe;EAC/B,KAAK,IAAI;EACT,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC5D,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;CACpD,CAAC;CACD,IAAI,CAAC,SAAS,IACb,OAAO,QACN,CACC,4DACA,GAAG,SAAS,QAAQ,KAAK,MAAM,OAAO,GAAG,CAC1C,EAAE,KAAK,IAAI,GACX,CACD;CAGD,IAAI;CACJ,IAAI;EAEH,WAAW,UAAU,MADH,sBAAsB,SAAS,KAAK,SAAS,OAAO,CAC9C;CACzB,SAAS,KA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AK,IAAI,SAAS,CAAC;CAChE,OAAO,QAAQ,OAAO,GAAG,GAAG,CAAC;AAC9B;AAEA,SAAS,YACR,KACA,SACA,UACgB;CAChB,MAAM,SAAwB;EAC7B;EACA,QAAQ;EACR,QAAQ,GAAG,QAAQ;CACpB;CACA,MAAM,QAAQ,eAAe,GAAG;CAChC,IAAI,OAAO,OAAO,YAAY;CAC9B,OAAO;AACR;AAEA,SAAS,eAAe,KAAkC;CACzD,IAAI,EAAE,eAAe,QAAQ,OAAO,KAAA;CACpC,MAAM,QAAkB,CAAC;CACzB,IAAI,eAAe,eAAe;EACjC,MAAM,KAAK,cAAc,IAAI,MAAM;EACnC,IAAI,OAAO,KAAK,IAAI,OAAO,EAAE,SAAS,GACrC,MAAM,KAAK,cAAc,KAAK,UAAU,IAAI,SAAS,MAAM,CAAC,GAAG;CAEjE;CACA,IAAI,IAAI,iBAAiB,OACxB,MAAM,KAAK,cAAc,IAAI,MAAM,KAAK,IAAI,IAAI,MAAM,SAAS;CAEhE,IAAI,IAAI,OACP,MAAM,KAAK,IAAI,KAAK;CAErB,OAAO,MAAM,SAAS,IAAI,MAAM,KAAK,IAAI,IAAI,KAAA;AAC9C;AAEA,SAAS,QAAQ,SAAiB,WAAW,GAAkB;CAC9D,OAAO;EAAE;EAAU,QAAQ;EAAI,QAAQ,GAAG,QAAQ;CAAI;AACvD"}
|
|
1
|
+
{"version":3,"file":"commands.js","names":[],"sources":["../../../src/lib/cli/commands.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport {\n\tConfigLoadError,\n\tErrorCode,\n\tloadConfigFromFile,\n\tMissingContextError,\n\ttype NeonApi,\n\tPlatformError,\n} from \"@neondatabase/config/v1\";\nimport { fetchEnv, toEntries } from \"../env.js\";\nimport { resolveContext } from \"./resolve-context.js\";\n\n/** File `env run` reads to layer one-time auth keys. Matches the Vercel/Next.js convention. */\nconst DEFAULT_ENV_FILE = \".env.local\";\n\n/**\n * Cross-cutting environment a CLI command is allowed to touch. Injected so tests can drive\n * the handler with a custom NeonApi and a controlled `cwd` without spawning child\n * processes.\n */\nexport interface CommandEnv {\n\tcwd: string;\n\t/**\n\t * When set, used directly as the NeonApi. When omitted, the real adapter is built from\n\t * `options.apiKey ?? NEON_API_KEY` inside `fetchEnv`.\n\t */\n\tapi?: NeonApi;\n}\n\nexport interface CommandResult {\n\t/** Process exit code. `0` for success, non-zero for failure. */\n\texitCode: number;\n\t/** Text intended for stdout. */\n\tstdout: string;\n\t/** Text intended for stderr (human-readable status / error messages). */\n\tstderr: string;\n\t/** Optional structured debug payload — printed only when `--debug` is passed. */\n\tdebugInfo?: string;\n}\n\n/**\n * Inputs needed to resolve a branch and fetch its env, shared by `run` and `export`: an\n * optional explicit `neon.ts` path, project/branch overrides, and an API key (otherwise\n * resolved from `.neon` / `NEON_*` env by the CLI and `NEON_API_KEY` by `fetchEnv`).\n */\nexport interface EnvResolveOptions {\n\tconfigPath?: string;\n\tprojectId?: string;\n\tbranch?: string;\n\tapiKey?: string;\n}\n\nexport interface EnvRunCommandOptions extends EnvResolveOptions {\n\t/** The user command to spawn (after `--`). The first element is the executable. */\n\tcommand: string[];\n}\n\n/**\n * Implementation of `neon-env run -- <cmd...>`. Loads `neon.ts`, fetches the env from\n * Neon, then spawns the user-supplied command with the env vars injected on top of the\n * inherited `process.env`. Stdio is inherited so interactive dev servers keep working.\n * The parent process exits with the child's exit code.\n */\nexport async function runEnvRun(\n\toptions: EnvRunCommandOptions,\n\tctx: CommandEnv,\n): Promise<CommandResult> {\n\tif (options.command.length === 0) {\n\t\treturn failure(\n\t\t\t[\n\t\t\t\t\"`env run` requires a command to spawn.\",\n\t\t\t\t\"Usage: neon-env run -- <command> [args...]\",\n\t\t\t\t\"Example: neon-env run -- npm run dev\",\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n\n\t// The CLI owns project/branch resolution (flags → NEON_* env → .neon file) so the\n\t// library functions stay filesystem/env-agnostic.\n\tconst resolved = resolveContext({\n\t\tcwd: ctx.cwd,\n\t\t...(options.projectId ? { projectId: options.projectId } : {}),\n\t\t...(options.branch ? { branch: options.branch } : {}),\n\t});\n\tif (!resolved.ok) {\n\t\treturn failure(\n\t\t\t[\n\t\t\t\t\"`env run` could not resolve the Neon project and branch:\",\n\t\t\t\t...resolved.missing.map((m) => ` - ${m}`),\n\t\t\t].join(\"\\n\"),\n\t\t\t3,\n\t\t);\n\t}\n\n\tlet injected: Record<string, string>;\n\ttry {\n\t\tconst env = await loadConfigAndFetchEnv(options, ctx, resolved.context);\n\t\tinjected = toEntries(env);\n\t} catch (err) {\n\t\treturn handleError(err);\n\t}\n\n\tconst [executable, ...args] = options.command;\n\tconst exitCode = await spawnAndWait(executable, args, {\n\t\tcwd: ctx.cwd,\n\t\tenv: { ...process.env, ...injected },\n\t});\n\treturn { exitCode, stdout: \"\", stderr: \"\" };\n}\n\nexport interface EnvExportCommandOptions extends EnvResolveOptions {\n\t/** Output format. `dotenv` (KEY=value lines) by default; `json` for tooling / bulk loaders. */\n\tformat?: \"dotenv\" | \"json\";\n}\n\n/**\n * Implementation of `neon-env export`. Resolves the branch's Neon env the same way `run`\n * does (neon.ts policy + linked branch), then writes it to stdout — as dotenv lines or JSON —\n * instead of spawning a process, so other env tools can consume it. For example, varlock can\n * bulk-load it with `@setValuesBulk(exec(\"neon-env export --format json\"), format=json)`.\n */\nexport async function runEnvExport(\n\toptions: EnvExportCommandOptions,\n\tctx: CommandEnv,\n): Promise<CommandResult> {\n\tconst resolved = resolveContext({\n\t\tcwd: ctx.cwd,\n\t\t...(options.projectId ? { projectId: options.projectId } : {}),\n\t\t...(options.branch ? { branch: options.branch } : {}),\n\t});\n\tif (!resolved.ok) {\n\t\treturn failure(\n\t\t\t[\n\t\t\t\t\"`env export` could not resolve the Neon project and branch:\",\n\t\t\t\t...resolved.missing.map((m) => ` - ${m}`),\n\t\t\t].join(\"\\n\"),\n\t\t\t3,\n\t\t);\n\t}\n\n\tlet entries: Record<string, string>;\n\ttry {\n\t\tconst env = await loadConfigAndFetchEnv(options, ctx, resolved.context);\n\t\tentries = toEntries(env);\n\t} catch (err) {\n\t\treturn handleError(err);\n\t}\n\n\tconst stdout =\n\t\toptions.format === \"json\"\n\t\t\t? `${JSON.stringify(entries, null, 2)}\\n`\n\t\t\t: toDotenv(entries);\n\treturn { exitCode: 0, stdout, stderr: \"\" };\n}\n\n/** Render an env map as dotenv `KEY=value` lines, quoting values that need it. */\nfunction toDotenv(entries: Record<string, string>): string {\n\tconst lines = Object.entries(entries).map(([key, value]) =>\n\t\tformatDotenvLine(key, value),\n\t);\n\treturn lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\";\n}\n\n/**\n * Render a single `KEY=value` dotenv line, double-quoting (and escaping) values that contain\n * whitespace, `#`, quotes, or `=` so connection strings round-trip through dotenv parsers.\n */\nfunction formatDotenvLine(key: string, value: string): string {\n\tif (!/[\\s#\"'=]/.test(value)) return `${key}=${value}`;\n\tconst escaped = value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n\treturn `${key}=\"${escaped}\"`;\n}\n\n/**\n * Load `neon.ts`, then call `fetchEnv` with the explicitly-resolved project + branch.\n * Layers any one-time Auth keys from `.env.local` (next to the config file) into the env\n * source so re-runs keep round-tripping values the Neon API only returns once at\n * integration-creation time.\n */\nasync function loadConfigAndFetchEnv(\n\toptions: EnvResolveOptions,\n\tctx: CommandEnv,\n\tresolved: { projectId: string; branchId: string },\n): Promise<Awaited<ReturnType<typeof fetchEnv>>> {\n\tconst { config, resolvedPath } = await loadConfigFromFile({\n\t\t...(options.configPath ? { path: options.configPath } : {}),\n\t\tcwd: ctx.cwd,\n\t});\n\tconst envFileSource = join(dirname(resolvedPath), DEFAULT_ENV_FILE);\n\tconst fileEnv = existsSync(envFileSource)\n\t\t? parseEnvFile(readFileSync(envFileSource, \"utf-8\"))\n\t\t: {};\n\treturn fetchEnv(config, {\n\t\tprojectId: resolved.projectId,\n\t\tbranchId: resolved.branchId,\n\t\tenv: { ...process.env, ...fileEnv },\n\t\t...(ctx.api ? { api: ctx.api } : {}),\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t});\n}\n\n/**\n * Spawn a child process with stdio inherited so dev servers stay interactive. Resolves\n * with the child's exit code (treating signal terminations as code 1 so the CLI surfaces\n * a non-zero exit consistently).\n */\nfunction spawnAndWait(\n\tcommand: string,\n\targs: string[],\n\toptions: { cwd: string; env: Record<string, string | undefined> },\n): Promise<number> {\n\treturn new Promise((resolve) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd: options.cwd,\n\t\t\tenv: options.env,\n\t\t\tstdio: \"inherit\",\n\t\t});\n\t\tchild.on(\"error\", (err) => {\n\t\t\tprocess.stderr.write(\n\t\t\t\t`neon-env run: failed to spawn '${command}': ${err.message}\\n`,\n\t\t\t);\n\t\t\tresolve(1);\n\t\t});\n\t\tchild.on(\"exit\", (code, signal) => {\n\t\t\tif (typeof code === \"number\") {\n\t\t\t\tresolve(code);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (signal) {\n\t\t\t\tprocess.stderr.write(\n\t\t\t\t\t`neon-env run: child terminated by signal ${signal}\\n`,\n\t\t\t\t);\n\t\t\t\tresolve(1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve(1);\n\t\t});\n\t});\n}\n\nfunction parseEnvFile(body: string): NodeJS.ProcessEnv {\n\tconst out: NodeJS.ProcessEnv = {};\n\tfor (const line of body.split(\"\\n\")) {\n\t\tconst parsed = parseEnvLine(line);\n\t\tif (parsed) out[parsed.key] = parsed.value;\n\t}\n\treturn out;\n}\n\nfunction parseEnvLine(line: string): { key: string; value: string } | null {\n\tconst match = line.match(\n\t\t/^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*)$/,\n\t);\n\tconst key = match?.[1];\n\tconst rawValue = match?.[2];\n\tif (key === undefined || rawValue === undefined) return null;\n\treturn { key, value: unescapeEnvValue(rawValue.trim()) };\n}\n\nfunction unescapeEnvValue(value: string): string {\n\tif (value.length >= 2 && value.startsWith('\"') && value.endsWith('\"')) {\n\t\treturn value.slice(1, -1).replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\");\n\t}\n\tif (value.length >= 2 && value.startsWith(\"'\") && value.endsWith(\"'\")) {\n\t\treturn value.slice(1, -1);\n\t}\n\treturn value;\n}\n\n/**\n * Stable exit code per `PlatformError` code. Mirrors the table in the config package so\n * shell pipelines can branch on the specific failure mode without parsing free text.\n */\nconst EXIT_CODE_BY_PLATFORM_ERROR_CODE: Readonly<Record<string, number>> = {\n\t[ErrorCode.MissingApiKey]: 1,\n\t[ErrorCode.Unauthorized]: 6,\n\t[ErrorCode.Forbidden]: 7,\n\t[ErrorCode.NotFound]: 8,\n\t[ErrorCode.RateLimited]: 9,\n\t[ErrorCode.NetworkError]: 10,\n\t[ErrorCode.ServerError]: 11,\n\t[ErrorCode.Locked]: 11,\n\t[ErrorCode.InternalError]: 99,\n};\n\nfunction handleError(err: unknown): CommandResult {\n\tif (err instanceof MissingContextError)\n\t\treturn errorResult(err, `Missing context: ${err.message}`, 3);\n\tif (err instanceof ConfigLoadError)\n\t\treturn errorResult(err, `Failed to load config: ${err.message}`, 4);\n\tif (err instanceof PlatformError) {\n\t\tconst exitCode = EXIT_CODE_BY_PLATFORM_ERROR_CODE[err.code];\n\t\tif (exitCode !== undefined)\n\t\t\treturn errorResult(err, err.message, exitCode);\n\t\treturn errorResult(err, `[${err.code}] ${err.message}`, 5);\n\t}\n\tif (err instanceof Error) return errorResult(err, err.message, 1);\n\treturn failure(String(err), 1);\n}\n\nfunction errorResult(\n\terr: unknown,\n\tmessage: string,\n\texitCode: number,\n): CommandResult {\n\tconst result: CommandResult = {\n\t\texitCode,\n\t\tstdout: \"\",\n\t\tstderr: `${message}\\n`,\n\t};\n\tconst debug = buildDebugInfo(err);\n\tif (debug) result.debugInfo = debug;\n\treturn result;\n}\n\nfunction buildDebugInfo(err: unknown): string | undefined {\n\tif (!(err instanceof Error)) return undefined;\n\tconst lines: string[] = [];\n\tif (err instanceof PlatformError) {\n\t\tlines.push(`code : ${err.code}`);\n\t\tif (Object.keys(err.details).length > 0) {\n\t\t\tlines.push(`details : ${JSON.stringify(err.details, null, 2)}`);\n\t\t}\n\t}\n\tif (err.cause instanceof Error) {\n\t\tlines.push(`cause : ${err.cause.name}: ${err.cause.message}`);\n\t}\n\tif (err.stack) {\n\t\tlines.push(err.stack);\n\t}\n\treturn lines.length > 0 ? lines.join(\"\\n\") : undefined;\n}\n\nfunction failure(message: string, exitCode = 1): CommandResult {\n\treturn { exitCode, stdout: \"\", stderr: `${message}\\n` };\n}\n"],"mappings":";;;;;;;;AAeA,MAAM,mBAAmB;;;;;;;AAkDzB,eAAsB,UACrB,SACA,KACyB;CACzB,IAAI,QAAQ,QAAQ,WAAW,GAC9B,OAAO,QACN;EACC;EACA;EACA;CACD,CAAC,CAAC,KAAK,IAAI,CACZ;CAKD,MAAM,WAAW,eAAe;EAC/B,KAAK,IAAI;EACT,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC5D,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;CACpD,CAAC;CACD,IAAI,CAAC,SAAS,IACb,OAAO,QACN,CACC,4DACA,GAAG,SAAS,QAAQ,KAAK,MAAM,OAAO,GAAG,CAC1C,CAAC,CAAC,KAAK,IAAI,GACX,CACD;CAGD,IAAI;CACJ,IAAI;EAEH,WAAW,UAAU,MADH,sBAAsB,SAAS,KAAK,SAAS,OAAO,CAC9C;CACzB,SAAS,KAAK;EACb,OAAO,YAAY,GAAG;CACvB;CAEA,MAAM,CAAC,YAAY,GAAG,QAAQ,QAAQ;CAKtC,OAAO;EAAE,UAAA,MAJc,aAAa,YAAY,MAAM;GACrD,KAAK,IAAI;GACT,KAAK;IAAE,GAAG,QAAQ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EACR,QAAQ,GAAG,QAAQ;CACpB;CACA,MAAM,QAAQ,eAAe,GAAG;CAChC,IAAI,OAAO,OAAO,YAAY;CAC9B,OAAO;AACR;AAEA,SAAS,eAAe,KAAkC;CACzD,IAAI,EAAE,eAAe,QAAQ,OAAO,KAAA;CACpC,MAAM,QAAkB,CAAC;CACzB,IAAI,eAAe,eAAe;EACjC,MAAM,KAAK,cAAc,IAAI,MAAM;EACnC,IAAI,OAAO,KAAK,IAAI,OAAO,CAAC,CAAC,SAAS,GACrC,MAAM,KAAK,cAAc,KAAK,UAAU,IAAI,SAAS,MAAM,CAAC,GAAG;CAEjE;CACA,IAAI,IAAI,iBAAiB,OACxB,MAAM,KAAK,cAAc,IAAI,MAAM,KAAK,IAAI,IAAI,MAAM,SAAS;CAEhE,IAAI,IAAI,OACP,MAAM,KAAK,IAAI,KAAK;CAErB,OAAO,MAAM,SAAS,IAAI,MAAM,KAAK,IAAI,IAAI,KAAA;AAC9C;AAEA,SAAS,QAAQ,SAAiB,WAAW,GAAkB;CAC9D,OAAO;EAAE;EAAU,QAAQ;EAAI,QAAQ,GAAG,QAAQ;CAAI;AACvD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-context.js","names":[],"sources":["../../../src/lib/cli/resolve-context.ts"],"sourcesContent":["import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, resolve } from \"node:path\";\n\n/**\n * Resolved project + branch context for the `neon-env` CLI. The CLI owns this resolution\n * (flags → `NEON_*` env → `.neon[/project.json]` file) so the `@neondatabase/env` library\n * functions can stay filesystem- and env-agnostic.\n */\nexport interface ResolvedContext {\n\tprojectId: string;\n\tbranchId: string;\n}\n\nexport interface ResolveContextOptions {\n\tprojectId?: string;\n\tbranch?: string;\n\tcwd: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\n/**\n * Resolve `projectId` and `branch` for a CLI invocation. Precedence (each wins over the\n * next): explicit flag → `NEON_*` env var → `.neon[/project.json]` walked up from `cwd`.\n *\n * Returns the resolved values plus a list of human-readable reasons for any field that\n * could not be resolved (so the caller can render one combined error).\n */\nexport function resolveContext(\n\toptions: ResolveContextOptions,\n): { ok: true; context: ResolvedContext } | { ok: false; missing: string[] } {\n\tconst env = options.env ?? process.env;\n\tconst file = findNeonFile(options.cwd);\n\n\tconst projectId =\n\t\tnonEmpty(options.projectId) ??\n\t\tnonEmpty(env.NEON_PROJECT_ID) ??\n\t\tfile?.projectId;\n\n\tconst branchId =\n\t\tnonEmpty(options.branch) ??\n\t\tnonEmpty(env.NEON_BRANCH_ID) ??\n\t\tfile?.branchId;\n\n\tconst missing: string[] = [];\n\tif (!projectId) {\n\t\tmissing.push(\n\t\t\t\"project id — pass `--project-id`, set `NEON_PROJECT_ID`, or add `projectId` to `.neon/project.json` (run `npx neonctl link`).\",\n\t\t);\n\t}\n\tif (!branchId) {\n\t\tmissing.push(\n\t\t\t\"branch — pass `--branch`, set `NEON_BRANCH_ID`, or add `branchId` to `.neon/project.json` (run `npx neonctl checkout <branch>`).\",\n\t\t);\n\t}\n\tif (!projectId || !branchId) return { ok: false, missing };\n\n\treturn {\n\t\tok: true,\n\t\tcontext: { projectId, branchId },\n\t};\n}\n\ninterface NeonFile {\n\tprojectId?: string;\n\tbranchId?: string;\n}\n\n/**\n * Walk up from `cwd` looking for `.neon/project.json` (preferred) or `.neon` (neonctl\n * convention). Stops at the first `.git` directory or the home directory. Read-only.\n */\nfunction findNeonFile(cwd: string): NeonFile | null {\n\tlet current = resolve(cwd);\n\tconst stop = resolve(homedir());\n\tlet lastSeen: string | null = null;\n\n\twhile (true) {\n\t\tconst parsed =\n\t\t\treadNeonFileAt(resolve(current, \".neon\", \"project.json\")) ??\n\t\t\treadNeonFileAt(resolve(current, \".neon\"));\n\t\tif (parsed) return parsed;\n\n\t\tif (current === stop) return null;\n\t\tif (existsSync(resolve(current, \".git\"))) return null;\n\n\t\tconst parent = dirname(current);\n\t\tif (parent === current || parent === lastSeen) return null;\n\t\tlastSeen = current;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction readNeonFileAt(path: string): NeonFile | null {\n\tif (!isFile(path)) return null;\n\tlet raw: string;\n\ttry {\n\t\traw = readFileSync(path, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\treturn null;\n\tconst obj = parsed as Record<string, unknown>;\n\tconst out: NeonFile = {};\n\tif (typeof obj.projectId === \"string\" && obj.projectId !== \"\")\n\t\tout.projectId = obj.projectId;\n\tif (typeof obj.branchId === \"string\" && obj.branchId !== \"\")\n\t\tout.branchId = obj.branchId;\n\treturn out;\n}\n\nfunction isFile(path: string): boolean {\n\ttry {\n\t\treturn statSync(path).isFile();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? undefined : trimmed;\n}\n"],"mappings":";;;;;;;;;;;AA4BA,SAAgB,eACf,SAC4E;CAC5E,MAAM,MAAM,QAAQ,OAAO,QAAQ;CACnC,MAAM,OAAO,aAAa,QAAQ,GAAG;CAErC,MAAM,YACL,SAAS,QAAQ,SAAS,KAC1B,SAAS,IAAI,eAAe,KAC5B,MAAM;CAEP,MAAM,WACL,SAAS,QAAQ,MAAM,KACvB,SAAS,IAAI,cAAc,KAC3B,MAAM;CAEP,MAAM,UAAoB,CAAC;CAC3B,IAAI,CAAC,WACJ,QAAQ,KACP,+HACD;CAED,IAAI,CAAC,UACJ,QAAQ,KACP,kIACD;CAED,IAAI,CAAC,aAAa,CAAC,UAAU,OAAO;EAAE,IAAI;EAAO;CAAQ;CAEzD,OAAO;EACN,IAAI;EACJ,SAAS;GAAE;GAAW;EAAS;CAChC;AACD;;;;;AAWA,SAAS,aAAa,KAA8B;CACnD,IAAI,UAAU,QAAQ,GAAG;CACzB,MAAM,OAAO,QAAQ,QAAQ,CAAC;CAC9B,IAAI,WAA0B;CAE9B,OAAO,MAAM;EACZ,MAAM,SACL,eAAe,QAAQ,SAAS,SAAS,cAAc,CAAC,KACxD,eAAe,QAAQ,SAAS,OAAO,CAAC;EACzC,IAAI,QAAQ,OAAO;EAEnB,IAAI,YAAY,MAAM,OAAO;EAC7B,IAAI,WAAW,QAAQ,SAAS,MAAM,CAAC,GAAG,OAAO;EAEjD,MAAM,SAAS,QAAQ,OAAO;EAC9B,IAAI,WAAW,WAAW,WAAW,UAAU,OAAO;EACtD,WAAW;EACX,UAAU;CACX;AACD;AAEA,SAAS,eAAe,MAA+B;CACtD,IAAI,CAAC,OAAO,IAAI,GAAG,OAAO;CAC1B,IAAI;CACJ,IAAI;EACH,MAAM,aAAa,MAAM,OAAO;CACjC,QAAQ;EACP,OAAO;CACR;CACA,IAAI;CACJ,IAAI;EACH,SAAS,KAAK,MAAM,GAAG;CACxB,QAAQ;EACP,OAAO;CACR;CACA,IAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GACxE,OAAO;CACR,MAAM,MAAM;CACZ,MAAM,MAAgB,CAAC;CACvB,IAAI,OAAO,IAAI,cAAc,YAAY,IAAI,cAAc,IAC1D,IAAI,YAAY,IAAI;CACrB,IAAI,OAAO,IAAI,aAAa,YAAY,IAAI,aAAa,IACxD,IAAI,WAAW,IAAI;CACpB,OAAO;AACR;AAEA,SAAS,OAAO,MAAuB;CACtC,IAAI;EACH,OAAO,SAAS,IAAI,
|
|
1
|
+
{"version":3,"file":"resolve-context.js","names":[],"sources":["../../../src/lib/cli/resolve-context.ts"],"sourcesContent":["import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, resolve } from \"node:path\";\n\n/**\n * Resolved project + branch context for the `neon-env` CLI. The CLI owns this resolution\n * (flags → `NEON_*` env → `.neon[/project.json]` file) so the `@neondatabase/env` library\n * functions can stay filesystem- and env-agnostic.\n */\nexport interface ResolvedContext {\n\tprojectId: string;\n\tbranchId: string;\n}\n\nexport interface ResolveContextOptions {\n\tprojectId?: string;\n\tbranch?: string;\n\tcwd: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\n/**\n * Resolve `projectId` and `branch` for a CLI invocation. Precedence (each wins over the\n * next): explicit flag → `NEON_*` env var → `.neon[/project.json]` walked up from `cwd`.\n *\n * Returns the resolved values plus a list of human-readable reasons for any field that\n * could not be resolved (so the caller can render one combined error).\n */\nexport function resolveContext(\n\toptions: ResolveContextOptions,\n): { ok: true; context: ResolvedContext } | { ok: false; missing: string[] } {\n\tconst env = options.env ?? process.env;\n\tconst file = findNeonFile(options.cwd);\n\n\tconst projectId =\n\t\tnonEmpty(options.projectId) ??\n\t\tnonEmpty(env.NEON_PROJECT_ID) ??\n\t\tfile?.projectId;\n\n\tconst branchId =\n\t\tnonEmpty(options.branch) ??\n\t\tnonEmpty(env.NEON_BRANCH_ID) ??\n\t\tfile?.branchId;\n\n\tconst missing: string[] = [];\n\tif (!projectId) {\n\t\tmissing.push(\n\t\t\t\"project id — pass `--project-id`, set `NEON_PROJECT_ID`, or add `projectId` to `.neon/project.json` (run `npx neonctl link`).\",\n\t\t);\n\t}\n\tif (!branchId) {\n\t\tmissing.push(\n\t\t\t\"branch — pass `--branch`, set `NEON_BRANCH_ID`, or add `branchId` to `.neon/project.json` (run `npx neonctl checkout <branch>`).\",\n\t\t);\n\t}\n\tif (!projectId || !branchId) return { ok: false, missing };\n\n\treturn {\n\t\tok: true,\n\t\tcontext: { projectId, branchId },\n\t};\n}\n\ninterface NeonFile {\n\tprojectId?: string;\n\tbranchId?: string;\n}\n\n/**\n * Walk up from `cwd` looking for `.neon/project.json` (preferred) or `.neon` (neonctl\n * convention). Stops at the first `.git` directory or the home directory. Read-only.\n */\nfunction findNeonFile(cwd: string): NeonFile | null {\n\tlet current = resolve(cwd);\n\tconst stop = resolve(homedir());\n\tlet lastSeen: string | null = null;\n\n\twhile (true) {\n\t\tconst parsed =\n\t\t\treadNeonFileAt(resolve(current, \".neon\", \"project.json\")) ??\n\t\t\treadNeonFileAt(resolve(current, \".neon\"));\n\t\tif (parsed) return parsed;\n\n\t\tif (current === stop) return null;\n\t\tif (existsSync(resolve(current, \".git\"))) return null;\n\n\t\tconst parent = dirname(current);\n\t\tif (parent === current || parent === lastSeen) return null;\n\t\tlastSeen = current;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction readNeonFileAt(path: string): NeonFile | null {\n\tif (!isFile(path)) return null;\n\tlet raw: string;\n\ttry {\n\t\traw = readFileSync(path, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\treturn null;\n\tconst obj = parsed as Record<string, unknown>;\n\tconst out: NeonFile = {};\n\tif (typeof obj.projectId === \"string\" && obj.projectId !== \"\")\n\t\tout.projectId = obj.projectId;\n\tif (typeof obj.branchId === \"string\" && obj.branchId !== \"\")\n\t\tout.branchId = obj.branchId;\n\treturn out;\n}\n\nfunction isFile(path: string): boolean {\n\ttry {\n\t\treturn statSync(path).isFile();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? undefined : trimmed;\n}\n"],"mappings":";;;;;;;;;;;AA4BA,SAAgB,eACf,SAC4E;CAC5E,MAAM,MAAM,QAAQ,OAAO,QAAQ;CACnC,MAAM,OAAO,aAAa,QAAQ,GAAG;CAErC,MAAM,YACL,SAAS,QAAQ,SAAS,KAC1B,SAAS,IAAI,eAAe,KAC5B,MAAM;CAEP,MAAM,WACL,SAAS,QAAQ,MAAM,KACvB,SAAS,IA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