@neondatabase/env 1.2.4 → 1.3.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/README.md +6 -4
- package/dist/cli.js +49 -57
- package/dist/cli.js.map +1 -1
- package/dist/env.js +66 -11
- package/dist/env.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/package.json +5 -5
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":["nonEmpty","nonEmpty","nonEmpty"],"sources":["../../../internals/env-core/dist/reuse-secrets.js","../../../internals/cli-core/dist/cli_config.js","../../../internals/cli-core/dist/paths.js","../../../internals/cli-core/dist/secure_file.js","../../../internals/cli-core/dist/profiles.js","../../../internals/cli-core/dist/auth_selection.js","../../../internals/cli-core/dist/credentials.js","../../../internals/cli-core/dist/credential_store.js","../src/lib/cli/keyring.ts","../src/lib/cli/resolve-api-key.ts","../src/lib/cli/resolve-context.ts","../src/lib/cli/commands.ts","../src/cli.ts"],"sourcesContent":["import { NEON_ENV_VAR_KEYS, createApiFromOptions, credentialEnvKeys, credentialName, fetchEnvKeysState, isFunctionBaseUrlKey, policyEnvKeys, previewCredentialScopes, resolveBranchPolicy, toEntries } from \"./env.js\";\nimport { credentialScopesSatisfied } from \"@neon/config/v1\";\n//#region src/reuse-secrets.ts\n/**\n* Resolve a branch's env while keeping one-time secrets the caller already holds.\n*\n* {@link fetchEnvKeys} — and the public `fetchEnv` — only ever *fetch*. The Neon API returns a\n* credential's `api_token` / `s3_secret_access_key` exactly once, at mint time, so \"fetching\"\n* them means minting a new credential; a plain `fetchEnv` on every `neon dev` start or `env\n* pull` would leave a live credential behind each time. This is the wrapper that avoids that:\n* it looks at what the caller already has, decides what is still usable, and asks `fetchEnv`\n* for only the rest.\n*\n* The check is a real verification, not a presence test. A persisted secret is kept only when\n* it names a credential that still exists on this branch, is not revoked or expired, and\n* carries every scope the policy needs. A `.env.example` placeholder, a credential revoked in\n* the console, one copied in from another branch, or one predating a newly-enabled feature all\n* fail that check and get replaced.\n*\n* None of this needs local bookkeeping, because the secrets carry their own credential id:\n* `AWS_ACCESS_KEY_ID` **is** the credential's `tokenId` (the storage gateway authenticates\n* against the full id), and the AI Gateway token is minted as `nt_live_<tokenIdShort>_<secret>`,\n* where `tokenIdShort` is what the credentials list reports. The env source being replaced is\n* the record of what the last call issued.\n*\n* ```ts\n* import { fetchEnvReusingSecrets } from \"@neon-internals/env-core/reuse-secrets\";\n*\n* const { vars, credential } = await fetchEnvReusingSecrets(config, {\n* projectId,\n* branch: \"main\",\n* env: { ...process.env, ...readEnvFile(\".env\") },\n* });\n* if (credential.issued) console.log(`new values for ${credential.keys.join(\", \")}`);\n* ```\n*/\nasync function fetchEnvReusingSecrets(config, options) {\n\tconst { env: source = process.env, keys: requestedKeys, revokeSuperseded = true, ...fetchOptions } = options;\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst { branch, desired } = await resolveBranchPolicy(config, options, api);\n\tconst allPolicyKeys = policyEnvKeys(desired);\n\tconst requested = requestedKeys ? new Set(requestedKeys) : null;\n\tconst selectedPolicyKeys = requested === null ? allPolicyKeys : [...allPolicyKeys.filter((key) => requested.has(key)), ...[...requested].filter(isFunctionBaseUrlKey).sort()];\n\tconst selected = new Set(selectedPolicyKeys);\n\tconst K = NEON_ENV_VAR_KEYS;\n\tconst storageCredentialSelected = (desired.preview?.buckets.length ?? 0) > 0 && (selected.has(K.storage.accessKeyId) || selected.has(K.storage.secretAccessKey));\n\tconst gatewayCredentialSelected = (desired.preview?.aiGatewayEnabled ?? false) && selected.has(K.aiGateway.apiKey);\n\tconst secretKeys = credentialEnvKeys({\n\t\tstorage: storageCredentialSelected,\n\t\taiGateway: gatewayCredentialSelected\n\t}).filter((key) => selected.has(key));\n\tif (secretKeys.length === 0) {\n\t\tconst fetched = await fetchEnvKeysState(config, fetchOptions, requested === null ? null : selectedPolicyKeys);\n\t\treturn {\n\t\t\tvars: preferPersisted(toEntries(fetched.env), source),\n\t\t\tcredential: {\n\t\t\t\tissued: false,\n\t\t\t\tkeys: [],\n\t\t\t\trevoked: [],\n\t\t\t\tsuperseded: []\n\t\t\t},\n\t\t\t...fetched.functionUrlsUnavailable ? { functionUrlsUnavailable: true } : {}\n\t\t};\n\t}\n\tconst persisted = readPersistedSecrets(source);\n\tconst storageCredentialManaged = requested === null || storageCredentialSelected;\n\tconst gatewayCredentialManaged = requested === null || gatewayCredentialSelected;\n\tconst complete = (!storageCredentialSelected || Boolean(persisted.accessKeyId && persisted.secretAccessKey)) && (!gatewayCredentialSelected || Boolean(persisted.apiToken));\n\tconst named = storageCredentialManaged && persisted.accessKeyId !== \"\" || gatewayCredentialManaged && persisted.apiToken !== \"\" ? namedCredentials(await api.listCredentials(options.projectId, branch.id), persisted) : {\n\t\tstorage: null,\n\t\tgateway: null\n\t};\n\tconst reusable = complete ? reusableCredential(named, {\n\t\tstorageEnabled: storageCredentialSelected,\n\t\tgatewayEnabled: gatewayCredentialSelected\n\t}) : null;\n\tconst scopes = previewCredentialScopes(desired.preview, {\n\t\tstorage: storageCredentialSelected,\n\t\taiGateway: gatewayCredentialSelected\n\t});\n\tconst keep = reusable !== null && credentialScopesSatisfied(reusable.scopes, scopes);\n\tconst fetchKeys = requested === null ? null : keep ? selectedPolicyKeys.filter((key) => !secretKeys.includes(key)) : selectedPolicyKeys;\n\tconst fetched = await fetchEnvKeysState(config, {\n\t\t...fetchOptions,\n\t\tbranchId: branch.id,\n\t\tapi,\n\t\t...keep && requested === null ? { omitKeys: secretKeys } : {}\n\t}, fetchKeys);\n\tconst vars = preferPersisted(toEntries(fetched.env), source);\n\tconst unavailable = fetched.functionUrlsUnavailable ? { functionUrlsUnavailable: true } : {};\n\tif (keep) {\n\t\tfor (const key of secretKeys) {\n\t\t\tconst value = source[key];\n\t\t\tif (value !== void 0) vars[key] = value;\n\t\t}\n\t\treturn {\n\t\t\tvars,\n\t\t\tcredential: {\n\t\t\t\tissued: false,\n\t\t\t\tkeys: secretKeys,\n\t\t\t\trevoked: [],\n\t\t\t\tsuperseded: []\n\t\t\t},\n\t\t\t...unavailable\n\t\t};\n\t}\n\tconst ours = /* @__PURE__ */ new Set();\n\tfor (const meta of [storageCredentialManaged ? named.storage : null, gatewayCredentialManaged ? named.gateway : null]) if (meta !== null && meta.principalType === \"user\" && meta.name === credentialName(branch.name)) ours.add(meta.tokenId);\n\tif (revokeSuperseded) for (const tokenId of ours) await api.revokeCredential(options.projectId, branch.id, tokenId);\n\treturn {\n\t\tvars,\n\t\tcredential: {\n\t\t\tissued: true,\n\t\t\tkeys: secretKeys,\n\t\t\trevoked: revokeSuperseded ? [...ours] : [],\n\t\t\tsuperseded: revokeSuperseded ? [] : [...ours]\n\t\t},\n\t\t...unavailable\n\t};\n}\n/** Read the branch credential's secrets out of an env source. */\nfunction readPersistedSecrets(source) {\n\tconst storage = NEON_ENV_VAR_KEYS.storage;\n\tconst gateway = NEON_ENV_VAR_KEYS.aiGateway;\n\treturn {\n\t\taccessKeyId: source[storage.accessKeyId] ?? \"\",\n\t\tsecretAccessKey: source[storage.secretAccessKey] ?? \"\",\n\t\tapiToken: source[gateway.apiKey] ?? \"\"\n\t};\n}\n/**\n* Keep a persisted value rather than overwriting it with an empty fetched one.\n*\n* Neon Auth's `base_url` is the case that needs this: integrations created before the API\n* returned it answer with an empty string, and the persisted copy is the only one left. An\n* empty fetched value never carries more information than a non-empty persisted one, so\n* preferring the latter is safe for every var — and it keeps a pull from blanking a working\n* line in someone's `.env`.\n*/\nfunction preferPersisted(vars, source) {\n\tconst out = { ...vars };\n\tfor (const [key, value] of Object.entries(out)) {\n\t\tif (value !== \"\") continue;\n\t\tconst persisted = source[key];\n\t\tif (persisted !== void 0 && persisted !== \"\") out[key] = persisted;\n\t}\n\treturn out;\n}\n/**\n* The credential id embedded in an AI Gateway token. The API mints them as\n* `nt_live_<tokenIdShort>_<secret>`, and `tokenIdShort` is the public identifier the credentials\n* list reports — so a persisted token names the credential that issued it. Returns `null` for\n* anything not in that shape (a `.env.example` placeholder, a hand-typed value), which callers\n* treat as unverifiable.\n*/\nfunction gatewayTokenIdShort(apiToken) {\n\treturn /^nt_live_([^_]+)_.+$/.exec(apiToken)?.[1] ?? null;\n}\n/** Whether an issued credential can still be used: not revoked, not past its expiry. */\nfunction isLiveCredential(meta, now) {\n\tif (meta.revokedAt !== void 0) return false;\n\tif (meta.expiresAt === void 0) return true;\n\tconst expiresAt = Date.parse(meta.expiresAt);\n\treturn Number.isNaN(expiresAt) || expiresAt > now;\n}\n/**\n* The live credentials the persisted secrets name — at most one per half. A half that names\n* nothing contributes nothing, which is what a placeholder, a credential revoked in the\n* console, and one copied in from another branch all look like from here.\n*/\nfunction namedCredentials(live, persisted) {\n\tconst usable = live.filter((meta) => isLiveCredential(meta, Date.now()));\n\tconst shortId = persisted.apiToken ? gatewayTokenIdShort(persisted.apiToken) : null;\n\treturn {\n\t\tstorage: persisted.accessKeyId ? usable.find((meta) => meta.tokenId === persisted.accessKeyId) ?? null : null,\n\t\tgateway: shortId ? usable.find((meta) => meta.tokenIdShort === shortId) ?? null : null\n\t};\n}\n/**\n* The credential the persisted secrets can be *reused* as, or `null`.\n*\n* Strict on purpose: every half the policy enables has to name a live credential, and when both\n* features are enabled they must name the *same* one — they share a single credential, so\n* halves that disagree came from two different calls and neither can be trusted.\n*/\nfunction reusableCredential(named, enabled) {\n\tif (enabled.storageEnabled && enabled.gatewayEnabled) return named.storage && named.gateway && named.storage.tokenId === named.gateway.tokenId ? named.storage : null;\n\tif (enabled.storageEnabled) return named.storage;\n\tif (enabled.gatewayEnabled) return named.gateway;\n\treturn null;\n}\n//#endregion\nexport { fetchEnvReusingSecrets };\n\n//# sourceMappingURL=reuse-secrets.js.map","//#region src/cli_config.ts\nconst CRED_STORAGE_FILE = \"file\";\nconst CRED_STORAGE_KEYRING = \"keyring\";\n//#endregion\nexport { CRED_STORAGE_FILE, CRED_STORAGE_KEYRING };\n\n//# sourceMappingURL=cli_config.js.map","import { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n//#region src/paths.ts\n/**\n* # Where the Neon CLIs keep their files on disk\n*\n**Deliberately impure.** It reads environment variables and touches the filesystem, which\n* `@neon/config` — the package this used to be a subpath of — must never do from its root\n* export. It lives here instead of there precisely so that a policy-facing package does not\n* carry implementor-only code.\n*\n* It exists because three separate readers each grew their own answer to \"where is the\n* config directory\", and all three disagreed: `packages/cli` honoured `XDG_CONFIG_HOME` but\n* not `NEONCTL_CONFIG_DIR`, `packages/env` honoured the env var but not XDG, and the init\n* flow hardcoded `~/.config/neonctl`. With `XDG_CONFIG_HOME` set, the CLI wrote\n* credentials somewhere the other two never looked.\n*\n* ## The directory\n*\n* `neon` is the current name; `neonctl` is the legacy one, kept readable forever. Resolution,\n* each entry winning over the next:\n*\n* 1. An explicit directory (a `--config-dir` flag) — **exact**, no legacy fallback.\n* 2. `NEON_CONFIG_DIR` — exact.\n* 3. `NEONCTL_CONFIG_DIR` (legacy name) — exact.\n* 4. `$XDG_CONFIG_HOME/neon`, else `<home>/.config/neon`.\n*\n* An explicitly chosen directory is never paired with a fallback: `--config-dir /tmp/ci` that\n* quietly read `~/.config/neonctl` would defeat the point of passing it.\n*\n* ## The files\n*\n* {@link resolveConfigFile} answers \"which path should I use for this file\", and it is the\n* same answer for reading and writing:\n*\n* - Present in `neon/` → use it.\n* - Present only in `neonctl/` → **use it there, in place.** An existing credentials file is\n* never copied or moved, so nothing is left behind to go stale and no other tool starts\n* reading an abandoned token.\n* - Present in neither → the new location. New files only ever appear under `neon/`.\n*/\n/** Current directory name. New files are created here. */\nconst CONFIG_DIR_NAME = \"neon\";\n/** Legacy directory name, read forever so existing installs keep working untouched. */\nconst LEGACY_CONFIG_DIR_NAME = \"neonctl\";\n/** Where files are created. See the module docs for the precedence. */\nfunction configDir(options = {}) {\n\tconst explicit = explicitDir(options);\n\tif (explicit) return explicit;\n\treturn join(configHome(options.env ?? process.env), CONFIG_DIR_NAME);\n}\n/**\n* The legacy directory, or `undefined` when the location was chosen explicitly (in which\n* case there is no legacy counterpart to fall back to).\n*/\nfunction legacyConfigDir(options = {}) {\n\tif (explicitDir(options)) return void 0;\n\treturn join(configHome(options.env ?? process.env), LEGACY_CONFIG_DIR_NAME);\n}\n/**\n* Resolve one file inside the config directory. Prefers the current location, falls back to\n* an existing legacy file **in place**, and otherwise points at the current location so new\n* files are created there.\n*/\nfunction resolveConfigFile(fileName, options = {}) {\n\tconst dir = configDir(options);\n\tconst current = resolve(dir, fileName);\n\tif (existsSync(current)) return {\n\t\tpath: current,\n\t\tdir,\n\t\tisLegacy: false,\n\t\texists: true\n\t};\n\tconst legacyDir = legacyConfigDir(options);\n\tif (legacyDir) {\n\t\tconst legacy = resolve(legacyDir, fileName);\n\t\tif (existsSync(legacy)) return {\n\t\t\tpath: legacy,\n\t\t\tdir: legacyDir,\n\t\t\tisLegacy: true,\n\t\t\texists: true\n\t\t};\n\t}\n\treturn {\n\t\tpath: current,\n\t\tdir,\n\t\tisLegacy: false,\n\t\texists: false\n\t};\n}\n/** `$XDG_CONFIG_HOME`, else `<home>/.config`. Falls back to a relative `.config` with no home. */\nfunction configHome(env) {\n\tconst xdg = nonEmpty(env.XDG_CONFIG_HOME);\n\tif (xdg) return xdg;\n\tconst home = nonEmpty(env.HOME) ?? nonEmpty(env.USERPROFILE);\n\treturn home ? join(home, \".config\") : \".config\";\n}\nfunction explicitDir(options) {\n\tconst env = options.env ?? process.env;\n\treturn nonEmpty(options.dir) ?? nonEmpty(env.NEON_CONFIG_DIR) ?? nonEmpty(env.NEONCTL_CONFIG_DIR);\n}\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\nconst CREDENTIALS_FILE = \"credentials.json\";\n/**\n* Default for `--config-dir`: `$XDG_CONFIG_HOME/neon`, else `~/.config/neon`.\n*\n* The directory was called `neonctl` until the CLI was renamed. An existing one is still read —\n* see {@link credentialsPath} — but it is never written to, moved, or deleted.\n*/\nconst defaultDir = configDir();\n/**\n* Where this invocation's `credentials.json` lives.\n*\n* When `--config-dir` was left at its default, an existing file in the legacy `neonctl`\n* directory is used **in place**: an install that predates the rename keeps working, and its\n* credentials are never duplicated into a second location where one copy could go stale while\n* another tool still reads it.\n*\n* A `--config-dir` the user actually passed is used exactly as given. Falling back out of an\n* explicitly chosen directory would defeat the reason for choosing it — a CI run pointed at a\n* scratch directory must never pick up a developer's real credentials.\n*/\nconst credentialsPath = (dir) => resolveConfigFile(CREDENTIALS_FILE, dir === defaultDir ? {} : { dir }).path;\n/**\n* Whether a credentials file is one the CLI created, rather than a path a profile adopted.\n*\n* Anything that deletes a credential has to ask this first. A profile entry may point anywhere —\n* that is what makes adopting an existing directory a one-line edit — and a file we did not\n* create is not ours to remove.\n*/\nconst isInsideConfigDir = (configDirectory, file) => `${resolve(file)}/`.startsWith(`${resolve(configDirectory)}/`);\n/**\n* Whether a credentials file is one the CLI owns, counting the legacy `neonctl` directory.\n*\n* {@link credentialsPath} deliberately reads an existing legacy file in place rather than\n* migrating it, so for a default config directory that file is ours even though it sits outside\n* `neon/`. Judging ownership on the current directory alone would call an install that predates\n* the rename \"adopted\".\n*/\nconst isOwnedCredentialPath = (configDirectory, file) => {\n\tif (isInsideConfigDir(configDirectory, file)) return true;\n\tif (configDirectory !== defaultDir) return false;\n\tconst legacy = legacyConfigDir();\n\treturn legacy !== void 0 && isInsideConfigDir(legacy, file);\n};\n//#endregion\nexport { CONFIG_DIR_NAME, CREDENTIALS_FILE, LEGACY_CONFIG_DIR_NAME, configDir, credentialsPath, defaultDir, isInsideConfigDir, isOwnedCredentialPath, legacyConfigDir, resolveConfigFile };\n\n//# sourceMappingURL=paths.js.map","import { renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\n//#region src/secure_file.ts\n/** Owner read/write. A credential needs those two and nothing else. */\nconst SECRET_FILE_MODE = 384;\n/**\n* Write a secret to disk owner-only, by creating a temporary file in the same directory and\n* renaming it over the target.\n*\n* The rename is what makes this correct rather than merely tidy. `writeFileSync`'s `mode`\n* applies only when it *creates* the file, so writing over an existing credentials file\n* leaves whatever permissions it already had — a file created `0700` by an older release\n* stays `0700` forever, and one created before a umask change stays world-readable. Renaming\n* a fresh inode into place means every write lands at {@link SECRET_FILE_MODE}, so the\n* permissions repair themselves instead of being inherited.\n*\n* It also closes the window where a reader could see the file at default permissions: the\n* temporary file is created `0600` *before* it holds the secret's final name, and `rename`\n* is atomic within a directory, so there is no moment at which the target is readable by\n* anyone else and no moment at which it is half-written.\n*\n* The temporary name carries the pid so two processes writing at once cannot collide on it.\n*/\nconst writeSecretFile = (path, contents) => {\n\tconst directory = dirname(path);\n\tconst temporary = join(directory, `.${basename(path)}.${process.pid}.${Date.now()}.tmp`);\n\ttry {\n\t\twriteFileSync(temporary, contents, {\n\t\t\tencoding: \"utf8\",\n\t\t\tmode: 384\n\t\t});\n\t\trenameSync(temporary, path);\n\t} catch (err) {\n\t\ttry {\n\t\t\tunlinkSync(temporary);\n\t\t} catch {}\n\t\tthrow err;\n\t}\n};\n//#endregion\nexport { SECRET_FILE_MODE, writeSecretFile };\n\n//# sourceMappingURL=secure_file.js.map","import { CRED_STORAGE_FILE, CRED_STORAGE_KEYRING } from \"./cli_config.js\";\nimport { credentialsPath, defaultDir, resolveConfigFile } from \"./paths.js\";\nimport { writeSecretFile } from \"./secure_file.js\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\n//#region src/profiles.ts\n/**\n* Pointer-only profiles avoid mirrored credentials and persistent active-profile\n* state while preserving existing single-account and legacy-directory installs.\n*/\nconst PROFILES_FILE = \"profiles.json\";\nconst KEYRING_CREDENTIALS = \"keyring\";\nconst isKeyringPointer = (credentials) => credentials === KEYRING_CREDENTIALS;\n/** The implicit profile. Backed by plain `credentials.json`, with or without a profiles file. */\nconst DEFAULT_PROFILE = \"DEFAULT\";\n/** Profile names become part of a filename, so keep them boring. */\nconst NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nconst locationOf = (profile) => profile.storage === \"keyring\" ? {\n\tprofile: profile.name,\n\tstorage: CRED_STORAGE_KEYRING\n} : {\n\tprofile: profile.name,\n\tstorage: CRED_STORAGE_FILE,\n\tpath: profile.credentialsPath\n};\nconst credentialsDisplay = (profile) => profile.storage === \"keyring\" ? KEYRING_CREDENTIALS : profile.credentialsPath;\n/** Which profile this invocation should use: `--profile` → `NEON_PROFILE` → `DEFAULT`. */\nconst selectProfileName = (flag, env = process.env) => nonEmpty(flag) ?? nonEmpty(env.NEON_PROFILE) ?? \"DEFAULT\";\nconst assertValidProfileName = (name) => {\n\tif (!NAME_PATTERN.test(name)) throw new Error(`Invalid profile name \"${name}\". Use letters, digits, dot, dash or underscore, starting with a letter or digit.`);\n};\n/** Where `profiles.json` lives for this config directory (whether or not it exists yet). */\nconst profilesFilePath = (dir) => resolveConfigFile(PROFILES_FILE, dir === defaultDir ? {} : { dir }).path;\n/**\n* Read and classify `profiles.json` without deciding what to do about it.\n*\n* Entry keys and shapes are validated here rather than at each use. A key is a profile name,\n* and a name that `assertValidProfileName` would reject cannot have been written by this CLI —\n* it would travel into error messages as a recovery command nobody can run, and into a\n* `credentials.<name>.json` filename.\n*/\nconst inspectProfiles = (dir) => {\n\tconst path = profilesFilePath(dir);\n\tif (!existsSync(path)) return { kind: \"absent\" };\n\tconst broken = (why) => ({\n\t\tkind: \"unusable\",\n\t\treason: `${path} could not be read as a profiles file: ${why}`\n\t});\n\tlet contents;\n\ttry {\n\t\tcontents = readFileSync(path, \"utf8\");\n\t} catch (err) {\n\t\tconst code = err.code;\n\t\treturn broken(code ? `reading it failed with ${code}` : \"reading it failed\");\n\t}\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(contents);\n\t} catch {\n\t\treturn broken(\"it is not valid JSON\");\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) return broken(\"it does not contain an object\");\n\tconst profiles = parsed.profiles;\n\tif (profiles === null || typeof profiles !== \"object\" || Array.isArray(profiles)) return broken(\"it has no `profiles` object\");\n\tfor (const [name, entry] of Object.entries(profiles)) {\n\t\tif (!NAME_PATTERN.test(name)) return broken(`\"${name}\" is not a valid profile name`);\n\t\tif (entry === null || typeof entry !== \"object\" || typeof entry.credentials !== \"string\" || entry.credentials.trim() === \"\") return broken(`profile \"${name}\" has no \\`credentials\\` pointer`);\n\t}\n\treturn {\n\t\tkind: \"ok\",\n\t\tfile: {\n\t\t\tversion: 1,\n\t\t\tprofiles\n\t\t}\n\t};\n};\n/**\n* Read `profiles.json`, or `null` when there is nothing usable there.\n*\n* A malformed file is reported through `onWarn` and treated as absent, because for a *read* the\n* worst case is a named profile turning up missing, which is recoverable — whereas throwing\n* would lock the user out of `neon auth` itself. Writing is the opposite: see\n* {@link upsertProfile}, which refuses rather than rebuilding a file it cannot read.\n*/\nconst readProfiles = (dir, onWarn = () => {}) => {\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"ok\") return read.file;\n\tif (read.kind === \"unusable\") onWarn(read.reason);\n\treturn null;\n};\n/**\n* Storage cannot be trusted when the profiles file cannot be read.\n*\n* Call this **before** anything that writes a credential, opens a browser, or spends an API\n* call. {@link upsertProfile} refuses too, but it runs last: by then `create` has already\n* overwritten `credentials.<name>.json` and revoked the key it replaced, and `neon auth\n* --profile` has already signed in over it — a refusal that arrives after the destruction it\n* exists to prevent. The path resolution itself is the unsound part, since with the metadata\n* unreadable the conventional filename is a guess about which account that file belongs to.\n*\n* DEFAULT follows the same rule because the broken file may be its only\n* keyring pointer.\n*/\nconst assertProfilesUsable = (dir, name) => {\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. Fix or delete the file before working with profile \"${name}\" — it is the only record of where each account's credentials live.`);\n};\n/** Resolve a profile to an absolute credentials path. Throws when a named profile is unknown. */\nconst resolveProfile = (dir, name) => {\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. Fix or delete the file — every profile is defined in it.`);\n\tconst file = read.kind === \"ok\" ? read.file : null;\n\tconst entry = file?.profiles[name];\n\tif (entry) {\n\t\tif (isKeyringPointer(entry.credentials)) return {\n\t\t\tname,\n\t\t\tstorage: CRED_STORAGE_KEYRING,\n\t\t\t...entry.label ? { label: entry.label } : {},\n\t\t\t...entry.userId ? { userId: entry.userId } : {},\n\t\t\tdeclared: true\n\t\t};\n\t\treturn {\n\t\t\tname,\n\t\t\tstorage: CRED_STORAGE_FILE,\n\t\t\tcredentialsPath: resolveEntryPath(dir, entry.credentials),\n\t\t\t...entry.label ? { label: entry.label } : {},\n\t\t\t...entry.userId ? { userId: entry.userId } : {},\n\t\t\tdeclared: true\n\t\t};\n\t}\n\tif (name === \"DEFAULT\") return {\n\t\tname,\n\t\tstorage: CRED_STORAGE_FILE,\n\t\tcredentialsPath: credentialsPath(dir),\n\t\tdeclared: false\n\t};\n\tconst known = file ? Object.keys(file.profiles).join(\", \") : DEFAULT_PROFILE;\n\tthrow new Error(`Unknown profile \"${name}\". Known profiles: ${known}. Create it with \\`neon profile create ${name}\\`.`);\n};\n/** Default location for a new named profile's credentials file. */\nconst newProfileCredentialsPath = (dir, name) => resolve(dir, `credentials.${name}.json`);\n/**\n* Record a profile, creating `profiles.json` if this is the first named one.\n*\n* When the file is created, `DEFAULT` is written explicitly and pointed at wherever\n* `credentials.json` actually is. That matters for an install predating the directory\n* rename: `profiles.json` is created in `neon/` while the credentials are still in\n* `neonctl/`, so `DEFAULT` is recorded as `../neonctl/credentials.json` rather than a\n* relative name that would resolve to a file that isn't there.\n*/\nconst upsertProfile = (dir, name, entry) => {\n\tassertValidProfileName(name);\n\tconst path = profilesFilePath(dir);\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. Refusing to rewrite it, because doing so would discard the profiles it defines. Fix or delete the file, then re-run.`);\n\tconst file = read.kind === \"ok\" ? read.file : {\n\t\tversion: 1,\n\t\tprofiles: { [DEFAULT_PROFILE]: { credentials: storedPointer(path, credentialsPath(dir)) } }\n\t};\n\tfile.profiles[name] = {\n\t\tcredentials: storedPointer(path, entry.credentials),\n\t\t...entry.label ? { label: entry.label } : {},\n\t\t...entry.userId ? { userId: entry.userId } : {}\n\t};\n\twriteProfiles(path, file);\n};\n/** Remove an entry. Returns false when it wasn't there. */\nconst removeProfileEntry = (dir, name) => {\n\tconst path = profilesFilePath(dir);\n\tconst file = readProfiles(dir);\n\tif (!file?.profiles[name]) return false;\n\tdelete file.profiles[name];\n\twriteProfiles(path, file);\n\treturn true;\n};\nconst onlyDefaultRemains = (file) => {\n\tconst names = Object.keys(file.profiles);\n\treturn names.length === 0 || names.length === 1 && names[0] === \"DEFAULT\";\n};\nconst canDropProfilesFile = (file) => {\n\tif (!onlyDefaultRemains(file)) return false;\n\tconst remaining = file.profiles[DEFAULT_PROFILE];\n\treturn remaining === void 0 || !isKeyringPointer(remaining.credentials);\n};\nconst locationForName = (dir, name) => locationOf(resolveProfile(dir, name));\nconst newProfileLocation = (dir, name, storage) => storage === \"keyring\" ? {\n\tprofile: name,\n\tstorage: CRED_STORAGE_KEYRING\n} : {\n\tprofile: name,\n\tstorage: CRED_STORAGE_FILE,\n\tpath: newProfileCredentialsPath(dir, name)\n};\nconst profilesUsingPath = (dir, path, except) => {\n\tconst resolved = resolve(path);\n\treturn listProfiles(dir).filter((profile) => profile.name !== except && profile.storage === \"file\" && resolve(profile.credentialsPath) === resolved).map((profile) => profile.name);\n};\nconst listProfiles = (dir) => {\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. Fix or delete the file — every named profile is defined in it.`);\n\tconst file = read.kind === \"ok\" ? read.file : null;\n\tif (!file) return [resolveProfile(dir, DEFAULT_PROFILE)];\n\tconst names = Object.keys(file.profiles);\n\tif (!names.includes(\"DEFAULT\")) names.unshift(DEFAULT_PROFILE);\n\treturn names.map((name) => resolveProfile(dir, name));\n};\nconst writeProfiles = (path, file) => {\n\twriteSecretFile(path, `${JSON.stringify(file, null, 2)}\\n`);\n};\nconst resolveEntryPath = (dir, entry) => isAbsolute(entry) ? entry : resolve(profilesDir(dir), entry);\n/** `profiles.json` may sit in the legacy directory, so entries resolve against its own dir. */\nconst profilesDir = (dir) => resolve(profilesFilePath(dir), \"..\");\n/** A relative file named `keyring` would otherwise collide with the storage sentinel. */\nconst storedPointer = (profilesPath, credentials) => {\n\tif (isKeyringPointer(credentials)) return KEYRING_CREDENTIALS;\n\tconst base = resolve(profilesPath, \"..\");\n\tconst abs = isAbsolute(credentials) ? credentials : resolve(base, credentials);\n\tconst rel = relative(base, abs);\n\tconst stored = rel && !isAbsolute(rel) ? rel : abs;\n\treturn stored === \"keyring\" ? `./${KEYRING_CREDENTIALS}` : stored;\n};\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\n//#endregion\nexport { DEFAULT_PROFILE, KEYRING_CREDENTIALS, PROFILES_FILE, assertProfilesUsable, assertValidProfileName, canDropProfilesFile, credentialsDisplay, inspectProfiles, isKeyringPointer, listProfiles, locationForName, locationOf, newProfileCredentialsPath, newProfileLocation, onlyDefaultRemains, profilesFilePath, profilesUsingPath, readProfiles, removeProfileEntry, resolveProfile, selectProfileName, upsertProfile };\n\n//# sourceMappingURL=profiles.js.map","import \"./profiles.js\";\n//#region src/auth_selection.ts\n/**\n* # Which credential an invocation authenticates with\n*\n* Four inputs can each answer \"who am I\": the `--api-key` flag, `NEON_API_KEY`, the\n* `--profile` flag, and `NEON_PROFILE`. This module decides between them, and it is pure so\n* the decision can be tested without a filesystem, a network, or a config directory.\n*\n* ## The rule\n*\n* **An explicit flag beats an ambient environment variable.** That single rule fixes the bug\n* this module exists for: before it, any API key — including one merely exported into the\n* shell — silently voided `--profile`, so `neon --profile work …` would quietly run as\n* whoever `NEON_API_KEY` belonged to and say nothing about it.\n*\n* | Given | What runs |\n* | --- | --- |\n* | `--api-key` and `--profile` | neither: contradictory explicit flags, so this throws |\n* | `--api-key` and `NEON_PROFILE` | the flag's key |\n* | `--profile` and `NEON_API_KEY` | the profile |\n* | `NEON_API_KEY` and `NEON_PROFILE` | the key, and the ignored profile is named in a warning |\n* | `--profile` or `NEON_PROFILE` alone | that profile |\n* | nothing | `DEFAULT` |\n*\n* Two explicit flags throw rather than picking a winner. They express different intents —\n* `--api-key` supplies a credential, `--profile` selects a stored one — so there is no\n* reading of the command that makes both true, and guessing is how the original bug behaved.\n*\n* When both are merely ambient, the key wins. That keeps CI exactly as it was: a pipeline\n* that injects `NEON_API_KEY` must not change behaviour because a `NEON_PROFILE` leaked into\n* the environment. It warns instead of staying silent, because a disregarded account\n* selection is precisely what nobody noticed last time.\n*\n* `auth` and the `profile` subcommands do not use any of this. They read the same flags with\n* different meanings — `neon auth --profile work` names where to *write* a credential, and\n* `neon profile create work --api-key …` names one to *store* — so their callers skip\n* selection entirely rather than passing exemptions down here.\n*/\nlet inputs = {\n\tapiKeyFlag: \"\",\n\tapiKeyEnv: \"\",\n\tprofileEnv: \"\",\n\tprofileFlag: \"\",\n\tconfigDir: \"\"\n};\nconst recordCredentialInputs = (recorded) => {\n\tinputs = recorded;\n};\nconst credentialInputs = () => inputs;\nconst selectCredential = ({ apiKeyFlag, profileFlag, apiKeyEnv, profileEnv }) => {\n\tconst flagKey = nonEmpty(apiKeyFlag);\n\tconst flagProfile = nonEmpty(profileFlag);\n\tif (flagKey !== void 0 && flagProfile !== void 0) throw new Error(\"Pass either --api-key or --profile, not both. --api-key supplies a credential directly; --profile selects a stored one.\");\n\tif (flagKey !== void 0) return {\n\t\tsource: \"explicit-api-key\",\n\t\tapiKey: flagKey\n\t};\n\tif (flagProfile !== void 0) return {\n\t\tsource: \"profile\",\n\t\tprofile: flagProfile,\n\t\texplicit: true\n\t};\n\tconst envKey = nonEmpty(apiKeyEnv);\n\tconst envProfile = nonEmpty(profileEnv);\n\tif (envKey !== void 0) return {\n\t\tsource: \"ambient-api-key\",\n\t\tapiKey: envKey,\n\t\t...envProfile !== void 0 ? { ignoredProfile: envProfile } : {}\n\t};\n\treturn {\n\t\tsource: \"profile\",\n\t\tprofile: envProfile ?? \"DEFAULT\",\n\t\texplicit: envProfile !== void 0\n\t};\n};\n/** The warning for an ambient key that displaced an ambient profile, or `null`. */\nconst displacedProfileWarning = (selection) => selection.source === \"ambient-api-key\" && selection.ignoredProfile !== void 0 ? `NEON_API_KEY is set, so profile \"${selection.ignoredProfile}\" from NEON_PROFILE was ignored. Pass --profile ${selection.ignoredProfile} to use it instead.` : null;\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\n//#endregion\nexport { credentialInputs, displacedProfileWarning, recordCredentialInputs, selectCredential };\n\n//# sourceMappingURL=auth_selection.js.map","import { writeSecretFile } from \"./secure_file.js\";\nimport { readFileSync } from \"node:fs\";\n//#region src/credentials.ts\n/**\n* # Stored credentials — one file per account, two kinds\n*\n* A profile points at exactly one credentials file (see `./profiles.ts`), and that file says\n* what kind of credential it holds. Adding API-key support this way rather than adding a\n* second pointer to `profiles.json` keeps a profile what it already was — one name, one path\n* — and means `profiles.json` needs no schema change at all.\n*\n* ```json\n* // oauth: every file written before this existed. An absent `type` means this.\n* { \"access_token\": \"…\", \"refresh_token\": \"…\", \"expires_at\": 1786…, \"user_id\": \"…\" }\n*\n* // api_key, stored by `neon profile create --api-key`\n* { \"type\": \"api_key\", \"api_key\": \"napi_…\", \"user_id\": \"…\" }\n*\n* // api_key minted by `--mint --org-id`, which records the scope it was issued at\n* { \"type\": \"api_key\", \"api_key\": \"napi_…\", \"key_id\": 123, \"org_id\": \"org-…\" }\n* ```\n*\n* ## One profile, one kind\n*\n* A credentials file holds an API key or an OAuth session, never both, and `type` states\n* which. An earlier draft let the two coexist — the idea being that a key could keep the\n* session it was minted from and so rotate without a browser. It did not survive review, for\n* two reasons that are worth recording so nobody rebuilds it:\n*\n* 1. **It never worked.** The resolver returned the key without testing it, so a revoked key\n* failed to mint and never fell back to the session sitting beside it.\n* 2. **It could mix accounts.** Nothing compared the identity of the credential being written\n* with the one already there, so a profile could hold one account's session and another's\n* key, told apart only by a single string. Flip or lose `type` and the profile silently\n* becomes a different person.\n*\n* Recovery from a dead key is therefore one browser login — `neon profile create <name>\n* --mint` — which is what the retained session was supposed to save and never did.\n*\n* ## Older releases\n*\n* A CLI predating this reads the pointer, finds no `type` it understands, ignores it, and\n* looks for `access_token`. An `api_key` profile has none, so an older release falls through\n* to its browser login rather than crashing. That it does not crash is why `credentials`\n* stays a required pointer: an entry without one makes 2.41 and 2.42 throw\n* `ERR_INVALID_ARG_TYPE` from `resolveEntryPath`.\n*/\nconst OAUTH = \"oauth\";\nconst API_KEY = \"api_key\";\nconst credentialLabel = (at) => at.storage === \"keyring\" ? `the OS keyring item for profile \"${at.profile}\"` : at.path;\n/**\n* Which credential in this file authenticates, by declaration alone.\n*\n* An unrecognised `type` throws rather than falling back to `oauth`. A file we cannot\n* interpret is a misconfiguration the user has to see: treating it as OAuth would send them\n* to a browser login that silently replaces a credential they meant to keep, and treating it\n* as an API key would authenticate with whatever `api_key` happened to be there.\n*\n* This deliberately does not check that an `api_key` file has a key — `neon profile list`\n* needs the kind of a file it is not about to authenticate with, and must be able to report a\n* broken one rather than throwing halfway through a table.\n*/\nconst credentialKind = (credentials, at, store = \"file\") => {\n\tconst declared = credentials.type;\n\tif (declared === void 0 || declared === \"oauth\") return OAUTH;\n\tif (declared === \"api_key\") return API_KEY;\n\tthrow new Error(`${credentialLabel(at)} declares a \"type\" this version does not understand. Expected \"${OAUTH}\" or \"${API_KEY}\". ${credentialsRepairHint(at, store)}`);\n};\nconst credentialsRepairHint = (at, store = \"file\") => store === \"keyring\" ? `Replace it deliberately with \\`neon profile create ${at.profile}\\`, or remove the profile with \\`neon profile remove ${at.profile}\\`.` : `Replace it deliberately with \\`neon profile create ${at.profile}\\`, or delete the file.`;\n/**\n* Resolve what to authenticate with, validating that the declared kind is actually usable.\n*\n* An `api_key` file with no key is a hard error rather than a fall-through to OAuth: the user\n* asked for a key, and quietly opening a browser instead would replace the credential they\n* were trying to fix.\n*/\nconst interpretCredentials = (credentials, at, store = \"file\") => {\n\tif (credentialKind(credentials, at, store) === \"oauth\") return { kind: OAUTH };\n\tconst apiKey = nonEmpty(credentials.api_key);\n\tif (apiKey === void 0) throw new Error(`${credentialLabel(at)} declares \"type\": \"${API_KEY}\" but has no \"api_key\" value. ${credentialsRepairHint(at, store)}`);\n\treturn {\n\t\tkind: API_KEY,\n\t\tapiKey\n\t};\n};\n/**\n* Read and classify a credentials file, without deciding what to do about it.\n*\n* A permission or I/O error still throws: there may be a perfectly good credential here that\n* we cannot see, and treating that as absent would send the user to a browser login that\n* overwrites it.\n*/\n/** Discard parser details because V8 may quote secret material near a syntax error. */\nconst parseCredentialsJson = (contents, label) => {\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(contents);\n\t} catch {\n\t\treturn {\n\t\t\tkind: \"unusable\",\n\t\t\treason: `${label} is not valid JSON, so the credential in it cannot be read`\n\t\t};\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) return {\n\t\tkind: \"unusable\",\n\t\treason: `${label} does not contain a credentials object`\n\t};\n\treturn {\n\t\tkind: \"ok\",\n\t\tcredentials: parsed\n\t};\n};\nconst inspectCredentials = (path) => {\n\tlet contents;\n\ttry {\n\t\tcontents = readFileSync(path, \"utf8\");\n\t} catch (err) {\n\t\tif (err.code === \"ENOENT\") return { kind: \"absent\" };\n\t\tthrow err;\n\t}\n\treturn parseCredentialsJson(contents, path);\n};\n/**\n* The credential at `path`, or `null` when the file is not there.\n*\n* A damaged file is an error, not an absence. Treating it as absent — which is what this used to\n* do — meant any read-only command could repair it by starting a browser sign-in and overwriting\n* it, **possibly as a different account**, with the user never having asked for a repair and no\n* way back to whatever was in the file. Failing here costs one deliberate command; the message\n* names it.\n*\n* `profile list` and telemetry use {@link inspectCredentials} instead, because describing a\n* broken credential is not the same as using one.\n*/\nconst readCredentials = (at) => {\n\tconst read = inspectCredentials(at.path);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. ${credentialsRepairHint(at)}`);\n\treturn read.kind === \"ok\" ? read.credentials : null;\n};\nconst writeCredentials = (path, credentials) => {\n\twriteSecretFile(path, JSON.stringify(credentials));\n};\n/**\n* Build an `api_key` credentials object. Nothing from a previous credential is carried over.\n*\n* The scope is stored because it is not recoverable from the secret: `rotate-key` has to mint\n* the replacement on the same endpoint, and an org or project key minted as an account key\n* would silently widen what the profile reaches.\n*/\nconst apiKeyCredentials = ({ apiKey, keyId, userId, scope }) => ({\n\ttype: API_KEY,\n\tapi_key: apiKey,\n\t...keyId !== void 0 ? { key_id: keyId } : {},\n\t...userId !== void 0 ? { user_id: userId } : {},\n\t...scope?.orgId !== void 0 ? { org_id: scope.orgId } : {},\n\t...scope?.projectId !== void 0 ? { project_id: scope.projectId } : {}\n});\n/** The scope recorded on a stored credential. */\nconst scopeOf = (credentials) => ({\n\t...typeof credentials.org_id === \"string\" ? { orgId: credentials.org_id } : {},\n\t...typeof credentials.project_id === \"string\" ? { projectId: credentials.project_id } : {}\n});\n/** How to describe a scope in output. */\nconst describeScope = (scope) => {\n\tif (scope.projectId !== void 0) return `project ${scope.projectId}`;\n\tif (scope.orgId !== void 0) return `org ${scope.orgId}`;\n\treturn \"account\";\n};\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\n/**\n* Whether a stored credential is the same secret as the one about to replace it.\n*\n* Re-storing the key a profile already holds is a no-op, not a replacement — and retiring it\n* would revoke the credential the command has just committed to. Trimmed on both sides, because\n* a key read from a file or a pipe arrives with a trailing newline.\n*/\nconst isSameCredential = (existingKey, replacementKey) => {\n\tif (existingKey === void 0 || replacementKey === void 0) return false;\n\tconst trimmed = existingKey.trim();\n\treturn trimmed !== \"\" && trimmed === replacementKey.trim();\n};\n//#endregion\nexport { API_KEY, OAUTH, apiKeyCredentials, credentialKind, credentialLabel, credentialsRepairHint, describeScope, inspectCredentials, interpretCredentials, isSameCredential, parseCredentialsJson, readCredentials, scopeOf, writeCredentials };\n\n//# sourceMappingURL=credentials.js.map","import { CRED_STORAGE_FILE, CRED_STORAGE_KEYRING } from \"./cli_config.js\";\nimport { isOwnedCredentialPath } from \"./paths.js\";\nimport { profilesFilePath } from \"./profiles.js\";\nimport { credentialLabel, inspectCredentials, parseCredentialsJson, readCredentials, writeCredentials } from \"./credentials.js\";\nimport { existsSync, rmSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { createHash } from \"node:crypto\";\n//#region src/credential_store.ts\nconst KEYRING_SERVICE = \"com.neon.neon-cli\";\n/** Hashing the resolved profiles directory isolates config roots while keeping profile names visible. */\nconst keyringAccount = (configDir, profile) => `cli:${createHash(\"sha256\").update(dirname(profilesFilePath(configDir))).digest(\"hex\")}:${profile}`;\nvar KeyringUnavailableError = class extends Error {\n\tconstructor(profile, kind = \"read\") {\n\t\tconst loaded = \"This CLI cannot use the OS keyring.\";\n\t\tsuper(profile === void 0 ? `${loaded} Drop \\`--keyring\\` to keep the credential in a file.` : kind === \"write\" ? `${loaded} Remove the profile with \\`neon profile remove ${profile} --yes\\`.` : `${loaded} Use --api-key or NEON_API_KEY. If this is a standalone neon binary, use the npm-installed neon instead. To reset the profile: \\`neon profile remove ${profile} --yes\\`.`);\n\t\tthis.name = \"KeyringUnavailableError\";\n\t}\n};\nvar KeyringUnreadableError = class extends Error {\n\tconstructor(profile) {\n\t\tconst replace = `\\`neon auth --profile ${profile}\\``;\n\t\tsuper(`Could not read the OS keyring item for profile \"${profile}\". Unlock the keyring and retry, or run ${replace}. To reset the profile: \\`neon profile remove ${profile} --yes\\`.`);\n\t\tthis.name = \"KeyringUnreadableError\";\n\t}\n};\nvar KeyringClearError = class extends Error {\n\tconstructor(profile, kind = \"visible\") {\n\t\tconst recovery = `\\`neon profile remove ${profile} --yes\\``;\n\t\tsuper(kind === \"unconfirmed\" ? `Could not confirm the OS keyring item for profile \"${profile}\" is gone. The OS store does not distinguish a missing item from denied access. Unlock the OS keyring and retry, or reset the profile with ${recovery} (a leftover may remain; it is unused once the profile is gone).` : `Could not clear the OS keyring item for profile \"${profile}\". Unlock the OS keyring and retry, or reset the profile with ${recovery} (a leftover may remain; it is unused once the profile is gone).`);\n\t\tthis.name = \"KeyringClearError\";\n\t}\n};\nconst deleteFileIfPresent = (path) => {\n\tif (!existsSync(path)) return false;\n\trmSync(path);\n\treturn true;\n};\nconst inspectKeyringItem = (keyring, account, label) => {\n\tif (keyring === null) return { kind: \"absent\" };\n\tlet raw;\n\ttry {\n\t\traw = keyring.get(KEYRING_SERVICE, account);\n\t} catch {\n\t\treturn { kind: \"absent\" };\n\t}\n\tif (raw === null) return { kind: \"absent\" };\n\treturn parseCredentialsJson(raw, label);\n};\nconst createCredentialStore = (dir, options = {}) => {\n\tconst keyring = options.keyring ?? null;\n\tconst accountFor = (profile) => keyringAccount(dir, profile);\n\tconst assertKeyringWritable = (profile) => {\n\t\tif (keyring === null) throw new KeyringUnavailableError(profile, \"write\");\n\t};\n\tconst setKeyringOrRollback = (profile, credentials, restorePrevious) => {\n\t\tassertKeyringWritable(profile);\n\t\tconst kr = keyring;\n\t\tif (kr === null) throw new KeyringUnavailableError(profile, \"write\");\n\t\tconst account = accountFor(profile);\n\t\tconst label = `profile \"${profile}\"`;\n\t\tlet previous = null;\n\t\ttry {\n\t\t\tprevious = kr.get(KEYRING_SERVICE, account);\n\t\t} catch {\n\t\t\tprevious = null;\n\t\t}\n\t\ttry {\n\t\t\tkr.set(KEYRING_SERVICE, account, JSON.stringify(credentials));\n\t\t} catch {\n\t\t\tthrow new KeyringUnavailableError();\n\t\t}\n\t\ttry {\n\t\t\tif (kr.get(\"com.neon.neon-cli\", account) === null) throw new Error(`Wrote credentials to the OS keyring for ${label} but could not read them back.`);\n\t\t} catch (err) {\n\t\t\tif (restorePrevious && previous !== null) {\n\t\t\t\ttry {\n\t\t\t\t\tkr.set(KEYRING_SERVICE, account, previous);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new KeyringClearError(profile, \"visible\");\n\t\t\t\t}\n\t\t\t\tlet restored = null;\n\t\t\t\ttry {\n\t\t\t\t\trestored = kr.get(KEYRING_SERVICE, account);\n\t\t\t\t} catch {\n\t\t\t\t\trestored = null;\n\t\t\t\t}\n\t\t\t\tif (restored === null) throw new KeyringClearError(profile, \"visible\");\n\t\t\t}\n\t\t\tthrow err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t};\n\tconst removeKeyringItem = (profile, required, account = accountFor(profile)) => {\n\t\tif (keyring === null) {\n\t\t\tif (required) throw new KeyringUnavailableError(profile, \"write\");\n\t\t\treturn \"unconfirmed\";\n\t\t}\n\t\tlet raw;\n\t\ttry {\n\t\t\traw = keyring.get(KEYRING_SERVICE, account);\n\t\t} catch (err) {\n\t\t\tif (!required) return \"unconfirmed\";\n\t\t\tthrow err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t\tif (raw === null) {\n\t\t\tif (required) throw new KeyringClearError(profile, \"unconfirmed\");\n\t\t\treturn \"unconfirmed\";\n\t\t}\n\t\tlet deleted;\n\t\ttry {\n\t\t\tdeleted = keyring.delete(KEYRING_SERVICE, account);\n\t\t} catch (err) {\n\t\t\tif (!required) return \"unconfirmed\";\n\t\t\tthrow err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t\tlet still;\n\t\ttry {\n\t\t\tstill = keyring.get(KEYRING_SERVICE, account);\n\t\t} catch (err) {\n\t\t\tif (!required) return \"unconfirmed\";\n\t\t\tthrow err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t\tif (!deleted || still !== null) {\n\t\t\tif (required) throw new KeyringClearError(profile, \"visible\");\n\t\t\treturn \"left\";\n\t\t}\n\t\treturn \"cleared\";\n\t};\n\tconst inspect = (at) => {\n\t\tif (at.storage === \"keyring\") {\n\t\t\tif (keyring === null) return {\n\t\t\t\tfile: \"unreadable\",\n\t\t\t\tstorage: CRED_STORAGE_KEYRING,\n\t\t\t\tcredentials: null,\n\t\t\t\treason: new KeyringUnavailableError(at.profile).message\n\t\t\t};\n\t\t\tconst keyringRead = inspectKeyringItem(keyring, accountFor(at.profile), credentialLabel(at));\n\t\t\tif (keyringRead.kind === \"ok\") return {\n\t\t\t\tfile: \"ok\",\n\t\t\t\tstorage: CRED_STORAGE_KEYRING,\n\t\t\t\tcredentials: keyringRead.credentials\n\t\t\t};\n\t\t\tif (keyringRead.kind === \"unusable\") return {\n\t\t\t\tfile: \"unreadable\",\n\t\t\t\tstorage: CRED_STORAGE_KEYRING,\n\t\t\t\tcredentials: null,\n\t\t\t\treason: keyringRead.reason\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tfile: \"unreadable\",\n\t\t\t\tstorage: CRED_STORAGE_KEYRING,\n\t\t\t\tcredentials: null,\n\t\t\t\treason: new KeyringUnreadableError(at.profile).message\n\t\t\t};\n\t\t}\n\t\tconst fileRead = inspectCredentials(at.path);\n\t\treturn {\n\t\t\tfile: fileRead.kind === \"ok\" ? \"ok\" : fileRead.kind === \"absent\" ? \"missing\" : \"invalid\",\n\t\t\tstorage: CRED_STORAGE_FILE,\n\t\t\tcredentials: fileRead.kind === \"ok\" ? fileRead.credentials : null,\n\t\t\t...fileRead.kind === \"unusable\" ? { reason: fileRead.reason } : {}\n\t\t};\n\t};\n\tconst read = (at) => {\n\t\tif (at.storage === \"keyring\") {\n\t\t\tif (keyring === null) throw new KeyringUnavailableError(at.profile);\n\t\t\tlet raw;\n\t\t\ttry {\n\t\t\t\traw = keyring.get(KEYRING_SERVICE, accountFor(at.profile));\n\t\t\t} catch {\n\t\t\t\tthrow new KeyringUnreadableError(at.profile);\n\t\t\t}\n\t\t\tif (raw === null) throw new KeyringUnreadableError(at.profile);\n\t\t\tconst parsed = parseCredentialsJson(raw, credentialLabel(at));\n\t\t\tif (parsed.kind === \"unusable\") throw new Error(parsed.reason);\n\t\t\tif (parsed.kind !== \"ok\") throw new KeyringUnreadableError(at.profile);\n\t\t\treturn {\n\t\t\t\tcredentials: parsed.credentials,\n\t\t\t\tbackend: CRED_STORAGE_KEYRING,\n\t\t\t\tprofile: at.profile\n\t\t\t};\n\t\t}\n\t\tconst credentials = readCredentials(at);\n\t\tif (credentials === null) return null;\n\t\treturn {\n\t\t\tcredentials,\n\t\t\tbackend: CRED_STORAGE_FILE,\n\t\t\tpath: at.path,\n\t\t\tprofile: at.profile\n\t\t};\n\t};\n\tconst write = (at, credentials, options) => {\n\t\tif (at.storage === \"keyring\") {\n\t\t\tsetKeyringOrRollback(at.profile, credentials, options?.restorePrevious !== false);\n\t\t\treturn {\n\t\t\t\tcredentials,\n\t\t\t\tbackend: CRED_STORAGE_KEYRING,\n\t\t\t\tprofile: at.profile\n\t\t\t};\n\t\t}\n\t\twriteCredentials(at.path, credentials);\n\t\treturn {\n\t\t\tcredentials,\n\t\t\tbackend: CRED_STORAGE_FILE,\n\t\t\tpath: at.path,\n\t\t\tprofile: at.profile\n\t\t};\n\t};\n\tconst del = (at, deleteOptions) => {\n\t\tconst required = deleteOptions?.required !== false;\n\t\tif (at.storage === \"keyring\") return removeKeyringItem(at.profile, required, deleteOptions?.account);\n\t\tif (!isOwnedCredentialPath(dir, at.path)) return \"skipped\";\n\t\treturn deleteFileIfPresent(at.path) ? \"cleared\" : \"absent\";\n\t};\n\treturn {\n\t\tinspect,\n\t\tread,\n\t\twrite,\n\t\tdelete: del,\n\t\tassertKeyringWritable\n\t};\n};\n//#endregion\nexport { KEYRING_SERVICE, KeyringClearError, KeyringUnavailableError, KeyringUnreadableError, createCredentialStore, keyringAccount };\n\n//# sourceMappingURL=credential_store.js.map","import { createRequire } from \"node:module\";\nimport type { KeyringBackend } from \"@neon-internals/cli-core/credential_store\";\n\ntype NapiEntry = {\n\tgetPassword(): string | null;\n\tsetPassword(password: string): void;\n\tdeletePassword(): boolean;\n};\n\ntype NapiKeyring = {\n\tEntry: new (service: string, account: string) => NapiEntry;\n};\n\nconst isPackaged = (): boolean =>\n\t(process as { pkg?: unknown }).pkg !== undefined;\n\nconst isMissingItem = (err: unknown): boolean => {\n\tconst message = err instanceof Error ? err.message : String(err);\n\treturn /no matching entry|not found|password not found/i.test(message);\n};\n\nexport const tryLoadKeyring = (): KeyringBackend | null => {\n\tif (isPackaged()) return null;\n\ttry {\n\t\tconst require = createRequire(import.meta.url);\n\t\tconst spec = [\"@napi-rs\", \"keyring\"].join(\"/\");\n\t\tconst loaded = require(spec) as NapiKeyring;\n\t\tconst { Entry } = loaded;\n\t\treturn {\n\t\t\tget(service, account) {\n\t\t\t\ttry {\n\t\t\t\t\treturn new Entry(service, account).getPassword();\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (isMissingItem(err)) return null;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t},\n\t\t\tset(service, account, password) {\n\t\t\t\tnew Entry(service, account).setPassword(password);\n\t\t\t},\n\t\t\tdelete(service, account) {\n\t\t\t\ttry {\n\t\t\t\t\treturn new Entry(service, account).deletePassword();\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (isMissingItem(err)) return false;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n};\n","import {\n\tdisplacedProfileWarning,\n\tselectCredential,\n} from \"@neon-internals/cli-core/auth_selection\";\nimport { createCredentialStore } from \"@neon-internals/cli-core/credential_store\";\nimport {\n\ttype CredentialLocation,\n\tcredentialLabel,\n\tinterpretCredentials,\n} from \"@neon-internals/cli-core/credentials\";\nimport { configDir, resolveConfigFile } from \"@neon-internals/cli-core/paths\";\nimport {\n\tDEFAULT_PROFILE,\n\tlocationForName,\n\treadProfiles,\n} from \"@neon-internals/cli-core/profiles\";\nimport { tryLoadKeyring } from \"./keyring.js\";\n\n/**\n * Resolve the Neon API key for a `neon-env` CLI invocation.\n *\n * Precedence is the `neon` CLI's, from the same module: **an explicit flag beats an ambient\n * environment variable.** `--api-key` and `--profile` together is an error; `--profile` beats\n * `NEON_API_KEY`; `--api-key` beats `NEON_PROFILE`; two ambient sources resolve to the key.\n *\n * Sharing that decision rather than restating it is the point. An earlier version of this file\n * checked `NEON_API_KEY` before the selected profile, so `NEON_API_KEY=… neon-env run --profile\n * work` silently used the wrong account — the very bug this feature fixes in `neon`.\n *\n * The CLI owns the resolution because `@neon/config` and `@neon/env`'s root export are\n * deliberately environment- and filesystem-agnostic: they accept an explicit `apiKey` and\n * nothing else, so the ambient sources a *user* expects have to be read out here.\n */\nexport function resolveApiKey(options: {\n\tapiKey?: string;\n\tprofile?: string;\n\tenv?: NodeJS.ProcessEnv;\n\t/** Where to say that an exported key displaced an exported profile. Defaults to stderr. */\n\twarn?: (message: string) => void;\n}): string | undefined {\n\tconst env = options.env ?? process.env;\n\tconst selection = selectCredential({\n\t\t...(options.apiKey !== undefined ? { apiKeyFlag: options.apiKey } : {}),\n\t\t...(options.profile !== undefined\n\t\t\t? { profileFlag: options.profile }\n\t\t\t: {}),\n\t\t...(env.NEON_API_KEY !== undefined\n\t\t\t? { apiKeyEnv: env.NEON_API_KEY }\n\t\t\t: {}),\n\t\t...(env.NEON_PROFILE !== undefined\n\t\t\t? { profileEnv: env.NEON_PROFILE }\n\t\t\t: {}),\n\t});\n\n\t// Sharing the decision is only half of it. The disclosure is the half that keeps a\n\t// displaced profile from being the original bug in a quieter form: `NEON_API_KEY=…\n\t// NEON_PROFILE=work neon-env run` legitimately uses the key, and saying nothing leaves the\n\t// user believing they ran as `work`. `neon` has warned here from the start; this did not.\n\tconst displaced = displacedProfileWarning(selection);\n\tif (displaced !== null) {\n\t\tconst warn =\n\t\t\toptions.warn ??\n\t\t\t((message: string) => process.stderr.write(`${message}\\n`));\n\t\twarn(displaced);\n\t}\n\n\tif (selection.source !== \"profile\") return selection.apiKey;\n\treturn readStoredCredential(selection, env);\n}\n\n/**\n * The credential stored for the selected profile.\n *\n * Two different situations, deliberately not merged. A **missing** credential under `DEFAULT` is\n * the ordinary not-signed-in state and resolves to no key; under a profile the user named it is\n * an error, because reporting a missing credential would hide that the real problem is the name\n * they typed. A **damaged** credential is always an error: the file is there, it is not an\n * absence, and no amount of signing in elsewhere explains it.\n */\nfunction readStoredCredential(\n\tselection: { profile: string; explicit: boolean },\n\tenv: NodeJS.ProcessEnv,\n): string | undefined {\n\tconst { profile, explicit } = selection;\n\t/**\n\t * An *absence* is only an error when the user named the profile. Not being signed in under\n\t * `DEFAULT` is the ordinary state, and the library's `PLATFORM_MISSING_API_KEY` says it\n\t * better than a stack trace.\n\t */\n\tconst absent = (reason: string): undefined => {\n\t\tif (explicit) throw new Error(reason);\n\t\treturn undefined;\n\t};\n\n\tconst dir = configDir({ env });\n\tlet at: CredentialLocation;\n\ttry {\n\t\tat = locationForName(dir, profile);\n\t} catch (err) {\n\t\t// An unknown profile name is a naming error whoever typed it can fix, so it is fatal\n\t\t// either way — it cannot be reported as \"not signed in\".\n\t\tthrow err instanceof Error ? err : new Error(String(err));\n\t}\n\t// The new config root would miss DEFAULT credentials left in legacy `neonctl/` installs.\n\tif (\n\t\tat.storage === \"file\" &&\n\t\tprofile === DEFAULT_PROFILE &&\n\t\treadProfiles(dir)?.profiles[DEFAULT_PROFILE] === undefined\n\t) {\n\t\tat = {\n\t\t\t...at,\n\t\t\tpath: resolveConfigFile(\"credentials.json\", { env }).path,\n\t\t};\n\t}\n\n\tconst store = createCredentialStore(configDir({ env }), {\n\t\tkeyring: tryLoadKeyring(),\n\t});\n\tconst loaded = store.read(at);\n\tif (loaded === null) {\n\t\treturn absent(\n\t\t\t`Profile \"${profile}\" has no stored credential at ${credentialLabel(at)}. Sign in with \\`neon profile create ${profile}\\`.`,\n\t\t);\n\t}\n\n\tconst credential = interpretCredentials(\n\t\tloaded.credentials,\n\t\tat,\n\t\tloaded.backend,\n\t);\n\tif (credential.kind === \"api_key\") return credential.apiKey;\n\tconst token = loaded.credentials.access_token;\n\tif (typeof token === \"string\" && token.trim() !== \"\") return token.trim();\n\tthrow new Error(\n\t\t`Profile \"${profile}\" holds a browser sign-in with no usable token at ${credentialLabel(at)}. Sign in again with \\`neon auth --profile ${profile}\\`.`,\n\t);\n}\n\nexport { DEFAULT_PROFILE };\n","import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, resolve } from \"node:path\";\n\n/**\n * Resolved project + branch context for the `neon-env` CLI. The CLI owns this resolution\n * (flags → `NEON_*` env → `.neon[/project.json]` file) so the `@neon/env` library\n * functions can stay filesystem- and env-agnostic.\n */\nexport interface ResolvedContext {\n\tprojectId: string;\n\t/** Branch ref — a name (preferred for readability) or an id (`br-…`). */\n\tbranch: string;\n}\n\nexport interface ResolveContextOptions {\n\tprojectId?: string;\n\tbranch?: string;\n\tcwd: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\n/**\n * Resolve `projectId` and `branch` for a CLI invocation. Precedence (each wins over the\n * next): explicit flag → `NEON_*` env var → `.neon[/project.json]` walked up from `cwd`.\n *\n * Returns the resolved values plus a list of human-readable reasons for any field that\n * could not be resolved (so the caller can render one combined error).\n */\nexport function resolveContext(\n\toptions: ResolveContextOptions,\n): { ok: true; context: ResolvedContext } | { ok: false; missing: string[] } {\n\tconst env = options.env ?? process.env;\n\tconst file = findNeonFile(options.cwd);\n\n\tconst projectId =\n\t\tnonEmpty(options.projectId) ??\n\t\tnonEmpty(env.NEON_PROJECT_ID) ??\n\t\tfile?.projectId;\n\n\t// A branch ref — name (preferred) or id. `NEON_BRANCH` carries the name; `NEON_BRANCH_ID`\n\t// is the legacy id-only var. The `.neon` file pins `branch` (name) via `neonctl link`,\n\t// with legacy `branchId` still honored. fetchEnv resolves either form by name or id.\n\tconst branch =\n\t\tnonEmpty(options.branch) ??\n\t\tnonEmpty(env.NEON_BRANCH) ??\n\t\tnonEmpty(env.NEON_BRANCH_ID) ??\n\t\tfile?.branch;\n\n\tconst missing: string[] = [];\n\tif (!projectId) {\n\t\tmissing.push(\n\t\t\t\"project id — pass `--project-id`, set `NEON_PROJECT_ID`, or add `projectId` to `.neon` (run `npx neon link`).\",\n\t\t);\n\t}\n\tif (!branch) {\n\t\tmissing.push(\n\t\t\t\"branch — pass `--branch`, set `NEON_BRANCH`/`NEON_BRANCH_ID`, or add `branch` to `.neon` (run `npx neon link` / `neon checkout <branch>`).\",\n\t\t);\n\t}\n\tif (!projectId || !branch) return { ok: false, missing };\n\n\treturn {\n\t\tok: true,\n\t\tcontext: { projectId, branch },\n\t};\n}\n\ninterface NeonFile {\n\tprojectId?: string;\n\t/** Branch ref — name (preferred) or id. Reads `branch`, falling back to legacy `branchId`. */\n\tbranch?: string;\n}\n\n/**\n * Walk up from `cwd` looking for `.neon/project.json` (preferred) or `.neon` (neonctl\n * convention). Stops at the first `.git` directory or the home directory. Read-only.\n */\nfunction findNeonFile(cwd: string): NeonFile | null {\n\tlet current = resolve(cwd);\n\tconst stop = resolve(homedir());\n\tlet lastSeen: string | null = null;\n\n\twhile (true) {\n\t\tconst parsed =\n\t\t\treadNeonFileAt(resolve(current, \".neon\", \"project.json\")) ??\n\t\t\treadNeonFileAt(resolve(current, \".neon\"));\n\t\tif (parsed) return parsed;\n\n\t\tif (current === stop) return null;\n\t\tif (existsSync(resolve(current, \".git\"))) return null;\n\n\t\tconst parent = dirname(current);\n\t\tif (parent === current || parent === lastSeen) return null;\n\t\tlastSeen = current;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction readNeonFileAt(path: string): NeonFile | null {\n\tif (!isFile(path)) return null;\n\tlet raw: string;\n\ttry {\n\t\traw = readFileSync(path, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\treturn null;\n\tconst obj = parsed as Record<string, unknown>;\n\tconst out: NeonFile = {};\n\tif (typeof obj.projectId === \"string\" && obj.projectId !== \"\")\n\t\tout.projectId = obj.projectId;\n\t// Prefer the `branch` field (name or id, written by `neonctl link`); fall back to the\n\t// legacy id-only `branchId`.\n\tconst branch =\n\t\ttypeof obj.branch === \"string\" && obj.branch !== \"\"\n\t\t\t? obj.branch\n\t\t\t: typeof obj.branchId === \"string\" && obj.branchId !== \"\"\n\t\t\t\t? obj.branchId\n\t\t\t\t: undefined;\n\tif (branch) out.branch = branch;\n\treturn out;\n}\n\nfunction isFile(path: string): boolean {\n\ttry {\n\t\treturn statSync(path).isFile();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? undefined : trimmed;\n}\n","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 \"@neon/config/v1\";\nimport { fetchEnvReusingSecrets } from \"@neon-internals/env-core/reuse-secrets\";\nimport { resolveApiKey } from \"./resolve-api-key.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 * the key {@link resolveApiKey} resolves (`--api-key` → `NEON_API_KEY` → the Neon CLI's\n\t * stored credentials).\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. Everything\n * ambient — `.neon`, `NEON_*` env, the Neon CLI's stored credentials — is resolved by the\n * CLI (see `resolveContext` and `resolveApiKey`), never by the library.\n */\nexport interface EnvResolveOptions {\n\tconfigPath?: string;\n\tprojectId?: string;\n\tbranch?: string;\n\tapiKey?: string;\n\t/** Neon CLI profile whose stored credential to use. `--profile`, else `NEON_PROFILE`. */\n\tprofile?: 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\tinjected = await loadConfigAndFetchEnv(options, ctx, resolved.context);\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\tentries = await loadConfigAndFetchEnv(options, ctx, resolved.context);\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 resolve the branch env for the explicitly-resolved project + branch.\n * Layers `.env.local` (next to the config file) into the env source so re-runs keep the\n * one-time secrets the Neon API only returns once — the branch credential's, and any Auth\n * values a pre-`base_url` integration can no longer report. Uses\n * {@link fetchEnvReusingSecrets} rather than a bare `fetchEnv` so a run that already has a\n * working credential verifies and keeps it instead of minting another one per invocation.\n */\nasync function loadConfigAndFetchEnv(\n\toptions: EnvResolveOptions,\n\tctx: CommandEnv,\n\tresolved: { projectId: string; branch: string },\n): Promise<Record<string, string>> {\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\tconst apiKey = resolveApiKey({\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.profile ? { profile: options.profile } : {}),\n\t});\n\tconst { vars } = await fetchEnvReusingSecrets(config, {\n\t\tprojectId: resolved.projectId,\n\t\tbranch: resolved.branch,\n\t\tenv: { ...process.env, ...fileEnv },\n\t\t...(ctx.api ? { api: ctx.api } : {}),\n\t\t...(apiKey ? { apiKey } : {}),\n\t});\n\treturn vars;\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\t// The library's own wording is right for a library (\"this package never reads\n\t// NEON_API_KEY on your behalf\") and wrong here: `neon-env` does read it. Render the\n\t// chain this CLI actually implements, the same way an unresolved context is rendered.\n\tif (err instanceof PlatformError && err.code === ErrorCode.MissingApiKey) {\n\t\treturn errorResult(\n\t\t\terr,\n\t\t\t[\n\t\t\t\t\"No Neon API key. `neon-env` looks for one in this order:\",\n\t\t\t\t\" - the `--api-key` flag\",\n\t\t\t\t\" - the `NEON_API_KEY` environment variable\",\n\t\t\t\t\" - `credentials.json` in `NEONCTL_CONFIG_DIR` (else `~/.config/neonctl`) — run `neon auth` to create it\",\n\t\t\t].join(\"\\n\"),\n\t\t\tEXIT_CODE_BY_PLATFORM_ERROR_CODE[ErrorCode.MissingApiKey] ?? 1,\n\t\t);\n\t}\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","#!/usr/bin/env node\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport {\n\ttype CommandResult,\n\trunEnvExport,\n\trunEnvRun,\n} from \"./lib/cli/commands.js\";\n\nconst pkgVersion = readPackageVersion();\n\nconst argv = yargs(hideBin(process.argv))\n\t.scriptName(\"neon-env\")\n\t.usage(\"$0 <command> [options]\")\n\t.parserConfiguration({ \"populate--\": true })\n\t.option(\"debug\", {\n\t\ttype: \"boolean\",\n\t\tdefault: false,\n\t\tdescribe:\n\t\t\t\"Print stack traces and structured error details when something fails\",\n\t})\n\t.command(\n\t\t\"run\",\n\t\t\"Run a command with Neon env vars (from your neon.ts policy) injected into its environment. Use `--` to separate the command: `neon-env run -- npm run dev`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.command(\n\t\t\"export\",\n\t\t\"Print the branch's Neon env vars (from your neon.ts policy) to stdout, as dotenv lines or JSON. Useful for piping into other env tools, e.g. `neon-env export --format json`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"format\", {\n\t\t\t\t\tchoices: [\"dotenv\", \"json\"] as const,\n\t\t\t\t\tdefault: \"dotenv\",\n\t\t\t\t\tdescribe: \"Output format: dotenv (KEY=value lines) or json\",\n\t\t\t\t})\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.demandCommand(1, \"Run `neon-env --help` to see the available commands.\")\n\t.strict()\n\t.help()\n\t.version(pkgVersion)\n\t.parseSync();\n\nconst command = String(argv._[0]);\nconst cwd = process.cwd();\n\nlet result: CommandResult;\nswitch (command) {\n\tcase \"run\": {\n\t\tconst passthrough = Array.isArray(argv[\"--\"])\n\t\t\t? argv[\"--\"].map(String)\n\t\t\t: [];\n\t\tresult = await runEnvRun(\n\t\t\t{\n\t\t\t\tcommand: passthrough,\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tcase \"export\": {\n\t\tresult = await runEnvExport(\n\t\t\t{\n\t\t\t\tformat: argv.format === \"json\" ? \"json\" : \"dotenv\",\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tresult = {\n\t\t\texitCode: 1,\n\t\t\tstdout: \"\",\n\t\t\tstderr: `Unknown command: ${command}\\n`,\n\t\t};\n}\n\nif (result.stdout) process.stdout.write(result.stdout);\nif (result.stderr) process.stderr.write(result.stderr);\nif (argv.debug && result.exitCode !== 0 && result.debugInfo) {\n\tprocess.stderr.write(`\\n--- debug ---\\n${result.debugInfo}\\n`);\n}\nprocess.exit(result.exitCode);\n\nfunction readPackageVersion(): string {\n\t// The built CLI lives at `dist/cli.js`, so `package.json` is one directory up. When\n\t// running from source (tsx, vitest), the file lives at `src/cli.ts` and `package.json`\n\t// is again one directory up. Single resolution covers both layouts.\n\ttry {\n\t\tconst pkgUrl = new URL(\"../package.json\", import.meta.url);\n\t\tconst raw = readFileSync(fileURLToPath(pkgUrl), \"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AAO,MAAM,oBAAoB,OAAO,UAAU,GAAG;AAE9D,QAAQ,KAAK,OAAO,QAAQ;AAE5B,SAAS,qBAA6B;CAIrC,IAAI;EACH,MAAM,SAAS,IAAI,IAAI,mBAAmB,YAAY,GAAG;EACzD,MAAM,MAAM,aAAa,cAAc,MAAM,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,OAAO,OAAO,OAAO,YAAY,WAAW,OAAO,UAAU;CAC9D,QAAQ;EACP,OAAO;CACR;AACD"}
|
|
1
|
+
{"version":3,"file":"cli.js","names":["nonEmpty","nonEmpty","nonEmpty"],"sources":["../../../internals/env-core/dist/reuse-secrets.js","../../../internals/cli-core/dist/cli_config.js","../../../internals/cli-core/dist/paths.js","../../../internals/cli-core/dist/secure_file.js","../../../internals/cli-core/dist/profiles.js","../../../internals/cli-core/dist/auth_selection.js","../../../internals/cli-core/dist/credentials.js","../../../internals/cli-core/dist/credential_store.js","../src/lib/cli/keyring.ts","../src/lib/cli/resolve-api-key.ts","../src/lib/cli/resolve-context.ts","../src/lib/cli/commands.ts","../src/cli.ts"],"sourcesContent":["import { NEON_ENV_VAR_KEYS, createApiFromOptions, credentialEnvKeys, credentialName, defaultAiGatewayCredential, defaultStorageCredential, fetchEnvKeysState, isFunctionBaseUrlKey, isLiveCredential, policyEnvKeys, resolveBranchPolicy, toEntries } from \"./env.js\";\nimport { credentialScopesSatisfied } from \"@neon/config/v1\";\n//#region src/reuse-secrets.ts\n/**\n* Resolve a branch's env while keeping secrets the caller already holds.\n*\n* {@link fetchEnvKeys} reveals the platform default credentials (or mints a fallback when a\n* region has none). Calling it on every `neon dev` start would rewrite `.env` with freshly\n* revealed secrets each time. This wrapper looks at what the caller already has, keeps a\n* half when it already *is* that default (storage and gateway are independent credentials),\n* and asks `fetchEnv` for only the rest.\n*\n* The check is a real verification, not a presence test. A persisted secret is kept only when\n* it names a credential that still exists on this branch, is not revoked or expired, and —\n* when defaults exist — *is* that default. A leftover `neon-env ${branch}` credential this\n* tool minted is replaced by the defaults and revoked. A `.env.example` placeholder, a\n* credential revoked in the console, or one copied in from another branch fails that check.\n*\n* None of this needs local bookkeeping, because the secrets carry their own credential id:\n* `AWS_ACCESS_KEY_ID` **is** the credential's `tokenId` (the storage gateway authenticates\n* against the full id), and the AI Gateway token is minted as `nt_live_<tokenIdShort>_<secret>`,\n* where `tokenIdShort` is what the credentials list reports. The env source being replaced is\n* the record of what the last call issued.\n*\n* ```ts\n* import { fetchEnvReusingSecrets } from \"@neon-internals/env-core/reuse-secrets\";\n*\n* const { vars, credential } = await fetchEnvReusingSecrets(config, {\n* projectId,\n* branch: \"main\",\n* env: { ...process.env, ...readEnvFile(\".env\") },\n* });\n* if (credential.issued) console.log(`new values for ${credential.keys.join(\", \")}`);\n* ```\n*/\nasync function fetchEnvReusingSecrets(config, options) {\n\tconst { env: source = process.env, keys: requestedKeys, revokeSuperseded = true, ...fetchOptions } = options;\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst { branch, desired } = await resolveBranchPolicy(config, options, api);\n\tconst allPolicyKeys = policyEnvKeys(desired);\n\tconst requested = requestedKeys ? new Set(requestedKeys) : null;\n\tconst selectedPolicyKeys = requested === null ? allPolicyKeys : [...allPolicyKeys.filter((key) => requested.has(key)), ...[...requested].filter(isFunctionBaseUrlKey).sort()];\n\tconst selected = new Set(selectedPolicyKeys);\n\tconst K = NEON_ENV_VAR_KEYS;\n\tconst storageCredentialSelected = (desired.preview?.buckets.length ?? 0) > 0 && (selected.has(K.storage.accessKeyId) || selected.has(K.storage.secretAccessKey));\n\tconst gatewayCredentialSelected = (desired.preview?.aiGatewayEnabled ?? false) && selected.has(K.aiGateway.apiKey);\n\tconst secretKeys = credentialEnvKeys({\n\t\tstorage: storageCredentialSelected,\n\t\taiGateway: gatewayCredentialSelected\n\t}).filter((key) => selected.has(key));\n\tif (secretKeys.length === 0) {\n\t\tconst fetched = await fetchEnvKeysState(config, fetchOptions, requested === null ? null : selectedPolicyKeys);\n\t\treturn {\n\t\t\tvars: preferPersisted(toEntries(fetched.env), source),\n\t\t\tcredential: {\n\t\t\t\tissued: false,\n\t\t\t\tkeys: [],\n\t\t\t\trevoked: [],\n\t\t\t\tsuperseded: []\n\t\t\t},\n\t\t\t...fetched.functionUrlsUnavailable ? { functionUrlsUnavailable: true } : {}\n\t\t};\n\t}\n\tconst persisted = readPersistedSecrets(source);\n\tconst storageCredentialManaged = requested === null || storageCredentialSelected;\n\tconst gatewayCredentialManaged = requested === null || gatewayCredentialSelected;\n\tconst storageComplete = Boolean(persisted.accessKeyId && persisted.secretAccessKey);\n\tconst gatewayComplete = Boolean(persisted.apiToken);\n\tconst listed = storageCredentialManaged && persisted.accessKeyId !== \"\" || gatewayCredentialManaged && persisted.apiToken !== \"\" ? await api.listCredentials(options.projectId, branch.id) : [];\n\tconst named = listed.length > 0 ? namedCredentials(listed, persisted) : {\n\t\tstorage: null,\n\t\tgateway: null\n\t};\n\tconst now = Date.now();\n\tconst storageDefault = defaultStorageCredential(listed, now);\n\tconst gatewayDefault = defaultAiGatewayCredential(listed, now);\n\tconst keepStorage = !storageCredentialSelected || storageComplete && halfReusable(named.storage, storageDefault, [\"storage:read\", \"storage:write\"]);\n\tconst keepGateway = !gatewayCredentialSelected || gatewayComplete && halfReusable(named.gateway, gatewayDefault, [\"ai_gateway:invoke\"]);\n\tconst keptSecretKeys = credentialEnvKeys({\n\t\tstorage: storageCredentialSelected && keepStorage,\n\t\taiGateway: gatewayCredentialSelected && keepGateway\n\t}).filter((key) => selected.has(key));\n\tconst fetchKeys = requested === null ? null : selectedPolicyKeys.filter((key) => !keptSecretKeys.includes(key));\n\tconst fetched = await fetchEnvKeysState(config, {\n\t\t...fetchOptions,\n\t\tbranchId: branch.id,\n\t\tapi,\n\t\t...keptSecretKeys.length > 0 && requested === null ? { omitKeys: keptSecretKeys } : {}\n\t}, fetchKeys);\n\tconst vars = preferPersisted(toEntries(fetched.env), source);\n\tconst unavailable = fetched.functionUrlsUnavailable ? { functionUrlsUnavailable: true } : {};\n\tfor (const key of keptSecretKeys) {\n\t\tconst value = source[key];\n\t\tif (value !== void 0) vars[key] = value;\n\t}\n\tif (!(storageCredentialSelected && !keepStorage || gatewayCredentialSelected && !keepGateway)) return {\n\t\tvars,\n\t\tcredential: {\n\t\t\tissued: false,\n\t\t\tkeys: secretKeys,\n\t\t\trevoked: [],\n\t\t\tsuperseded: []\n\t\t},\n\t\t...unavailable\n\t};\n\tconst ours = /* @__PURE__ */ new Set();\n\tfor (const meta of [storageCredentialManaged && !keepStorage ? named.storage : null, gatewayCredentialManaged && !keepGateway ? named.gateway : null]) if (meta !== null && meta.principalType === \"user\" && meta.name === credentialName(branch.name)) ours.add(meta.tokenId);\n\tif (revokeSuperseded) for (const tokenId of ours) await api.revokeCredential(options.projectId, branch.id, tokenId);\n\treturn {\n\t\tvars,\n\t\tcredential: {\n\t\t\tissued: true,\n\t\t\tkeys: secretKeys,\n\t\t\trevoked: revokeSuperseded ? [...ours] : [],\n\t\t\tsuperseded: revokeSuperseded ? [] : [...ours]\n\t\t},\n\t\t...unavailable\n\t};\n}\n/** Read the branch credential's secrets out of an env source. */\nfunction readPersistedSecrets(source) {\n\tconst storage = NEON_ENV_VAR_KEYS.storage;\n\tconst gateway = NEON_ENV_VAR_KEYS.aiGateway;\n\treturn {\n\t\taccessKeyId: source[storage.accessKeyId] ?? \"\",\n\t\tsecretAccessKey: source[storage.secretAccessKey] ?? \"\",\n\t\tapiToken: source[gateway.apiKey] ?? \"\"\n\t};\n}\n/**\n* Keep a persisted value rather than overwriting it with an empty fetched one.\n*\n* Neon Auth's `base_url` is the case that needs this: integrations created before the API\n* returned it answer with an empty string, and the persisted copy is the only one left. An\n* empty fetched value never carries more information than a non-empty persisted one, so\n* preferring the latter is safe for every var — and it keeps a pull from blanking a working\n* line in someone's `.env`.\n*/\nfunction preferPersisted(vars, source) {\n\tconst out = { ...vars };\n\tfor (const [key, value] of Object.entries(out)) {\n\t\tif (value !== \"\") continue;\n\t\tconst persisted = source[key];\n\t\tif (persisted !== void 0 && persisted !== \"\") out[key] = persisted;\n\t}\n\treturn out;\n}\n/**\n* The credential id embedded in an AI Gateway token. The API mints them as\n* `nt_live_<tokenIdShort>_<secret>`, and `tokenIdShort` is the public identifier the credentials\n* list reports — so a persisted token names the credential that issued it. Returns `null` for\n* anything not in that shape (a `.env.example` placeholder, a hand-typed value), which callers\n* treat as unverifiable.\n*/\nfunction gatewayTokenIdShort(apiToken) {\n\treturn /^nt_live_([^_]+)_.+$/.exec(apiToken)?.[1] ?? null;\n}\n/**\n* The live credentials the persisted secrets name — at most one per half. A half that names\n* nothing contributes nothing, which is what a placeholder, a credential revoked in the\n* console, and one copied in from another branch all look like from here.\n*/\nfunction namedCredentials(live, persisted) {\n\tconst usable = live.filter((meta) => isLiveCredential(meta, Date.now()));\n\tconst shortId = persisted.apiToken ? gatewayTokenIdShort(persisted.apiToken) : null;\n\treturn {\n\t\tstorage: persisted.accessKeyId ? usable.find((meta) => meta.tokenId === persisted.accessKeyId) ?? null : null,\n\t\tgateway: shortId ? usable.find((meta) => meta.tokenIdShort === shortId) ?? null : null\n\t};\n}\n/**\n* Whether a persisted half can be reused.\n*\n* When a platform default exists, only that default is reusable — a leftover\n* `neon-env ${branch}` mint is replaced. When no default exists (mint fallback),\n* any live credential the secrets name is reusable if it still carries the\n* scopes that half needs.\n*/\nfunction halfReusable(named, defaultMeta, requiredScopes) {\n\tif (named === null) return false;\n\tif (defaultMeta !== null) return named.tokenId === defaultMeta.tokenId;\n\treturn credentialScopesSatisfied(named.scopes, requiredScopes);\n}\n//#endregion\nexport { fetchEnvReusingSecrets };\n\n//# sourceMappingURL=reuse-secrets.js.map","//#region src/cli_config.ts\nconst CRED_STORAGE_FILE = \"file\";\nconst CRED_STORAGE_KEYRING = \"keyring\";\n//#endregion\nexport { CRED_STORAGE_FILE, CRED_STORAGE_KEYRING };\n\n//# sourceMappingURL=cli_config.js.map","import { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n//#region src/paths.ts\n/**\n* # Where the Neon CLIs keep their files on disk\n*\n**Deliberately impure.** It reads environment variables and touches the filesystem, which\n* `@neon/config` — the package this used to be a subpath of — must never do from its root\n* export. It lives here instead of there precisely so that a policy-facing package does not\n* carry implementor-only code.\n*\n* It exists because three separate readers each grew their own answer to \"where is the\n* config directory\", and all three disagreed: `packages/cli` honoured `XDG_CONFIG_HOME` but\n* not `NEONCTL_CONFIG_DIR`, `packages/env` honoured the env var but not XDG, and the init\n* flow hardcoded `~/.config/neonctl`. With `XDG_CONFIG_HOME` set, the CLI wrote\n* credentials somewhere the other two never looked.\n*\n* ## The directory\n*\n* `neon` is the current name; `neonctl` is the legacy one, kept readable forever. Resolution,\n* each entry winning over the next:\n*\n* 1. An explicit directory (a `--config-dir` flag) — **exact**, no legacy fallback.\n* 2. `NEON_CONFIG_DIR` — exact.\n* 3. `NEONCTL_CONFIG_DIR` (legacy name) — exact.\n* 4. `$XDG_CONFIG_HOME/neon`, else `<home>/.config/neon`.\n*\n* An explicitly chosen directory is never paired with a fallback: `--config-dir /tmp/ci` that\n* quietly read `~/.config/neonctl` would defeat the point of passing it.\n*\n* ## The files\n*\n* {@link resolveConfigFile} answers \"which path should I use for this file\", and it is the\n* same answer for reading and writing:\n*\n* - Present in `neon/` → use it.\n* - Present only in `neonctl/` → **use it there, in place.** An existing credentials file is\n* never copied or moved, so nothing is left behind to go stale and no other tool starts\n* reading an abandoned token.\n* - Present in neither → the new location. New files only ever appear under `neon/`.\n*/\n/** Current directory name. New files are created here. */\nconst CONFIG_DIR_NAME = \"neon\";\n/** Legacy directory name, read forever so existing installs keep working untouched. */\nconst LEGACY_CONFIG_DIR_NAME = \"neonctl\";\n/** Where files are created. See the module docs for the precedence. */\nfunction configDir(options = {}) {\n\tconst explicit = explicitDir(options);\n\tif (explicit) return explicit;\n\treturn join(configHome(options.env ?? process.env), CONFIG_DIR_NAME);\n}\n/**\n* The legacy directory, or `undefined` when the location was chosen explicitly (in which\n* case there is no legacy counterpart to fall back to).\n*/\nfunction legacyConfigDir(options = {}) {\n\tif (explicitDir(options)) return void 0;\n\treturn join(configHome(options.env ?? process.env), LEGACY_CONFIG_DIR_NAME);\n}\n/**\n* Resolve one file inside the config directory. Prefers the current location, falls back to\n* an existing legacy file **in place**, and otherwise points at the current location so new\n* files are created there.\n*/\nfunction resolveConfigFile(fileName, options = {}) {\n\tconst dir = configDir(options);\n\tconst current = resolve(dir, fileName);\n\tif (existsSync(current)) return {\n\t\tpath: current,\n\t\tdir,\n\t\tisLegacy: false,\n\t\texists: true\n\t};\n\tconst legacyDir = legacyConfigDir(options);\n\tif (legacyDir) {\n\t\tconst legacy = resolve(legacyDir, fileName);\n\t\tif (existsSync(legacy)) return {\n\t\t\tpath: legacy,\n\t\t\tdir: legacyDir,\n\t\t\tisLegacy: true,\n\t\t\texists: true\n\t\t};\n\t}\n\treturn {\n\t\tpath: current,\n\t\tdir,\n\t\tisLegacy: false,\n\t\texists: false\n\t};\n}\n/** `$XDG_CONFIG_HOME`, else `<home>/.config`. Falls back to a relative `.config` with no home. */\nfunction configHome(env) {\n\tconst xdg = nonEmpty(env.XDG_CONFIG_HOME);\n\tif (xdg) return xdg;\n\tconst home = nonEmpty(env.HOME) ?? nonEmpty(env.USERPROFILE);\n\treturn home ? join(home, \".config\") : \".config\";\n}\nfunction explicitDir(options) {\n\tconst env = options.env ?? process.env;\n\treturn nonEmpty(options.dir) ?? nonEmpty(env.NEON_CONFIG_DIR) ?? nonEmpty(env.NEONCTL_CONFIG_DIR);\n}\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\nconst CREDENTIALS_FILE = \"credentials.json\";\n/**\n* Default for `--config-dir`: `$XDG_CONFIG_HOME/neon`, else `~/.config/neon`.\n*\n* The directory was called `neonctl` until the CLI was renamed. An existing one is still read —\n* see {@link credentialsPath} — but it is never written to, moved, or deleted.\n*/\nconst defaultDir = configDir();\n/**\n* Where this invocation's `credentials.json` lives.\n*\n* When `--config-dir` was left at its default, an existing file in the legacy `neonctl`\n* directory is used **in place**: an install that predates the rename keeps working, and its\n* credentials are never duplicated into a second location where one copy could go stale while\n* another tool still reads it.\n*\n* A `--config-dir` the user actually passed is used exactly as given. Falling back out of an\n* explicitly chosen directory would defeat the reason for choosing it — a CI run pointed at a\n* scratch directory must never pick up a developer's real credentials.\n*/\nconst credentialsPath = (dir) => resolveConfigFile(CREDENTIALS_FILE, dir === defaultDir ? {} : { dir }).path;\n/**\n* Whether a credentials file is one the CLI created, rather than a path a profile adopted.\n*\n* Anything that deletes a credential has to ask this first. A profile entry may point anywhere —\n* that is what makes adopting an existing directory a one-line edit — and a file we did not\n* create is not ours to remove.\n*/\nconst isInsideConfigDir = (configDirectory, file) => `${resolve(file)}/`.startsWith(`${resolve(configDirectory)}/`);\n/**\n* Whether a credentials file is one the CLI owns, counting the legacy `neonctl` directory.\n*\n* {@link credentialsPath} deliberately reads an existing legacy file in place rather than\n* migrating it, so for a default config directory that file is ours even though it sits outside\n* `neon/`. Judging ownership on the current directory alone would call an install that predates\n* the rename \"adopted\".\n*/\nconst isOwnedCredentialPath = (configDirectory, file) => {\n\tif (isInsideConfigDir(configDirectory, file)) return true;\n\tif (configDirectory !== defaultDir) return false;\n\tconst legacy = legacyConfigDir();\n\treturn legacy !== void 0 && isInsideConfigDir(legacy, file);\n};\n//#endregion\nexport { CONFIG_DIR_NAME, CREDENTIALS_FILE, LEGACY_CONFIG_DIR_NAME, configDir, credentialsPath, defaultDir, isInsideConfigDir, isOwnedCredentialPath, legacyConfigDir, resolveConfigFile };\n\n//# sourceMappingURL=paths.js.map","import { renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\n//#region src/secure_file.ts\n/** Owner read/write. A credential needs those two and nothing else. */\nconst SECRET_FILE_MODE = 384;\n/**\n* Write a secret to disk owner-only, by creating a temporary file in the same directory and\n* renaming it over the target.\n*\n* The rename is what makes this correct rather than merely tidy. `writeFileSync`'s `mode`\n* applies only when it *creates* the file, so writing over an existing credentials file\n* leaves whatever permissions it already had — a file created `0700` by an older release\n* stays `0700` forever, and one created before a umask change stays world-readable. Renaming\n* a fresh inode into place means every write lands at {@link SECRET_FILE_MODE}, so the\n* permissions repair themselves instead of being inherited.\n*\n* It also closes the window where a reader could see the file at default permissions: the\n* temporary file is created `0600` *before* it holds the secret's final name, and `rename`\n* is atomic within a directory, so there is no moment at which the target is readable by\n* anyone else and no moment at which it is half-written.\n*\n* The temporary name carries the pid so two processes writing at once cannot collide on it.\n*/\nconst writeSecretFile = (path, contents) => {\n\tconst directory = dirname(path);\n\tconst temporary = join(directory, `.${basename(path)}.${process.pid}.${Date.now()}.tmp`);\n\ttry {\n\t\twriteFileSync(temporary, contents, {\n\t\t\tencoding: \"utf8\",\n\t\t\tmode: 384\n\t\t});\n\t\trenameSync(temporary, path);\n\t} catch (err) {\n\t\ttry {\n\t\t\tunlinkSync(temporary);\n\t\t} catch {}\n\t\tthrow err;\n\t}\n};\n//#endregion\nexport { SECRET_FILE_MODE, writeSecretFile };\n\n//# sourceMappingURL=secure_file.js.map","import { CRED_STORAGE_FILE, CRED_STORAGE_KEYRING } from \"./cli_config.js\";\nimport { credentialsPath, defaultDir, resolveConfigFile } from \"./paths.js\";\nimport { writeSecretFile } from \"./secure_file.js\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\n//#region src/profiles.ts\n/**\n* Pointer-only profiles avoid mirrored credentials and persistent active-profile\n* state while preserving existing single-account and legacy-directory installs.\n*/\nconst PROFILES_FILE = \"profiles.json\";\nconst KEYRING_CREDENTIALS = \"keyring\";\nconst isKeyringPointer = (credentials) => credentials === KEYRING_CREDENTIALS;\n/** The implicit profile. Backed by plain `credentials.json`, with or without a profiles file. */\nconst DEFAULT_PROFILE = \"DEFAULT\";\n/** Profile names become part of a filename, so keep them boring. */\nconst NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nconst locationOf = (profile) => profile.storage === \"keyring\" ? {\n\tprofile: profile.name,\n\tstorage: CRED_STORAGE_KEYRING\n} : {\n\tprofile: profile.name,\n\tstorage: CRED_STORAGE_FILE,\n\tpath: profile.credentialsPath\n};\nconst credentialsDisplay = (profile) => profile.storage === \"keyring\" ? KEYRING_CREDENTIALS : profile.credentialsPath;\n/** Which profile this invocation should use: `--profile` → `NEON_PROFILE` → `DEFAULT`. */\nconst selectProfileName = (flag, env = process.env) => nonEmpty(flag) ?? nonEmpty(env.NEON_PROFILE) ?? \"DEFAULT\";\nconst assertValidProfileName = (name) => {\n\tif (!NAME_PATTERN.test(name)) throw new Error(`Invalid profile name \"${name}\". Use letters, digits, dot, dash or underscore, starting with a letter or digit.`);\n};\n/** Where `profiles.json` lives for this config directory (whether or not it exists yet). */\nconst profilesFilePath = (dir) => resolveConfigFile(PROFILES_FILE, dir === defaultDir ? {} : { dir }).path;\n/**\n* Read and classify `profiles.json` without deciding what to do about it.\n*\n* Entry keys and shapes are validated here rather than at each use. A key is a profile name,\n* and a name that `assertValidProfileName` would reject cannot have been written by this CLI —\n* it would travel into error messages as a recovery command nobody can run, and into a\n* `credentials.<name>.json` filename.\n*/\nconst inspectProfiles = (dir) => {\n\tconst path = profilesFilePath(dir);\n\tif (!existsSync(path)) return { kind: \"absent\" };\n\tconst broken = (why) => ({\n\t\tkind: \"unusable\",\n\t\treason: `${path} could not be read as a profiles file: ${why}`\n\t});\n\tlet contents;\n\ttry {\n\t\tcontents = readFileSync(path, \"utf8\");\n\t} catch (err) {\n\t\tconst code = err.code;\n\t\treturn broken(code ? `reading it failed with ${code}` : \"reading it failed\");\n\t}\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(contents);\n\t} catch {\n\t\treturn broken(\"it is not valid JSON\");\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) return broken(\"it does not contain an object\");\n\tconst profiles = parsed.profiles;\n\tif (profiles === null || typeof profiles !== \"object\" || Array.isArray(profiles)) return broken(\"it has no `profiles` object\");\n\tfor (const [name, entry] of Object.entries(profiles)) {\n\t\tif (!NAME_PATTERN.test(name)) return broken(`\"${name}\" is not a valid profile name`);\n\t\tif (entry === null || typeof entry !== \"object\" || typeof entry.credentials !== \"string\" || entry.credentials.trim() === \"\") return broken(`profile \"${name}\" has no \\`credentials\\` pointer`);\n\t}\n\treturn {\n\t\tkind: \"ok\",\n\t\tfile: {\n\t\t\tversion: 1,\n\t\t\tprofiles\n\t\t}\n\t};\n};\n/**\n* Read `profiles.json`, or `null` when there is nothing usable there.\n*\n* A malformed file is reported through `onWarn` and treated as absent, because for a *read* the\n* worst case is a named profile turning up missing, which is recoverable — whereas throwing\n* would lock the user out of `neon auth` itself. Writing is the opposite: see\n* {@link upsertProfile}, which refuses rather than rebuilding a file it cannot read.\n*/\nconst readProfiles = (dir, onWarn = () => {}) => {\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"ok\") return read.file;\n\tif (read.kind === \"unusable\") onWarn(read.reason);\n\treturn null;\n};\n/**\n* Storage cannot be trusted when the profiles file cannot be read.\n*\n* Call this **before** anything that writes a credential, opens a browser, or spends an API\n* call. {@link upsertProfile} refuses too, but it runs last: by then `create` has already\n* overwritten `credentials.<name>.json` and revoked the key it replaced, and `neon auth\n* --profile` has already signed in over it — a refusal that arrives after the destruction it\n* exists to prevent. The path resolution itself is the unsound part, since with the metadata\n* unreadable the conventional filename is a guess about which account that file belongs to.\n*\n* DEFAULT follows the same rule because the broken file may be its only\n* keyring pointer.\n*/\nconst assertProfilesUsable = (dir, name) => {\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. Fix or delete the file before working with profile \"${name}\" — it is the only record of where each account's credentials live.`);\n};\n/** Resolve a profile to an absolute credentials path. Throws when a named profile is unknown. */\nconst resolveProfile = (dir, name) => {\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. Fix or delete the file — every profile is defined in it.`);\n\tconst file = read.kind === \"ok\" ? read.file : null;\n\tconst entry = file?.profiles[name];\n\tif (entry) {\n\t\tif (isKeyringPointer(entry.credentials)) return {\n\t\t\tname,\n\t\t\tstorage: CRED_STORAGE_KEYRING,\n\t\t\t...entry.label ? { label: entry.label } : {},\n\t\t\t...entry.userId ? { userId: entry.userId } : {},\n\t\t\tdeclared: true\n\t\t};\n\t\treturn {\n\t\t\tname,\n\t\t\tstorage: CRED_STORAGE_FILE,\n\t\t\tcredentialsPath: resolveEntryPath(dir, entry.credentials),\n\t\t\t...entry.label ? { label: entry.label } : {},\n\t\t\t...entry.userId ? { userId: entry.userId } : {},\n\t\t\tdeclared: true\n\t\t};\n\t}\n\tif (name === \"DEFAULT\") return {\n\t\tname,\n\t\tstorage: CRED_STORAGE_FILE,\n\t\tcredentialsPath: credentialsPath(dir),\n\t\tdeclared: false\n\t};\n\tconst known = file ? Object.keys(file.profiles).join(\", \") : DEFAULT_PROFILE;\n\tthrow new Error(`Unknown profile \"${name}\". Known profiles: ${known}. Create it with \\`neon profile create ${name}\\`.`);\n};\n/** Default location for a new named profile's credentials file. */\nconst newProfileCredentialsPath = (dir, name) => resolve(dir, `credentials.${name}.json`);\n/**\n* Record a profile, creating `profiles.json` if this is the first named one.\n*\n* When the file is created, `DEFAULT` is written explicitly and pointed at wherever\n* `credentials.json` actually is. That matters for an install predating the directory\n* rename: `profiles.json` is created in `neon/` while the credentials are still in\n* `neonctl/`, so `DEFAULT` is recorded as `../neonctl/credentials.json` rather than a\n* relative name that would resolve to a file that isn't there.\n*/\nconst upsertProfile = (dir, name, entry) => {\n\tassertValidProfileName(name);\n\tconst path = profilesFilePath(dir);\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. Refusing to rewrite it, because doing so would discard the profiles it defines. Fix or delete the file, then re-run.`);\n\tconst file = read.kind === \"ok\" ? read.file : {\n\t\tversion: 1,\n\t\tprofiles: { [DEFAULT_PROFILE]: { credentials: storedPointer(path, credentialsPath(dir)) } }\n\t};\n\tfile.profiles[name] = {\n\t\tcredentials: storedPointer(path, entry.credentials),\n\t\t...entry.label ? { label: entry.label } : {},\n\t\t...entry.userId ? { userId: entry.userId } : {}\n\t};\n\twriteProfiles(path, file);\n};\n/** Remove an entry. Returns false when it wasn't there. */\nconst removeProfileEntry = (dir, name) => {\n\tconst path = profilesFilePath(dir);\n\tconst file = readProfiles(dir);\n\tif (!file?.profiles[name]) return false;\n\tdelete file.profiles[name];\n\twriteProfiles(path, file);\n\treturn true;\n};\nconst onlyDefaultRemains = (file) => {\n\tconst names = Object.keys(file.profiles);\n\treturn names.length === 0 || names.length === 1 && names[0] === \"DEFAULT\";\n};\nconst canDropProfilesFile = (file) => {\n\tif (!onlyDefaultRemains(file)) return false;\n\tconst remaining = file.profiles[DEFAULT_PROFILE];\n\treturn remaining === void 0 || !isKeyringPointer(remaining.credentials);\n};\nconst locationForName = (dir, name) => locationOf(resolveProfile(dir, name));\nconst newProfileLocation = (dir, name, storage) => storage === \"keyring\" ? {\n\tprofile: name,\n\tstorage: CRED_STORAGE_KEYRING\n} : {\n\tprofile: name,\n\tstorage: CRED_STORAGE_FILE,\n\tpath: newProfileCredentialsPath(dir, name)\n};\nconst profilesUsingPath = (dir, path, except) => {\n\tconst resolved = resolve(path);\n\treturn listProfiles(dir).filter((profile) => profile.name !== except && profile.storage === \"file\" && resolve(profile.credentialsPath) === resolved).map((profile) => profile.name);\n};\nconst listProfiles = (dir) => {\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. Fix or delete the file — every named profile is defined in it.`);\n\tconst file = read.kind === \"ok\" ? read.file : null;\n\tif (!file) return [resolveProfile(dir, DEFAULT_PROFILE)];\n\tconst names = Object.keys(file.profiles);\n\tif (!names.includes(\"DEFAULT\")) names.unshift(DEFAULT_PROFILE);\n\treturn names.map((name) => resolveProfile(dir, name));\n};\nconst writeProfiles = (path, file) => {\n\twriteSecretFile(path, `${JSON.stringify(file, null, 2)}\\n`);\n};\nconst resolveEntryPath = (dir, entry) => isAbsolute(entry) ? entry : resolve(profilesDir(dir), entry);\n/** `profiles.json` may sit in the legacy directory, so entries resolve against its own dir. */\nconst profilesDir = (dir) => resolve(profilesFilePath(dir), \"..\");\n/** A relative file named `keyring` would otherwise collide with the storage sentinel. */\nconst storedPointer = (profilesPath, credentials) => {\n\tif (isKeyringPointer(credentials)) return KEYRING_CREDENTIALS;\n\tconst base = resolve(profilesPath, \"..\");\n\tconst abs = isAbsolute(credentials) ? credentials : resolve(base, credentials);\n\tconst rel = relative(base, abs);\n\tconst stored = rel && !isAbsolute(rel) ? rel : abs;\n\treturn stored === \"keyring\" ? `./${KEYRING_CREDENTIALS}` : stored;\n};\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\n//#endregion\nexport { DEFAULT_PROFILE, KEYRING_CREDENTIALS, PROFILES_FILE, assertProfilesUsable, assertValidProfileName, canDropProfilesFile, credentialsDisplay, inspectProfiles, isKeyringPointer, listProfiles, locationForName, locationOf, newProfileCredentialsPath, newProfileLocation, onlyDefaultRemains, profilesFilePath, profilesUsingPath, readProfiles, removeProfileEntry, resolveProfile, selectProfileName, upsertProfile };\n\n//# sourceMappingURL=profiles.js.map","import \"./profiles.js\";\n//#region src/auth_selection.ts\n/**\n* # Which credential an invocation authenticates with\n*\n* Four inputs can each answer \"who am I\": the `--api-key` flag, `NEON_API_KEY`, the\n* `--profile` flag, and `NEON_PROFILE`. This module decides between them, and it is pure so\n* the decision can be tested without a filesystem, a network, or a config directory.\n*\n* ## The rule\n*\n* **An explicit flag beats an ambient environment variable.** That single rule fixes the bug\n* this module exists for: before it, any API key — including one merely exported into the\n* shell — silently voided `--profile`, so `neon --profile work …` would quietly run as\n* whoever `NEON_API_KEY` belonged to and say nothing about it.\n*\n* | Given | What runs |\n* | --- | --- |\n* | `--api-key` and `--profile` | neither: contradictory explicit flags, so this throws |\n* | `--api-key` and `NEON_PROFILE` | the flag's key |\n* | `--profile` and `NEON_API_KEY` | the profile |\n* | `NEON_API_KEY` and `NEON_PROFILE` | the key, and the ignored profile is named in a warning |\n* | `--profile` or `NEON_PROFILE` alone | that profile |\n* | nothing | `DEFAULT` |\n*\n* Two explicit flags throw rather than picking a winner. They express different intents —\n* `--api-key` supplies a credential, `--profile` selects a stored one — so there is no\n* reading of the command that makes both true, and guessing is how the original bug behaved.\n*\n* When both are merely ambient, the key wins. That keeps CI exactly as it was: a pipeline\n* that injects `NEON_API_KEY` must not change behaviour because a `NEON_PROFILE` leaked into\n* the environment. It warns instead of staying silent, because a disregarded account\n* selection is precisely what nobody noticed last time.\n*\n* `auth` and the `profile` subcommands do not use any of this. They read the same flags with\n* different meanings — `neon auth --profile work` names where to *write* a credential, and\n* `neon profile create work --api-key …` names one to *store* — so their callers skip\n* selection entirely rather than passing exemptions down here.\n*/\nlet inputs = {\n\tapiKeyFlag: \"\",\n\tapiKeyEnv: \"\",\n\tprofileEnv: \"\",\n\tprofileFlag: \"\",\n\tconfigDir: \"\"\n};\nconst recordCredentialInputs = (recorded) => {\n\tinputs = recorded;\n};\nconst credentialInputs = () => inputs;\nconst selectCredential = ({ apiKeyFlag, profileFlag, apiKeyEnv, profileEnv }) => {\n\tconst flagKey = nonEmpty(apiKeyFlag);\n\tconst flagProfile = nonEmpty(profileFlag);\n\tif (flagKey !== void 0 && flagProfile !== void 0) throw new Error(\"Pass either --api-key or --profile, not both. --api-key supplies a credential directly; --profile selects a stored one.\");\n\tif (flagKey !== void 0) return {\n\t\tsource: \"explicit-api-key\",\n\t\tapiKey: flagKey\n\t};\n\tif (flagProfile !== void 0) return {\n\t\tsource: \"profile\",\n\t\tprofile: flagProfile,\n\t\texplicit: true\n\t};\n\tconst envKey = nonEmpty(apiKeyEnv);\n\tconst envProfile = nonEmpty(profileEnv);\n\tif (envKey !== void 0) return {\n\t\tsource: \"ambient-api-key\",\n\t\tapiKey: envKey,\n\t\t...envProfile !== void 0 ? { ignoredProfile: envProfile } : {}\n\t};\n\treturn {\n\t\tsource: \"profile\",\n\t\tprofile: envProfile ?? \"DEFAULT\",\n\t\texplicit: envProfile !== void 0\n\t};\n};\n/** The warning for an ambient key that displaced an ambient profile, or `null`. */\nconst displacedProfileWarning = (selection) => selection.source === \"ambient-api-key\" && selection.ignoredProfile !== void 0 ? `NEON_API_KEY is set, so profile \"${selection.ignoredProfile}\" from NEON_PROFILE was ignored. Pass --profile ${selection.ignoredProfile} to use it instead.` : null;\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\n//#endregion\nexport { credentialInputs, displacedProfileWarning, recordCredentialInputs, selectCredential };\n\n//# sourceMappingURL=auth_selection.js.map","import { writeSecretFile } from \"./secure_file.js\";\nimport { readFileSync } from \"node:fs\";\n//#region src/credentials.ts\n/**\n* # Stored credentials — one file per account, two kinds\n*\n* A profile points at exactly one credentials file (see `./profiles.ts`), and that file says\n* what kind of credential it holds. Adding API-key support this way rather than adding a\n* second pointer to `profiles.json` keeps a profile what it already was — one name, one path\n* — and means `profiles.json` needs no schema change at all.\n*\n* ```json\n* // oauth: every file written before this existed. An absent `type` means this.\n* { \"access_token\": \"…\", \"refresh_token\": \"…\", \"expires_at\": 1786…, \"user_id\": \"…\" }\n*\n* // api_key, stored by `neon profile create --api-key`\n* { \"type\": \"api_key\", \"api_key\": \"napi_…\", \"user_id\": \"…\" }\n*\n* // api_key minted by `--mint --org-id`, which records the scope it was issued at\n* { \"type\": \"api_key\", \"api_key\": \"napi_…\", \"key_id\": 123, \"org_id\": \"org-…\" }\n* ```\n*\n* ## One profile, one kind\n*\n* A credentials file holds an API key or an OAuth session, never both, and `type` states\n* which. An earlier draft let the two coexist — the idea being that a key could keep the\n* session it was minted from and so rotate without a browser. It did not survive review, for\n* two reasons that are worth recording so nobody rebuilds it:\n*\n* 1. **It never worked.** The resolver returned the key without testing it, so a revoked key\n* failed to mint and never fell back to the session sitting beside it.\n* 2. **It could mix accounts.** Nothing compared the identity of the credential being written\n* with the one already there, so a profile could hold one account's session and another's\n* key, told apart only by a single string. Flip or lose `type` and the profile silently\n* becomes a different person.\n*\n* Recovery from a dead key is therefore one browser login — `neon profile create <name>\n* --mint` — which is what the retained session was supposed to save and never did.\n*\n* ## Older releases\n*\n* A CLI predating this reads the pointer, finds no `type` it understands, ignores it, and\n* looks for `access_token`. An `api_key` profile has none, so an older release falls through\n* to its browser login rather than crashing. That it does not crash is why `credentials`\n* stays a required pointer: an entry without one makes 2.41 and 2.42 throw\n* `ERR_INVALID_ARG_TYPE` from `resolveEntryPath`.\n*/\nconst OAUTH = \"oauth\";\nconst API_KEY = \"api_key\";\nconst credentialLabel = (at) => at.storage === \"keyring\" ? `the OS keyring item for profile \"${at.profile}\"` : at.path;\n/**\n* Which credential in this file authenticates, by declaration alone.\n*\n* An unrecognised `type` throws rather than falling back to `oauth`. A file we cannot\n* interpret is a misconfiguration the user has to see: treating it as OAuth would send them\n* to a browser login that silently replaces a credential they meant to keep, and treating it\n* as an API key would authenticate with whatever `api_key` happened to be there.\n*\n* This deliberately does not check that an `api_key` file has a key — `neon profile list`\n* needs the kind of a file it is not about to authenticate with, and must be able to report a\n* broken one rather than throwing halfway through a table.\n*/\nconst credentialKind = (credentials, at, store = \"file\") => {\n\tconst declared = credentials.type;\n\tif (declared === void 0 || declared === \"oauth\") return OAUTH;\n\tif (declared === \"api_key\") return API_KEY;\n\tthrow new Error(`${credentialLabel(at)} declares a \"type\" this version does not understand. Expected \"${OAUTH}\" or \"${API_KEY}\". ${credentialsRepairHint(at, store)}`);\n};\nconst credentialsRepairHint = (at, store = \"file\") => store === \"keyring\" ? `Replace it deliberately with \\`neon profile create ${at.profile}\\`, or remove the profile with \\`neon profile remove ${at.profile}\\`.` : `Replace it deliberately with \\`neon profile create ${at.profile}\\`, or delete the file.`;\n/**\n* Resolve what to authenticate with, validating that the declared kind is actually usable.\n*\n* An `api_key` file with no key is a hard error rather than a fall-through to OAuth: the user\n* asked for a key, and quietly opening a browser instead would replace the credential they\n* were trying to fix.\n*/\nconst interpretCredentials = (credentials, at, store = \"file\") => {\n\tif (credentialKind(credentials, at, store) === \"oauth\") return { kind: OAUTH };\n\tconst apiKey = nonEmpty(credentials.api_key);\n\tif (apiKey === void 0) throw new Error(`${credentialLabel(at)} declares \"type\": \"${API_KEY}\" but has no \"api_key\" value. ${credentialsRepairHint(at, store)}`);\n\treturn {\n\t\tkind: API_KEY,\n\t\tapiKey\n\t};\n};\n/**\n* Read and classify a credentials file, without deciding what to do about it.\n*\n* A permission or I/O error still throws: there may be a perfectly good credential here that\n* we cannot see, and treating that as absent would send the user to a browser login that\n* overwrites it.\n*/\n/** Discard parser details because V8 may quote secret material near a syntax error. */\nconst parseCredentialsJson = (contents, label) => {\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(contents);\n\t} catch {\n\t\treturn {\n\t\t\tkind: \"unusable\",\n\t\t\treason: `${label} is not valid JSON, so the credential in it cannot be read`\n\t\t};\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) return {\n\t\tkind: \"unusable\",\n\t\treason: `${label} does not contain a credentials object`\n\t};\n\treturn {\n\t\tkind: \"ok\",\n\t\tcredentials: parsed\n\t};\n};\nconst inspectCredentials = (path) => {\n\tlet contents;\n\ttry {\n\t\tcontents = readFileSync(path, \"utf8\");\n\t} catch (err) {\n\t\tif (err.code === \"ENOENT\") return { kind: \"absent\" };\n\t\tthrow err;\n\t}\n\treturn parseCredentialsJson(contents, path);\n};\n/**\n* The credential at `path`, or `null` when the file is not there.\n*\n* A damaged file is an error, not an absence. Treating it as absent — which is what this used to\n* do — meant any read-only command could repair it by starting a browser sign-in and overwriting\n* it, **possibly as a different account**, with the user never having asked for a repair and no\n* way back to whatever was in the file. Failing here costs one deliberate command; the message\n* names it.\n*\n* `profile list` and telemetry use {@link inspectCredentials} instead, because describing a\n* broken credential is not the same as using one.\n*/\nconst readCredentials = (at) => {\n\tconst read = inspectCredentials(at.path);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. ${credentialsRepairHint(at)}`);\n\treturn read.kind === \"ok\" ? read.credentials : null;\n};\nconst writeCredentials = (path, credentials) => {\n\twriteSecretFile(path, JSON.stringify(credentials));\n};\n/**\n* Build an `api_key` credentials object. Nothing from a previous credential is carried over.\n*\n* The scope is stored because it is not recoverable from the secret: `rotate-key` has to mint\n* the replacement on the same endpoint, and an org or project key minted as an account key\n* would silently widen what the profile reaches.\n*/\nconst apiKeyCredentials = ({ apiKey, keyId, userId, scope }) => ({\n\ttype: API_KEY,\n\tapi_key: apiKey,\n\t...keyId !== void 0 ? { key_id: keyId } : {},\n\t...userId !== void 0 ? { user_id: userId } : {},\n\t...scope?.orgId !== void 0 ? { org_id: scope.orgId } : {},\n\t...scope?.projectId !== void 0 ? { project_id: scope.projectId } : {}\n});\n/** The scope recorded on a stored credential. */\nconst scopeOf = (credentials) => ({\n\t...typeof credentials.org_id === \"string\" ? { orgId: credentials.org_id } : {},\n\t...typeof credentials.project_id === \"string\" ? { projectId: credentials.project_id } : {}\n});\n/** How to describe a scope in output. */\nconst describeScope = (scope) => {\n\tif (scope.projectId !== void 0) return `project ${scope.projectId}`;\n\tif (scope.orgId !== void 0) return `org ${scope.orgId}`;\n\treturn \"account\";\n};\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\n/**\n* Whether a stored credential is the same secret as the one about to replace it.\n*\n* Re-storing the key a profile already holds is a no-op, not a replacement — and retiring it\n* would revoke the credential the command has just committed to. Trimmed on both sides, because\n* a key read from a file or a pipe arrives with a trailing newline.\n*/\nconst isSameCredential = (existingKey, replacementKey) => {\n\tif (existingKey === void 0 || replacementKey === void 0) return false;\n\tconst trimmed = existingKey.trim();\n\treturn trimmed !== \"\" && trimmed === replacementKey.trim();\n};\n//#endregion\nexport { API_KEY, OAUTH, apiKeyCredentials, credentialKind, credentialLabel, credentialsRepairHint, describeScope, inspectCredentials, interpretCredentials, isSameCredential, parseCredentialsJson, readCredentials, scopeOf, writeCredentials };\n\n//# sourceMappingURL=credentials.js.map","import { CRED_STORAGE_FILE, CRED_STORAGE_KEYRING } from \"./cli_config.js\";\nimport { isOwnedCredentialPath } from \"./paths.js\";\nimport { profilesFilePath } from \"./profiles.js\";\nimport { credentialLabel, inspectCredentials, parseCredentialsJson, readCredentials, writeCredentials } from \"./credentials.js\";\nimport { existsSync, rmSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { createHash } from \"node:crypto\";\n//#region src/credential_store.ts\nconst KEYRING_SERVICE = \"com.neon.neon-cli\";\n/** Hashing the resolved profiles directory isolates config roots while keeping profile names visible. */\nconst keyringAccount = (configDir, profile) => `cli:${createHash(\"sha256\").update(dirname(profilesFilePath(configDir))).digest(\"hex\")}:${profile}`;\nvar KeyringUnavailableError = class extends Error {\n\tconstructor(profile, kind = \"read\") {\n\t\tconst loaded = \"This CLI cannot use the OS keyring.\";\n\t\tsuper(profile === void 0 ? `${loaded} Drop \\`--keyring\\` to keep the credential in a file.` : kind === \"write\" ? `${loaded} Remove the profile with \\`neon profile remove ${profile} --yes\\`.` : `${loaded} Use --api-key or NEON_API_KEY. If this is a standalone neon binary, use the npm-installed neon instead. To reset the profile: \\`neon profile remove ${profile} --yes\\`.`);\n\t\tthis.name = \"KeyringUnavailableError\";\n\t}\n};\nvar KeyringUnreadableError = class extends Error {\n\tconstructor(profile) {\n\t\tconst replace = `\\`neon auth --profile ${profile}\\``;\n\t\tsuper(`Could not read the OS keyring item for profile \"${profile}\". Unlock the keyring and retry, or run ${replace}. To reset the profile: \\`neon profile remove ${profile} --yes\\`.`);\n\t\tthis.name = \"KeyringUnreadableError\";\n\t}\n};\nvar KeyringClearError = class extends Error {\n\tconstructor(profile, kind = \"visible\") {\n\t\tconst recovery = `\\`neon profile remove ${profile} --yes\\``;\n\t\tsuper(kind === \"unconfirmed\" ? `Could not confirm the OS keyring item for profile \"${profile}\" is gone. The OS store does not distinguish a missing item from denied access. Unlock the OS keyring and retry, or reset the profile with ${recovery} (a leftover may remain; it is unused once the profile is gone).` : `Could not clear the OS keyring item for profile \"${profile}\". Unlock the OS keyring and retry, or reset the profile with ${recovery} (a leftover may remain; it is unused once the profile is gone).`);\n\t\tthis.name = \"KeyringClearError\";\n\t}\n};\nconst deleteFileIfPresent = (path) => {\n\tif (!existsSync(path)) return false;\n\trmSync(path);\n\treturn true;\n};\nconst inspectKeyringItem = (keyring, account, label) => {\n\tif (keyring === null) return { kind: \"absent\" };\n\tlet raw;\n\ttry {\n\t\traw = keyring.get(KEYRING_SERVICE, account);\n\t} catch {\n\t\treturn { kind: \"absent\" };\n\t}\n\tif (raw === null) return { kind: \"absent\" };\n\treturn parseCredentialsJson(raw, label);\n};\nconst createCredentialStore = (dir, options = {}) => {\n\tconst keyring = options.keyring ?? null;\n\tconst accountFor = (profile) => keyringAccount(dir, profile);\n\tconst assertKeyringWritable = (profile) => {\n\t\tif (keyring === null) throw new KeyringUnavailableError(profile, \"write\");\n\t};\n\tconst setKeyringOrRollback = (profile, credentials, restorePrevious) => {\n\t\tassertKeyringWritable(profile);\n\t\tconst kr = keyring;\n\t\tif (kr === null) throw new KeyringUnavailableError(profile, \"write\");\n\t\tconst account = accountFor(profile);\n\t\tconst label = `profile \"${profile}\"`;\n\t\tlet previous = null;\n\t\ttry {\n\t\t\tprevious = kr.get(KEYRING_SERVICE, account);\n\t\t} catch {\n\t\t\tprevious = null;\n\t\t}\n\t\ttry {\n\t\t\tkr.set(KEYRING_SERVICE, account, JSON.stringify(credentials));\n\t\t} catch {\n\t\t\tthrow new KeyringUnavailableError();\n\t\t}\n\t\ttry {\n\t\t\tif (kr.get(\"com.neon.neon-cli\", account) === null) throw new Error(`Wrote credentials to the OS keyring for ${label} but could not read them back.`);\n\t\t} catch (err) {\n\t\t\tif (restorePrevious && previous !== null) {\n\t\t\t\ttry {\n\t\t\t\t\tkr.set(KEYRING_SERVICE, account, previous);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new KeyringClearError(profile, \"visible\");\n\t\t\t\t}\n\t\t\t\tlet restored = null;\n\t\t\t\ttry {\n\t\t\t\t\trestored = kr.get(KEYRING_SERVICE, account);\n\t\t\t\t} catch {\n\t\t\t\t\trestored = null;\n\t\t\t\t}\n\t\t\t\tif (restored === null) throw new KeyringClearError(profile, \"visible\");\n\t\t\t}\n\t\t\tthrow err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t};\n\tconst removeKeyringItem = (profile, required, account = accountFor(profile)) => {\n\t\tif (keyring === null) {\n\t\t\tif (required) throw new KeyringUnavailableError(profile, \"write\");\n\t\t\treturn \"unconfirmed\";\n\t\t}\n\t\tlet raw;\n\t\ttry {\n\t\t\traw = keyring.get(KEYRING_SERVICE, account);\n\t\t} catch (err) {\n\t\t\tif (!required) return \"unconfirmed\";\n\t\t\tthrow err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t\tif (raw === null) {\n\t\t\tif (required) throw new KeyringClearError(profile, \"unconfirmed\");\n\t\t\treturn \"unconfirmed\";\n\t\t}\n\t\tlet deleted;\n\t\ttry {\n\t\t\tdeleted = keyring.delete(KEYRING_SERVICE, account);\n\t\t} catch (err) {\n\t\t\tif (!required) return \"unconfirmed\";\n\t\t\tthrow err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t\tlet still;\n\t\ttry {\n\t\t\tstill = keyring.get(KEYRING_SERVICE, account);\n\t\t} catch (err) {\n\t\t\tif (!required) return \"unconfirmed\";\n\t\t\tthrow err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t\tif (!deleted || still !== null) {\n\t\t\tif (required) throw new KeyringClearError(profile, \"visible\");\n\t\t\treturn \"left\";\n\t\t}\n\t\treturn \"cleared\";\n\t};\n\tconst inspect = (at) => {\n\t\tif (at.storage === \"keyring\") {\n\t\t\tif (keyring === null) return {\n\t\t\t\tfile: \"unreadable\",\n\t\t\t\tstorage: CRED_STORAGE_KEYRING,\n\t\t\t\tcredentials: null,\n\t\t\t\treason: new KeyringUnavailableError(at.profile).message\n\t\t\t};\n\t\t\tconst keyringRead = inspectKeyringItem(keyring, accountFor(at.profile), credentialLabel(at));\n\t\t\tif (keyringRead.kind === \"ok\") return {\n\t\t\t\tfile: \"ok\",\n\t\t\t\tstorage: CRED_STORAGE_KEYRING,\n\t\t\t\tcredentials: keyringRead.credentials\n\t\t\t};\n\t\t\tif (keyringRead.kind === \"unusable\") return {\n\t\t\t\tfile: \"unreadable\",\n\t\t\t\tstorage: CRED_STORAGE_KEYRING,\n\t\t\t\tcredentials: null,\n\t\t\t\treason: keyringRead.reason\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tfile: \"unreadable\",\n\t\t\t\tstorage: CRED_STORAGE_KEYRING,\n\t\t\t\tcredentials: null,\n\t\t\t\treason: new KeyringUnreadableError(at.profile).message\n\t\t\t};\n\t\t}\n\t\tconst fileRead = inspectCredentials(at.path);\n\t\treturn {\n\t\t\tfile: fileRead.kind === \"ok\" ? \"ok\" : fileRead.kind === \"absent\" ? \"missing\" : \"invalid\",\n\t\t\tstorage: CRED_STORAGE_FILE,\n\t\t\tcredentials: fileRead.kind === \"ok\" ? fileRead.credentials : null,\n\t\t\t...fileRead.kind === \"unusable\" ? { reason: fileRead.reason } : {}\n\t\t};\n\t};\n\tconst read = (at) => {\n\t\tif (at.storage === \"keyring\") {\n\t\t\tif (keyring === null) throw new KeyringUnavailableError(at.profile);\n\t\t\tlet raw;\n\t\t\ttry {\n\t\t\t\traw = keyring.get(KEYRING_SERVICE, accountFor(at.profile));\n\t\t\t} catch {\n\t\t\t\tthrow new KeyringUnreadableError(at.profile);\n\t\t\t}\n\t\t\tif (raw === null) throw new KeyringUnreadableError(at.profile);\n\t\t\tconst parsed = parseCredentialsJson(raw, credentialLabel(at));\n\t\t\tif (parsed.kind === \"unusable\") throw new Error(parsed.reason);\n\t\t\tif (parsed.kind !== \"ok\") throw new KeyringUnreadableError(at.profile);\n\t\t\treturn {\n\t\t\t\tcredentials: parsed.credentials,\n\t\t\t\tbackend: CRED_STORAGE_KEYRING,\n\t\t\t\tprofile: at.profile\n\t\t\t};\n\t\t}\n\t\tconst credentials = readCredentials(at);\n\t\tif (credentials === null) return null;\n\t\treturn {\n\t\t\tcredentials,\n\t\t\tbackend: CRED_STORAGE_FILE,\n\t\t\tpath: at.path,\n\t\t\tprofile: at.profile\n\t\t};\n\t};\n\tconst write = (at, credentials, options) => {\n\t\tif (at.storage === \"keyring\") {\n\t\t\tsetKeyringOrRollback(at.profile, credentials, options?.restorePrevious !== false);\n\t\t\treturn {\n\t\t\t\tcredentials,\n\t\t\t\tbackend: CRED_STORAGE_KEYRING,\n\t\t\t\tprofile: at.profile\n\t\t\t};\n\t\t}\n\t\twriteCredentials(at.path, credentials);\n\t\treturn {\n\t\t\tcredentials,\n\t\t\tbackend: CRED_STORAGE_FILE,\n\t\t\tpath: at.path,\n\t\t\tprofile: at.profile\n\t\t};\n\t};\n\tconst del = (at, deleteOptions) => {\n\t\tconst required = deleteOptions?.required !== false;\n\t\tif (at.storage === \"keyring\") return removeKeyringItem(at.profile, required, deleteOptions?.account);\n\t\tif (!isOwnedCredentialPath(dir, at.path)) return \"skipped\";\n\t\treturn deleteFileIfPresent(at.path) ? \"cleared\" : \"absent\";\n\t};\n\treturn {\n\t\tinspect,\n\t\tread,\n\t\twrite,\n\t\tdelete: del,\n\t\tassertKeyringWritable\n\t};\n};\n//#endregion\nexport { KEYRING_SERVICE, KeyringClearError, KeyringUnavailableError, KeyringUnreadableError, createCredentialStore, keyringAccount };\n\n//# sourceMappingURL=credential_store.js.map","import { createRequire } from \"node:module\";\nimport type { KeyringBackend } from \"@neon-internals/cli-core/credential_store\";\n\ntype NapiEntry = {\n\tgetPassword(): string | null;\n\tsetPassword(password: string): void;\n\tdeletePassword(): boolean;\n};\n\ntype NapiKeyring = {\n\tEntry: new (service: string, account: string) => NapiEntry;\n};\n\nconst isPackaged = (): boolean =>\n\t(process as { pkg?: unknown }).pkg !== undefined;\n\nconst isMissingItem = (err: unknown): boolean => {\n\tconst message = err instanceof Error ? err.message : String(err);\n\treturn /no matching entry|not found|password not found/i.test(message);\n};\n\nexport const tryLoadKeyring = (): KeyringBackend | null => {\n\tif (isPackaged()) return null;\n\ttry {\n\t\tconst require = createRequire(import.meta.url);\n\t\tconst spec = [\"@napi-rs\", \"keyring\"].join(\"/\");\n\t\tconst loaded = require(spec) as NapiKeyring;\n\t\tconst { Entry } = loaded;\n\t\treturn {\n\t\t\tget(service, account) {\n\t\t\t\ttry {\n\t\t\t\t\treturn new Entry(service, account).getPassword();\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (isMissingItem(err)) return null;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t},\n\t\t\tset(service, account, password) {\n\t\t\t\tnew Entry(service, account).setPassword(password);\n\t\t\t},\n\t\t\tdelete(service, account) {\n\t\t\t\ttry {\n\t\t\t\t\treturn new Entry(service, account).deletePassword();\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (isMissingItem(err)) return false;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n};\n","import {\n\tdisplacedProfileWarning,\n\tselectCredential,\n} from \"@neon-internals/cli-core/auth_selection\";\nimport { createCredentialStore } from \"@neon-internals/cli-core/credential_store\";\nimport {\n\ttype CredentialLocation,\n\tcredentialLabel,\n\tinterpretCredentials,\n} from \"@neon-internals/cli-core/credentials\";\nimport { configDir, resolveConfigFile } from \"@neon-internals/cli-core/paths\";\nimport {\n\tDEFAULT_PROFILE,\n\tlocationForName,\n\treadProfiles,\n} from \"@neon-internals/cli-core/profiles\";\nimport { tryLoadKeyring } from \"./keyring.js\";\n\n/**\n * Resolve the Neon API key for a `neon-env` CLI invocation.\n *\n * Precedence is the `neon` CLI's, from the same module: **an explicit flag beats an ambient\n * environment variable.** `--api-key` and `--profile` together is an error; `--profile` beats\n * `NEON_API_KEY`; `--api-key` beats `NEON_PROFILE`; two ambient sources resolve to the key.\n *\n * Sharing that decision rather than restating it is the point. An earlier version of this file\n * checked `NEON_API_KEY` before the selected profile, so `NEON_API_KEY=… neon-env run --profile\n * work` silently used the wrong account — the very bug this feature fixes in `neon`.\n *\n * The CLI owns the resolution because `@neon/config` and `@neon/env`'s root export are\n * deliberately environment- and filesystem-agnostic: they accept an explicit `apiKey` and\n * nothing else, so the ambient sources a *user* expects have to be read out here.\n */\nexport function resolveApiKey(options: {\n\tapiKey?: string;\n\tprofile?: string;\n\tenv?: NodeJS.ProcessEnv;\n\t/** Where to say that an exported key displaced an exported profile. Defaults to stderr. */\n\twarn?: (message: string) => void;\n}): string | undefined {\n\tconst env = options.env ?? process.env;\n\tconst selection = selectCredential({\n\t\t...(options.apiKey !== undefined ? { apiKeyFlag: options.apiKey } : {}),\n\t\t...(options.profile !== undefined\n\t\t\t? { profileFlag: options.profile }\n\t\t\t: {}),\n\t\t...(env.NEON_API_KEY !== undefined\n\t\t\t? { apiKeyEnv: env.NEON_API_KEY }\n\t\t\t: {}),\n\t\t...(env.NEON_PROFILE !== undefined\n\t\t\t? { profileEnv: env.NEON_PROFILE }\n\t\t\t: {}),\n\t});\n\n\t// Sharing the decision is only half of it. The disclosure is the half that keeps a\n\t// displaced profile from being the original bug in a quieter form: `NEON_API_KEY=…\n\t// NEON_PROFILE=work neon-env run` legitimately uses the key, and saying nothing leaves the\n\t// user believing they ran as `work`. `neon` has warned here from the start; this did not.\n\tconst displaced = displacedProfileWarning(selection);\n\tif (displaced !== null) {\n\t\tconst warn =\n\t\t\toptions.warn ??\n\t\t\t((message: string) => process.stderr.write(`${message}\\n`));\n\t\twarn(displaced);\n\t}\n\n\tif (selection.source !== \"profile\") return selection.apiKey;\n\treturn readStoredCredential(selection, env);\n}\n\n/**\n * The credential stored for the selected profile.\n *\n * Two different situations, deliberately not merged. A **missing** credential under `DEFAULT` is\n * the ordinary not-signed-in state and resolves to no key; under a profile the user named it is\n * an error, because reporting a missing credential would hide that the real problem is the name\n * they typed. A **damaged** credential is always an error: the file is there, it is not an\n * absence, and no amount of signing in elsewhere explains it.\n */\nfunction readStoredCredential(\n\tselection: { profile: string; explicit: boolean },\n\tenv: NodeJS.ProcessEnv,\n): string | undefined {\n\tconst { profile, explicit } = selection;\n\t/**\n\t * An *absence* is only an error when the user named the profile. Not being signed in under\n\t * `DEFAULT` is the ordinary state, and the library's `PLATFORM_MISSING_API_KEY` says it\n\t * better than a stack trace.\n\t */\n\tconst absent = (reason: string): undefined => {\n\t\tif (explicit) throw new Error(reason);\n\t\treturn undefined;\n\t};\n\n\tconst dir = configDir({ env });\n\tlet at: CredentialLocation;\n\ttry {\n\t\tat = locationForName(dir, profile);\n\t} catch (err) {\n\t\t// An unknown profile name is a naming error whoever typed it can fix, so it is fatal\n\t\t// either way — it cannot be reported as \"not signed in\".\n\t\tthrow err instanceof Error ? err : new Error(String(err));\n\t}\n\t// The new config root would miss DEFAULT credentials left in legacy `neonctl/` installs.\n\tif (\n\t\tat.storage === \"file\" &&\n\t\tprofile === DEFAULT_PROFILE &&\n\t\treadProfiles(dir)?.profiles[DEFAULT_PROFILE] === undefined\n\t) {\n\t\tat = {\n\t\t\t...at,\n\t\t\tpath: resolveConfigFile(\"credentials.json\", { env }).path,\n\t\t};\n\t}\n\n\tconst store = createCredentialStore(configDir({ env }), {\n\t\tkeyring: tryLoadKeyring(),\n\t});\n\tconst loaded = store.read(at);\n\tif (loaded === null) {\n\t\treturn absent(\n\t\t\t`Profile \"${profile}\" has no stored credential at ${credentialLabel(at)}. Sign in with \\`neon profile create ${profile}\\`.`,\n\t\t);\n\t}\n\n\tconst credential = interpretCredentials(\n\t\tloaded.credentials,\n\t\tat,\n\t\tloaded.backend,\n\t);\n\tif (credential.kind === \"api_key\") return credential.apiKey;\n\tconst token = loaded.credentials.access_token;\n\tif (typeof token === \"string\" && token.trim() !== \"\") return token.trim();\n\tthrow new Error(\n\t\t`Profile \"${profile}\" holds a browser sign-in with no usable token at ${credentialLabel(at)}. Sign in again with \\`neon auth --profile ${profile}\\`.`,\n\t);\n}\n\nexport { DEFAULT_PROFILE };\n","import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, resolve } from \"node:path\";\n\n/**\n * Resolved project + branch context for the `neon-env` CLI. The CLI owns this resolution\n * (flags → `NEON_*` env → `.neon[/project.json]` file) so the `@neon/env` library\n * functions can stay filesystem- and env-agnostic.\n */\nexport interface ResolvedContext {\n\tprojectId: string;\n\t/** Branch ref — a name (preferred for readability) or an id (`br-…`). */\n\tbranch: string;\n}\n\nexport interface ResolveContextOptions {\n\tprojectId?: string;\n\tbranch?: string;\n\tcwd: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\n/**\n * Resolve `projectId` and `branch` for a CLI invocation. Precedence (each wins over the\n * next): explicit flag → `NEON_*` env var → `.neon[/project.json]` walked up from `cwd`.\n *\n * Returns the resolved values plus a list of human-readable reasons for any field that\n * could not be resolved (so the caller can render one combined error).\n */\nexport function resolveContext(\n\toptions: ResolveContextOptions,\n): { ok: true; context: ResolvedContext } | { ok: false; missing: string[] } {\n\tconst env = options.env ?? process.env;\n\tconst file = findNeonFile(options.cwd);\n\n\tconst projectId =\n\t\tnonEmpty(options.projectId) ??\n\t\tnonEmpty(env.NEON_PROJECT_ID) ??\n\t\tfile?.projectId;\n\n\t// A branch ref — name (preferred) or id. `NEON_BRANCH` carries the name; `NEON_BRANCH_ID`\n\t// is the legacy id-only var. The `.neon` file pins `branch` (name) via `neonctl link`,\n\t// with legacy `branchId` still honored. fetchEnv resolves either form by name or id.\n\tconst branch =\n\t\tnonEmpty(options.branch) ??\n\t\tnonEmpty(env.NEON_BRANCH) ??\n\t\tnonEmpty(env.NEON_BRANCH_ID) ??\n\t\tfile?.branch;\n\n\tconst missing: string[] = [];\n\tif (!projectId) {\n\t\tmissing.push(\n\t\t\t\"project id — pass `--project-id`, set `NEON_PROJECT_ID`, or add `projectId` to `.neon` (run `npx neon link`).\",\n\t\t);\n\t}\n\tif (!branch) {\n\t\tmissing.push(\n\t\t\t\"branch — pass `--branch`, set `NEON_BRANCH`/`NEON_BRANCH_ID`, or add `branch` to `.neon` (run `npx neon link` / `neon checkout <branch>`).\",\n\t\t);\n\t}\n\tif (!projectId || !branch) return { ok: false, missing };\n\n\treturn {\n\t\tok: true,\n\t\tcontext: { projectId, branch },\n\t};\n}\n\ninterface NeonFile {\n\tprojectId?: string;\n\t/** Branch ref — name (preferred) or id. Reads `branch`, falling back to legacy `branchId`. */\n\tbranch?: string;\n}\n\n/**\n * Walk up from `cwd` looking for `.neon/project.json` (preferred) or `.neon` (neonctl\n * convention). Stops at the first `.git` directory or the home directory. Read-only.\n */\nfunction findNeonFile(cwd: string): NeonFile | null {\n\tlet current = resolve(cwd);\n\tconst stop = resolve(homedir());\n\tlet lastSeen: string | null = null;\n\n\twhile (true) {\n\t\tconst parsed =\n\t\t\treadNeonFileAt(resolve(current, \".neon\", \"project.json\")) ??\n\t\t\treadNeonFileAt(resolve(current, \".neon\"));\n\t\tif (parsed) return parsed;\n\n\t\tif (current === stop) return null;\n\t\tif (existsSync(resolve(current, \".git\"))) return null;\n\n\t\tconst parent = dirname(current);\n\t\tif (parent === current || parent === lastSeen) return null;\n\t\tlastSeen = current;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction readNeonFileAt(path: string): NeonFile | null {\n\tif (!isFile(path)) return null;\n\tlet raw: string;\n\ttry {\n\t\traw = readFileSync(path, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\treturn null;\n\tconst obj = parsed as Record<string, unknown>;\n\tconst out: NeonFile = {};\n\tif (typeof obj.projectId === \"string\" && obj.projectId !== \"\")\n\t\tout.projectId = obj.projectId;\n\t// Prefer the `branch` field (name or id, written by `neonctl link`); fall back to the\n\t// legacy id-only `branchId`.\n\tconst branch =\n\t\ttypeof obj.branch === \"string\" && obj.branch !== \"\"\n\t\t\t? obj.branch\n\t\t\t: typeof obj.branchId === \"string\" && obj.branchId !== \"\"\n\t\t\t\t? obj.branchId\n\t\t\t\t: undefined;\n\tif (branch) out.branch = branch;\n\treturn out;\n}\n\nfunction isFile(path: string): boolean {\n\ttry {\n\t\treturn statSync(path).isFile();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? undefined : trimmed;\n}\n","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 \"@neon/config/v1\";\nimport { fetchEnvReusingSecrets } from \"@neon-internals/env-core/reuse-secrets\";\nimport { resolveApiKey } from \"./resolve-api-key.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 * the key {@link resolveApiKey} resolves (`--api-key` → `NEON_API_KEY` → the Neon CLI's\n\t * stored credentials).\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. Everything\n * ambient — `.neon`, `NEON_*` env, the Neon CLI's stored credentials — is resolved by the\n * CLI (see `resolveContext` and `resolveApiKey`), never by the library.\n */\nexport interface EnvResolveOptions {\n\tconfigPath?: string;\n\tprojectId?: string;\n\tbranch?: string;\n\tapiKey?: string;\n\t/** Neon CLI profile whose stored credential to use. `--profile`, else `NEON_PROFILE`. */\n\tprofile?: 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\tinjected = await loadConfigAndFetchEnv(options, ctx, resolved.context);\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\tentries = await loadConfigAndFetchEnv(options, ctx, resolved.context);\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 resolve the branch env for the explicitly-resolved project + branch.\n * Layers `.env.local` (next to the config file) into the env source so re-runs keep the\n * one-time secrets the Neon API only returns once — the branch credential's, and any Auth\n * values a pre-`base_url` integration can no longer report. Uses\n * {@link fetchEnvReusingSecrets} rather than a bare `fetchEnv` so a run that already has a\n * working credential verifies and keeps it instead of minting another one per invocation.\n */\nasync function loadConfigAndFetchEnv(\n\toptions: EnvResolveOptions,\n\tctx: CommandEnv,\n\tresolved: { projectId: string; branch: string },\n): Promise<Record<string, string>> {\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\tconst apiKey = resolveApiKey({\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.profile ? { profile: options.profile } : {}),\n\t});\n\tconst { vars } = await fetchEnvReusingSecrets(config, {\n\t\tprojectId: resolved.projectId,\n\t\tbranch: resolved.branch,\n\t\tenv: { ...process.env, ...fileEnv },\n\t\t...(ctx.api ? { api: ctx.api } : {}),\n\t\t...(apiKey ? { apiKey } : {}),\n\t});\n\treturn vars;\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\t// The library's own wording is right for a library (\"this package never reads\n\t// NEON_API_KEY on your behalf\") and wrong here: `neon-env` does read it. Render the\n\t// chain this CLI actually implements, the same way an unresolved context is rendered.\n\tif (err instanceof PlatformError && err.code === ErrorCode.MissingApiKey) {\n\t\treturn errorResult(\n\t\t\terr,\n\t\t\t[\n\t\t\t\t\"No Neon API key. `neon-env` looks for one in this order:\",\n\t\t\t\t\" - the `--api-key` flag\",\n\t\t\t\t\" - the `NEON_API_KEY` environment variable\",\n\t\t\t\t\" - `credentials.json` in `NEONCTL_CONFIG_DIR` (else `~/.config/neonctl`) — run `neon auth` to create it\",\n\t\t\t].join(\"\\n\"),\n\t\t\tEXIT_CODE_BY_PLATFORM_ERROR_CODE[ErrorCode.MissingApiKey] ?? 1,\n\t\t);\n\t}\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","#!/usr/bin/env node\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport {\n\ttype CommandResult,\n\trunEnvExport,\n\trunEnvRun,\n} from \"./lib/cli/commands.js\";\n\nconst pkgVersion = readPackageVersion();\n\nconst argv = yargs(hideBin(process.argv))\n\t.scriptName(\"neon-env\")\n\t.usage(\"$0 <command> [options]\")\n\t.parserConfiguration({ \"populate--\": true })\n\t.option(\"debug\", {\n\t\ttype: \"boolean\",\n\t\tdefault: false,\n\t\tdescribe:\n\t\t\t\"Print stack traces and structured error details when something fails\",\n\t})\n\t.command(\n\t\t\"run\",\n\t\t\"Run a command with Neon env vars (from your neon.ts policy) injected into its environment. Use `--` to separate the command: `neon-env run -- npm run dev`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.command(\n\t\t\"export\",\n\t\t\"Print the branch's Neon env vars (from your neon.ts policy) to stdout, as dotenv lines or JSON. Useful for piping into other env tools, e.g. `neon-env export --format json`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"format\", {\n\t\t\t\t\tchoices: [\"dotenv\", \"json\"] as const,\n\t\t\t\t\tdefault: \"dotenv\",\n\t\t\t\t\tdescribe: \"Output format: dotenv (KEY=value lines) or json\",\n\t\t\t\t})\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.demandCommand(1, \"Run `neon-env --help` to see the available commands.\")\n\t.strict()\n\t.help()\n\t.version(pkgVersion)\n\t.parseSync();\n\nconst command = String(argv._[0]);\nconst cwd = process.cwd();\n\nlet result: CommandResult;\nswitch (command) {\n\tcase \"run\": {\n\t\tconst passthrough = Array.isArray(argv[\"--\"])\n\t\t\t? argv[\"--\"].map(String)\n\t\t\t: [];\n\t\tresult = await runEnvRun(\n\t\t\t{\n\t\t\t\tcommand: passthrough,\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tcase \"export\": {\n\t\tresult = await runEnvExport(\n\t\t\t{\n\t\t\t\tformat: argv.format === \"json\" ? \"json\" : \"dotenv\",\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tresult = {\n\t\t\texitCode: 1,\n\t\t\tstdout: \"\",\n\t\t\tstderr: `Unknown command: ${command}\\n`,\n\t\t};\n}\n\nif (result.stdout) process.stdout.write(result.stdout);\nif (result.stderr) process.stderr.write(result.stderr);\nif (argv.debug && result.exitCode !== 0 && result.debugInfo) {\n\tprocess.stderr.write(`\\n--- debug ---\\n${result.debugInfo}\\n`);\n}\nprocess.exit(result.exitCode);\n\nfunction readPackageVersion(): string {\n\t// The built CLI lives at `dist/cli.js`, so `package.json` is one directory up. When\n\t// running from source (tsx, vitest), the file lives at `src/cli.ts` and `package.json`\n\t// is again one directory up. Single resolution covers both layouts.\n\ttry {\n\t\tconst pkgUrl = new URL(\"../package.json\", import.meta.url);\n\t\tconst raw = readFileSync(fileURLToPath(pkgUrl), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as { version?: unknown };\n\t\treturn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