@receiverdotemail/cli 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Receiver.email
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,80 @@
1
- # Temporary Holding Version
1
+ # @receiverdotemail/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
+ `receiver`: [Receiver.email](https://www.receiver.email), the programmable inbox API for tests, AI agents and scripts, from the terminal. Create an inbox, wait for the email and print the OTP code or links, in shell scripts, CI jobs, an agent's shell or by hand.
4
+
5
+ ```bash
6
+ npm install -g @receiverdotemail/cli # or run it once: npx @receiverdotemail/cli --help
7
+ receiver login # paste a project API key (recv_live_...)
8
+
9
+ ADDR=$(receiver inbox new --prefix signup)
10
+ ./my-app signup "$ADDR"
11
+ CODE=$(receiver otp "$ADDR" --timeout 60) # prints only the code; exit code 2 on timeout
12
+ ```
13
+
14
+ In CI, set `RECEIVER_API_KEY` instead of running `receiver login`. Node.js 20 or later.
15
+
16
+ **Docs:** [CLI reference](https://www.receiver.email/docs/cli) · [Quick start: create a project and an API key](https://www.receiver.email/docs/quickstart). Also available: the [TypeScript SDK](https://www.npmjs.com/package/@receiverdotemail/sdk), [Python SDK](https://pypi.org/project/receiverdotemail/) and [MCP server](https://www.npmjs.com/package/@receiverdotemail/mcp).
17
+
18
+ To keep the `since` of the new inbox (so older mail never matches):
19
+
20
+ ```bash
21
+ INBOX=$(receiver --json inbox new --prefix signup)
22
+ ADDR=$(echo "$INBOX" | jq -r .address)
23
+ SINCE=$(echo "$INBOX" | jq -r .since)
24
+ receiver otp "$ADDR" --since "$SINCE"
25
+ ```
26
+
27
+ ## Authentication
28
+
29
+ `RECEIVER_API_KEY` wins when set. Otherwise the key saved by `receiver login` in `~/.config/receiver/config.json` (or `$XDG_CONFIG_HOME/receiver/config.json`, mode 0600) is used.
30
+
31
+ `receiver login` checks the key with the API before saving it. Without `--key` it prompts (hidden input) in a terminal, or reads the key from stdin: `echo "$KEY" | receiver login`. Logging in with `--api-url` or `RECEIVER_API_URL` set to a non-default API also saves that URL.
32
+
33
+ API URL order: `--api-url`, `RECEIVER_API_URL`, the saved login, `https://api.receiver.email/api/v1`.
34
+
35
+ ## Commands
36
+
37
+ | Command | Does |
38
+ | --- | --- |
39
+ | `receiver login [--key <key>]` | Validates the key with `whoami` and saves it |
40
+ | `receiver whoami` | Project name, id and email suffix |
41
+ | `receiver inbox new [--prefix p]` | Prints a fresh address (`{ address, since }` with `--json`) |
42
+ | `receiver wait <address> [--since ISO] [--timeout s] [--otp [--code-length n] \| --links]` | Waits (default 60 s) and prints a from/subject/body summary, only the code with `--otp`, or the links one per line with `--links` |
43
+ | `receiver otp <address> [--since ISO] [--timeout s] [--code-length n]` | Same as `wait --otp`: prints only the code |
44
+ | `receiver list [--address a] [--limit n]` | Table of recent emails (default 20) |
45
+ | `receiver read <emailId> [--html \| --raw]` | Prints the full text body, the HTML, or the original RFC 822 message |
46
+ | `receiver watch [address]` | Prints new emails as they arrive until Ctrl-C |
47
+ | `receiver test-email <address>` | Sends a test email with a 6-digit code to one of your addresses |
48
+
49
+ Without `--since`, waits match mail from the last 60 seconds. `--code-length` (4 to 8) is the expected length of the code; without it the length is detected, and 5- and 7-digit codes are only found when asked for.
50
+
51
+ ### Global options
52
+
53
+ - `--json`: machine-readable output, one JSON document per command (`watch` prints one JSON object per line). Errors print `{ "error": { "code", "message" } }`; timeouts print `{ "status": "timeout", "since", "waitedSeconds" }`.
54
+ - `--api-url <url>`: talk to another API (e.g. staging).
55
+
56
+ Human output goes to stdout, hints and diagnostics to stderr, so `$(receiver otp ...)` captures just the code.
57
+
58
+ ### Exit codes
59
+
60
+ | Code | Meaning |
61
+ | --- | --- |
62
+ | 0 | Success (also Ctrl-C during `watch`) |
63
+ | 1 | Error (bad arguments, not logged in, API error) |
64
+ | 2 | Timeout: nothing arrived in time; rerun with the printed `--since` to keep waiting |
65
+ | 130 | Interrupted with Ctrl-C during `wait` or `otp` |
66
+
67
+ ## Development
68
+
69
+ ```bash
70
+ npm ci
71
+ npm run typecheck && npm test # uses ../typescript-sdk/src directly; no build needed
72
+ npm run build # builds ../typescript-sdk, then dist/
73
+ node dist/index.js --help
74
+ ```
75
+
76
+ The SDK dependency is `file:../typescript-sdk` inside this monorepo; the release workflow replaces it with the released `@receiverdotemail/sdk` version range, and `prepublishOnly` refuses a hand-run `npm publish` while it is still `file:`.
77
+
78
+ ## License
79
+
80
+ MIT
package/dist/cli.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The `receiver` command. `run()` takes its I/O and SDK client factory as
3
+ * arguments so tests can drive it without a terminal or network.
4
+ */
5
+ import { ReceiverClient, type ReceiverClientOptions } from '@receiverdotemail/sdk';
6
+ export type CliClient = Pick<ReceiverClient, 'whoami' | 'inboxes' | 'emails'>;
7
+ export interface CliIO {
8
+ stdout: (text: string) => void;
9
+ stderr: (text: string) => void;
10
+ env: Record<string, string | undefined>;
11
+ /** Builds the SDK client (tests pass a fake). */
12
+ createClient?: (options: ReceiverClientOptions) => CliClient;
13
+ /** Whether stdin is an interactive terminal. */
14
+ stdinIsTTY?: boolean;
15
+ /** Prompts for the API key without echoing it (TTY only). */
16
+ promptSecret?: (question: string) => Promise<string>;
17
+ /** Reads all of stdin (for `echo $KEY | receiver login`). */
18
+ readStdin?: () => Promise<string>;
19
+ /** Aborted on Ctrl-C; stops `wait` and `watch`. */
20
+ signal?: AbortSignal;
21
+ }
22
+ export declare const EXIT_OK = 0;
23
+ export declare const EXIT_ERROR = 1;
24
+ export declare const EXIT_TIMEOUT = 2;
25
+ /** Ctrl-C during `wait`/`otp` (`watch` exits 0 on Ctrl-C). */
26
+ export declare const EXIT_INTERRUPTED = 130;
27
+ export declare function run(argv: string[], io: CliIO): Promise<number>;
package/dist/cli.js ADDED
@@ -0,0 +1,349 @@
1
+ /**
2
+ * The `receiver` command. `run()` takes its I/O and SDK client factory as
3
+ * arguments so tests can drive it without a terminal or network.
4
+ */
5
+ import { Command, CommanderError, Option } from 'commander';
6
+ import { AuthenticationError, DEFAULT_BASE_URL, RateLimitError, ReceiverClient, ReceiverError, ReceiverTimeoutError, } from '@receiverdotemail/sdk';
7
+ import { configPath, readConfig, writeConfig } from './config.js';
8
+ import { USER_AGENT, VERSION } from './version.js';
9
+ export const EXIT_OK = 0;
10
+ export const EXIT_ERROR = 1;
11
+ export const EXIT_TIMEOUT = 2;
12
+ /** Ctrl-C during `wait`/`otp` (`watch` exits 0 on Ctrl-C). */
13
+ export const EXIT_INTERRUPTED = 130;
14
+ /** Thrown inside commands to exit with a message (and an optional fix). */
15
+ class CliError extends Error {
16
+ code;
17
+ constructor(message, code = 'CLI_ERROR') {
18
+ super(message);
19
+ this.code = code;
20
+ }
21
+ }
22
+ const BODY_PREVIEW = 1000;
23
+ export async function run(argv, io) {
24
+ let exitCode = EXIT_OK;
25
+ const createClient = io.createClient ?? ((options) => new ReceiverClient(options));
26
+ const cfgPath = configPath(io.env);
27
+ const out = (line = '') => io.stdout(line + '\n');
28
+ const err = (line = '') => io.stderr(line + '\n');
29
+ const program = new Command('receiver')
30
+ .description('Receiver.email from the terminal: create inboxes, wait for emails and OTP codes.')
31
+ .version(VERSION, '-v, --version')
32
+ .option('--json', 'machine-readable output (one JSON document; JSON lines for watch)')
33
+ .option('--api-url <url>', 'API base URL (default: RECEIVER_API_URL, then the saved login, then production)')
34
+ .showHelpAfterError('(run `receiver --help` for usage)')
35
+ .exitOverride()
36
+ .configureOutput({ writeOut: io.stdout, writeErr: io.stderr });
37
+ /** Wraps a command: resolves globals, prints errors, sets the exit code. */
38
+ const action = (fn) => async (...args) => {
39
+ const command = args[args.length - 1];
40
+ const globals = command.optsWithGlobals();
41
+ try {
42
+ await fn(globals, ...args.slice(0, -1));
43
+ }
44
+ catch (error) {
45
+ exitCode = report(error, globals);
46
+ }
47
+ };
48
+ const json = (globals, value) => out(JSON.stringify(value, null, 2));
49
+ function report(error, globals) {
50
+ if (error instanceof ReceiverTimeoutError) {
51
+ if (globals.json)
52
+ json(globals, { status: 'timeout', since: error.since, waitedSeconds: error.waitedSeconds });
53
+ else
54
+ err(`Timed out after ${error.waitedSeconds}s with no matching email (since ${error.since}). Run the same command with --since ${error.since} to keep waiting.`);
55
+ return EXIT_TIMEOUT;
56
+ }
57
+ if (error instanceof ReceiverError && error.code === 'ABORTED')
58
+ return EXIT_INTERRUPTED;
59
+ const { code, message } = describe(error);
60
+ if (globals.json)
61
+ json(globals, { error: { code, message } });
62
+ else
63
+ err(`Error: ${message}`);
64
+ return EXIT_ERROR;
65
+ }
66
+ async function client(globals, apiKeyOverride) {
67
+ const config = await readConfig(cfgPath);
68
+ const apiKey = apiKeyOverride ?? (io.env.RECEIVER_API_KEY || config.apiKey);
69
+ if (!apiKey)
70
+ throw new CliError('Not logged in. Run `receiver login`, or set RECEIVER_API_KEY.', 'NOT_LOGGED_IN');
71
+ // The saved project only belongs to the saved key; any other key looks its own up
72
+ const projectId = apiKey === config.apiKey ? config.projectId : undefined;
73
+ return createClient({ apiKey, baseUrl: apiUrl(globals, config.apiUrl), userAgent: USER_AGENT, projectId });
74
+ }
75
+ const apiUrl = (globals, saved) => globals.apiUrl || io.env.RECEIVER_API_URL || saved || DEFAULT_BASE_URL;
76
+ const parseSince = (value) => {
77
+ if (value === undefined)
78
+ return undefined;
79
+ if (Number.isNaN(Date.parse(value)))
80
+ throw new CliError(`--since must be an ISO 8601 timestamp, got "${value}"`, 'INVALID_ARGUMENT');
81
+ return value;
82
+ };
83
+ const parseTimeout = (value) => {
84
+ const seconds = Number(value);
85
+ if (!Number.isFinite(seconds) || seconds < 0)
86
+ throw new CommanderError(1, 'invalid', `--timeout must be a number of seconds, got "${value}"`);
87
+ return seconds;
88
+ };
89
+ const parseCodeLength = (value) => {
90
+ const n = Number(value);
91
+ if (!Number.isInteger(n) || n < 4 || n > 8)
92
+ throw new CommanderError(1, 'invalid', `--code-length must be an integer from 4 to 8, got "${value}"`);
93
+ return n;
94
+ };
95
+ const parseLimit = (value) => {
96
+ const n = Number(value);
97
+ if (!Number.isInteger(n) || n < 1 || n > 100)
98
+ throw new CommanderError(1, 'invalid', `--limit must be an integer from 1 to 100, got "${value}"`);
99
+ return n;
100
+ };
101
+ // receiver login
102
+ program
103
+ .command('login')
104
+ .description('validate an API key and save it to ' + cfgPath)
105
+ .option('--key <key>', 'the API key (recv_live_...); prompted for when omitted')
106
+ .action(action(async (globals, options) => {
107
+ let key = options.key;
108
+ if (!key && io.stdinIsTTY && io.promptSecret) {
109
+ key = await io.promptSecret('API key (recv_live_...): ');
110
+ }
111
+ else if (!key && !io.stdinIsTTY && io.readStdin) {
112
+ key = (await io.readStdin()).split(/\r?\n/)[0];
113
+ }
114
+ key = key?.trim();
115
+ if (!key)
116
+ throw new CliError('No API key given. Pass --key recv_live_... or pipe it on stdin.', 'INVALID_ARGUMENT');
117
+ const me = await (await client(globals, key)).whoami();
118
+ if (me.authType !== 'apikey') {
119
+ throw new CliError('That is a dashboard session token. Create a project API key (recv_live_...) in the dashboard.', 'NOT_AN_API_KEY');
120
+ }
121
+ const config = await readConfig(cfgPath);
122
+ const url = globals.apiUrl || io.env.RECEIVER_API_URL;
123
+ await writeConfig(cfgPath, { ...config, apiKey: key, apiUrl: url && url !== DEFAULT_BASE_URL ? url : undefined, projectId: me.project.id });
124
+ if (globals.json)
125
+ return json(globals, { ...me, configPath: cfgPath });
126
+ out(`Logged in to project ${me.project.name} (${me.project.id}).`);
127
+ out(`Addresses end with ${me.project.emailSuffix}`);
128
+ err(`Key saved to ${cfgPath}`);
129
+ }));
130
+ // receiver whoami
131
+ program
132
+ .command('whoami')
133
+ .description('show the project the API key belongs to')
134
+ .action(action(async (globals) => {
135
+ const me = await (await client(globals)).whoami();
136
+ if (globals.json)
137
+ return json(globals, me);
138
+ if (me.authType === 'jwt') {
139
+ out(`Dashboard session for ${me.user.email} (${me.user.id})`);
140
+ return;
141
+ }
142
+ out(`Project: ${me.project.name}`);
143
+ out(`Project ID: ${me.project.id}`);
144
+ out(`Email suffix: ${me.project.emailSuffix}`);
145
+ out(`API key: ${me.apiKey.name} (${me.apiKey.id})`);
146
+ }));
147
+ // receiver inbox new
148
+ const inbox = program.command('inbox').description('mint addresses');
149
+ inbox
150
+ .command('new')
151
+ .description('create a fresh address and print it')
152
+ .option('--prefix <prefix>', 'readable start of the address, e.g. signup')
153
+ .action(action(async (globals, options) => {
154
+ const created = await (await client(globals)).inboxes.create({ prefix: options.prefix });
155
+ if (globals.json)
156
+ return json(globals, { address: created.address, since: created.createdAt });
157
+ out(created.address);
158
+ }));
159
+ // receiver wait / receiver otp
160
+ const waitFor = async (globals, address, options) => {
161
+ if (options.otp && options.links)
162
+ throw new CliError('Use either --otp or --links, not both.', 'INVALID_ARGUMENT');
163
+ if (options.codeLength !== undefined && !options.otp) {
164
+ throw new CliError('--code-length only applies to OTP codes: add --otp, or use `receiver otp`.', 'INVALID_ARGUMENT');
165
+ }
166
+ const c = await client(globals);
167
+ const since = parseSince(options.since);
168
+ if (options.otp) {
169
+ const otp = await c.emails.waitForOtp({
170
+ recipient: address,
171
+ since,
172
+ timeout: options.timeout,
173
+ codeLength: options.codeLength,
174
+ signal: io.signal,
175
+ });
176
+ if (globals.json)
177
+ return json(globals, { status: 'found', ...otp });
178
+ out(otp.code);
179
+ return;
180
+ }
181
+ const email = await c.emails.waitFor({ recipient: address, since, timeout: options.timeout, signal: io.signal });
182
+ if (options.links) {
183
+ if (globals.json)
184
+ return json(globals, { status: 'received', email, links: email.links });
185
+ for (const link of email.links)
186
+ out(link);
187
+ if (email.links.length === 0)
188
+ err('The email has no links.');
189
+ return;
190
+ }
191
+ if (globals.json)
192
+ return json(globals, { status: 'received', email });
193
+ printSummary(email);
194
+ };
195
+ const printSummary = (email) => {
196
+ out(`From: ${email.sender}`);
197
+ out(`To: ${email.sendTo}`);
198
+ out(`Subject: ${email.subject}`);
199
+ out(`Received: ${email.receivedAt}`);
200
+ out(`ID: ${email.id}`);
201
+ if (email.links?.length)
202
+ out(`Links: ${email.links.length}`);
203
+ const body = (email.textBody ?? email.textBodyPreview ?? '').trim();
204
+ if (body) {
205
+ out();
206
+ out(body.length > BODY_PREVIEW ? body.slice(0, BODY_PREVIEW) + '...' : body);
207
+ if (body.length > BODY_PREVIEW)
208
+ err(`(body truncated: run \`receiver read ${email.id}\` for the full text)`);
209
+ }
210
+ };
211
+ const timeoutOption = () => new Option('--timeout <seconds>', 'how long to wait').argParser(parseTimeout).default(60);
212
+ const sinceOption = () => new Option('--since <iso>', 'only email received after this time (default: the last 60 s)');
213
+ const codeLengthOption = (description) => new Option('--code-length <n>', description).argParser(parseCodeLength);
214
+ program
215
+ .command('wait')
216
+ .description('wait for an email to <address>')
217
+ .argument('<address>', 'the address to wait on')
218
+ .addOption(sinceOption())
219
+ .addOption(timeoutOption())
220
+ .option('--otp', 'print only the OTP code')
221
+ .addOption(codeLengthOption('with --otp: the code length, 4 to 8 (default: auto-detect)'))
222
+ .option('--links', 'print only the links, one per line')
223
+ .action(action(async (globals, address, options) => waitFor(globals, address, options)));
224
+ program
225
+ .command('otp')
226
+ .description('wait for an OTP code sent to <address> and print only the code')
227
+ .argument('<address>', 'the address to wait on')
228
+ .addOption(sinceOption())
229
+ .addOption(timeoutOption())
230
+ .addOption(codeLengthOption('the code length, 4 to 8 (default: auto-detect)'))
231
+ .action(action(async (globals, address, options) => waitFor(globals, address, { ...options, otp: true })));
232
+ // receiver list
233
+ program
234
+ .command('list')
235
+ .description('show recent emails, newest first')
236
+ .option('--address <address>', 'only emails sent to this address')
237
+ .addOption(new Option('--limit <n>', 'how many').argParser(parseLimit).default(20))
238
+ .action(action(async (globals, options) => {
239
+ const { emails } = await (await client(globals)).emails.list({ recipient: options.address, limit: options.limit });
240
+ if (globals.json)
241
+ return json(globals, { emails });
242
+ if (emails.length === 0) {
243
+ err('No emails.');
244
+ return;
245
+ }
246
+ table(['RECEIVED', 'FROM', 'TO', 'SUBJECT', 'ID'], emails.map(e => [e.receivedAt.replace(/\.\d+Z$/, 'Z'), e.sender, e.sendTo, truncate(e.subject, 50), e.id])).forEach(line => out(line));
247
+ }));
248
+ // receiver read
249
+ program
250
+ .command('read')
251
+ .description('print the body of an email')
252
+ .argument('<emailId>', 'email id (from list or wait)')
253
+ .option('--html', 'print the HTML body')
254
+ .option('--raw', 'print the original message (RFC 822)')
255
+ .action(action(async (globals, emailId, options) => {
256
+ if (options.html && options.raw)
257
+ throw new CliError('Use either --html or --raw, not both.', 'INVALID_ARGUMENT');
258
+ const type = options.raw ? 'raw' : options.html ? 'html' : 'text';
259
+ const c = await client(globals);
260
+ if (globals.json) {
261
+ const [email, body] = await Promise.all([c.emails.get(emailId), c.emails.getContent(emailId, type)]);
262
+ return json(globals, { email, format: type, body });
263
+ }
264
+ const body = await c.emails.getContent(emailId, type);
265
+ io.stdout(body.endsWith('\n') ? body : body + '\n');
266
+ }));
267
+ // receiver watch
268
+ program
269
+ .command('watch')
270
+ .description('print new emails as they arrive, until Ctrl-C')
271
+ .argument('[address]', 'only emails to this address (default: the whole project)')
272
+ .action(action(async (globals, address) => {
273
+ const c = await client(globals);
274
+ if (!globals.json)
275
+ err(`Watching ${address ?? 'all addresses'} for new email (Ctrl-C to stop)...`);
276
+ for await (const event of c.emails.stream({ recipient: address, signal: io.signal })) {
277
+ if (globals.json) {
278
+ out(JSON.stringify(event));
279
+ continue;
280
+ }
281
+ const otp = event.otp ? ` code ${event.otp.code}` : '';
282
+ out(`${event.email.receivedAt} ${event.email.sender} -> ${event.email.sendTo} ${event.email.subject}${otp} (${event.id})`);
283
+ }
284
+ }));
285
+ // receiver test-email
286
+ program
287
+ .command('test-email')
288
+ .description('send a test email (with a 6-digit code) to one of your addresses')
289
+ .argument('<address>', 'an address ending with your project\'s email suffix')
290
+ .action(action(async (globals, address) => {
291
+ const sent = await (await client(globals)).emails.sendTest({ to: address });
292
+ if (globals.json)
293
+ return json(globals, sent);
294
+ out(`Sent a test email to ${sent.to}.`);
295
+ err(`Get its code with: receiver otp ${sent.to} --since ${sent.sentAt}`);
296
+ }));
297
+ try {
298
+ await program.parseAsync(argv, { from: 'user' });
299
+ }
300
+ catch (error) {
301
+ if (error instanceof CommanderError) {
302
+ // --help and --version exit 0; usage errors already printed by commander
303
+ if (error.code === 'invalid')
304
+ err(`error: ${error.message}`);
305
+ return error.exitCode === 0 ? EXIT_OK : EXIT_ERROR;
306
+ }
307
+ throw error;
308
+ }
309
+ return exitCode;
310
+ }
311
+ function describe(error) {
312
+ if (error instanceof CliError)
313
+ return { code: error.code, message: error.message };
314
+ if (error instanceof AuthenticationError) {
315
+ return { code: 'UNAUTHORIZED', message: `The API key was rejected (${error.message}). Run \`receiver login\` with a valid key, or check RECEIVER_API_KEY.` };
316
+ }
317
+ if (error instanceof RateLimitError) {
318
+ const when = error.resetAt ? `after ${error.resetAt.toISOString()}` : 'in a minute';
319
+ return { code: 'RATE_LIMIT_EXCEEDED', message: `${error.message}. Try again ${when}.` };
320
+ }
321
+ if (error instanceof ReceiverError) {
322
+ const code = error.code ?? `HTTP_${error.statusCode}`;
323
+ const message = error.message.replace(/\.$/, '');
324
+ if (error.statusCode === 0 || error.statusCode === 408) {
325
+ return { code, message: `Could not reach the API (${message}). Check your network, or --api-url / RECEIVER_API_URL.` };
326
+ }
327
+ if (error.code === 'PROJECT_ID_REQUIRED') {
328
+ return { code, message: 'This is a dashboard session token. Use a project API key (recv_live_...): run `receiver login`.' };
329
+ }
330
+ if (error.statusCode === 403) {
331
+ return { code, message: `${message}. The API key only works for its own project: check it with \`receiver whoami\`.` };
332
+ }
333
+ if (error.statusCode === 404)
334
+ return { code, message: `${message}. Check the id with \`receiver list\`.` };
335
+ if (error.statusCode >= 500) {
336
+ return { code, message: `${message} (HTTP ${error.statusCode}). Try again in a minute.` };
337
+ }
338
+ return { code, message: `${message}.` };
339
+ }
340
+ return { code: 'ERROR', message: error?.message ?? String(error) };
341
+ }
342
+ function truncate(text, max) {
343
+ return text.length > max ? text.slice(0, max - 3) + '...' : text;
344
+ }
345
+ function table(header, rows) {
346
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map(r => r[i].length)));
347
+ const line = (cells) => cells.map((c, i) => (i === cells.length - 1 ? c : c.padEnd(widths[i]))).join(' ');
348
+ return [line(header), ...rows.map(line)];
349
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * ~/.config/receiver/config.json, written by `receiver login`.
3
+ */
4
+ export interface CliConfig {
5
+ apiKey?: string;
6
+ /** Saved when `login` ran against a non-default API (e.g. staging). */
7
+ apiUrl?: string;
8
+ /** The saved key's project, so commands skip a `whoami` request. */
9
+ projectId?: string;
10
+ }
11
+ export declare function configPath(env: Record<string, string | undefined>): string;
12
+ export declare function readConfig(path: string): Promise<CliConfig>;
13
+ export declare function writeConfig(path: string, config: CliConfig): Promise<void>;
package/dist/config.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * ~/.config/receiver/config.json, written by `receiver login`.
3
+ */
4
+ import { mkdir, readFile, writeFile, chmod } from 'node:fs/promises';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, join } from 'node:path';
7
+ export function configPath(env) {
8
+ const base = env.XDG_CONFIG_HOME || join(env.HOME || homedir(), '.config');
9
+ return join(base, 'receiver', 'config.json');
10
+ }
11
+ export async function readConfig(path) {
12
+ try {
13
+ return JSON.parse(await readFile(path, 'utf8'));
14
+ }
15
+ catch (error) {
16
+ if (error.code === 'ENOENT')
17
+ return {};
18
+ throw new Error(`Could not read ${path}: ${error.message}. Fix or delete the file, then run \`receiver login\`.`);
19
+ }
20
+ }
21
+ export async function writeConfig(path, config) {
22
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
23
+ await writeFile(path, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
24
+ await chmod(path, 0o600); // writeFile's mode only applies when creating the file
25
+ }
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * receiver: the Receiver.email CLI.
4
+ */
5
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * receiver: the Receiver.email CLI.
4
+ */
5
+ import { createInterface } from 'node:readline';
6
+ import { run } from './cli.js';
7
+ const controller = new AbortController();
8
+ let interrupted = false;
9
+ process.on('SIGINT', () => {
10
+ // First Ctrl-C stops `wait`/`watch` cleanly; a second one exits at once
11
+ if (interrupted)
12
+ process.exit(130);
13
+ interrupted = true;
14
+ controller.abort();
15
+ });
16
+ /** Reads a line from the terminal without echoing it. */
17
+ function promptSecret(question) {
18
+ return new Promise(resolve => {
19
+ const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
20
+ const output = rl;
21
+ process.stderr.write(question);
22
+ output._writeToOutput = () => { }; // mute echo
23
+ rl.question('', answer => {
24
+ rl.close();
25
+ process.stderr.write('\n');
26
+ resolve(answer);
27
+ });
28
+ });
29
+ }
30
+ async function readStdin() {
31
+ const chunks = [];
32
+ for await (const chunk of process.stdin)
33
+ chunks.push(chunk);
34
+ return Buffer.concat(chunks).toString('utf8');
35
+ }
36
+ const code = await run(process.argv.slice(2), {
37
+ stdout: text => process.stdout.write(text),
38
+ stderr: text => process.stderr.write(text),
39
+ env: process.env,
40
+ stdinIsTTY: Boolean(process.stdin.isTTY),
41
+ promptSecret,
42
+ readStdin,
43
+ signal: controller.signal,
44
+ });
45
+ process.exitCode = code;
@@ -0,0 +1,3 @@
1
+ /** Kept in sync with package.json by a test. */
2
+ export declare const VERSION = "0.2.0";
3
+ export declare const USER_AGENT = "receiver-cli/0.2.0";
@@ -0,0 +1,3 @@
1
+ /** Kept in sync with package.json by a test. */
2
+ export const VERSION = '0.2.0';
3
+ export const USER_AGENT = `receiver-cli/${VERSION}`;
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@receiverdotemail/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Receiver.email from the terminal: create an inbox, wait for the email and print the OTP code or links. For CI, shell scripts and AI agents.",
5
+ "type": "module",
6
+ "bin": {
7
+ "receiver": "dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "engines": {
13
+ "node": ">=20"
14
+ },
15
+ "scripts": {
16
+ "build:sdk": "cd ../typescript-sdk && ([ -d node_modules ] || npm ci --no-audit --no-fund --loglevel=error) && npm run build",
17
+ "build": "npm run build:sdk && tsc -p tsconfig.build.json",
18
+ "typecheck": "tsc --noEmit",
19
+ "test": "vitest run",
20
+ "test:watch": "vitest",
21
+ "check:sdk-dep": "node -e \"const d=require('./package.json').dependencies['@receiverdotemail/sdk'];if(d.startsWith('file:')){console.error('@receiverdotemail/sdk is '+d+', which would publish a broken package. Release with .github/workflows/release.yml (README: Releasing Packages), which points it at the released SDK.');process.exit(1)}\"",
22
+ "prepublishOnly": "npm run check:sdk-dep && npm run build"
23
+ },
24
+ "keywords": [
25
+ "receiver.email",
26
+ "cli",
27
+ "email",
28
+ "email-testing",
29
+ "inbox",
30
+ "otp",
31
+ "2fa",
32
+ "magic-link",
33
+ "email-verification",
34
+ "e2e",
35
+ "ci",
36
+ "github-actions",
37
+ "shell",
38
+ "test-automation",
39
+ "ai-agents",
40
+ "inbound-email",
41
+ "testing"
42
+ ],
43
+ "author": {
44
+ "name": "Receiver.email",
45
+ "email": "contact@receiver.email",
46
+ "url": "https://www.receiver.email"
47
+ },
48
+ "license": "MIT",
49
+ "dependencies": {
50
+ "@receiverdotemail/sdk": "^2.1.0",
51
+ "commander": "^14.0.3"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "^20.0.0",
55
+ "typescript": "^5.0.0",
56
+ "vitest": "^3.2.4"
57
+ },
58
+ "repository": {
59
+ "type": "git",
60
+ "url": "git+https://github.com/BUW91/mailingestion.git",
61
+ "directory": "packages/cli"
62
+ },
63
+ "homepage": "https://www.receiver.email/docs/cli",
64
+ "bugs": {
65
+ "url": "https://github.com/BUW91/mailingestion/issues",
66
+ "email": "contact@receiver.email"
67
+ },
68
+ "publishConfig": {
69
+ "access": "public"
70
+ }
71
+ }