delivrie-cli 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,819 @@
1
+ // The Delivrie CLI. `run(argv, io)` returns an exit code; io carries stdout/stderr/stdin/env/fetch so tests can drive it.
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { randomUUID, createHash } from "node:crypto";
5
+ import { parseArgs, UsageError } from "./args.js";
6
+ import { createClient, ApiError } from "./api.js";
7
+ import { readConfig, writeConfig, clearConfig, configPath } from "./config.js";
8
+ import { makeOut, when, list } from "./format.js";
9
+ import { VERSION } from "./version.js";
10
+ const DEFAULT_BASE = "https://delivrie.io/api";
11
+ const BOOLEANS = ["json", "yes", "help", "version", "sending", "received", "quiet", "publish", "force"];
12
+ const REPEATABLE = ["to", "cc", "bcc", "reply-to", "attach", "tag", "header", "var", "events"];
13
+ const ALIASES = { h: "help", v: "version", y: "yes", q: "quiet", f: "from", t: "to", s: "subject", n: "limit" };
14
+ const HELP = {
15
+ main: `Delivrie CLI ${VERSION}
16
+
17
+ Usage: delivrie <command> [options]
18
+
19
+ Account
20
+ login Save an API key (or set DELIVRIE_API_KEY)
21
+ logout Forget the saved key
22
+ whoami Show which key and account the CLI is using
23
+ usage Plan, emails sent this month and today
24
+
25
+ Sending
26
+ send Send an email (see delivrie send --help)
27
+ emails list|get|cancel|reschedule
28
+
29
+ Agent skills
30
+ init Install Delivrie's skills for your coding agent in this project
31
+ skills list|status|update
32
+
33
+ Setup
34
+ domains list|add|get|verify|delete
35
+ keys list|create|delete
36
+ webhooks list|create|test|deliveries
37
+ templates list|get|import|create|update|publish|delete
38
+
39
+ Audience and logs
40
+ contacts list|add|get|delete
41
+ suppressions list|add|remove
42
+ logs list|get
43
+
44
+ Options for every command
45
+ --json Print the raw JSON response
46
+ --api-key <key> Use this key instead of the saved one
47
+ --base-url <url> API address (default ${DEFAULT_BASE})
48
+ -h, --help Help for a command
49
+ -v, --version Print the version
50
+
51
+ Docs: https://delivrie.io/docs/cli`,
52
+ login: `Usage: delivrie login [--api-key <key>]
53
+
54
+ Saves an API key to ${"~/.config/delivrie/config.json"} (readable only by you). Without --api-key it asks for it.
55
+ Create a key at https://delivrie.io/api-keys. In CI, set DELIVRIE_API_KEY instead of logging in.`,
56
+ send: `Usage: delivrie send --from <sender> --to <address> --subject <text> (--html <html> | --text <text> | --template <id>)
57
+
58
+ -f, --from <sender> "Acme <hi@acme.com>" on a verified domain
59
+ -t, --to <address> Repeat or comma-separate for several (up to 50)
60
+ --cc, --bcc <address> Repeatable
61
+ --reply-to <address> Repeatable
62
+ -s, --subject <text>
63
+ --html <html> HTML body
64
+ --html-file <path> HTML body from a file ("-" reads stdin)
65
+ --text <text> Plain-text body (made from the HTML when left out)
66
+ --text-file <path> Plain-text body from a file ("-" reads stdin)
67
+ --template <id|alias> Send a published template
68
+ --var key=value Template variable, repeatable
69
+ --attach <path> Attach a file, repeatable
70
+ --tag name=value Repeatable
71
+ --header Name:value Custom header, repeatable
72
+ --schedule <when> ISO time or "in 1 hour", "tomorrow at 9am" (UTC)
73
+ --idempotency-key <k> Retrying with the same key never sends twice (one is made for you if left out)
74
+ -q, --quiet Print only the email id
75
+
76
+ Examples
77
+ delivrie send -f "Acme <hi@acme.com>" -t ada@example.com -s "Hello" --text "It works"
78
+ cat welcome.html | delivrie send -f hi@acme.com -t ada@example.com -s Welcome --html-file -
79
+ delivrie send -t ada@example.com --template welcome --var name=Ada`,
80
+ emails: `Usage:
81
+ delivrie emails list [--limit 20] [--offset 0] [--received]
82
+ delivrie emails get <id>
83
+ delivrie emails cancel <id> Cancel a scheduled email
84
+ delivrie emails reschedule <id> --at <when> Move a scheduled email`,
85
+ domains: `Usage:
86
+ delivrie domains list
87
+ delivrie domains add <name> [--region eu-west-1] [--return-path send]
88
+ delivrie domains get <id|name> Shows the DNS records to add
89
+ delivrie domains verify <id|name> Check DNS now
90
+ delivrie domains delete <id|name> [--yes]`,
91
+ keys: `Usage:
92
+ delivrie keys list
93
+ delivrie keys create <name> [--sending] [--domain <id|name>] The key is shown once
94
+ delivrie keys delete <id> [--yes]`,
95
+ webhooks: `Usage:
96
+ delivrie webhooks list
97
+ delivrie webhooks create <https-url> --events email.delivered,email.bounced ("*" for all)
98
+ delivrie webhooks test <id>
99
+ delivrie webhooks deliveries <id>`,
100
+ templates: `Usage:
101
+ delivrie templates list
102
+ delivrie templates get <id|alias>
103
+ delivrie templates import <file.html|-> [--name <name>] [--alias <alias>] [--subject <text>] [--from <sender>] [--publish]
104
+ delivrie templates create --name <name> [--html-file <file|->] [--alias <alias>] [--subject <text>] [--from <sender>]
105
+ delivrie templates update <id|alias> [--html-file <file|->] [--name ..] [--alias ..] [--subject ..] [--from ..]
106
+ delivrie templates publish <id|alias>
107
+ delivrie templates delete <id|alias> [--yes]
108
+
109
+ import keeps your HTML exactly as written. The name comes from the file (or its <title>), the alias from the file name,
110
+ and every {{variable}} in it is listed on the template. Changes stay a draft until you publish.
111
+ delivrie templates import emails/order-shipped.html --publish
112
+ cat welcome.html | delivrie templates import - --name Welcome --alias welcome`,
113
+ contacts: `Usage:
114
+ delivrie contacts list [--limit 50] [--offset 0]
115
+ delivrie contacts add <email> [--first-name Ada] [--last-name Lovelace]
116
+ delivrie contacts get <id|email>
117
+ delivrie contacts delete <id|email> [--yes]`,
118
+ suppressions: `Usage:
119
+ delivrie suppressions list
120
+ delivrie suppressions add <email> [<email>...]
121
+ delivrie suppressions remove <email>`,
122
+ init: `Usage: delivrie init [--dir <path>] [--force]
123
+
124
+ Installs Delivrie's agent skills (send-email, inbox-triage, broadcasts, domain-setup, deliverability-check, automations
125
+ and more) into .claude/skills/ in this project, where Claude Code picks them up. Other agents: point --dir at their
126
+ skills folder. Then connect the MCP server so the skills can act on your account: https://delivrie.io/docs/mcp
127
+
128
+ --dir <path> Where to install (default .claude/skills)
129
+ --force Overwrite skills you've edited
130
+
131
+ Keep them current with \`delivrie skills status\` and \`delivrie skills update\`.`,
132
+ skills: `Usage:
133
+ delivrie skills list Every published skill
134
+ delivrie skills status [--dir <path>] Installed skills: up to date, out of date, edited or missing
135
+ delivrie skills update [<name>...] [--dir <path>] [--force]
136
+
137
+ update leaves skills you've edited alone unless you add --force. Skills come from https://delivrie.io/skills/index.json.`,
138
+ logs: `Usage:
139
+ delivrie logs list [--limit 20] [--offset 0]
140
+ delivrie logs get <id>`,
141
+ };
142
+ /** Runs one command and resolves with its exit code. */
143
+ export async function run(argv, io = {}) {
144
+ const stdout = io.stdout || process.stdout, stderr = io.stderr || process.stderr, env = io.env || process.env;
145
+ const out = makeOut(stdout, env), err = makeOut(stderr, env);
146
+ const print = (s = "") => stdout.write(s + "\n");
147
+ const fail = (msg, code = 1) => { stderr.write(err.red("Error: ") + msg + "\n"); return code; };
148
+ let flags, pos;
149
+ try {
150
+ ({ flags, positionals: pos } = parseArgs(argv, { booleans: BOOLEANS, repeatable: REPEATABLE, aliases: ALIASES }));
151
+ }
152
+ catch (e) {
153
+ return fail(e.message, 2);
154
+ }
155
+ const [cmd, sub, ...rest] = pos;
156
+ if (flags.version) {
157
+ print(VERSION);
158
+ return 0;
159
+ }
160
+ if (!cmd || cmd === "help") {
161
+ print(HELP[sub] || HELP.main);
162
+ return 0;
163
+ }
164
+ if (flags.help) {
165
+ print(HELP[cmd] || HELP.main);
166
+ return 0;
167
+ }
168
+ const cfg = readConfig(env);
169
+ const baseUrl = flags["base-url"] || env.DELIVRIE_BASE_URL || cfg.base_url || DEFAULT_BASE;
170
+ const keyFrom = flags["api-key"] ? "--api-key" : env.DELIVRIE_API_KEY ? "DELIVRIE_API_KEY" : cfg.api_key ? configPath(env) : null;
171
+ const key = flags["api-key"] || env.DELIVRIE_API_KEY || cfg.api_key;
172
+ const client = (k = key) => createClient({ key: k, baseUrl, fetchImpl: io.fetch || globalThis.fetch });
173
+ const need = () => { if (!key)
174
+ throw new UsageError("No API key. Run `delivrie login`, or set DELIVRIE_API_KEY. Create one at https://delivrie.io/api-keys"); return client(); };
175
+ const json = (v) => print(JSON.stringify(v, null, 2));
176
+ const show = (v, human) => (flags.json ? json(v) : human(v));
177
+ const listOf = (r) => (Array.isArray(r?.data) ? r.data : Array.isArray(r) ? r : []);
178
+ const empty = (what) => print(out.dim(`No ${what} yet.`));
179
+ const confirm = async (q) => {
180
+ if (flags.yes)
181
+ return true;
182
+ const stdin = io.stdin || process.stdin;
183
+ if (!stdin.isTTY)
184
+ throw new UsageError(`${q} Add --yes to confirm.`);
185
+ stderr.write(`${q} [y/N] `);
186
+ const ans = await readLine(stdin);
187
+ return /^y(es)?$/i.test(ans.trim());
188
+ };
189
+ const resolveDomain = async (api, ref) => {
190
+ if (!ref)
191
+ throw new UsageError("Give a domain id or name");
192
+ if (!ref.includes("."))
193
+ return ref;
194
+ const d = listOf(await api.request("GET", "/domains")).find((x) => x.name === ref.toLowerCase());
195
+ if (!d)
196
+ throw new ApiError(404, "not_found", `No domain named ${ref} on this account`);
197
+ return d.id;
198
+ };
199
+ try {
200
+ switch (cmd) {
201
+ // ------------------------------------------------------------ account
202
+ case "login": {
203
+ let k = flags["api-key"];
204
+ if (!k) {
205
+ const stdin = io.stdin || process.stdin;
206
+ if (!stdin.isTTY)
207
+ k = (await readAll(stdin)).trim();
208
+ else {
209
+ stderr.write("API key (from https://delivrie.io/api-keys): ");
210
+ k = (await readLine(stdin, { hidden: true })).trim();
211
+ stderr.write("\n");
212
+ }
213
+ }
214
+ if (!/^dlv_[A-Za-z0-9_-]{8,}$/.test(k || ""))
215
+ return fail("That doesn't look like a Delivrie API key (they start with dlv_).");
216
+ const who = await checkKey(client(k));
217
+ if (who.permission === "invalid")
218
+ return fail("Delivrie didn't accept that key. Check it, or create a new one at https://delivrie.io/api-keys");
219
+ const file = writeConfig({ ...cfg, api_key: k, ...(flags["base-url"] ? { base_url: flags["base-url"] } : {}) }, env);
220
+ if (flags.json)
221
+ return json({ saved: file, permission: who.permission }), 0;
222
+ print(out.green("✓") + ` Logged in with a ${who.permission === "sending" ? "sending-only" : "full-access"} key. Saved to ${file}`);
223
+ if (who.permission === "sending")
224
+ print(out.dim(" Sending-only keys can send email but can't list or change domains, keys or webhooks."));
225
+ return 0;
226
+ }
227
+ case "logout": {
228
+ const had = clearConfig(env);
229
+ print(had ? "Logged out. The saved key was removed." : "No saved key to remove.");
230
+ if (env.DELIVRIE_API_KEY)
231
+ print(out.dim("DELIVRIE_API_KEY is still set in this shell."));
232
+ return 0;
233
+ }
234
+ case "whoami": {
235
+ if (!key)
236
+ return fail("Not logged in. Run `delivrie login`, or set DELIVRIE_API_KEY.");
237
+ const who = await checkKey(client());
238
+ if (flags.json)
239
+ return json({ key_prefix: key.slice(0, 10), source: keyFrom, base_url: baseUrl, ...who }), 0;
240
+ if (who.permission === "invalid")
241
+ return fail("The key in use was rejected. Run `delivrie login` with a new one.");
242
+ print(`${out.bold("Key")} ${key.slice(0, 10)}… (${who.permission === "sending" ? "sending only" : "full access"})`);
243
+ print(`${out.bold("From")} ${keyFrom}`);
244
+ print(`${out.bold("API")} ${baseUrl}`);
245
+ if (who.usage)
246
+ print(`${out.bold("Plan")} ${who.usage.plan} · ${fmtUsage(who.usage)}`);
247
+ return 0;
248
+ }
249
+ case "usage": {
250
+ const u = await need().request("GET", "/usage");
251
+ return show(u, () => {
252
+ print(`${out.bold("Plan")} ${u.plan}${u.marketing_plan && u.marketing_plan !== "free" ? ` (marketing: ${u.marketing_plan})` : ""}`);
253
+ print(`${out.bold("This month")} ${fmtUsage(u)}`);
254
+ print(`${out.bold("Today")} ${num(u.emails_today)}${u.daily_limit ? ` of ${num(u.daily_limit)}` : ""}`);
255
+ if (u.credits_emails)
256
+ print(`${out.bold("Credits")} ${num(u.credits_emails)} emails`);
257
+ }), 0;
258
+ }
259
+ // ------------------------------------------------------------ sending
260
+ case "send": {
261
+ const api = need();
262
+ const stdin = io.stdin || process.stdin;
263
+ const read = async (p) => (p === "-" ? readAll(stdin) : fs.readFileSync(p, "utf8"));
264
+ const splitList = (v) => (v || []).flatMap((x) => String(x).split(",")).map((x) => x.trim()).filter(Boolean);
265
+ const to = splitList(flags.to).concat(sub && sub.includes("@") ? [sub] : []);
266
+ if (!to.length)
267
+ throw new UsageError("Add at least one --to address");
268
+ const body = { to };
269
+ if (flags.from)
270
+ body.from = flags.from;
271
+ if (flags.subject)
272
+ body.subject = flags.subject;
273
+ if (flags.html !== undefined)
274
+ body.html = flags.html;
275
+ if (flags["html-file"])
276
+ body.html = await read(flags["html-file"]);
277
+ if (flags.text !== undefined)
278
+ body.text = flags.text;
279
+ if (flags["text-file"])
280
+ body.text = await read(flags["text-file"]);
281
+ if (flags.cc)
282
+ body.cc = splitList(flags.cc);
283
+ if (flags.bcc)
284
+ body.bcc = splitList(flags.bcc);
285
+ if (flags["reply-to"])
286
+ body.reply_to = splitList(flags["reply-to"]);
287
+ if (flags.template)
288
+ body.template = { id: flags.template, ...(flags.var ? { variables: pairs(flags.var, "=", "--var") } : {}) };
289
+ if (flags.tag)
290
+ body.tags = Object.entries(pairs(flags.tag, "=", "--tag")).map(([name, value]) => ({ name, value }));
291
+ if (flags.header)
292
+ body.headers = pairs(flags.header, ":", "--header");
293
+ if (flags.schedule)
294
+ body.scheduled_at = flags.schedule;
295
+ if (flags.attach)
296
+ body.attachments = flags.attach.map((p) => ({ filename: path.basename(p), content: fs.readFileSync(p).toString("base64") }));
297
+ if (!body.template && body.html === undefined && body.text === undefined)
298
+ throw new UsageError("Add a body: --html, --html-file, --text, --text-file or --template");
299
+ if (!body.template && !body.subject)
300
+ throw new UsageError("Add a --subject");
301
+ const r = await api.request("POST", "/emails", body, { idempotencyKey: flags["idempotency-key"] || randomUUID() });
302
+ if (flags.json)
303
+ return json(r), 0;
304
+ if (flags.quiet)
305
+ return print(r.id), 0;
306
+ print(out.green("✓") + ` ${body.scheduled_at ? "Scheduled" : "Sent"} ${out.bold(r.id)} to ${to.join(", ")}`);
307
+ print(out.dim(` Track it: delivrie emails get ${r.id}`));
308
+ return 0;
309
+ }
310
+ case "emails": {
311
+ const api = need();
312
+ if (sub === "list" || !sub) {
313
+ const r = await api.request("GET", flags.received ? "/emails/received" : "/emails", undefined, { query: { limit: flags.limit || 20, offset: flags.offset } });
314
+ return show(r, () => {
315
+ const rows = listOf(r);
316
+ if (!rows.length)
317
+ return empty(flags.received ? "received emails" : "emails");
318
+ print(out.table(rows, [
319
+ { label: "ID", get: (e) => e.id },
320
+ { label: "STATUS", get: (e) => out.statusColor(e.last_event || e.status || (flags.received ? "received" : "")) },
321
+ { label: flags.received ? "FROM" : "TO", get: (e) => trunc(flags.received ? e.from : list(e.to), 32) },
322
+ { label: "SUBJECT", get: (e) => trunc(e.subject, 40) },
323
+ { label: "WHEN", get: (e) => when(e.scheduled_at && /scheduled/.test(e.last_event || e.status) ? e.scheduled_at : e.created_at) },
324
+ ]));
325
+ }), 0;
326
+ }
327
+ const id = need1(rest[0], "email id");
328
+ if (sub === "get") {
329
+ const e = await api.request("GET", `/emails/${enc(id)}`);
330
+ return show(e, () => {
331
+ print(`${out.bold(e.subject || "(no subject)")} ${out.statusColor(e.last_event)}`);
332
+ print(`${out.dim("ID")} ${e.id}`);
333
+ print(`${out.dim("From")} ${e.from}`);
334
+ print(`${out.dim("To")} ${list(e.to)}`);
335
+ if (e.cc?.length)
336
+ print(`${out.dim("Cc")} ${list(e.cc)}`);
337
+ print(`${out.dim("Created")} ${when(e.created_at)}`);
338
+ if (e.scheduled_at)
339
+ print(`${out.dim("Sends")} ${e.scheduled_at}`);
340
+ if (e.error)
341
+ print(`${out.dim("Error")} ${out.red(e.error)}`);
342
+ if (e.events?.length) {
343
+ print("");
344
+ print(out.dim("Events"));
345
+ for (const ev of e.events)
346
+ print(` ${when(ev.created_at).padEnd(17)} ${out.statusColor(ev.type.replace(/^email\./, ""))}`);
347
+ }
348
+ }), 0;
349
+ }
350
+ if (sub === "cancel") {
351
+ const r = await api.request("POST", `/emails/${enc(id)}/cancel`);
352
+ return show(r, () => print(out.green("✓") + ` Canceled ${id}`)), 0;
353
+ }
354
+ if (sub === "reschedule") {
355
+ if (!flags.at)
356
+ throw new UsageError("Add --at <when>, like --at \"in 2 hours\" or an ISO time");
357
+ const r = await api.request("PATCH", `/emails/${enc(id)}`, { scheduled_at: flags.at });
358
+ return show(r, () => print(out.green("✓") + ` ${id} now sends ${flags.at}`)), 0;
359
+ }
360
+ throw new UsageError(`Unknown: emails ${sub}. Try delivrie emails --help`);
361
+ }
362
+ // ------------------------------------------------------------ setup
363
+ case "domains": {
364
+ const api = need();
365
+ if (sub === "list" || !sub) {
366
+ const r = await api.request("GET", "/domains");
367
+ return show(r, () => {
368
+ const rows = listOf(r);
369
+ if (!rows.length)
370
+ return empty("domains") || print(out.dim("Add one: delivrie domains add example.com"));
371
+ print(out.table(rows, [{ label: "ID", get: (d) => d.id }, { label: "NAME", get: (d) => d.name }, { label: "STATUS", get: (d) => out.statusColor(d.status) }, { label: "REGION", get: (d) => d.region_label || d.region }, { label: "ADDED", get: (d) => when(d.created_at) }]));
372
+ }), 0;
373
+ }
374
+ if (sub === "add") {
375
+ const name = need1(rest[0], "domain name");
376
+ const d = await api.request("POST", "/domains", { name, ...(flags.region ? { region: flags.region } : {}), ...(flags["return-path"] ? { return_path: flags["return-path"] } : {}) });
377
+ return show(d, () => { print(out.green("✓") + ` Added ${out.bold(d.name)} (${d.id}). Add these DNS records, then run: delivrie domains verify ${d.name}`); print(""); printRecords(d); }), 0;
378
+ }
379
+ const id = await resolveDomain(api, rest[0]);
380
+ if (sub === "get") {
381
+ const d = await api.request("GET", `/domains/${enc(id)}`);
382
+ return show(d, () => { print(`${out.bold(d.name)} ${out.statusColor(d.status)} ${out.dim(d.id)}`); print(""); printRecords(d); }), 0;
383
+ }
384
+ if (sub === "verify") {
385
+ const d = await api.request("POST", `/domains/${enc(id)}/verify`);
386
+ return show(d, () => { print(`${out.bold(d.name)}: ${out.statusColor(d.status)}`); if (d.status !== "verified") {
387
+ print("");
388
+ printRecords(d);
389
+ print("");
390
+ print(out.dim("DNS changes can take a few minutes to show up. Run verify again later."));
391
+ } }), 0;
392
+ }
393
+ if (sub === "delete") {
394
+ if (!(await confirm(`Delete ${rest[0]}? Emails can't be sent from it afterwards.`)))
395
+ return print("Kept it."), 0;
396
+ const r = await api.request("DELETE", `/domains/${enc(id)}`);
397
+ return show(r, () => print(out.green("✓") + ` Deleted ${rest[0]}`)), 0;
398
+ }
399
+ throw new UsageError(`Unknown: domains ${sub}. Try delivrie domains --help`);
400
+ }
401
+ case "keys": {
402
+ const api = need();
403
+ if (sub === "list" || !sub) {
404
+ const r = await api.request("GET", "/api-keys");
405
+ return show(r, () => {
406
+ const rows = listOf(r);
407
+ if (!rows.length)
408
+ return empty("API keys");
409
+ print(out.table(rows, [{ label: "ID", get: (k) => k.id }, { label: "NAME", get: (k) => k.name }, { label: "KEY", get: (k) => (k.prefix || "") + "…" }, { label: "ACCESS", get: (k) => k.permission }, { label: "LAST USED", get: (k) => (k.last_used_at ? when(k.last_used_at) : out.dim("never")) }]));
410
+ }), 0;
411
+ }
412
+ if (sub === "create") {
413
+ const name = need1(rest[0], "key name");
414
+ const body = { name, permission: flags.sending ? "sending_access" : "full_access" };
415
+ if (flags.domain)
416
+ body.domain_id = await resolveDomain(api, flags.domain);
417
+ const r = await api.request("POST", "/api-keys", body);
418
+ return show(r, () => { print(out.green("✓") + ` Created ${out.bold(name)} (${r.id}). Copy it now, it's only shown once:`); print(""); print(" " + out.bold(r.token)); print(""); }), 0;
419
+ }
420
+ if (sub === "delete") {
421
+ const id = need1(rest[0], "key id");
422
+ if (!(await confirm(`Delete key ${id}? Anything using it stops working.`)))
423
+ return print("Kept it."), 0;
424
+ const r = await api.request("DELETE", `/api-keys/${enc(id)}`);
425
+ return show(r, () => print(out.green("✓") + ` Deleted ${id}`)), 0;
426
+ }
427
+ throw new UsageError(`Unknown: keys ${sub}. Try delivrie keys --help`);
428
+ }
429
+ case "webhooks": {
430
+ const api = need();
431
+ if (sub === "list" || !sub) {
432
+ const r = await api.request("GET", "/webhooks");
433
+ return show(r, () => {
434
+ const rows = listOf(r);
435
+ if (!rows.length)
436
+ return empty("webhooks");
437
+ print(out.table(rows, [{ label: "ID", get: (w) => w.id }, { label: "ENDPOINT", get: (w) => trunc(w.endpoint, 44) }, { label: "EVENTS", get: (w) => trunc(list(w.events), 40) }, { label: "STATUS", get: (w) => out.statusColor(w.status) }]));
438
+ }), 0;
439
+ }
440
+ if (sub === "create") {
441
+ const endpoint = need1(rest[0], "endpoint URL");
442
+ const events = (flags.events || []).flatMap((e) => e.split(",")).map((e) => e.trim()).filter(Boolean);
443
+ if (!events.length)
444
+ throw new UsageError("Add --events, like --events email.delivered,email.bounced (or \"*\" for all)");
445
+ const r = await api.request("POST", "/webhooks", { endpoint, events });
446
+ return show(r, () => { print(out.green("✓") + ` Created ${r.id}. Its signing secret (shown once):`); print(""); print(" " + out.bold(r.signing_secret)); print(""); print(out.dim(" Verify requests with it: https://delivrie.io/docs/webhooks")); }), 0;
447
+ }
448
+ const id = need1(rest[0], "webhook id");
449
+ if (sub === "test") {
450
+ const r = await api.request("POST", `/webhooks/${enc(id)}/test`);
451
+ return show(r, () => print(out.green("✓") + ` Sent a test event to ${id}${r?.status_code ? ` (endpoint answered ${r.status_code})` : ""}`)), 0;
452
+ }
453
+ if (sub === "deliveries") {
454
+ const r = await api.request("GET", `/webhooks/${enc(id)}/events`);
455
+ return show(r, () => {
456
+ const rows = listOf(r);
457
+ if (!rows.length)
458
+ return empty("deliveries");
459
+ print(out.table(rows, [{ label: "ID", get: (d) => d.id }, { label: "EVENT", get: (d) => d.event_type }, { label: "RESULT", get: (d) => (d.delivered ? out.green("delivered") : out.red("failing")) }, { label: "HTTP", get: (d) => d.status_code ?? "" }, { label: "TRIES", get: (d) => d.attempts }, { label: "WHEN", get: (d) => when(d.created_at) }]));
460
+ }), 0;
461
+ }
462
+ throw new UsageError(`Unknown: webhooks ${sub}. Try delivrie webhooks --help`);
463
+ }
464
+ case "templates": {
465
+ const api = need();
466
+ if (sub === "list" || !sub) {
467
+ const r = await api.request("GET", "/templates");
468
+ return show(r, () => {
469
+ const rows = listOf(r);
470
+ if (!rows.length)
471
+ return empty("templates");
472
+ print(out.table(rows, [{ label: "ID", get: (t) => t.id }, { label: "NAME", get: (t) => trunc(t.name, 36) }, { label: "ALIAS", get: (t) => t.alias || "" }, { label: "STATUS", get: (t) => out.statusColor(t.status) }, { label: "UPDATED", get: (t) => when(t.updated_at) }]));
473
+ }), 0;
474
+ }
475
+ const stdin = io.stdin || process.stdin;
476
+ const readHtml = async (p) => (p === "-" ? readAll(stdin) : fs.readFileSync(p, "utf8"));
477
+ const varsIn = (html) => [...new Set([...html.matchAll(/\{\{\{?\s*([a-zA-Z_]\w*)/g)].map((m) => m[1]))];
478
+ const fields = (body) => { for (const k of ["name", "alias", "subject", "from"])
479
+ if (typeof flags[k] === "string")
480
+ body[k] = flags[k]; return body; };
481
+ if (sub === "import" || sub === "create") {
482
+ const file = sub === "import" ? need1(rest[0], "HTML file (or - to read stdin)") : flags["html-file"];
483
+ if (sub === "create" && !flags.name)
484
+ throw new UsageError("Give the template a --name");
485
+ const html = file ? await readHtml(file) : undefined;
486
+ if (sub === "import" && !html?.trim())
487
+ throw new UsageError("That file is empty");
488
+ const base = file && file !== "-" ? path.basename(file).replace(/\.html?$/i, "") : "";
489
+ const title = html?.match(/<title>([^<]+)<\/title>/i)?.[1]?.trim();
490
+ const body = { name: title || base.replace(/[-_]+/g, " ").replace(/^./, (c) => c.toUpperCase()) || "Imported template" };
491
+ if (base)
492
+ body.alias = base.toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
493
+ if (title)
494
+ body.subject = title;
495
+ if (html !== undefined) {
496
+ body.html = html;
497
+ body.variables = varsIn(html).map((name) => ({ name, type: "string" }));
498
+ }
499
+ fields(body);
500
+ const t = await api.request("POST", "/templates", body);
501
+ let pub = null;
502
+ if (flags.publish)
503
+ pub = await api.request("POST", `/templates/${enc(t.id)}/publish`);
504
+ const kb = html ? Math.max(1, Math.round(Buffer.byteLength(html) / 1024)) : 0;
505
+ const warn = [];
506
+ if (html && /<link\b[^>]*rel=["']?stylesheet/i.test(html))
507
+ warn.push("It links an external stylesheet. Gmail and Outlook ignore those, so move the styles inline.");
508
+ if (kb > 102)
509
+ warn.push(`It's ${kb} KB. Gmail cuts emails off at 102 KB.`);
510
+ return show({ ...t, ...(pub ? { published_version: pub.version } : {}), variables: body.variables?.map((v) => v.name) || [] }, () => {
511
+ print(out.green("✓") + ` ${sub === "import" ? "Imported" : "Created"} ${out.bold(body.name)} ${out.dim(t.id)}`);
512
+ if (body.alias)
513
+ print(`${out.dim("Alias")} ${body.alias}`);
514
+ if (body.variables?.length)
515
+ print(`${out.dim("Variables")} ${body.variables.map((v) => v.name).join(", ")}`);
516
+ for (const w of warn)
517
+ print(out.yellow("!") + " " + w);
518
+ print(pub ? `${out.green("✓")} Published v${pub.version}. Send it with --template ${body.alias || t.id}` : out.dim(`Draft. Publish with: delivrie templates publish ${body.alias || t.id}`));
519
+ }), 0;
520
+ }
521
+ const id = need1(rest[0], "template id or alias");
522
+ if (sub === "update") {
523
+ const body = fields({});
524
+ if (flags["html-file"]) {
525
+ body.html = await readHtml(flags["html-file"]);
526
+ body.variables = varsIn(body.html).map((name) => ({ name, type: "string" }));
527
+ }
528
+ if (!Object.keys(body).length)
529
+ throw new UsageError("Nothing to change. Pass --html-file, --name, --alias, --subject or --from");
530
+ const t = await api.request("GET", `/templates/${enc(id)}`);
531
+ const r = await api.request("PATCH", `/templates/${enc(t.id)}`, body);
532
+ return show(r, () => { print(out.green("✓") + ` Updated ${t.name}`); if (r.note)
533
+ print(out.dim(r.note)); }), 0;
534
+ }
535
+ if (sub === "delete") {
536
+ if (!(await confirm(`Delete template ${id}? API calls that use it will fail.`)))
537
+ return print("Kept it."), 0;
538
+ const t = await api.request("GET", `/templates/${enc(id)}`);
539
+ const r = await api.request("DELETE", `/templates/${enc(t.id)}`);
540
+ return show(r, () => print(out.green("✓") + ` Deleted ${t.name}`)), 0;
541
+ }
542
+ if (sub === "get") {
543
+ const t = await api.request("GET", `/templates/${enc(id)}`);
544
+ return show(t, () => { print(`${out.bold(t.name)} ${out.statusColor(t.status)} ${out.dim(t.id)}`); if (t.alias)
545
+ print(`${out.dim("Alias")} ${t.alias}`); if (t.subject)
546
+ print(`${out.dim("Subject")} ${t.subject}`); if (t.from)
547
+ print(`${out.dim("From")} ${t.from}`); if (t.variables?.length)
548
+ print(`${out.dim("Variables")} ${t.variables.map((v) => v.name || v.key).join(", ")}`); if (typeof t.content?.raw === "string")
549
+ print(`${out.dim("Format")} HTML, sent as written`); }), 0;
550
+ }
551
+ if (sub === "publish") {
552
+ const t = await api.request("POST", `/templates/${enc(id)}/publish`);
553
+ return show(t, () => print(out.green("✓") + ` Published ${t.name || id}`)), 0;
554
+ }
555
+ throw new UsageError(`Unknown: templates ${sub}. Try delivrie templates --help`);
556
+ }
557
+ // ------------------------------------------------------------ audience, logs
558
+ case "contacts": {
559
+ const api = need();
560
+ if (sub === "list" || !sub) {
561
+ const r = await api.request("GET", "/contacts", undefined, { query: { limit: flags.limit || 50, offset: flags.offset } });
562
+ return show(r, () => {
563
+ const rows = listOf(r);
564
+ if (!rows.length)
565
+ return empty("contacts");
566
+ print(out.table(rows, [{ label: "EMAIL", get: (c) => c.email }, { label: "NAME", get: (c) => [c.first_name, c.last_name].filter(Boolean).join(" ") }, { label: "SUBSCRIBED", get: (c) => (c.unsubscribed ? out.red("no") : out.green("yes")) }, { label: "ADDED", get: (c) => when(c.created_at) }]));
567
+ }), 0;
568
+ }
569
+ const ref = need1(rest[0], "contact email or id");
570
+ if (sub === "add") {
571
+ const r = await api.request("POST", "/contacts", { email: ref, ...(flags["first-name"] ? { first_name: flags["first-name"] } : {}), ...(flags["last-name"] ? { last_name: flags["last-name"] } : {}) });
572
+ return show(r, () => print(out.green("✓") + ` Added ${ref} (${r.id})`)), 0;
573
+ }
574
+ if (sub === "get") {
575
+ const c = await api.request("GET", `/contacts/${enc(ref)}`);
576
+ return show(c, () => { print(`${out.bold(c.email)} ${c.unsubscribed ? out.red("unsubscribed") : out.green("subscribed")}`); const name = [c.first_name, c.last_name].filter(Boolean).join(" "); if (name)
577
+ print(`${out.dim("Name")} ${name}`); print(`${out.dim("ID")} ${c.id}`); print(`${out.dim("Added")} ${when(c.created_at)}`); for (const [k, v] of Object.entries(c.properties || {}))
578
+ print(`${out.dim(k.padEnd(8))} ${v}`); }), 0;
579
+ }
580
+ if (sub === "delete") {
581
+ if (!(await confirm(`Delete contact ${ref}?`)))
582
+ return print("Kept it."), 0;
583
+ const r = await api.request("DELETE", `/contacts/${enc(ref)}`);
584
+ return show(r, () => print(out.green("✓") + ` Deleted ${ref}`)), 0;
585
+ }
586
+ throw new UsageError(`Unknown: contacts ${sub}. Try delivrie contacts --help`);
587
+ }
588
+ case "suppressions": {
589
+ const api = need();
590
+ if (sub === "list" || !sub) {
591
+ const r = await api.request("GET", "/suppressions");
592
+ return show(r, () => {
593
+ const rows = listOf(r);
594
+ if (!rows.length)
595
+ return empty("suppressed addresses");
596
+ print(out.table(rows, [{ label: "EMAIL", get: (s) => s.email }, { label: "REASON", get: (s) => s.reason }, { label: "SINCE", get: (s) => when(s.created_at) }]));
597
+ }), 0;
598
+ }
599
+ if (sub === "add") {
600
+ const emails = rest.flatMap((e) => e.split(",")).map((e) => e.trim()).filter(Boolean);
601
+ if (!emails.length)
602
+ throw new UsageError("Give one or more email addresses");
603
+ const r = await api.request("POST", "/suppressions", emails.length === 1 ? { email: emails[0] } : { emails });
604
+ return show(r, () => print(out.green("✓") + ` Suppressed ${emails.join(", ")}. Delivrie won't send to ${emails.length === 1 ? "it" : "them"}.`)), 0;
605
+ }
606
+ if (sub === "remove") {
607
+ const e = need1(rest[0], "email address");
608
+ const r = await api.request("DELETE", `/suppressions/${enc(e)}`);
609
+ return show(r, () => print(out.green("✓") + ` ${e} can receive email again`)), 0;
610
+ }
611
+ throw new UsageError(`Unknown: suppressions ${sub}. Try delivrie suppressions --help`);
612
+ }
613
+ case "logs": {
614
+ const api = need();
615
+ if (sub === "list" || !sub) {
616
+ const r = await api.request("GET", "/logs", undefined, { query: { limit: flags.limit || 20, offset: flags.offset } });
617
+ return show(r, () => {
618
+ const rows = listOf(r);
619
+ if (!rows.length)
620
+ return empty("API requests");
621
+ print(out.table(rows, [{ label: "ID", get: (l) => l.id }, { label: "REQUEST", get: (l) => `${l.method} ${l.endpoint}` }, { label: "STATUS", get: (l) => (l.status >= 400 ? out.red(l.status) : out.green(l.status)) }, { label: "CLIENT", get: (l) => trunc(l.user_agent, 24) }, { label: "WHEN", get: (l) => when(l.created_at) }]));
622
+ }), 0;
623
+ }
624
+ if (sub === "get") {
625
+ const l = await api.request("GET", `/logs/${enc(need1(rest[0], "log id"))}`);
626
+ return json(l), 0;
627
+ }
628
+ throw new UsageError(`Unknown: logs ${sub}. Try delivrie logs --help`);
629
+ }
630
+ // ------------------------------------------------------------ agent skills
631
+ case "init":
632
+ case "skills": {
633
+ const action = cmd === "init" ? "init" : sub || "status";
634
+ const dir = path.resolve(flags.dir || ".claude/skills");
635
+ const base = (env.DELIVRIE_SKILLS_URL || "https://delivrie.io/skills").replace(/\/$/, "");
636
+ const fetchImpl = io.fetch || globalThis.fetch;
637
+ const get = async (url) => {
638
+ const r = await fetchImpl(url, { headers: { "user-agent": `delivrie-cli/${VERSION}` } });
639
+ if (!r.ok)
640
+ throw new ApiError(r.status, "skills_unavailable", `Couldn't download ${url} (${r.status})`);
641
+ return r;
642
+ };
643
+ const index = (await (await get(`${base}/index.json`)).json());
644
+ const manifestPath = path.join(dir, ".delivrie.json");
645
+ const manifest = (() => { try {
646
+ return JSON.parse(fs.readFileSync(manifestPath, "utf8"));
647
+ }
648
+ catch {
649
+ return { skills: {} };
650
+ } })();
651
+ manifest.skills ||= {};
652
+ const sha = (b) => createHash("sha256").update(b).digest("hex");
653
+ const fileOf = (n) => path.join(dir, n, "SKILL.md");
654
+ // Each installed skill: missing, current, outdated (Delivrie published a newer one), edited (changed locally).
655
+ const state = (n, remote) => {
656
+ if (!fs.existsSync(fileOf(n)))
657
+ return "missing";
658
+ const local = sha(fs.readFileSync(fileOf(n)));
659
+ if (manifest.skills[n] && local !== manifest.skills[n])
660
+ return "edited";
661
+ return local === remote ? "current" : "outdated";
662
+ };
663
+ const install = async (names) => {
664
+ const done = [], kept = [];
665
+ for (const s of index.skills.filter((x) => names.includes(x.name))) {
666
+ const st = state(s.name, s.sha256);
667
+ if (st === "current") {
668
+ manifest.skills[s.name] = s.sha256;
669
+ continue;
670
+ }
671
+ if (st === "edited" && !flags.force) {
672
+ kept.push(s.name);
673
+ continue;
674
+ }
675
+ const body = Buffer.from(await (await get(s.url)).arrayBuffer());
676
+ fs.mkdirSync(path.dirname(fileOf(s.name)), { recursive: true });
677
+ fs.writeFileSync(fileOf(s.name), body);
678
+ manifest.skills[s.name] = sha(body);
679
+ done.push(s.name);
680
+ }
681
+ manifest.version = index.version;
682
+ fs.mkdirSync(dir, { recursive: true });
683
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
684
+ return { done, kept };
685
+ };
686
+ const rel = path.relative(process.cwd(), dir) || ".";
687
+ if (action === "list") {
688
+ return show(index, () => { print(out.table(index.skills, [{ label: "SKILL", get: (s) => s.name }, { label: "WHAT IT DOES", get: (s) => trunc(s.description.split(". Use when")[0], 90) }])); }), 0;
689
+ }
690
+ if (action === "init" || action === "update") {
691
+ const want = action === "update" && rest.length ? rest : action === "update" ? Object.keys(manifest.skills).filter((n) => index.skills.some((s) => s.name === n)) : index.skills.map((s) => s.name);
692
+ const unknown = want.filter((n) => !index.skills.some((s) => s.name === n));
693
+ if (unknown.length)
694
+ throw new UsageError(`No skill named ${unknown.join(", ")}. Run delivrie skills list`);
695
+ if (action === "update" && !want.length)
696
+ return fail("No Delivrie skills installed here. Run `delivrie init` first.");
697
+ const r = await install(want);
698
+ if (flags.json)
699
+ return json({ dir, version: index.version, installed: r.done, kept_edited: r.kept }), 0;
700
+ if (r.done.length)
701
+ print(out.green("✓") + ` ${action === "init" ? "Installed" : "Updated"} ${r.done.length} skill${r.done.length === 1 ? "" : "s"} in ${rel}: ${r.done.join(", ")}`);
702
+ else
703
+ print(out.green("✓") + ` Skills in ${rel} are up to date (${index.version}).`);
704
+ if (r.kept.length)
705
+ print(out.yellow("!") + ` Kept your edits to ${r.kept.join(", ")}. Add --force to replace them.`);
706
+ if (action === "init") {
707
+ print("");
708
+ print("Next: connect the MCP server so the skills can work with your account.");
709
+ print(out.dim(" Claude Code: claude mcp add --transport http delivrie https://delivrie.io/api/mcp"));
710
+ print(out.dim(" Or the plugin, which includes both: /plugin marketplace add bysurce/delivrie"));
711
+ print(out.dim(" Then try: \"Why are emails to Outlook bouncing this week?\""));
712
+ }
713
+ return 0;
714
+ }
715
+ if (action === "status") {
716
+ const rows = index.skills.map((s) => ({ name: s.name, status: state(s.name, s.sha256), tracked: !!manifest.skills[s.name] }))
717
+ .filter((r) => r.status !== "missing" || Object.keys(manifest.skills).length);
718
+ if (flags.json)
719
+ return json({ dir, latest: index.version, installed: manifest.version || null, skills: rows }), 0;
720
+ if (!rows.length) {
721
+ print(`No Delivrie skills in ${rel}. Run ${out.bold("delivrie init")} to install them.`);
722
+ return 0;
723
+ }
724
+ const label = { current: out.green("up to date"), outdated: out.yellow("update available"), edited: out.yellow("edited locally"), missing: out.dim("not installed") };
725
+ print(out.table(rows, [{ label: "SKILL", get: (r) => r.name }, { label: "STATUS", get: (r) => label[r.status] }]));
726
+ const n = rows.filter((r) => r.status === "outdated" || r.status === "missing").length;
727
+ print(n ? `\n${n} to install or update. Run ${out.bold("delivrie skills update")}${rows.some((r) => r.status === "missing") ? ` (or ${out.bold("delivrie init")} for new ones)` : ""}.` : `\nAll up to date (${index.version}).`);
728
+ return 0;
729
+ }
730
+ throw new UsageError(`Unknown: skills ${action}. Try delivrie skills --help`);
731
+ }
732
+ default:
733
+ return fail(`Unknown command "${cmd}". Run delivrie --help to see them all.`, 2);
734
+ }
735
+ }
736
+ catch (e) {
737
+ if (e instanceof UsageError)
738
+ return fail(e.message, 2);
739
+ if (e instanceof ApiError) {
740
+ if (flags.json) {
741
+ stdout.write(JSON.stringify({ error: { statusCode: e.status, name: e.code, message: e.message } }, null, 2) + "\n");
742
+ return 1;
743
+ }
744
+ const hint = e.status === 401 ? " Run `delivrie login` with a valid key." : e.code === "restricted_api_key" ? " This needs a full-access key." : "";
745
+ return fail(`${e.message}${hint}`);
746
+ }
747
+ if (e?.code === "ENOENT")
748
+ return fail(`File not found: ${e.path}`);
749
+ return fail(e?.message || String(e));
750
+ }
751
+ function printRecords(d) {
752
+ const recs = d.records || [];
753
+ if (!recs.length)
754
+ return;
755
+ print(out.table(recs, [{ label: "TYPE", get: (r) => r.type }, { label: "NAME", get: (r) => r.name }, { label: "VALUE", get: (r) => (r.priority != null ? `${r.priority} ` : "") + r.value }, { label: "STATUS", get: (r) => out.statusColor(r.status) }]));
756
+ }
757
+ }
758
+ // A sending-only key gets 403 from /usage; a bad key gets 401.
759
+ async function checkKey(api) {
760
+ try {
761
+ const usage = await api.request("GET", "/usage");
762
+ return { permission: "full", usage };
763
+ }
764
+ catch (e) {
765
+ if (e instanceof ApiError && e.status === 403)
766
+ return { permission: "sending" };
767
+ if (e instanceof ApiError && e.status === 401)
768
+ return { permission: "invalid" };
769
+ throw e;
770
+ }
771
+ }
772
+ const enc = encodeURIComponent;
773
+ const num = (n) => Number(n || 0).toLocaleString("en-US");
774
+ const trunc = (v, n) => { const s = String(v ?? ""); return s.length > n ? s.slice(0, n - 1) + "…" : s; };
775
+ const fmtUsage = (u) => `${num(u.emails_this_month)}${u.monthly_allowance ? ` of ${num(u.monthly_allowance)}` : ""} emails this month`;
776
+ function need1(v, what) { if (!v)
777
+ throw new UsageError(`Give the ${what}`); return v; }
778
+ function pairs(items, sep, flag) {
779
+ const o = {};
780
+ for (const it of items) {
781
+ const i = it.indexOf(sep);
782
+ if (i < 1)
783
+ throw new UsageError(`${flag} expects name${sep}value, got "${it}"`);
784
+ o[it.slice(0, i).trim()] = it.slice(i + 1).trim();
785
+ }
786
+ return o;
787
+ }
788
+ function readAll(stream) {
789
+ return new Promise((resolve, reject) => { let s = ""; stream.setEncoding?.("utf8"); stream.on("data", (c) => (s += c)); stream.on("end", () => resolve(s)); stream.on("error", reject); });
790
+ }
791
+ function readLine(stream, { hidden = false } = {}) {
792
+ return new Promise((resolve) => {
793
+ let s = "";
794
+ const raw = hidden && typeof stream.setRawMode === "function";
795
+ if (raw)
796
+ stream.setRawMode(true);
797
+ stream.resume();
798
+ stream.setEncoding?.("utf8");
799
+ const onData = (chunk) => {
800
+ for (const ch of String(chunk)) {
801
+ if (ch === "\r" || ch === "\n") {
802
+ done();
803
+ return;
804
+ }
805
+ if (ch === "\u0003") {
806
+ done();
807
+ process.exit(130);
808
+ }
809
+ if (ch === "\u007f")
810
+ s = s.slice(0, -1);
811
+ else
812
+ s += ch;
813
+ }
814
+ };
815
+ const done = () => { stream.off("data", onData); if (raw)
816
+ stream.setRawMode(false); stream.pause(); resolve(s); };
817
+ stream.on("data", onData);
818
+ });
819
+ }