@postshiba/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/src/cli.js ADDED
@@ -0,0 +1,415 @@
1
+ // @ts-check
2
+
3
+ import { writeFile } from "node:fs/promises";
4
+ import { parseArgs } from "node:util";
5
+ import { PostShibaError, request } from "./client.js";
6
+ import { actionsFor, commands, findCommand, interpolatePath, resources } from "./commands.js";
7
+ import { readConfig, resolveCredentials } from "./config.js";
8
+ import { createSendingDomainWizard } from "./domains.js";
9
+ import { runDoctor, doctorLabel } from "./doctor.js";
10
+ import { CancelError, UsageError, writeApiError } from "./errors.js";
11
+ import { formatHelp } from "./help.js";
12
+ import { login, logout } from "./login.js";
13
+ import { mainMenu } from "./menu.js";
14
+ import { isInteractive } from "./mode.js";
15
+ import { VERSION } from "./pkg.js";
16
+ import { createClackPrompts, spinning } from "./prompts.js";
17
+ import { asRecords, colorsFor, formatSummary, formatTable, writeJson } from "./render.js";
18
+ import { buildSendBody, completeSendFlags, loadData, sendPreview, sendRoute } from "./send.js";
19
+ import { installSkill } from "./skills.js";
20
+
21
+ const OPTIONS = {
22
+ help: { type: /** @type {const} */ ("boolean"), short: "h" },
23
+ version: { type: /** @type {const} */ ("boolean") },
24
+ json: { type: /** @type {const} */ ("boolean") },
25
+ "no-input": { type: /** @type {const} */ ("boolean") },
26
+ yes: { type: /** @type {const} */ ("boolean") },
27
+ "api-key": { type: /** @type {const} */ ("string") },
28
+ team: { type: /** @type {const} */ ("string") },
29
+ "base-url": { type: /** @type {const} */ ("string") },
30
+ data: { type: /** @type {const} */ ("string") },
31
+ output: { type: /** @type {const} */ ("string") },
32
+ from: { type: /** @type {const} */ ("string") },
33
+ to: { type: /** @type {const} */ ("string"), multiple: true },
34
+ cc: { type: /** @type {const} */ ("string"), multiple: true },
35
+ bcc: { type: /** @type {const} */ ("string"), multiple: true },
36
+ "reply-to": { type: /** @type {const} */ ("string") },
37
+ subject: { type: /** @type {const} */ ("string") },
38
+ text: { type: /** @type {const} */ ("string") },
39
+ "text-file": { type: /** @type {const} */ ("string") },
40
+ html: { type: /** @type {const} */ ("string") },
41
+ "html-file": { type: /** @type {const} */ ("string") },
42
+ template: { type: /** @type {const} */ ("string") },
43
+ var: { type: /** @type {const} */ ("string"), multiple: true },
44
+ header: { type: /** @type {const} */ ("string"), multiple: true },
45
+ arg: { type: /** @type {const} */ ("string"), multiple: true },
46
+ attach: { type: /** @type {const} */ ("string"), multiple: true },
47
+ tenant: { type: /** @type {const} */ ("string") },
48
+ cluster: { type: /** @type {const} */ ("string") },
49
+ sandbox: { type: /** @type {const} */ ("boolean") },
50
+ "idempotency-key": { type: /** @type {const} */ ("string") },
51
+ global: { type: /** @type {const} */ ("boolean") },
52
+ target: { type: /** @type {const} */ ("string") },
53
+ };
54
+
55
+ export { commands, formatHelp };
56
+
57
+ /**
58
+ * @param {string[]} argv
59
+ * @param {object} [io]
60
+ * @param {NodeJS.ProcessEnv} [io.env]
61
+ * @param {{ write: (chunk: string | Uint8Array) => unknown, isTTY?: boolean }} [io.stdout]
62
+ * @param {{ write: (chunk: string | Uint8Array) => unknown, isTTY?: boolean }} [io.stderr]
63
+ * @param {AsyncIterable<string | Uint8Array> & { isTTY?: boolean }} [io.stdin]
64
+ * @param {string} [io.configDir]
65
+ * @param {boolean} [io.isTTY]
66
+ * @param {string} [io.cwd]
67
+ * @param {string} [io.home]
68
+ * @param {typeof fetch} [io.fetch]
69
+ * @param {import("./prompts.js").Prompts} [io.prompts]
70
+ * @param {(ms: number) => Promise<void>} [io.sleep]
71
+ */
72
+ export async function main(argv, io = {}) {
73
+ const ctx = {
74
+ env: io.env ?? process.env,
75
+ stdout: io.stdout ?? process.stdout,
76
+ stderr: io.stderr ?? process.stderr,
77
+ stdin: io.stdin ?? process.stdin,
78
+ configDir: io.configDir,
79
+ isTTY: io.isTTY,
80
+ cwd: io.cwd,
81
+ home: io.home,
82
+ fetch: io.fetch ?? globalThis.fetch,
83
+ prompts: io.prompts,
84
+ sleep: io.sleep,
85
+ interactive: false,
86
+ };
87
+
88
+ try {
89
+ return await run(argv, ctx);
90
+ } catch (err) {
91
+ if (err instanceof UsageError) {
92
+ ctx.stderr.write(`${err.message}\n`);
93
+ ctx.stderr.write(`See postshiba help${err.helpResource ? ` ${err.helpResource}` : ""}.\n`);
94
+ return 2;
95
+ }
96
+ if (err instanceof PostShibaError) {
97
+ writeApiError(ctx.stderr, err);
98
+ return 1;
99
+ }
100
+ if (err instanceof CancelError) {
101
+ ctx.stderr.write("Cancelled.\n");
102
+ return 130;
103
+ }
104
+ ctx.stderr.write(`${err && /** @type {Error} */ (err).message ? /** @type {Error} */ (err).message : err}\n`);
105
+ return 1;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * @param {string[]} argv
111
+ * @param {any} ctx
112
+ */
113
+ async function run(argv, ctx) {
114
+ let parsed;
115
+ try {
116
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
117
+ } catch (err) {
118
+ throw new UsageError(/** @type {Error} */ (err).message);
119
+ }
120
+
121
+ const { values, positionals } = parsed;
122
+ ctx.interactive = isInteractive(values, ctx);
123
+ if (ctx.interactive && !ctx.prompts) ctx.prompts = createClackPrompts();
124
+
125
+ if (values.help || positionals[0] === "help") {
126
+ const topic = values.help ? positionals[0] : positionals[1];
127
+ if (topic && topic !== "send" && topic !== "login" && topic !== "logout" && topic !== "whoami" && topic !== "doctor" && topic !== "skills") {
128
+ if (actionsFor(topic).length === 0) throw new UsageError(`Unknown resource ${topic}`);
129
+ }
130
+ ctx.stdout.write(`${formatHelp(topic)}\n`);
131
+ return 0;
132
+ }
133
+ if (values.version) {
134
+ ctx.stdout.write(`postshiba ${VERSION}\n`);
135
+ return 0;
136
+ }
137
+ if (positionals.length === 0) {
138
+ if (ctx.interactive && ctx.prompts) {
139
+ return mainMenu(ctx, (choice, action) => dispatch(choice, action ? [action] : [], values, ctx));
140
+ }
141
+ throw new UsageError("Missing command");
142
+ }
143
+
144
+ const [command, ...rest] = positionals;
145
+ return dispatch(command, rest, values, ctx);
146
+ }
147
+
148
+ /**
149
+ * @param {string} command
150
+ * @param {string[]} rest
151
+ * @param {Record<string, any>} values
152
+ * @param {any} ctx
153
+ */
154
+ async function dispatch(command, rest, values, ctx) {
155
+ if (command === "login") return login(values, ctx);
156
+ if (command === "logout") return logout(ctx);
157
+ if (command === "whoami") return whoami(values, ctx);
158
+ if (command === "send") return send(values, ctx);
159
+ if (command === "doctor") return doctor(values, ctx);
160
+ if (command === "skills") {
161
+ if (rest[0] !== "install") throw new UsageError("Usage: postshiba skills install", { helpResource: "skills" });
162
+ return installSkill(values, ctx);
163
+ }
164
+ return resourceCommand(command, rest, values, ctx);
165
+ }
166
+
167
+ /**
168
+ * @param {Record<string, any>} values
169
+ * @param {any} ctx
170
+ */
171
+ async function whoami(values, ctx) {
172
+ const creds = await credentials(values, ctx, { team: false });
173
+ const body = await request({
174
+ method: "GET",
175
+ url: `${creds.baseUrl}/api/v1/users/me`,
176
+ apiKey: creds.apiKey,
177
+ fetch: ctx.fetch,
178
+ });
179
+ writeJson(ctx.stdout, body);
180
+ return 0;
181
+ }
182
+
183
+ /**
184
+ * @param {Record<string, any>} values
185
+ * @param {any} ctx
186
+ */
187
+ async function send(values, ctx) {
188
+ const creds = await credentials(values, ctx, { team: false });
189
+ let next = values;
190
+ if (ctx.interactive && ctx.prompts) {
191
+ next = await completeSendFlags(
192
+ values,
193
+ {
194
+ prompts: ctx.prompts,
195
+ api: (method, path) =>
196
+ request({
197
+ method,
198
+ url: `${creds.baseUrl}${path}`,
199
+ apiKey: creds.apiKey,
200
+ fetch: ctx.fetch,
201
+ }),
202
+ },
203
+ creds,
204
+ );
205
+ }
206
+ const route = sendRoute(next, creds.clusterId);
207
+ if (route.team && !creds.teamId) {
208
+ throw new UsageError("Missing team id. Pass --team, set POSTSHIBA_TEAM_ID, or save one with postshiba login.");
209
+ }
210
+ const body = await buildSendBody(next, ctx.stdin);
211
+ if (route.sandbox) body.sandbox = true;
212
+ /** @type {Record<string, string>} */
213
+ const headers = {};
214
+ if (route.team) {
215
+ if (route.idempotencyKey) headers["Idempotency-Key"] = route.idempotencyKey;
216
+ } else if (route.clusterId) {
217
+ headers["X-Capsule-Cluster-Id"] = String(route.clusterId);
218
+ }
219
+ const path = interpolatePath(route.path, { teamId: creds.teamId, clusterId: route.clusterId });
220
+
221
+ if (ctx.interactive && ctx.prompts) {
222
+ ctx.prompts.note(sendPreview(body, route), "Send");
223
+ const ok = await ctx.prompts.confirm({ message: "Send this email?" });
224
+ if (!ok) throw new CancelError();
225
+ const result = /** @type {Record<string, unknown>} */ (
226
+ await spinning(
227
+ ctx.prompts,
228
+ "Sending",
229
+ () => request({ method: "POST", url: `${creds.baseUrl}${path}`, apiKey: creds.apiKey, body, headers, fetch: ctx.fetch }),
230
+ () => (body.sandbox ? "Checked in sandbox. Nothing was delivered." : "Queued"),
231
+ )
232
+ );
233
+ ctx.prompts.outro(`Message id ${colorsFor(ctx).cyan(String(result.message_id ?? ""))}`);
234
+ return 0;
235
+ }
236
+
237
+ const result = await request({
238
+ method: "POST",
239
+ url: `${creds.baseUrl}${path}`,
240
+ apiKey: creds.apiKey,
241
+ body,
242
+ headers,
243
+ fetch: ctx.fetch,
244
+ });
245
+ writeJson(ctx.stdout, result);
246
+ return 0;
247
+ }
248
+
249
+ /**
250
+ * @param {Record<string, any>} values
251
+ * @param {any} ctx
252
+ */
253
+ async function doctor(values, ctx) {
254
+ const file = await readConfig(ctx.env, ctx.configDir);
255
+ const creds = resolveCredentials(values, ctx.env, file);
256
+ const report = await runDoctor(creds, ctx.fetch);
257
+ if (!ctx.interactive || values.json) {
258
+ writeJson(ctx.stdout, report);
259
+ return report.ok ? 0 : 1;
260
+ }
261
+ const c = colorsFor(ctx);
262
+ for (const check of report.checks) {
263
+ const mark = check.ok ? c.green("✔") : c.red("✖");
264
+ const extra = check.detail ? ` ${c.dim(check.detail)}` : "";
265
+ ctx.stdout.write(`${mark} ${doctorLabel(check)}${extra}\n`);
266
+ if (!check.ok && check.fix) ctx.stdout.write(` ${c.dim(check.fix)}\n`);
267
+ }
268
+ return report.ok ? 0 : 1;
269
+ }
270
+
271
+ /**
272
+ * @param {string} resource
273
+ * @param {string[]} rest
274
+ * @param {Record<string, any>} values
275
+ * @param {any} ctx
276
+ */
277
+ async function resourceCommand(resource, rest, values, ctx) {
278
+ const known = resources();
279
+ if (!known.includes(resource)) {
280
+ throw new UsageError(`Unknown command ${resource}`);
281
+ }
282
+ let action = rest[0];
283
+ if (!action) {
284
+ if (ctx.interactive && ctx.prompts) {
285
+ action = await ctx.prompts.select({
286
+ message: `${resource} action`,
287
+ options: actionsFor(resource).map((row) => ({ value: row.action, label: row.action })),
288
+ });
289
+ } else {
290
+ throw new UsageError(`Missing action for ${resource}`, { helpResource: resource });
291
+ }
292
+ }
293
+ const row = findCommand(resource, action);
294
+ if (!row) {
295
+ throw new UsageError(`Unknown action ${action} for ${resource}`, { helpResource: resource });
296
+ }
297
+
298
+ const names = row.ids;
299
+ /** @type {string[]} */
300
+ let ids = rest.slice(1);
301
+ if (ctx.interactive && ctx.prompts) {
302
+ while (ids.length < names.length) {
303
+ const name = names[ids.length];
304
+ ids.push(await ctx.prompts.text({ message: name ?? "id" }));
305
+ }
306
+ }
307
+ if (ids.length < names.length) {
308
+ throw new UsageError(`Missing ${names[ids.length]}`, { helpResource: resource });
309
+ }
310
+ if (ids.length > names.length) {
311
+ throw new UsageError(`Unexpected extra argument ${ids[names.length]}`, { helpResource: resource });
312
+ }
313
+
314
+ const wizard =
315
+ ctx.interactive &&
316
+ resource === "sending-domains" &&
317
+ action === "create" &&
318
+ values.data === undefined;
319
+ if (row.data && values.data === undefined && !wizard) {
320
+ if (ctx.interactive && ctx.prompts) {
321
+ const raw = await ctx.prompts.text({ message: "--data JSON" });
322
+ values = { ...values, data: raw };
323
+ } else {
324
+ throw new UsageError(`Missing --data`, { helpResource: resource });
325
+ }
326
+ }
327
+
328
+ if (row.destructive && !values.yes) {
329
+ if (ctx.interactive && ctx.prompts) {
330
+ const ok = await ctx.prompts.confirm({ message: `Run ${resource} ${action}?` });
331
+ if (!ok) throw new CancelError();
332
+ } else {
333
+ throw new UsageError(`Refusing ${action} without --yes.`, { helpResource: resource });
334
+ }
335
+ }
336
+
337
+ const creds = await credentials(values, ctx, { team: row.team });
338
+
339
+ if (wizard) {
340
+ const created = await createSendingDomainWizard(ctx, {
341
+ apiKey: creds.apiKey,
342
+ teamId: /** @type {string} */ (creds.teamId),
343
+ baseUrl: creds.baseUrl,
344
+ });
345
+ if (values.json) writeJson(ctx.stdout, created);
346
+ return 0;
347
+ }
348
+
349
+ /** @type {Record<string, string | undefined>} */
350
+ const params = { teamId: creds.teamId };
351
+ names.forEach((name, i) => {
352
+ params[name] = ids[i];
353
+ });
354
+ const path = interpolatePath(row.path, params);
355
+ const body = row.data ? await loadData(values.data, ctx.stdin) : undefined;
356
+ const result = await request({
357
+ method: row.method,
358
+ url: `${creds.baseUrl}${path}`,
359
+ apiKey: creds.apiKey,
360
+ body,
361
+ binary: row.binary,
362
+ fetch: ctx.fetch,
363
+ });
364
+
365
+ if (row.binary) {
366
+ const bytes = /** @type {Buffer} */ (result);
367
+ if (values.output) await writeFile(values.output, bytes);
368
+ else ctx.stdout.write(bytes);
369
+ return 0;
370
+ }
371
+
372
+ if (ctx.interactive && !values.json) {
373
+ renderResult(ctx, row, result);
374
+ return 0;
375
+ }
376
+ writeJson(ctx.stdout, result);
377
+ return 0;
378
+ }
379
+
380
+ /**
381
+ * @param {any} ctx
382
+ * @param {import("./commands.js").CommandRow} row
383
+ * @param {unknown} result
384
+ */
385
+ function renderResult(ctx, row, result) {
386
+ const c = colorsFor(ctx);
387
+ const records = asRecords(result);
388
+ if (records.length && row.columns) {
389
+ ctx.stdout.write(`${formatTable(records, row.columns, c)}\n`);
390
+ return;
391
+ }
392
+ if (result && typeof result === "object" && !Array.isArray(result)) {
393
+ ctx.stdout.write(`${formatSummary(/** @type {Record<string, unknown>} */ (result), c)}\n`);
394
+ return;
395
+ }
396
+ writeJson(ctx.stdout, result);
397
+ }
398
+
399
+ /**
400
+ * @param {Record<string, any>} values
401
+ * @param {any} ctx
402
+ * @param {{ team: boolean }} opts
403
+ * @returns {Promise<{ apiKey: string, teamId?: string, clusterId?: string, baseUrl: string }>}
404
+ */
405
+ async function credentials(values, ctx, opts) {
406
+ const file = await readConfig(ctx.env, ctx.configDir);
407
+ const creds = resolveCredentials(values, ctx.env, file);
408
+ if (!creds.apiKey) {
409
+ throw new UsageError("Missing API key. Run postshiba login or set POSTSHIBA_API_KEY.");
410
+ }
411
+ if (opts.team && !creds.teamId) {
412
+ throw new UsageError("Missing team id. Pass --team, set POSTSHIBA_TEAM_ID, or save one with postshiba login.");
413
+ }
414
+ return { apiKey: creds.apiKey, teamId: creds.teamId, clusterId: creds.clusterId, baseUrl: creds.baseUrl };
415
+ }
package/src/client.js ADDED
@@ -0,0 +1,74 @@
1
+ // @ts-check
2
+
3
+ export class PostShibaError extends Error {
4
+ /**
5
+ * @param {{ error?: string, field?: string | null, message?: string, status?: number | null }} [attrs]
6
+ */
7
+ constructor(attrs = {}) {
8
+ super(attrs.message ?? attrs.error ?? "Request failed");
9
+ this.name = "PostShibaError";
10
+ this.error = attrs.error ?? "error";
11
+ this.field = attrs.field ?? null;
12
+ this.status = attrs.status ?? null;
13
+ }
14
+ }
15
+
16
+ /**
17
+ * @param {string} text
18
+ * @returns {unknown}
19
+ */
20
+ function parseJson(text) {
21
+ if (!text) return {};
22
+ try {
23
+ return JSON.parse(text);
24
+ } catch {
25
+ return text;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * @param {object} opts
31
+ * @param {string} opts.method
32
+ * @param {string} opts.url
33
+ * @param {string} opts.apiKey
34
+ * @param {unknown} [opts.body]
35
+ * @param {Record<string, string>} [opts.headers]
36
+ * @param {boolean} [opts.binary]
37
+ * @param {typeof fetch} [opts.fetch]
38
+ */
39
+ export async function request(opts) {
40
+ /** @type {Record<string, string>} */
41
+ const headers = {
42
+ Authorization: `Bearer ${opts.apiKey}`,
43
+ Accept: "application/json",
44
+ ...opts.headers,
45
+ };
46
+ if (opts.body !== undefined) headers["Content-Type"] = "application/json";
47
+
48
+ const fetchImpl = opts.fetch ?? globalThis.fetch;
49
+ let res;
50
+ try {
51
+ res = await fetchImpl(opts.url, {
52
+ method: opts.method,
53
+ headers,
54
+ body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
55
+ });
56
+ } catch (err) {
57
+ const message = err instanceof Error ? err.message : String(err);
58
+ throw new PostShibaError({ error: "network", message });
59
+ }
60
+
61
+ if (!res.ok) {
62
+ const payload = parseJson(await res.text());
63
+ const attrs = payload && typeof payload === "object" ? /** @type {Record<string, unknown>} */ (payload) : {};
64
+ throw new PostShibaError({
65
+ error: typeof attrs.error === "string" ? attrs.error : undefined,
66
+ field: typeof attrs.field === "string" ? attrs.field : null,
67
+ message: typeof attrs.message === "string" ? attrs.message : undefined,
68
+ status: res.status,
69
+ });
70
+ }
71
+
72
+ if (opts.binary) return Buffer.from(await res.arrayBuffer());
73
+ return parseJson(await res.text());
74
+ }
@@ -0,0 +1,190 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * @typedef {object} CommandRow
5
+ * @property {string} resource
6
+ * @property {string} action
7
+ * @property {string} method
8
+ * @property {string} path
9
+ * @property {boolean} team
10
+ * @property {string[]} ids
11
+ * @property {boolean} data
12
+ * @property {boolean} destructive
13
+ * @property {boolean} binary
14
+ * @property {string[]} [columns]
15
+ */
16
+
17
+ /**
18
+ * @param {string} resource
19
+ * @param {string} action
20
+ * @param {string} method
21
+ * @param {string} path
22
+ * @param {{ data?: boolean, binary?: boolean, columns?: string[] }} [extra]
23
+ * @returns {CommandRow}
24
+ */
25
+ function row(resource, action, method, path, extra = {}) {
26
+ return {
27
+ resource,
28
+ action,
29
+ method,
30
+ path,
31
+ team: path.includes(":teamId"),
32
+ ids: pathParamNames(path),
33
+ data: extra.data ?? false,
34
+ destructive: /^(delete|suspend|release|unassign)/.test(action),
35
+ binary: extra.binary ?? false,
36
+ columns: extra.columns,
37
+ };
38
+ }
39
+
40
+ /** @type {CommandRow[]} */
41
+ export const commands = [
42
+ row("clusters", "list", "GET", "/api/v1/teams/:teamId/clusters", {
43
+ columns: ["id", "name", "status", "plan", "sending_ready"],
44
+ }),
45
+ row("clusters", "get", "GET", "/api/v1/clusters/:id"),
46
+ row("clusters", "create", "POST", "/api/v1/teams/:teamId/clusters", { data: true }),
47
+ row("clusters", "update", "PATCH", "/api/v1/clusters/:id", { data: true }),
48
+ row("clusters", "suspend", "POST", "/api/v1/clusters/:id/suspend"),
49
+ row("clusters", "resume", "POST", "/api/v1/clusters/:id/resume"),
50
+ row("clusters", "delete", "DELETE", "/api/v1/clusters/:id"),
51
+ row("clusters", "boost", "POST", "/api/v1/clusters/:id/boost", { data: true }),
52
+ row("clusters", "extend-boost", "POST", "/api/v1/clusters/:id/extend_boost", { data: true }),
53
+ row("clusters", "cancel-boost", "POST", "/api/v1/clusters/:id/cancel_boost"),
54
+ row("network", "list", "GET", "/api/v1/teams/:teamId/network", {
55
+ columns: ["id", "address", "status", "kind", "classification"],
56
+ }),
57
+ row("network", "create", "POST", "/api/v1/teams/:teamId/network", { data: true }),
58
+ row("network", "assign", "POST", "/api/v1/teams/:teamId/network/assign", { data: true }),
59
+ row("network", "unassign", "POST", "/api/v1/teams/:teamId/network/unassign", { data: true }),
60
+ row("network", "switch", "POST", "/api/v1/teams/:teamId/network/switch", { data: true }),
61
+ row("network", "release", "POST", "/api/v1/teams/:teamId/network/release", { data: true }),
62
+ row("sending-domains", "list", "GET", "/api/v1/teams/:teamId/sending_domains", {
63
+ columns: ["id", "name", "dkim_status", "return_path_status", "primary"],
64
+ }),
65
+ row("sending-domains", "get", "GET", "/api/v1/sending_domains/:id"),
66
+ row("sending-domains", "create", "POST", "/api/v1/teams/:teamId/sending_domains", { data: true }),
67
+ row("sending-domains", "update", "PATCH", "/api/v1/sending_domains/:id", { data: true }),
68
+ row("sending-domains", "refresh", "POST", "/api/v1/sending_domains/:id/refresh"),
69
+ row("sending-domains", "verify", "POST", "/api/v1/sending_domains/:id/verify"),
70
+ row("sending-domains", "suspend", "POST", "/api/v1/sending_domains/:id/suspend"),
71
+ row("sending-domains", "resume", "POST", "/api/v1/sending_domains/:id/resume"),
72
+ row("sending-domains", "make-primary", "POST", "/api/v1/sending_domains/:id/make_primary"),
73
+ row("sending-domains", "delete", "DELETE", "/api/v1/sending_domains/:id"),
74
+ row("tenants", "list", "GET", "/api/v1/teams/:teamId/tenants", {
75
+ columns: ["id", "name", "slug", "suspended"],
76
+ }),
77
+ row("tenants", "get", "GET", "/api/v1/tenants/:id"),
78
+ row("tenants", "create", "POST", "/api/v1/teams/:teamId/tenants", { data: true }),
79
+ row("tenants", "delete", "DELETE", "/api/v1/tenants/:id"),
80
+ row("inboxes", "list", "GET", "/api/v1/teams/:teamId/inboxes", {
81
+ columns: ["id", "name", "address", "mx_status"],
82
+ }),
83
+ row("inboxes", "get", "GET", "/api/v1/inboxes/:id"),
84
+ row("inboxes", "create", "POST", "/api/v1/teams/:teamId/inboxes", { data: true }),
85
+ row("inboxes", "verify", "POST", "/api/v1/inboxes/:id/verify"),
86
+ row("inboxes", "delete", "DELETE", "/api/v1/inboxes/:id"),
87
+ row("messages", "list", "GET", "/api/v1/inboxes/:inboxId/inbound_messages", {
88
+ columns: ["id", "from", "subject", "drain_status"],
89
+ }),
90
+ row("messages", "get", "GET", "/api/v1/inboxes/:inboxId/inbound_messages/:id"),
91
+ row("messages", "download-attachment", "GET", "/api/v1/inboxes/:inboxId/inbound_messages/:id/attachments/:index", {
92
+ binary: true,
93
+ }),
94
+ row("events", "list-team", "GET", "/api/v1/teams/:teamId/message_events", {
95
+ columns: ["id", "event_type", "recipient", "occurred_at"],
96
+ }),
97
+ row("events", "list", "GET", "/api/v1/teams/:teamId/clusters/:clusterId/message_events", {
98
+ columns: ["id", "event_type", "recipient", "occurred_at"],
99
+ }),
100
+ row("events", "get", "GET", "/api/v1/message_events/:id"),
101
+ row("smtp-credentials", "create", "POST", "/api/v1/teams/:teamId/clusters/:clusterId/smtp_credentials", {
102
+ data: true,
103
+ }),
104
+ row("smtp-credentials", "delete", "DELETE", "/api/v1/teams/:teamId/clusters/:clusterId/smtp_credentials/:id"),
105
+ row("webhooks", "list", "GET", "/api/v1/teams/:teamId/webhook_endpoints", {
106
+ columns: ["id", "url", "enabled"],
107
+ }),
108
+ row("webhooks", "get", "GET", "/api/v1/webhook_endpoints/:id"),
109
+ row("webhooks", "create", "POST", "/api/v1/teams/:teamId/webhook_endpoints", { data: true }),
110
+ row("webhooks", "update", "PATCH", "/api/v1/webhook_endpoints/:id", { data: true }),
111
+ row("webhooks", "delete", "DELETE", "/api/v1/webhook_endpoints/:id"),
112
+ row("templates", "list", "GET", "/api/v1/teams/:teamId/templates", {
113
+ columns: ["id", "name", "alias", "published"],
114
+ }),
115
+ row("templates", "get", "GET", "/api/v1/templates/:id"),
116
+ row("templates", "create", "POST", "/api/v1/teams/:teamId/templates", { data: true }),
117
+ row("templates", "update", "PATCH", "/api/v1/templates/:id", { data: true }),
118
+ row("templates", "publish", "POST", "/api/v1/templates/:id/publish"),
119
+ row("templates", "duplicate", "POST", "/api/v1/templates/:id/duplicate"),
120
+ row("templates", "delete", "DELETE", "/api/v1/templates/:id"),
121
+ row("suppressions", "list", "GET", "/api/v1/teams/:teamId/suppressions", {
122
+ columns: ["id", "email", "reason", "tenant"],
123
+ }),
124
+ row("suppressions", "create", "POST", "/api/v1/teams/:teamId/suppressions", { data: true }),
125
+ row("suppressions", "import", "POST", "/api/v1/teams/:teamId/suppressions/import", { data: true }),
126
+ row("suppressions", "delete", "DELETE", "/api/v1/suppressions/:id"),
127
+ row("firewall", "get", "GET", "/api/v1/teams/:teamId/firewall"),
128
+ row("firewall", "update", "PATCH", "/api/v1/teams/:teamId/firewall", { data: true }),
129
+ row("firewall", "add-entry", "POST", "/api/v1/teams/:teamId/firewall_entries", { data: true }),
130
+ row("firewall", "delete-entry", "DELETE", "/api/v1/firewall_entries/:id"),
131
+ ];
132
+
133
+ /**
134
+ * @param {string} name
135
+ */
136
+ export function kebab(name) {
137
+ return name.replace(/[A-Z]/g, (ch) => `-${ch.toLowerCase()}`);
138
+ }
139
+
140
+ /**
141
+ * @param {string} resource
142
+ * @param {string} action
143
+ */
144
+ export function findCommand(resource, action) {
145
+ return commands.find((item) => item.resource === resource && item.action === action);
146
+ }
147
+
148
+ export function resources() {
149
+ return [...new Set(commands.map((item) => item.resource))];
150
+ }
151
+
152
+ /**
153
+ * @param {string} resource
154
+ */
155
+ export function actionsFor(resource) {
156
+ return commands.filter((item) => item.resource === resource);
157
+ }
158
+
159
+ /**
160
+ * @param {string} path
161
+ */
162
+ export function pathParamNames(path) {
163
+ return [...path.matchAll(/:([A-Za-z]+)/g)].map((match) => match[1]).filter((name) => name !== "teamId");
164
+ }
165
+
166
+ /**
167
+ * @param {string} path
168
+ * @param {Record<string, string | undefined>} params
169
+ */
170
+ export function interpolatePath(path, params) {
171
+ return path.replace(/:([A-Za-z]+)/g, (_, name) => {
172
+ const value = params[name];
173
+ if (value === undefined || value === null || value === "") {
174
+ throw new Error(`missing path param :${name}`);
175
+ }
176
+ const text = String(value);
177
+ return /[^A-Za-z0-9._~-]/.test(text) ? encodeURIComponent(text) : text;
178
+ });
179
+ }
180
+
181
+ /**
182
+ * @param {CommandRow} item
183
+ */
184
+ export function actionUsage(item) {
185
+ const ids = item.ids.map((name) => `<${name}>`);
186
+ const parts = [item.action, ...ids];
187
+ if (item.data) parts.push("--data");
188
+ if (item.binary) parts.push("[--output PATH]");
189
+ return parts.join(" ");
190
+ }