neon 2.1.2 → 2.29.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/LICENSE.md +178 -0
- package/README.md +601 -0
- package/dist/analytics.js +156 -0
- package/dist/api.js +665 -0
- package/dist/auth.js +127 -0
- package/dist/callback.html +51 -0
- package/dist/cli.js +9 -0
- package/dist/commands/auth.js +214 -0
- package/dist/commands/bootstrap.js +481 -0
- package/dist/commands/branches.js +481 -0
- package/dist/commands/bucket.js +543 -0
- package/dist/commands/checkout.js +289 -0
- package/dist/commands/config.js +544 -0
- package/dist/commands/connection_string.js +172 -0
- package/dist/commands/data_api.js +285 -0
- package/dist/commands/databases.js +82 -0
- package/dist/commands/deploy.js +26 -0
- package/dist/commands/dev.js +698 -0
- package/dist/commands/env.js +166 -0
- package/dist/commands/functions.js +373 -0
- package/dist/commands/index.js +54 -0
- package/dist/commands/init.js +73 -0
- package/dist/commands/ip_allow.js +137 -0
- package/dist/commands/link.js +1121 -0
- package/dist/commands/neon_auth.js +1028 -0
- package/dist/commands/operations.js +28 -0
- package/dist/commands/orgs.js +24 -0
- package/dist/commands/projects.js +372 -0
- package/dist/commands/psql.js +62 -0
- package/dist/commands/roles.js +65 -0
- package/dist/commands/schema_diff.js +151 -0
- package/dist/commands/set_context.js +29 -0
- package/dist/commands/status.js +40 -0
- package/dist/commands/user.js +15 -0
- package/dist/commands/vpc_endpoints.js +134 -0
- package/dist/config.js +11 -0
- package/dist/config_format.js +72 -0
- package/dist/context.js +177 -0
- package/dist/current_branch_fast_path.js +55 -0
- package/dist/dev/env.js +240 -0
- package/dist/dev/functions.js +70 -0
- package/dist/dev/inputs.js +63 -0
- package/dist/dev/runtime.js +146 -0
- package/dist/env.js +36 -0
- package/dist/env_file.js +159 -0
- package/dist/errors.js +80 -0
- package/dist/functions_api.js +44 -0
- package/dist/help.js +146 -0
- package/dist/index.js +234 -0
- package/dist/log.js +18 -0
- package/dist/parameters.gen.js +480 -0
- package/dist/pkg.js +25 -0
- package/dist/psql/cli.js +53 -0
- package/dist/psql/command/cmd_cond.js +437 -0
- package/dist/psql/command/cmd_connect.js +820 -0
- package/dist/psql/command/cmd_copy.js +1035 -0
- package/dist/psql/command/cmd_describe.js +1815 -0
- package/dist/psql/command/cmd_format.js +922 -0
- package/dist/psql/command/cmd_io.js +2193 -0
- package/dist/psql/command/cmd_lo.js +393 -0
- package/dist/psql/command/cmd_meta.js +970 -0
- package/dist/psql/command/cmd_misc.js +187 -0
- package/dist/psql/command/cmd_pipeline.js +1148 -0
- package/dist/psql/command/cmd_restrict.js +171 -0
- package/dist/psql/command/cmd_show.js +766 -0
- package/dist/psql/command/dispatch.js +343 -0
- package/dist/psql/command/inputQueue.js +42 -0
- package/dist/psql/command/shared.js +71 -0
- package/dist/psql/complete/filenames.js +139 -0
- package/dist/psql/complete/index.js +104 -0
- package/dist/psql/complete/matcher.js +315 -0
- package/dist/psql/complete/psqlVars.js +247 -0
- package/dist/psql/complete/queries.js +493 -0
- package/dist/psql/complete/rules.js +2424 -0
- package/dist/psql/core/common.js +1253 -0
- package/dist/psql/core/help.js +576 -0
- package/dist/psql/core/mainloop.js +1360 -0
- package/dist/psql/core/prompt.js +440 -0
- package/dist/psql/core/settings.js +684 -0
- package/dist/psql/core/sqlHelp.js +1066 -0
- package/dist/psql/core/startup.js +846 -0
- package/dist/psql/core/syncVars.js +116 -0
- package/dist/psql/core/variables.js +287 -0
- package/dist/psql/describe/formatters.js +1290 -0
- package/dist/psql/describe/processNamePattern.js +270 -0
- package/dist/psql/describe/queries.js +2378 -0
- package/dist/psql/describe/versionGate.js +43 -0
- package/dist/psql/index.js +2030 -0
- package/dist/psql/io/history.js +299 -0
- package/dist/psql/io/input.js +120 -0
- package/dist/psql/io/lineEditor/buffer.js +325 -0
- package/dist/psql/io/lineEditor/complete.js +227 -0
- package/dist/psql/io/lineEditor/filename.js +159 -0
- package/dist/psql/io/lineEditor/index.js +894 -0
- package/dist/psql/io/lineEditor/keymap.js +745 -0
- package/dist/psql/io/lineEditor/vt100.js +363 -0
- package/dist/psql/io/pgpass.js +202 -0
- package/dist/psql/io/pgservice.js +194 -0
- package/dist/psql/io/psqlrc.js +422 -0
- package/dist/psql/print/aligned.js +1765 -0
- package/dist/psql/print/asciidoc.js +248 -0
- package/dist/psql/print/crosstab.js +463 -0
- package/dist/psql/print/csv.js +95 -0
- package/dist/psql/print/html.js +258 -0
- package/dist/psql/print/json.js +96 -0
- package/dist/psql/print/latex.js +396 -0
- package/dist/psql/print/pager.js +267 -0
- package/dist/psql/print/troff.js +258 -0
- package/dist/psql/print/unaligned.js +119 -0
- package/dist/psql/print/units.js +135 -0
- package/dist/psql/scanner/slash.js +515 -0
- package/dist/psql/scanner/sql.js +914 -0
- package/dist/psql/scanner/stringutils.js +394 -0
- package/dist/psql/types/backslash.js +1 -0
- package/dist/psql/types/connection.js +1 -0
- package/dist/psql/types/index.js +7 -0
- package/dist/psql/types/printer.js +1 -0
- package/dist/psql/types/repl.js +1 -0
- package/dist/psql/types/scanner.js +24 -0
- package/dist/psql/types/settings.js +1 -0
- package/dist/psql/types/variables.js +1 -0
- package/dist/psql/wire/connection.js +2858 -0
- package/dist/psql/wire/copy.js +108 -0
- package/dist/psql/wire/notify.js +59 -0
- package/dist/psql/wire/pipeline.js +521 -0
- package/dist/psql/wire/protocol.js +466 -0
- package/dist/psql/wire/sasl.js +296 -0
- package/dist/psql/wire/tls.js +602 -0
- package/dist/storage_api.js +147 -0
- package/dist/test_utils/fixtures.js +122 -0
- package/dist/test_utils/oauth_server.js +9 -0
- package/dist/types.js +1 -0
- package/dist/utils/api_enums.js +33 -0
- package/dist/utils/auth.js +5 -0
- package/dist/utils/branch_notice.js +22 -0
- package/dist/utils/branch_picker.js +103 -0
- package/dist/utils/compute_units.js +28 -0
- package/dist/utils/enrichers.js +161 -0
- package/dist/utils/esbuild.js +158 -0
- package/dist/utils/formats.js +18 -0
- package/dist/utils/middlewares.js +20 -0
- package/dist/utils/package_manager.js +68 -0
- package/dist/utils/point_in_time.js +56 -0
- package/dist/utils/psql.js +120 -0
- package/dist/utils/string.js +5 -0
- package/dist/utils/ui.js +59 -0
- package/dist/utils/zip.js +4 -0
- package/dist/writer.js +97 -0
- package/package.json +117 -14
- package/.jshintrc +0 -3
- package/CHANGELOG.markdown +0 -22
- package/LICENSE +0 -21
- package/README.markdown +0 -76
- package/bower.json +0 -23
- package/license.txt +0 -9
- package/neon.js +0 -234
- package/stdlib/bubbling_support.js +0 -32
- package/stdlib/custom_event.js +0 -54
- package/stdlib/custom_event_support.js +0 -195
- package/stdlib/index.js +0 -7
- package/stdlib/node_support.js +0 -123
- package/stdlib/widget.js +0 -340
- package/test/neon_browser.html +0 -11
- package/test/neon_stdlib_browser.html +0 -15
- package/test/neon_stdlib_test.js +0 -84
- package/test/neon_test.js +0 -64
package/dist/env_file.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
/**
|
|
4
|
+
* Default dotenv file `env pull` writes to: `.env` when one already exists in the working
|
|
5
|
+
* directory (update where secrets already live), otherwise `.env.local` — matching the
|
|
6
|
+
* `vercel env pull` convention. An explicit `--file` always wins over this.
|
|
7
|
+
*/
|
|
8
|
+
export const resolveEnvFilePath = (cwd, file) => {
|
|
9
|
+
if (file)
|
|
10
|
+
return join(cwd, file);
|
|
11
|
+
if (existsSync(join(cwd, ".env")))
|
|
12
|
+
return join(cwd, ".env");
|
|
13
|
+
return join(cwd, ".env.local");
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Merge `updates` into the dotenv content at `path`, preserving every other line
|
|
17
|
+
* (comments, blank lines, unrelated keys) and the file's existing order. Keys present in
|
|
18
|
+
* both are updated in place; keys only in `updates` are appended. A non-existent file is
|
|
19
|
+
* treated as empty. When `managedKeys` is given, any owned key on disk that is absent from
|
|
20
|
+
* `updates` is removed. Returns the keys written and the (managed) keys removed.
|
|
21
|
+
*/
|
|
22
|
+
export const mergeEnvFile = (path, updates, options = {}) => {
|
|
23
|
+
const original = existsSync(path) ? readFileSync(path, "utf8") : "";
|
|
24
|
+
const { content, written, removed } = mergeEnvContent(original, updates, options);
|
|
25
|
+
writeFileSync(path, content);
|
|
26
|
+
return { written, removed };
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Pure core of {@link mergeEnvFile}: takes the current file content and the updates, and
|
|
30
|
+
* returns the new content plus which keys were written / removed. Kept side-effect-free so
|
|
31
|
+
* it can be unit-tested without touching the filesystem.
|
|
32
|
+
*/
|
|
33
|
+
export const mergeEnvContent = (original, updates, options = {}) => {
|
|
34
|
+
const keys = Object.keys(updates);
|
|
35
|
+
// Owned keys the current pull did not produce: stale Neon-managed vars to prune. Anything
|
|
36
|
+
// not in `managedKeys` is always kept, so a user's own lines are never removed.
|
|
37
|
+
const stale = new Set([...(options.managedKeys ?? [])].filter((key) => !(key in updates)));
|
|
38
|
+
if (keys.length === 0 && stale.size === 0) {
|
|
39
|
+
return { content: original, written: [], removed: [] };
|
|
40
|
+
}
|
|
41
|
+
const remaining = new Set(keys);
|
|
42
|
+
const removed = [];
|
|
43
|
+
const lines = original === "" ? [] : original.split("\n");
|
|
44
|
+
// Walk the file: drop stale owned lines, update existing keys in place (so their position
|
|
45
|
+
// and any surrounding comments are preserved), and pass everything else through untouched.
|
|
46
|
+
const updatedLines = [];
|
|
47
|
+
for (const line of lines) {
|
|
48
|
+
const key = parseKey(line);
|
|
49
|
+
if (key !== null && stale.has(key)) {
|
|
50
|
+
removed.push(key);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (key !== null && remaining.has(key)) {
|
|
54
|
+
remaining.delete(key);
|
|
55
|
+
updatedLines.push(formatLine(key, updates[key]));
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
updatedLines.push(line);
|
|
59
|
+
}
|
|
60
|
+
// Append keys that weren't already present, in the order they were given.
|
|
61
|
+
const appended = keys
|
|
62
|
+
.filter((key) => remaining.has(key))
|
|
63
|
+
.map((key) => formatLine(key, updates[key]));
|
|
64
|
+
const body = trimTrailingBlank(updatedLines);
|
|
65
|
+
const content = [...body, ...appended].join("\n");
|
|
66
|
+
return {
|
|
67
|
+
// A dotenv file ends with a trailing newline.
|
|
68
|
+
content: content === "" ? "" : `${content}\n`,
|
|
69
|
+
written: keys,
|
|
70
|
+
removed,
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* Read a dotenv file at `path` into a plain `{ KEY: value }` map. A non-existent file is an
|
|
75
|
+
* error (callers pass an explicit `--env` path, so a typo should fail loudly rather than
|
|
76
|
+
* silently load nothing). Quotes are stripped and `\"` / `\\` unescaped, matching the
|
|
77
|
+
* quoting {@link mergeEnvFile} writes. Comments, blank lines, and non-assignment lines are
|
|
78
|
+
* ignored.
|
|
79
|
+
*/
|
|
80
|
+
export const readEnvFile = (path) => {
|
|
81
|
+
if (!existsSync(path)) {
|
|
82
|
+
throw new Error(`Env file not found: ${path}`);
|
|
83
|
+
}
|
|
84
|
+
const out = {};
|
|
85
|
+
for (const line of readFileSync(path, "utf8").split("\n")) {
|
|
86
|
+
const parsed = parseAssignment(line);
|
|
87
|
+
if (parsed)
|
|
88
|
+
out[parsed.key] = parsed.value;
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Load a dotenv file into `process.env` so values are available to anything read later
|
|
94
|
+
* (e.g. a `neon.ts` whose function `env` values come from `process.env.X`). Existing
|
|
95
|
+
* `process.env` entries are **not** overridden — an already-exported var wins over the
|
|
96
|
+
* file, matching dotenv's default. Returns the keys that were applied.
|
|
97
|
+
*/
|
|
98
|
+
export const loadEnvFileIntoProcess = (path) => {
|
|
99
|
+
const parsed = readEnvFile(path);
|
|
100
|
+
const applied = [];
|
|
101
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
102
|
+
if (process.env[key] === undefined) {
|
|
103
|
+
process.env[key] = value;
|
|
104
|
+
applied.push(key);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return applied;
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Extract the variable name from a dotenv line, or `null` for comments / blank lines / any
|
|
111
|
+
* line that isn't a `KEY=value` assignment. Tolerates a leading `export ` and surrounding
|
|
112
|
+
* whitespace, matching common `.env` styles.
|
|
113
|
+
*/
|
|
114
|
+
const parseKey = (line) => {
|
|
115
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
|
|
116
|
+
return match ? match[1] : null;
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Parse a `KEY=value` dotenv line into its key and unquoted value, or `null` for
|
|
120
|
+
* comments / blank lines / non-assignments. Mirrors {@link formatLine}'s quoting.
|
|
121
|
+
*/
|
|
122
|
+
const parseAssignment = (line) => {
|
|
123
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
|
|
124
|
+
const key = match?.[1];
|
|
125
|
+
const raw = match?.[2];
|
|
126
|
+
if (key === undefined || raw === undefined)
|
|
127
|
+
return null;
|
|
128
|
+
return { key, value: unquote(raw.trim()) };
|
|
129
|
+
};
|
|
130
|
+
/** Strip matching surrounding quotes and unescape `\"` / `\\` inside double quotes. */
|
|
131
|
+
const unquote = (value) => {
|
|
132
|
+
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
|
|
133
|
+
return value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\");
|
|
134
|
+
}
|
|
135
|
+
if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) {
|
|
136
|
+
return value.slice(1, -1);
|
|
137
|
+
}
|
|
138
|
+
return value;
|
|
139
|
+
};
|
|
140
|
+
/**
|
|
141
|
+
* Render a `KEY=value` line. The value is wrapped in double quotes when it contains
|
|
142
|
+
* characters that would otherwise break parsing (spaces, `#`, quotes, `=`), with inner
|
|
143
|
+
* quotes/backslashes escaped — Neon connection strings and URLs are safe either way, but
|
|
144
|
+
* quoting defensively avoids surprises for tools that re-parse the file.
|
|
145
|
+
*/
|
|
146
|
+
const formatLine = (key, value) => {
|
|
147
|
+
const needsQuotes = /[\s#"'=]/.test(value);
|
|
148
|
+
if (!needsQuotes)
|
|
149
|
+
return `${key}=${value}`;
|
|
150
|
+
const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
151
|
+
return `${key}="${escaped}"`;
|
|
152
|
+
};
|
|
153
|
+
/** Drop trailing blank lines so we don't accumulate them across repeated merges. */
|
|
154
|
+
const trimTrailingBlank = (lines) => {
|
|
155
|
+
const out = [...lines];
|
|
156
|
+
while (out.length > 0 && out[out.length - 1]?.trim() === "")
|
|
157
|
+
out.pop();
|
|
158
|
+
return out;
|
|
159
|
+
};
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
const ERROR_MATCHERS = [
|
|
2
|
+
[/^Unknown command: (.*)$/, "UNKNOWN_COMMAND"],
|
|
3
|
+
[/^Missing required argument: (.*)$/, "MISSING_ARGUMENT"],
|
|
4
|
+
[/^Failed to open web browser. (.*)$/, "AUTH_BROWSER_FAILED"],
|
|
5
|
+
];
|
|
6
|
+
export const matchErrorCode = (message) => {
|
|
7
|
+
if (!message) {
|
|
8
|
+
return "UNKNOWN_ERROR";
|
|
9
|
+
}
|
|
10
|
+
for (const [matcher, code] of ERROR_MATCHERS) {
|
|
11
|
+
const match = message.match(matcher);
|
|
12
|
+
if (match) {
|
|
13
|
+
return code;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return "UNKNOWN_ERROR";
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* The single, human-readable line shown when the CLI couldn't reach the Neon API because
|
|
20
|
+
* of a connection-level failure (DNS, refused/reset connection, offline). It replaces the
|
|
21
|
+
* cryptic `fetch failed` / empty axios message a network blip otherwise surfaces (see
|
|
22
|
+
* {@link isNetworkError}), pointing at the two things the user can actually check.
|
|
23
|
+
*/
|
|
24
|
+
export const NETWORK_ERROR_MESSAGE = "Could not reach the Neon API. Please check your internet connection and try again. " +
|
|
25
|
+
"If your connection is fine and this keeps happening, check https://neonstatus.com for ongoing incidents.";
|
|
26
|
+
/**
|
|
27
|
+
* Node-level socket/DNS error codes that mean the request never reached the server — a
|
|
28
|
+
* genuine connectivity problem rather than an API response we should surface. Deliberately
|
|
29
|
+
* excludes `ECONNABORTED` (axios' timeout), which the CLI already reports as a timeout.
|
|
30
|
+
*/
|
|
31
|
+
const NETWORK_ERROR_CODES = new Set([
|
|
32
|
+
"ECONNREFUSED",
|
|
33
|
+
"ECONNRESET",
|
|
34
|
+
"ETIMEDOUT",
|
|
35
|
+
"ENOTFOUND",
|
|
36
|
+
"EAI_AGAIN",
|
|
37
|
+
"EPIPE",
|
|
38
|
+
"EHOSTUNREACH",
|
|
39
|
+
"ENETUNREACH",
|
|
40
|
+
"EHOSTDOWN",
|
|
41
|
+
"ENETDOWN",
|
|
42
|
+
]);
|
|
43
|
+
/**
|
|
44
|
+
* Message fragments that mark a connection-level failure across our two transports: the
|
|
45
|
+
* `@neon/sdk` / global `fetch` path (used by `env pull` / `config` / `deploy`, and `link`'s
|
|
46
|
+
* bundled env pull) throws a bare `TypeError: fetch failed` / "Failed to fetch", while the
|
|
47
|
+
* axios `api-client` path throws an `AxiosError` whose message is "Network Error".
|
|
48
|
+
*/
|
|
49
|
+
const NETWORK_ERROR_MESSAGE_PATTERN = /fetch failed|failed to fetch|network error/i;
|
|
50
|
+
const readErrorCode = (value) => {
|
|
51
|
+
if (value === null || typeof value !== "object")
|
|
52
|
+
return undefined;
|
|
53
|
+
const code = value.code;
|
|
54
|
+
return typeof code === "string" ? code : undefined;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Whether `err` is a connection-level failure (the network blip the user sees as a cryptic
|
|
58
|
+
* `fetch failed`, or no message at all on the axios path) rather than an actual API response.
|
|
59
|
+
*
|
|
60
|
+
* A Node `fetch` failure is a bare `TypeError: fetch failed` whose underlying `cause` carries
|
|
61
|
+
* the real socket `code` (e.g. `ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`), so we walk the
|
|
62
|
+
* `cause` chain checking both the code and the message. This is what lets the CLI swap the
|
|
63
|
+
* confusing default for {@link NETWORK_ERROR_MESSAGE}. It matches only failures where no
|
|
64
|
+
* response was ever received, so it never masks a real 4xx/5xx the user needs to see.
|
|
65
|
+
*/
|
|
66
|
+
export const isNetworkError = (err) => {
|
|
67
|
+
let current = err;
|
|
68
|
+
for (let depth = 0; depth < 6 && current !== null && current !== undefined; depth++) {
|
|
69
|
+
const code = readErrorCode(current);
|
|
70
|
+
if (code !== undefined && NETWORK_ERROR_CODES.has(code)) {
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
if (current instanceof Error &&
|
|
74
|
+
NETWORK_ERROR_MESSAGE_PATTERN.test(current.message)) {
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
current = current.cause;
|
|
78
|
+
}
|
|
79
|
+
return false;
|
|
80
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { ContentType } from "./api.js";
|
|
2
|
+
const functionsPath = (projectId, branchId) => `/projects/${encodeURIComponent(projectId)}/branches/${encodeURIComponent(branchId)}/functions`;
|
|
3
|
+
export const listFunctions = async (apiClient, projectId, branchId, { cursor, limit } = {}) => {
|
|
4
|
+
const { data } = await apiClient.request({
|
|
5
|
+
path: functionsPath(projectId, branchId),
|
|
6
|
+
method: "GET",
|
|
7
|
+
query: { cursor, limit },
|
|
8
|
+
secure: true,
|
|
9
|
+
format: "json",
|
|
10
|
+
});
|
|
11
|
+
return { functions: data.functions ?? [], next: data.pagination?.next };
|
|
12
|
+
};
|
|
13
|
+
export const getFunction = async (apiClient, projectId, branchId, slug) => {
|
|
14
|
+
const { data } = await apiClient.request({
|
|
15
|
+
path: `${functionsPath(projectId, branchId)}/${encodeURIComponent(slug)}`,
|
|
16
|
+
method: "GET",
|
|
17
|
+
secure: true,
|
|
18
|
+
format: "json",
|
|
19
|
+
});
|
|
20
|
+
return data.function;
|
|
21
|
+
};
|
|
22
|
+
export const deleteFunction = async (apiClient, projectId, branchId, slug) => {
|
|
23
|
+
await apiClient.request({
|
|
24
|
+
path: `${functionsPath(projectId, branchId)}/${encodeURIComponent(slug)}`,
|
|
25
|
+
method: "DELETE",
|
|
26
|
+
secure: true,
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
export const createDeployment = async (apiClient, projectId, branchId, slug, params) => {
|
|
30
|
+
const form = new FormData();
|
|
31
|
+
form.append("zip", new Blob([params.zip]), "bundle.zip");
|
|
32
|
+
form.append("runtime", params.runtime);
|
|
33
|
+
if (params.environment)
|
|
34
|
+
form.append("environment", params.environment);
|
|
35
|
+
// The deploy POST returns an operation the CLI cannot poll; the body is
|
|
36
|
+
// ignored. We only need the request to succeed.
|
|
37
|
+
await apiClient.request({
|
|
38
|
+
path: `${functionsPath(projectId, branchId)}/${encodeURIComponent(slug)}/deployments`,
|
|
39
|
+
method: "POST",
|
|
40
|
+
type: ContentType.FormData,
|
|
41
|
+
body: form,
|
|
42
|
+
secure: true,
|
|
43
|
+
});
|
|
44
|
+
};
|
package/dist/help.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import cliui from "cliui";
|
|
3
|
+
import { consumeBlockIfMatches, consumeNextMatching, drawPointer, splitColumns, } from "./utils/ui.js";
|
|
4
|
+
// target width for the leftmost column
|
|
5
|
+
const SPACE_WIDTH = 20;
|
|
6
|
+
const formatHelp = (help) => {
|
|
7
|
+
const lines = help.split("\n");
|
|
8
|
+
const result = [];
|
|
9
|
+
// full command, like `neonctl projects list`
|
|
10
|
+
const topLevelCommand = consumeNextMatching(lines, /^.*/);
|
|
11
|
+
if (topLevelCommand) {
|
|
12
|
+
result.push(chalk.bold(topLevelCommand.replace("[options]", chalk.reset.green("[options]"))));
|
|
13
|
+
result.push("");
|
|
14
|
+
}
|
|
15
|
+
// commands description block
|
|
16
|
+
// example command to see: neonctl projects
|
|
17
|
+
const commandsBlock = consumeBlockIfMatches(lines, /^Commands:/);
|
|
18
|
+
if (commandsBlock.length > 0) {
|
|
19
|
+
const header = commandsBlock.shift();
|
|
20
|
+
result.push(header);
|
|
21
|
+
const ui = cliui({
|
|
22
|
+
width: 0,
|
|
23
|
+
});
|
|
24
|
+
commandsBlock.forEach((line) => {
|
|
25
|
+
if (/^\s{3,}/.exec(line)) {
|
|
26
|
+
ui.div({
|
|
27
|
+
text: "",
|
|
28
|
+
width: SPACE_WIDTH,
|
|
29
|
+
padding: [0, 0, 0, 0],
|
|
30
|
+
}, { text: line.trim(), padding: [0, 0, 0, 0] });
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const [command, description] = splitColumns(line);
|
|
34
|
+
// patch the previous command if it was multiline
|
|
35
|
+
if (!description && ui.rows.length > 1) {
|
|
36
|
+
ui.rows[ui.rows.length - 2][0].text += command;
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
ui.div(chalk.cyan(command));
|
|
40
|
+
ui.div({
|
|
41
|
+
text: chalk.gray(drawPointer(SPACE_WIDTH)),
|
|
42
|
+
width: SPACE_WIDTH,
|
|
43
|
+
padding: [0, 0, 0, 0],
|
|
44
|
+
}, { text: description, padding: [0, 0, 0, 2] });
|
|
45
|
+
});
|
|
46
|
+
result.push(ui.toString());
|
|
47
|
+
result.push("");
|
|
48
|
+
}
|
|
49
|
+
// positional args block
|
|
50
|
+
// example command to see: neonctl branches rename
|
|
51
|
+
const positionalsBlock = consumeBlockIfMatches(lines, /Positionals:/);
|
|
52
|
+
if (positionalsBlock.length > 0) {
|
|
53
|
+
const header = positionalsBlock.shift();
|
|
54
|
+
result.push(header);
|
|
55
|
+
const ui = cliui({
|
|
56
|
+
width: 0,
|
|
57
|
+
});
|
|
58
|
+
positionalsBlock.forEach((line) => {
|
|
59
|
+
const [positional, description] = splitColumns(line);
|
|
60
|
+
ui.div({
|
|
61
|
+
text: positional,
|
|
62
|
+
width: SPACE_WIDTH,
|
|
63
|
+
padding: [0, 2, 0, 0],
|
|
64
|
+
}, {
|
|
65
|
+
text: description,
|
|
66
|
+
padding: [0, 0, 0, 0],
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
result.push(ui.toString());
|
|
70
|
+
result.push("");
|
|
71
|
+
}
|
|
72
|
+
// command description
|
|
73
|
+
// example command to see: neonctl projects list
|
|
74
|
+
const descriptionBlock = consumeBlockIfMatches(lines, /^(?!.*options:)/i);
|
|
75
|
+
if (descriptionBlock.length > 0) {
|
|
76
|
+
result.push(...descriptionBlock);
|
|
77
|
+
result.push("");
|
|
78
|
+
}
|
|
79
|
+
while (true) {
|
|
80
|
+
// there are two options blocks: global and specific
|
|
81
|
+
// example to see both: neonctl projects create
|
|
82
|
+
const optionsBlock = consumeBlockIfMatches(lines, /.*options:/i);
|
|
83
|
+
if (optionsBlock.length === 0) {
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
result.push(optionsBlock.shift());
|
|
87
|
+
optionsBlock.forEach((line) => {
|
|
88
|
+
const [option, description] = splitColumns(line);
|
|
89
|
+
const ui = cliui({
|
|
90
|
+
width: 0,
|
|
91
|
+
});
|
|
92
|
+
if (option.startsWith("-")) {
|
|
93
|
+
ui.div({
|
|
94
|
+
text: chalk.green(option),
|
|
95
|
+
padding: [0, 0, 0, 0],
|
|
96
|
+
});
|
|
97
|
+
ui.div({
|
|
98
|
+
text: chalk.gray(drawPointer(SPACE_WIDTH)),
|
|
99
|
+
width: SPACE_WIDTH,
|
|
100
|
+
padding: [0, 2, 0, 0],
|
|
101
|
+
}, {
|
|
102
|
+
text: chalk.rgb(210, 210, 210)(description ?? ""),
|
|
103
|
+
padding: [0, 0, 0, 0],
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
ui.div({
|
|
108
|
+
padding: [0, 0, 0, 0],
|
|
109
|
+
text: "",
|
|
110
|
+
width: SPACE_WIDTH,
|
|
111
|
+
}, {
|
|
112
|
+
text: chalk.rgb(210, 210, 210)(option),
|
|
113
|
+
padding: [0, 0, 0, 0],
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
result.push(ui.toString());
|
|
117
|
+
});
|
|
118
|
+
result.push("");
|
|
119
|
+
}
|
|
120
|
+
const exampleBlock = consumeBlockIfMatches(lines, /Examples:/);
|
|
121
|
+
if (exampleBlock.length > 0) {
|
|
122
|
+
result.push(exampleBlock.shift());
|
|
123
|
+
const ui = cliui({
|
|
124
|
+
width: 0,
|
|
125
|
+
});
|
|
126
|
+
for (const line of exampleBlock) {
|
|
127
|
+
const [command, description] = splitColumns(line);
|
|
128
|
+
ui.div({
|
|
129
|
+
text: chalk.bold(command),
|
|
130
|
+
padding: [0, 0, 0, 0],
|
|
131
|
+
});
|
|
132
|
+
ui.div({
|
|
133
|
+
text: chalk.reset(description),
|
|
134
|
+
padding: [0, 0, 0, 2],
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
result.push(ui.toString());
|
|
138
|
+
}
|
|
139
|
+
return [...result, ...lines];
|
|
140
|
+
};
|
|
141
|
+
export const showHelp = async (argv) => {
|
|
142
|
+
// add wrap to ensure that there are no line breaks
|
|
143
|
+
const help = await argv.getHelp();
|
|
144
|
+
process.stderr.write(formatHelp(help).join("\n") + "\n");
|
|
145
|
+
process.exit(0);
|
|
146
|
+
};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { basename } from "node:path";
|
|
2
|
+
import yargs from "yargs";
|
|
3
|
+
import { hideBin } from "yargs/helpers";
|
|
4
|
+
import { analyticsMiddleware, closeAnalytics, getAnalyticsEventProperties, initAnalyticsClientMiddleware, sendError, trackEvent, } from "./analytics.js";
|
|
5
|
+
import { isNeonApiError, messageFromBody } from "./api.js";
|
|
6
|
+
import { defaultClientID } from "./auth.js";
|
|
7
|
+
import { deleteCredentials, ensureAuth } from "./commands/auth.js";
|
|
8
|
+
import commands from "./commands/index.js";
|
|
9
|
+
import { defaultDir, ensureConfigDir } from "./config.js";
|
|
10
|
+
import { currentContextFile, enrichFromContext } from "./context.js";
|
|
11
|
+
import { isNetworkError, matchErrorCode, NETWORK_ERROR_MESSAGE, } from "./errors.js";
|
|
12
|
+
import { showHelp } from "./help.js";
|
|
13
|
+
import { log } from "./log.js";
|
|
14
|
+
import pkg from "./pkg.js";
|
|
15
|
+
import { fillInArgs } from "./utils/middlewares.js";
|
|
16
|
+
const NO_SUBCOMMANDS_VERBS = [
|
|
17
|
+
// aliases
|
|
18
|
+
"auth",
|
|
19
|
+
"login",
|
|
20
|
+
"me",
|
|
21
|
+
// aliases
|
|
22
|
+
"cs",
|
|
23
|
+
"connection-string",
|
|
24
|
+
"psql",
|
|
25
|
+
"set-context",
|
|
26
|
+
"checkout",
|
|
27
|
+
"link",
|
|
28
|
+
"init",
|
|
29
|
+
"dev",
|
|
30
|
+
"deploy",
|
|
31
|
+
"bootstrap",
|
|
32
|
+
// alias of `config status`
|
|
33
|
+
"status",
|
|
34
|
+
];
|
|
35
|
+
let builder = yargs(hideBin(process.argv));
|
|
36
|
+
builder = builder
|
|
37
|
+
.scriptName(pkg.name)
|
|
38
|
+
.locale("en")
|
|
39
|
+
.usage("$0 <command> [options]")
|
|
40
|
+
.parserConfiguration({
|
|
41
|
+
"populate--": true,
|
|
42
|
+
})
|
|
43
|
+
.help()
|
|
44
|
+
.option("output", {
|
|
45
|
+
alias: "o",
|
|
46
|
+
group: "Global options:",
|
|
47
|
+
describe: "Set output format",
|
|
48
|
+
type: "string",
|
|
49
|
+
choices: ["json", "yaml", "table"],
|
|
50
|
+
default: "table",
|
|
51
|
+
})
|
|
52
|
+
.option("api-host", {
|
|
53
|
+
describe: "The API host",
|
|
54
|
+
hidden: true,
|
|
55
|
+
default: process.env.NEON_API_HOST ?? "https://console.neon.tech/api/v2",
|
|
56
|
+
})
|
|
57
|
+
// Setup config directory
|
|
58
|
+
.option("config-dir", {
|
|
59
|
+
describe: "Path to config directory",
|
|
60
|
+
group: "Global options:",
|
|
61
|
+
type: "string",
|
|
62
|
+
default: defaultDir,
|
|
63
|
+
})
|
|
64
|
+
.option("force-auth", {
|
|
65
|
+
describe: "Force authentication",
|
|
66
|
+
type: "boolean",
|
|
67
|
+
hidden: true,
|
|
68
|
+
default: false,
|
|
69
|
+
})
|
|
70
|
+
.middleware(ensureConfigDir)
|
|
71
|
+
.options({
|
|
72
|
+
"oauth-host": {
|
|
73
|
+
description: "URL to Neon OAuth host",
|
|
74
|
+
hidden: true,
|
|
75
|
+
default: process.env.NEON_OAUTH_HOST ?? "https://oauth2.neon.tech",
|
|
76
|
+
},
|
|
77
|
+
"client-id": {
|
|
78
|
+
description: "OAuth client id",
|
|
79
|
+
hidden: true,
|
|
80
|
+
type: "string",
|
|
81
|
+
default: defaultClientID,
|
|
82
|
+
},
|
|
83
|
+
"api-key": {
|
|
84
|
+
describe: "API key",
|
|
85
|
+
group: "Global options:",
|
|
86
|
+
type: "string",
|
|
87
|
+
default: process.env.NEON_API_KEY ?? "",
|
|
88
|
+
},
|
|
89
|
+
apiClient: {
|
|
90
|
+
hidden: true,
|
|
91
|
+
coerce: (v) => v,
|
|
92
|
+
default: null,
|
|
93
|
+
},
|
|
94
|
+
"context-file": {
|
|
95
|
+
describe: "Context file",
|
|
96
|
+
type: "string",
|
|
97
|
+
default: currentContextFile,
|
|
98
|
+
},
|
|
99
|
+
color: {
|
|
100
|
+
group: "Global options:",
|
|
101
|
+
describe: "Colorize the output. Example: --no-color, --color false",
|
|
102
|
+
type: "boolean",
|
|
103
|
+
default: true,
|
|
104
|
+
},
|
|
105
|
+
analytics: {
|
|
106
|
+
describe: "Manage analytics. Example: --no-analytics, --analytics false",
|
|
107
|
+
group: "Global options:",
|
|
108
|
+
type: "boolean",
|
|
109
|
+
default: true,
|
|
110
|
+
},
|
|
111
|
+
})
|
|
112
|
+
.middleware((args) => {
|
|
113
|
+
fillInArgs(args);
|
|
114
|
+
}, true)
|
|
115
|
+
.middleware(initAnalyticsClientMiddleware, true)
|
|
116
|
+
.help(false)
|
|
117
|
+
.group("help", "Global options:")
|
|
118
|
+
.option("help", {
|
|
119
|
+
describe: "Show help",
|
|
120
|
+
type: "boolean",
|
|
121
|
+
default: false,
|
|
122
|
+
})
|
|
123
|
+
.alias("help", "h")
|
|
124
|
+
.middleware(async (args) => {
|
|
125
|
+
if (args.help ||
|
|
126
|
+
(args._.length === 1 &&
|
|
127
|
+
!NO_SUBCOMMANDS_VERBS.includes(args._[0]))) {
|
|
128
|
+
await showHelp(builder);
|
|
129
|
+
}
|
|
130
|
+
})
|
|
131
|
+
.middleware(ensureAuth)
|
|
132
|
+
.middleware(enrichFromContext)
|
|
133
|
+
.middleware(analyticsMiddleware)
|
|
134
|
+
.command(commands)
|
|
135
|
+
.strictCommands()
|
|
136
|
+
.version(pkg.version)
|
|
137
|
+
.group("version", "Global options:")
|
|
138
|
+
.alias("version", "v")
|
|
139
|
+
.completion()
|
|
140
|
+
.scriptName(basename(process.argv[1]) === "neon" ? "neon" : "neonctl")
|
|
141
|
+
.epilog("For more information, visit https://neon.com/docs/reference/neon-cli")
|
|
142
|
+
.wrap(null)
|
|
143
|
+
.fail(false);
|
|
144
|
+
async function handleError(msg, err) {
|
|
145
|
+
if (process.argv.some((arg) => arg === "--help" || arg === "-h")) {
|
|
146
|
+
await showHelp(builder);
|
|
147
|
+
process.exit(0);
|
|
148
|
+
}
|
|
149
|
+
// Log stack trace if available
|
|
150
|
+
if (err instanceof Error && err.stack) {
|
|
151
|
+
log.debug("Stack: %s", err.stack);
|
|
152
|
+
}
|
|
153
|
+
// A connection-level failure (no response ever reached us) reads as a cryptic
|
|
154
|
+
// `fetch failed` from the @neon/sdk / global `fetch` path. Detect it first and
|
|
155
|
+
// swap in one clear "check your connection" hint. We deliberately do not retry
|
|
156
|
+
// here: re-running the whole command could re-trigger a non-idempotent step
|
|
157
|
+
// (e.g. project create), so retries belong at the request layer.
|
|
158
|
+
if (isNetworkError(err)) {
|
|
159
|
+
log.error(NETWORK_ERROR_MESSAGE);
|
|
160
|
+
const error = err instanceof Error ? err : new Error(NETWORK_ERROR_MESSAGE);
|
|
161
|
+
sendError(error, "NETWORK_ERROR");
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
if (isNeonApiError(err)) {
|
|
165
|
+
if (err.code === "ECONNABORTED") {
|
|
166
|
+
log.error("Request timed out");
|
|
167
|
+
sendError(err, "REQUEST_TIMEOUT");
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
else if (err.status === 401) {
|
|
171
|
+
sendError(err, "AUTH_FAILED");
|
|
172
|
+
log.info("Authentication failed, deleting credentials...");
|
|
173
|
+
try {
|
|
174
|
+
deleteCredentials(defaultDir);
|
|
175
|
+
return true; // Allow retry for auth failures
|
|
176
|
+
}
|
|
177
|
+
catch (deleteErr) {
|
|
178
|
+
log.debug("Failed to delete credentials: %s", deleteErr instanceof Error
|
|
179
|
+
? deleteErr.message
|
|
180
|
+
: "unknown error");
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
const serverMessage = messageFromBody(err.data);
|
|
186
|
+
if (serverMessage) {
|
|
187
|
+
log.error(serverMessage);
|
|
188
|
+
}
|
|
189
|
+
log.debug("status: %d %s | path: %s", err.status, err.statusText, err.requestPath);
|
|
190
|
+
sendError(err, "API_ERROR");
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
const error = err instanceof Error ? err : new Error(msg || "Unknown error");
|
|
196
|
+
sendError(error, matchErrorCode(error.message));
|
|
197
|
+
log.error(error.message);
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
void (async () => {
|
|
202
|
+
// Main loop with max 2 attempts (initial + 1 retry):
|
|
203
|
+
let attempts = 0;
|
|
204
|
+
const MAX_ATTEMPTS = 2;
|
|
205
|
+
while (attempts < MAX_ATTEMPTS) {
|
|
206
|
+
try {
|
|
207
|
+
const args = await builder.argv;
|
|
208
|
+
// Send analytics for a successful attempt
|
|
209
|
+
trackEvent("cli_command_success", {
|
|
210
|
+
...getAnalyticsEventProperties(args),
|
|
211
|
+
projectId: args.projectId,
|
|
212
|
+
branchId: args.branchId,
|
|
213
|
+
accountId: args.accountId,
|
|
214
|
+
authMethod: args.authMethod,
|
|
215
|
+
authData: args.authData,
|
|
216
|
+
});
|
|
217
|
+
if (args._.length === 0 || args.help) {
|
|
218
|
+
await showHelp(builder);
|
|
219
|
+
process.exit(0);
|
|
220
|
+
}
|
|
221
|
+
await closeAnalytics();
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
catch (err) {
|
|
225
|
+
attempts++;
|
|
226
|
+
const shouldRetry = await handleError("", err);
|
|
227
|
+
if (!shouldRetry || attempts >= MAX_ATTEMPTS) {
|
|
228
|
+
await closeAnalytics();
|
|
229
|
+
process.exit(1);
|
|
230
|
+
}
|
|
231
|
+
// If shouldRetry is true and we haven't hit max attempts, loop continues
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
})();
|
package/dist/log.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { format } from "node:util";
|
|
2
|
+
import { isDebug } from "./env.js";
|
|
3
|
+
export const log = {
|
|
4
|
+
debug: (...args) => {
|
|
5
|
+
if (isDebug()) {
|
|
6
|
+
process.stderr.write(`DEBUG: ${format(...args)}\n`);
|
|
7
|
+
}
|
|
8
|
+
},
|
|
9
|
+
warning: (...args) => {
|
|
10
|
+
process.stderr.write(`WARNING: ${format(...args)}\n`);
|
|
11
|
+
},
|
|
12
|
+
info: (...args) => {
|
|
13
|
+
process.stderr.write(`INFO: ${format(...args)}\n`);
|
|
14
|
+
},
|
|
15
|
+
error: (...args) => {
|
|
16
|
+
process.stderr.write(`ERROR: ${format(...args)}\n`);
|
|
17
|
+
},
|
|
18
|
+
};
|