pidgey-cli 0.0.0-stage → 0.1.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 CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # pidgey-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `pidgey` is the command-line client of the [Pidgey](https://github.com/darthjee/pidgey)
4
+ email-delivery service's `/v1` API. It is a thin layer over
5
+ [`pidgey-client`](https://github.com/darthjee/pidgey/tree/main/clients/nodejs): the HTTP
6
+ and the retries live in the library, not here.
7
+
8
+ Requires Node.js 22.12 or later.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install -g pidgey-cli
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ```sh
19
+ pidgey --to user@example.com --subject Hello --text 'Hi!'
20
+
21
+ printf 'Hi!' | pidgey --to user@example.com --subject Hello
22
+
23
+ PIDGEY_URL=https://pidgey.example.com PIDGEY_TOKEN=pdg_example... \
24
+ pidgey --to user@example.com --subject Hello --html '<p>Hi!</p>'
25
+
26
+ PIDGEY_URL=https://pidgey.example.com \
27
+ pidgey --token-file /run/secrets/pidgey_token --to user@example.com --subject Hello --text 'Hi!'
28
+
29
+ pidgey --version # pidgey-cli <version> (pidgey-client <version>)
30
+ pidgey --help # prints the usage
31
+ ```
32
+
33
+ ### Flags
34
+
35
+ | Flag | Value |
36
+ | --- | --- |
37
+ | `--to` | Recipient address (required). |
38
+ | `--subject` | Subject (required). |
39
+ | `--text` | Plain-text body. |
40
+ | `--html` | HTML body. |
41
+ | `--token-file` | Path to a file holding the API token. |
42
+ | `--url` | Pidgey base URL. |
43
+ | `--idempotency-key` | Idempotency key, 1 to 255 printable ASCII characters. Without it, the library generates one per call. |
44
+ | `--retry-ambiguous` | Retry also when the server may have sent the message (risks a duplicate). |
45
+ | `--allow-insecure-http` | Allow an `http://` URL on a non-loopback host. |
46
+ | `--verbose` | Print the result on success. |
47
+ | `--help` | Print the usage. |
48
+ | `--version` | Print the CLI and library versions. |
49
+
50
+ An unknown or repeated flag, a positional argument or a missing `--to` or `--subject` prints the
51
+ reason and the usage on stderr and exits with `2`. Values are forwarded as given: `--text ''` is
52
+ sent, and the API decides whether an empty body is valid.
53
+
54
+ ### Token and URL
55
+
56
+ - The token comes from `--token-file`, otherwise from the `PIDGEY_TOKEN` environment variable.
57
+ **There is no `--token` flag**: command-line arguments are visible to every local user and land
58
+ in shell history.
59
+ - The URL comes from `--url`, otherwise from `PIDGEY_URL`.
60
+ - A missing token or URL exits with `2`.
61
+ - The token file must be a regular file (a symlink to one is fine; a FIFO, a device such as
62
+ `/dev/stdin` or a directory is refused) of at most 4096 bytes. One trailing newline (`\n` or
63
+ `\r\n`) is trimmed. An empty token, or one that still holds a control character, is refused.
64
+ - On POSIX systems, a token file readable by group or others prints a warning on stderr and the
65
+ send goes on.
66
+ - The token is never read from stdin, never prompted for and never printed.
67
+
68
+ ### Body and stdin
69
+
70
+ - With `--text` and/or `--html`, those are the body and stdin is not read.
71
+ - With neither, stdin is the plain-text body, read as UTF-8.
72
+ - With neither and a terminal as stdin, the command exits with `2` instead of waiting for input.
73
+ - Stdin is read up to 1 MiB (1048576 bytes): one more byte exits with `2` and nothing is sent.
74
+ `--text` and `--html` are not capped.
75
+ - A stdin that never closes (`tail -f | pidgey ...`) blocks forever: there is no stdin timeout.
76
+
77
+ ### Output
78
+
79
+ - On success nothing is printed. With `--verbose`, one JSON line goes to stdout:
80
+ `{"status":"sent","smtp":{"code":250,"message":"OK"},"replayed":false}`.
81
+ - On failure, stderr gets `pidgey: <code>: <message>`, then `pidgey: SMTP reply: <code> <message>`
82
+ when the server gave one, then `pidgey: the message was possibly sent` when it may have been
83
+ delivered. The message content, the token and the response body are never printed.
84
+
85
+ ### Exit codes
86
+
87
+ | Code | Meaning |
88
+ | --- | --- |
89
+ | `0` | The message was sent. |
90
+ | `1` | The send failed or could not complete (network failures included). |
91
+ | `2` | Usage error: a bad command line, a missing token or URL, an unusable token file, a rejected `--url` or `--idempotency-key`, an unreadable or oversized stdin, or no body with a terminal stdin. |
92
+ | `130` | Interrupted by SIGINT (Ctrl-C). A request in flight is aborted. |
93
+
94
+ ## More
95
+
96
+ Source, issues and the design notes are in the
97
+ [repository](https://github.com/darthjee/pidgey/tree/main/clients/cli).
package/bin/pidgey.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { run } from '../cli/run.js';
3
+
4
+ const controller = new AbortController();
5
+ // `once`: a second SIGINT gets Node's default behaviour and ends the process at once.
6
+ process.once('SIGINT', () => controller.abort());
7
+
8
+ // No process.exit(): the process ends by itself once stdout is flushed and the library has
9
+ // left no socket open.
10
+ process.exitCode = await run(process.argv.slice(2), {
11
+ env: process.env,
12
+ stdin: process.stdin,
13
+ stdout: process.stdout,
14
+ stderr: process.stderr,
15
+ signal: controller.signal,
16
+ });
@@ -0,0 +1,163 @@
1
+ import { parseArgs } from 'node:util';
2
+
3
+ /**
4
+ * The usage text of the `pidgey` command.
5
+ * @type {string}
6
+ */
7
+ export const USAGE = `Usage: pidgey --to <address> --subject <text> [--text <body>] [--html <body>] [options]
8
+ pidgey --help | --version
9
+
10
+ Sends one message through a Pidgey server. Without --text and --html, the body is read
11
+ from stdin (at most 1 MiB; a TTY stdin is an error).
12
+
13
+ Options:
14
+ --to <address> Recipient address (required).
15
+ --subject <text> Subject (required).
16
+ --text <body> Plain-text body.
17
+ --html <body> HTML body.
18
+ --token-file <path> File holding the API token (at most 4 KiB).
19
+ Without it, the token comes from PIDGEY_TOKEN.
20
+ --url <url> Pidgey base URL. Without it, the URL comes from PIDGEY_URL.
21
+ --idempotency-key <key> Idempotency key (1 to 255 printable ASCII characters).
22
+ --retry-ambiguous Retry also when the server may have sent the message.
23
+ --allow-insecure-http Allow an http:// URL on a non-loopback host.
24
+ --verbose Print the result on success.
25
+ --help Print this usage and exit.
26
+ --version Print the CLI and library versions and exit.
27
+
28
+ The token is never taken from the command line.
29
+
30
+ Exit codes:
31
+ 0 The message was sent.
32
+ 1 The send failed.
33
+ 2 Usage error.
34
+ 130 Interrupted by SIGINT.
35
+ `;
36
+
37
+ /**
38
+ * Raised when the command line or the environment is not valid. The CLI answers it with exit 2.
39
+ */
40
+ export class UsageError extends Error {
41
+ /**
42
+ * Builds a UsageError.
43
+ * @param {string} message - One-line description of the mistake.
44
+ * @param {{ showUsage?: boolean }} [options] - `showUsage` asks the CLI to print the usage
45
+ * after the message; only parse errors set it.
46
+ */
47
+ constructor(message, { showUsage = false } = {}) {
48
+ super(message);
49
+ this.name = 'UsageError';
50
+ /** @type {boolean} */
51
+ this.showUsage = showUsage;
52
+ }
53
+ }
54
+
55
+ const OPTIONS = /** @type {const} */ ({
56
+ to: { type: 'string' },
57
+ subject: { type: 'string' },
58
+ text: { type: 'string' },
59
+ html: { type: 'string' },
60
+ 'token-file': { type: 'string' },
61
+ url: { type: 'string' },
62
+ 'idempotency-key': { type: 'string' },
63
+ 'retry-ambiguous': { type: 'boolean' },
64
+ 'allow-insecure-http': { type: 'boolean' },
65
+ verbose: { type: 'boolean' },
66
+ help: { type: 'boolean' },
67
+ version: { type: 'boolean' },
68
+ });
69
+
70
+ /**
71
+ * What a send needs from the command line.
72
+ * @typedef {object} SendArguments
73
+ * @property {'send'} mode - The send mode.
74
+ * @property {string} to - The recipient.
75
+ * @property {string} subject - The subject.
76
+ * @property {string | undefined} text - The plain-text body, when given (possibly empty).
77
+ * @property {string | undefined} html - The HTML body, when given (possibly empty).
78
+ * @property {string | undefined} tokenFile - The token file path, when given.
79
+ * @property {string | undefined} url - The base URL, when given.
80
+ * @property {string | undefined} idempotencyKey - The idempotency key, when given.
81
+ * @property {boolean} retryAmbiguous - Whether to retry ambiguous failures.
82
+ * @property {boolean} allowInsecureHttp - Whether to allow cleartext HTTP.
83
+ * @property {boolean} verbose - Whether to print the result on success.
84
+ */
85
+
86
+ /**
87
+ * Parses the command line arguments (without the node binary and the script path).
88
+ * @param {string[]} argv - The arguments.
89
+ * @returns {{ mode: 'help' } | { mode: 'version' } | SendArguments} What was asked for.
90
+ * @throws {UsageError} On an unknown flag, a positional argument, a repeated flag, a missing
91
+ * value or a missing required flag. The error asks for the usage to be printed.
92
+ */
93
+ export function parseArguments(argv) {
94
+ const { values, tokens } = parse(argv);
95
+
96
+ rejectRepeated(tokens);
97
+
98
+ if (values.help) {
99
+ return { mode: 'help' };
100
+ }
101
+ if (values.version) {
102
+ return { mode: 'version' };
103
+ }
104
+
105
+ for (const required of ['to', 'subject']) {
106
+ if (values[required] === undefined) {
107
+ throw new UsageError(`Missing required option '--${required}'`, { showUsage: true });
108
+ }
109
+ }
110
+
111
+ return {
112
+ mode: 'send',
113
+ to: /** @type {string} */ (values.to),
114
+ subject: /** @type {string} */ (values.subject),
115
+ text: /** @type {string | undefined} */ (values.text),
116
+ html: /** @type {string | undefined} */ (values.html),
117
+ tokenFile: /** @type {string | undefined} */ (values['token-file']),
118
+ url: /** @type {string | undefined} */ (values.url),
119
+ idempotencyKey: /** @type {string | undefined} */ (values['idempotency-key']),
120
+ retryAmbiguous: values['retry-ambiguous'] === true,
121
+ allowInsecureHttp: values['allow-insecure-http'] === true,
122
+ verbose: values.verbose === true,
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Runs `parseArgs` in strict mode and turns its errors into UsageErrors.
128
+ * @param {string[]} argv - The arguments.
129
+ * @returns {{ values: Record<string, unknown>, tokens: Array<{ kind: string, name: string }> }}
130
+ * The parsed values and tokens.
131
+ */
132
+ function parse(argv) {
133
+ try {
134
+ const { values, tokens } = parseArgs({
135
+ args: argv,
136
+ options: OPTIONS,
137
+ strict: true,
138
+ allowPositionals: false,
139
+ tokens: true,
140
+ });
141
+ return { values, tokens };
142
+ } catch (error) {
143
+ throw new UsageError(/** @type {Error} */ (error).message.split('\n')[0], { showUsage: true });
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Rejects a flag given more than once.
149
+ * @param {Array<{ kind: string, name: string }>} tokens - The parsed tokens.
150
+ * @returns {void}
151
+ * @throws {UsageError} When a flag appears twice.
152
+ */
153
+ function rejectRepeated(tokens) {
154
+ const seen = new Set();
155
+ for (const token of tokens) {
156
+ if (token.kind === 'option') {
157
+ if (seen.has(token.name)) {
158
+ throw new UsageError(`Option '--${token.name}' given more than once`, { showUsage: true });
159
+ }
160
+ seen.add(token.name);
161
+ }
162
+ }
163
+ }
package/cli/Body.js ADDED
@@ -0,0 +1,95 @@
1
+ import { UsageError } from './Arguments.js';
2
+
3
+ /**
4
+ * The most bytes read from stdin: 1 MiB, the request body limit of the API.
5
+ * @type {number}
6
+ */
7
+ export const STDIN_LIMIT = 1048576;
8
+
9
+ /**
10
+ * The readable the body can come from.
11
+ * @typedef {AsyncIterable<Uint8Array> & { isTTY?: boolean, destroy: () => unknown }} BodyStdin
12
+ */
13
+
14
+ /**
15
+ * Picks the body parts of the message. With `--text` and/or `--html` those are used and stdin
16
+ * is not touched; with neither, stdin is the plain-text body, unless it is a TTY.
17
+ * @param {{ text?: string, html?: string }} args - The parsed flags.
18
+ * @param {{ stdin: BodyStdin, signal: AbortSignal }} io - Standard input and the abort signal.
19
+ * @returns {Promise<{ text?: string, html?: string } | null>} The body parts, or `null` when the
20
+ * signal aborted while stdin was being read (nothing is to be sent).
21
+ * @throws {UsageError} On a TTY stdin with no body flag, an unreadable stdin or one over 1 MiB.
22
+ */
23
+ export async function readBody({ text, html }, { stdin, signal }) {
24
+ if (text !== undefined || html !== undefined) {
25
+ return {
26
+ ...(text === undefined ? {} : { text }),
27
+ ...(html === undefined ? {} : { html }),
28
+ };
29
+ }
30
+ if (stdin.isTTY) {
31
+ throw new UsageError('No body: pass --text or --html, or pipe the body through stdin');
32
+ }
33
+
34
+ const stdinText = await readStdin(stdin, signal);
35
+ return stdinText === null ? null : { text: stdinText };
36
+ }
37
+
38
+ /**
39
+ * Reads stdin as UTF-8 text, stopping as soon as it goes over the limit.
40
+ * @param {BodyStdin} stdin - The readable.
41
+ * @param {AbortSignal} signal - Aborted on SIGINT.
42
+ * @returns {Promise<string | null>} The text, or `null` when the signal aborted.
43
+ * @throws {UsageError} When stdin cannot be read or goes over 1 MiB.
44
+ */
45
+ async function readStdin(stdin, signal) {
46
+ if (signal.aborted) {
47
+ return null;
48
+ }
49
+
50
+ const chunks = [];
51
+ let total = 0;
52
+ let overLimit = false;
53
+ const onAbort = () => stdin.destroy();
54
+ signal.addEventListener('abort', onAbort, { once: true });
55
+ try {
56
+ for await (const chunk of stdin) {
57
+ total += chunk.length;
58
+ if (total > STDIN_LIMIT) {
59
+ overLimit = true;
60
+ stdin.destroy();
61
+ break;
62
+ }
63
+ chunks.push(chunk);
64
+ }
65
+ } catch (error) {
66
+ if (signal.aborted) {
67
+ return null;
68
+ }
69
+ const { code } = /** @type {{ code?: string }} */ (error);
70
+ throw new UsageError(`Cannot read stdin${code ? `: ${code}` : ''}`);
71
+ } finally {
72
+ signal.removeEventListener('abort', onAbort);
73
+ }
74
+
75
+ if (overLimit) {
76
+ throw new UsageError(`Stdin is larger than the ${STDIN_LIMIT} byte (1 MiB) limit; nothing was sent`);
77
+ }
78
+ return new TextDecoder('utf-8').decode(concat(chunks, total));
79
+ }
80
+
81
+ /**
82
+ * Joins chunks into one buffer.
83
+ * @param {Uint8Array[]} chunks - The chunks.
84
+ * @param {number} total - Their total length.
85
+ * @returns {Uint8Array} The joined bytes.
86
+ */
87
+ function concat(chunks, total) {
88
+ const joined = new Uint8Array(total);
89
+ let offset = 0;
90
+ for (const chunk of chunks) {
91
+ joined.set(chunk, offset);
92
+ offset += chunk.length;
93
+ }
94
+ return joined;
95
+ }
@@ -0,0 +1,139 @@
1
+ import { constants } from 'node:fs';
2
+ import { open } from 'node:fs/promises';
3
+ import { UsageError } from './Arguments.js';
4
+
5
+ const TOKEN_FILE_LIMIT = 4096;
6
+ // eslint-disable-next-line no-control-regex -- matching control characters is the point
7
+ const CONTROL_CHARACTER =/[\u0000-\u001f\u007f]/;
8
+
9
+ /**
10
+ * Resolves the API token and the base URL from the parsed flags and the environment.
11
+ * The token comes from `--token-file`, otherwise from `PIDGEY_TOKEN`; the URL from `--url`,
12
+ * otherwise from `PIDGEY_URL`. The token is never taken from the command line.
13
+ * @param {{ tokenFile?: string, url?: string }} args - The parsed flags.
14
+ * @param {{ env: Record<string, string | undefined>, stderr: { write: (text: string) => unknown },
15
+ * platform: string }} io - The environment, the error stream (for the mode warning) and the platform.
16
+ * @returns {Promise<{ token: string, baseUrl: string }>} The token and the base URL.
17
+ * @throws {UsageError} When either is missing or the token file is not acceptable.
18
+ */
19
+ export async function resolveCredentials(args, { env, stderr, platform }) {
20
+ const token = args.tokenFile === undefined
21
+ ? tokenFromEnvironment(env)
22
+ : await readTokenFile(args.tokenFile, { stderr, platform });
23
+
24
+ const baseUrl = args.url || env.PIDGEY_URL;
25
+ if (!baseUrl) {
26
+ throw new UsageError('Missing URL: pass --url or set PIDGEY_URL');
27
+ }
28
+
29
+ return { token, baseUrl };
30
+ }
31
+
32
+ /**
33
+ * Takes the token from `PIDGEY_TOKEN`.
34
+ * @param {Record<string, string | undefined>} env - The environment variables.
35
+ * @returns {string} The token.
36
+ * @throws {UsageError} When `PIDGEY_TOKEN` is unset or empty.
37
+ */
38
+ function tokenFromEnvironment(env) {
39
+ if (!env.PIDGEY_TOKEN) {
40
+ throw new UsageError('Missing token: pass --token-file or set PIDGEY_TOKEN');
41
+ }
42
+ return env.PIDGEY_TOKEN;
43
+ }
44
+
45
+ /**
46
+ * Reads the token from a file, through a single descriptor, following the rules of the spec.
47
+ * @param {string} path - The token file path.
48
+ * @param {{ stderr: { write: (text: string) => unknown }, platform: string }} io - The error
49
+ * stream and the platform.
50
+ * @returns {Promise<string>} The token.
51
+ * @throws {UsageError} On any problem with the file; the message names the path, never the content.
52
+ */
53
+ async function readTokenFile(path, { stderr, platform }) {
54
+ let handle;
55
+ try {
56
+ // O_NONBLOCK keeps the open of a FIFO from blocking; the fstat below refuses it anyway.
57
+ // The constant is undefined on Windows, where `|` reads it as 0.
58
+ handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK);
59
+ } catch (error) {
60
+ throw unreadable(path, error);
61
+ }
62
+
63
+ let stat;
64
+ let bytes;
65
+ try {
66
+ stat = await handle.stat();
67
+ // A FIFO, a device or a directory is refused before anything is read from it.
68
+ if (stat.isFile()) {
69
+ bytes = await readAtMost(handle, TOKEN_FILE_LIMIT + 1);
70
+ }
71
+ /* c8 ignore start */
72
+ // A failing fstat or read on a descriptor that just opened cannot be provoked from a spec.
73
+ } catch (error) {
74
+ throw unreadable(path, error);
75
+ /* c8 ignore stop */
76
+ } finally {
77
+ await handle.close();
78
+ }
79
+
80
+ if (bytes === undefined) {
81
+ throw new UsageError(`Token file '${path}' is not a regular file`);
82
+ }
83
+ if (platform !== 'win32' && (stat.mode & 0o077) !== 0) {
84
+ stderr.write(`pidgey: warning: token file '${path}' is readable by group or others\n`);
85
+ }
86
+ if (bytes.length > TOKEN_FILE_LIMIT) {
87
+ throw new UsageError(`Token file '${path}' is larger than the ${TOKEN_FILE_LIMIT} byte (4 KiB) limit`);
88
+ }
89
+ return parseToken(new TextDecoder().decode(bytes), path);
90
+ }
91
+
92
+ /**
93
+ * Reads up to `limit` bytes from a file handle, from its start.
94
+ * @param {{ read: (buffer: Uint8Array, offset: number, length: number, position: number | null)
95
+ * => Promise<{ bytesRead: number }> }} handle - The open file.
96
+ * @param {number} limit - The most bytes to read.
97
+ * @returns {Promise<Uint8Array>} The bytes read.
98
+ */
99
+ async function readAtMost(handle, limit) {
100
+ const buffer = new Uint8Array(limit);
101
+ let total = 0;
102
+ while (total < limit) {
103
+ const { bytesRead } = await handle.read(buffer, total, limit - total, total);
104
+ if (bytesRead === 0) {
105
+ break;
106
+ }
107
+ total += bytesRead;
108
+ }
109
+ return buffer.subarray(0, total);
110
+ }
111
+
112
+ /**
113
+ * Trims one trailing newline and validates the token text.
114
+ * @param {string} text - The file content.
115
+ * @param {string} path - The token file path, for the messages.
116
+ * @returns {string} The token.
117
+ * @throws {UsageError} When the token is empty or holds a control character.
118
+ */
119
+ function parseToken(text, path) {
120
+ const token = text.replace(/\r?\n$/, '');
121
+ if (token.trim() === '') {
122
+ throw new UsageError(`Token file '${path}' is empty`);
123
+ }
124
+ if (CONTROL_CHARACTER.test(token)) {
125
+ throw new UsageError(`Token file '${path}' holds a control character`);
126
+ }
127
+ return token;
128
+ }
129
+
130
+ /**
131
+ * Builds the error for a token file that could not be opened or read.
132
+ * @param {string} path - The token file path.
133
+ * @param {unknown} error - The system error.
134
+ * @returns {UsageError} The usage error, naming the path and the error code only.
135
+ */
136
+ function unreadable(path, error) {
137
+ const { code } = /** @type {{ code: string }} */ (error);
138
+ return new UsageError(`Cannot read token file '${path}': ${code}`);
139
+ }
@@ -0,0 +1,32 @@
1
+ import { PidgeyError } from 'pidgey-client';
2
+ import { UsageError } from './Arguments.js';
3
+
4
+ /**
5
+ * The exit codes of the `pidgey` command.
6
+ * @type {{ OK: number, FAILURE: number, USAGE: number, INTERRUPTED: number }}
7
+ */
8
+ export const EXIT = Object.freeze({ OK: 0, FAILURE: 1, USAGE: 2, INTERRUPTED: 130 });
9
+
10
+ /**
11
+ * Maps a failure to the exit code.
12
+ * - a usage error, or the library's `CLIENT_CONFIGURATION`, is `2`;
13
+ * - an `ABORTED` error while the signal is aborted (SIGINT) is `130`;
14
+ * - any other failure is `1`.
15
+ * @param {unknown} error - What was thrown.
16
+ * @param {AbortSignal} signal - The signal aborted on SIGINT.
17
+ * @returns {number} The exit code.
18
+ */
19
+ export function exitCodeFor(error, signal) {
20
+ if (error instanceof UsageError) {
21
+ return EXIT.USAGE;
22
+ }
23
+ if (error instanceof PidgeyError) {
24
+ if (error.code === 'CLIENT_CONFIGURATION') {
25
+ return EXIT.USAGE;
26
+ }
27
+ if (error.code === 'ABORTED' && signal.aborted) {
28
+ return EXIT.INTERRUPTED;
29
+ }
30
+ }
31
+ return EXIT.FAILURE;
32
+ }
package/cli/Output.js ADDED
@@ -0,0 +1,47 @@
1
+ import { PidgeyError } from 'pidgey-client';
2
+ import { UsageError, USAGE } from './Arguments.js';
3
+
4
+ /**
5
+ * Formats the `--verbose` line printed after a successful send.
6
+ * @param {object} result - What `send` resolved with.
7
+ * @returns {string} One JSON line.
8
+ */
9
+ export function formatResult(result) {
10
+ return `${JSON.stringify(result)}\n`;
11
+ }
12
+
13
+ /**
14
+ * Formats a failure for stderr. Never includes the message content, the token, the URL or the
15
+ * response body of the error.
16
+ * - a `PidgeyError`: its code and message, the SMTP reply when present, and a notice when the
17
+ * message was possibly sent;
18
+ * - a `UsageError`: its message, followed by the usage text for a parse error;
19
+ * - anything else: only the name of the error.
20
+ * @param {unknown} error - What was thrown.
21
+ * @returns {string} The text for stderr, ending in a newline.
22
+ */
23
+ export function formatFailure(error) {
24
+ if (error instanceof PidgeyError) {
25
+ return formatPidgeyError(error);
26
+ }
27
+ if (error instanceof UsageError) {
28
+ return `pidgey: ${error.message}\n${error.showUsage ? USAGE : ''}`;
29
+ }
30
+ return `pidgey: unexpected error (${error instanceof Error ? error.name : 'unknown'})\n`;
31
+ }
32
+
33
+ /**
34
+ * Formats a `PidgeyError`.
35
+ * @param {PidgeyError} error - The error.
36
+ * @returns {string} The lines for stderr.
37
+ */
38
+ function formatPidgeyError(error) {
39
+ let text = `pidgey: ${error.code}: ${error.message}\n`;
40
+ if (error.smtp) {
41
+ text += `pidgey: SMTP reply: ${error.smtp.code} ${error.smtp.message}\n`;
42
+ }
43
+ if (error.possiblySent) {
44
+ text += 'pidgey: the message was possibly sent\n';
45
+ }
46
+ return text;
47
+ }
package/cli/run.js ADDED
@@ -0,0 +1,94 @@
1
+ import { PidgeyClient, VERSION as LIBRARY_VERSION } from 'pidgey-client';
2
+ import { parseArguments, USAGE } from './Arguments.js';
3
+ import { readBody } from './Body.js';
4
+ import { resolveCredentials } from './Credentials.js';
5
+ import { EXIT, exitCodeFor } from './ExitCode.js';
6
+ import { formatFailure, formatResult } from './Output.js';
7
+ import { VERSION } from './version.js';
8
+
9
+ /**
10
+ * The part of the library client the CLI uses.
11
+ * @typedef {object} SendClient
12
+ * @property {(message: object, options: object) => Promise<object>} send - Sends the message.
13
+ */
14
+
15
+ /**
16
+ * The environment the CLI runs in, injected so specs can drive it in-process.
17
+ * @typedef {object} RunIo
18
+ * @property {Record<string, string | undefined>} env - The environment variables.
19
+ * @property {import('./Body.js').BodyStdin} stdin - The standard input.
20
+ * @property {{ write: (text: string) => unknown }} stdout - The standard output.
21
+ * @property {{ write: (text: string) => unknown }} stderr - The standard error.
22
+ * @property {AbortSignal} signal - Aborted on SIGINT.
23
+ * @property {(options: object) => SendClient} [createClient] - Builds the library client;
24
+ * defaults to `new PidgeyClient(options)`.
25
+ * @property {string} [platform] - The platform; defaults to `process.platform`.
26
+ */
27
+
28
+ /**
29
+ * Runs the `pidgey` command.
30
+ * @param {string[]} argv - The arguments (without the node binary and the script path).
31
+ * @param {RunIo} io - The environment: variables, streams, abort signal and factories.
32
+ * @returns {Promise<number>} The exit code: `0` sent, `1` a failed send, `2` a usage error and
33
+ * `130` interrupted.
34
+ */
35
+ export async function run(argv, io) {
36
+ try {
37
+ const args = parseArguments(argv);
38
+ if (args.mode === 'help') {
39
+ io.stdout.write(USAGE);
40
+ return EXIT.OK;
41
+ }
42
+ if (args.mode === 'version') {
43
+ io.stdout.write(`pidgey-cli ${VERSION} (pidgey-client ${LIBRARY_VERSION})\n`);
44
+ return EXIT.OK;
45
+ }
46
+
47
+ const result = await send(args, io);
48
+ if (result === null) {
49
+ return EXIT.INTERRUPTED;
50
+ }
51
+ if (args.verbose) {
52
+ io.stdout.write(formatResult(result));
53
+ }
54
+ return EXIT.OK;
55
+ } catch (error) {
56
+ io.stderr.write(formatFailure(error));
57
+ return exitCodeFor(error, io.signal);
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Sends the message: credentials, body, client, `send`.
63
+ * @param {import('./Arguments.js').SendArguments} args - The parsed flags.
64
+ * @param {RunIo} io - The environment.
65
+ * @returns {Promise<object | null>} What `send` resolved with, or `null` when interrupted while
66
+ * stdin was being read.
67
+ * @throws {Error} A `UsageError`, or a `PidgeyError` from the library.
68
+ */
69
+ async function send(args, io) {
70
+ const { token, baseUrl } = await resolveCredentials(args, {
71
+ env: io.env,
72
+ stderr: io.stderr,
73
+ platform: io.platform ?? process.platform,
74
+ });
75
+ const body = await readBody(args, io);
76
+ if (body === null) {
77
+ return null;
78
+ }
79
+
80
+ const createClient = io.createClient ?? ((options) => new PidgeyClient(options));
81
+ const client = createClient({
82
+ token,
83
+ baseUrl,
84
+ retryAmbiguous: args.retryAmbiguous,
85
+ allowInsecureHttp: args.allowInsecureHttp,
86
+ });
87
+ return client.send(
88
+ { to: args.to, subject: args.subject, ...body },
89
+ {
90
+ signal: io.signal,
91
+ ...(args.idempotencyKey === undefined ? {} : { idempotencyKey: args.idempotencyKey }),
92
+ },
93
+ );
94
+ }
package/cli/version.js ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The CLI version. It must equal the `version` of `package.json`.
3
+ * @type {string}
4
+ */
5
+ export const VERSION = '0.1.0';
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "pidgey-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Command-line client for the Pidgey email-delivery API",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/darthjee/pidgey.git",
10
+ "directory": "clients/cli"
11
+ },
12
+ "bin": {
13
+ "pidgey": "bin/pidgey.js"
14
+ },
15
+ "engines": {
16
+ "node": ">=22.12.0"
17
+ },
18
+ "files": [
19
+ "bin/",
20
+ "cli/"
21
+ ],
22
+ "scripts": {
23
+ "lint": "eslint bin cli specs",
24
+ "typecheck": "tsc --allowJs --checkJs --noEmit -p .",
25
+ "test": "jasmine \"specs/cli/**/*_spec.js\" \"specs/bin/**/*_spec.js\"",
26
+ "coverage": "c8 jasmine \"specs/cli/**/*_spec.js\" \"specs/bin/**/*_spec.js\"",
27
+ "test:integration": "jasmine \"specs/integration/**/*_spec.js\""
28
+ },
29
+ "dependencies": {
30
+ "pidgey-client": "^0.1.0"
31
+ },
32
+ "devDependencies": {
33
+ "@eslint/js": "^9.39.2",
34
+ "c8": "11.0.0",
35
+ "eslint": "^9.39.1",
36
+ "eslint-plugin-jasmine": "^4.1.3",
37
+ "eslint-plugin-jsdoc": "61.5.0",
38
+ "globals": "^16.5.0",
39
+ "jasmine": "^5.0.0",
40
+ "typescript": "^5.9.3"
41
+ },
42
+ "c8": {
43
+ "reporter": [
44
+ "text",
45
+ "lcov"
46
+ ],
47
+ "include": [
48
+ "bin/**/*.js",
49
+ "cli/**/*.js"
50
+ ],
51
+ "exclude": [
52
+ "specs/**",
53
+ "coverage/**"
54
+ ],
55
+ "all": true,
56
+ "check-coverage": true,
57
+ "lines": 100,
58
+ "branches": 100,
59
+ "functions": 100,
60
+ "statements": 100
61
+ }
62
+ }