@postshiba/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 +21 -0
- package/README.md +149 -2
- package/bin/postshiba.js +11 -0
- package/package.json +41 -4
- package/skills/postshiba-cli/SKILL.md +146 -0
- package/src/cli.js +467 -0
- package/src/client.js +74 -0
- package/src/commands.js +300 -0
- package/src/config.js +91 -0
- package/src/doctor.js +124 -0
- package/src/domains.js +67 -0
- package/src/errors.js +33 -0
- package/src/help.js +91 -0
- package/src/login.js +107 -0
- package/src/menu.js +51 -0
- package/src/mode.js +16 -0
- package/src/pkg.js +9 -0
- package/src/prompts.js +118 -0
- package/src/render.js +177 -0
- package/src/send.js +283 -0
- package/src/skills.js +40 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
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 { BOOLEAN_QUERY, actionsFor, commands, findCommand, interpolatePath, queryFlag, 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
|
+
...queryOptions(),
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* One flag per query parameter any command accepts, for example `--min-processed`.
|
|
58
|
+
*/
|
|
59
|
+
function queryOptions() {
|
|
60
|
+
/** @type {Record<string, { type: "string" | "boolean" }>} */
|
|
61
|
+
const out = {};
|
|
62
|
+
for (const name of new Set(commands.flatMap((item) => item.query))) {
|
|
63
|
+
out[queryFlag(name)] = { type: BOOLEAN_QUERY.has(name) ? "boolean" : "string" };
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const QUERY_FLAGS = new Set(commands.flatMap((item) => item.query).map(queryFlag));
|
|
69
|
+
|
|
70
|
+
export { commands, formatHelp };
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @param {string[]} argv
|
|
74
|
+
* @param {object} [io]
|
|
75
|
+
* @param {NodeJS.ProcessEnv} [io.env]
|
|
76
|
+
* @param {{ write: (chunk: string | Uint8Array) => unknown, isTTY?: boolean }} [io.stdout]
|
|
77
|
+
* @param {{ write: (chunk: string | Uint8Array) => unknown, isTTY?: boolean }} [io.stderr]
|
|
78
|
+
* @param {AsyncIterable<string | Uint8Array> & { isTTY?: boolean }} [io.stdin]
|
|
79
|
+
* @param {string} [io.configDir]
|
|
80
|
+
* @param {boolean} [io.isTTY]
|
|
81
|
+
* @param {string} [io.cwd]
|
|
82
|
+
* @param {string} [io.home]
|
|
83
|
+
* @param {typeof fetch} [io.fetch]
|
|
84
|
+
* @param {import("./prompts.js").Prompts} [io.prompts]
|
|
85
|
+
* @param {(ms: number) => Promise<void>} [io.sleep]
|
|
86
|
+
*/
|
|
87
|
+
export async function main(argv, io = {}) {
|
|
88
|
+
const ctx = {
|
|
89
|
+
env: io.env ?? process.env,
|
|
90
|
+
stdout: io.stdout ?? process.stdout,
|
|
91
|
+
stderr: io.stderr ?? process.stderr,
|
|
92
|
+
stdin: io.stdin ?? process.stdin,
|
|
93
|
+
configDir: io.configDir,
|
|
94
|
+
isTTY: io.isTTY,
|
|
95
|
+
cwd: io.cwd,
|
|
96
|
+
home: io.home,
|
|
97
|
+
fetch: io.fetch ?? globalThis.fetch,
|
|
98
|
+
prompts: io.prompts,
|
|
99
|
+
sleep: io.sleep,
|
|
100
|
+
interactive: false,
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
try {
|
|
104
|
+
return await run(argv, ctx);
|
|
105
|
+
} catch (err) {
|
|
106
|
+
if (err instanceof UsageError) {
|
|
107
|
+
ctx.stderr.write(`${err.message}\n`);
|
|
108
|
+
ctx.stderr.write(`See postshiba help${err.helpResource ? ` ${err.helpResource}` : ""}.\n`);
|
|
109
|
+
return 2;
|
|
110
|
+
}
|
|
111
|
+
if (err instanceof PostShibaError) {
|
|
112
|
+
writeApiError(ctx.stderr, err);
|
|
113
|
+
return 1;
|
|
114
|
+
}
|
|
115
|
+
if (err instanceof CancelError) {
|
|
116
|
+
ctx.stderr.write("Cancelled.\n");
|
|
117
|
+
return 130;
|
|
118
|
+
}
|
|
119
|
+
ctx.stderr.write(`${err && /** @type {Error} */ (err).message ? /** @type {Error} */ (err).message : err}\n`);
|
|
120
|
+
return 1;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* @param {string[]} argv
|
|
126
|
+
* @param {any} ctx
|
|
127
|
+
*/
|
|
128
|
+
async function run(argv, ctx) {
|
|
129
|
+
let parsed;
|
|
130
|
+
try {
|
|
131
|
+
parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
|
|
132
|
+
} catch (err) {
|
|
133
|
+
throw new UsageError(/** @type {Error} */ (err).message);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const { values, positionals } = parsed;
|
|
137
|
+
ctx.interactive = isInteractive(values, ctx);
|
|
138
|
+
if (ctx.interactive && !ctx.prompts) ctx.prompts = createClackPrompts();
|
|
139
|
+
|
|
140
|
+
if (values.help || positionals[0] === "help") {
|
|
141
|
+
const topic = values.help ? positionals[0] : positionals[1];
|
|
142
|
+
if (topic && topic !== "send" && topic !== "login" && topic !== "logout" && topic !== "whoami" && topic !== "doctor" && topic !== "skills") {
|
|
143
|
+
if (actionsFor(topic).length === 0) throw new UsageError(`Unknown resource ${topic}`);
|
|
144
|
+
}
|
|
145
|
+
ctx.stdout.write(`${formatHelp(topic)}\n`);
|
|
146
|
+
return 0;
|
|
147
|
+
}
|
|
148
|
+
if (values.version) {
|
|
149
|
+
ctx.stdout.write(`postshiba ${VERSION}\n`);
|
|
150
|
+
return 0;
|
|
151
|
+
}
|
|
152
|
+
if (positionals.length === 0) {
|
|
153
|
+
if (ctx.interactive && ctx.prompts) {
|
|
154
|
+
return mainMenu(ctx, (choice, action) => dispatch(choice, action ? [action] : [], values, ctx));
|
|
155
|
+
}
|
|
156
|
+
throw new UsageError("Missing command");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const [command, ...rest] = positionals;
|
|
160
|
+
return dispatch(command, rest, values, ctx);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* @param {string} command
|
|
165
|
+
* @param {string[]} rest
|
|
166
|
+
* @param {Record<string, any>} values
|
|
167
|
+
* @param {any} ctx
|
|
168
|
+
*/
|
|
169
|
+
async function dispatch(command, rest, values, ctx) {
|
|
170
|
+
if (command === "login") return login(values, ctx);
|
|
171
|
+
if (command === "logout") return logout(ctx);
|
|
172
|
+
if (command === "whoami") return whoami(values, ctx);
|
|
173
|
+
if (command === "send") return send(values, ctx);
|
|
174
|
+
if (command === "doctor") return doctor(values, ctx);
|
|
175
|
+
if (command === "skills") {
|
|
176
|
+
if (rest[0] !== "install") throw new UsageError("Usage: postshiba skills install", { helpResource: "skills" });
|
|
177
|
+
return installSkill(values, ctx);
|
|
178
|
+
}
|
|
179
|
+
return resourceCommand(command, rest, values, ctx);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* @param {Record<string, any>} values
|
|
184
|
+
* @param {any} ctx
|
|
185
|
+
*/
|
|
186
|
+
async function whoami(values, ctx) {
|
|
187
|
+
const creds = await credentials(values, ctx, { team: false });
|
|
188
|
+
const body = await request({
|
|
189
|
+
method: "GET",
|
|
190
|
+
url: `${creds.baseUrl}/api/v1/users/me`,
|
|
191
|
+
apiKey: creds.apiKey,
|
|
192
|
+
fetch: ctx.fetch,
|
|
193
|
+
});
|
|
194
|
+
writeJson(ctx.stdout, body);
|
|
195
|
+
return 0;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* @param {Record<string, any>} values
|
|
200
|
+
* @param {any} ctx
|
|
201
|
+
*/
|
|
202
|
+
async function send(values, ctx) {
|
|
203
|
+
const creds = await credentials(values, ctx, { team: false });
|
|
204
|
+
let next = values;
|
|
205
|
+
if (ctx.interactive && ctx.prompts) {
|
|
206
|
+
next = await completeSendFlags(
|
|
207
|
+
values,
|
|
208
|
+
{
|
|
209
|
+
prompts: ctx.prompts,
|
|
210
|
+
api: (method, path) =>
|
|
211
|
+
request({
|
|
212
|
+
method,
|
|
213
|
+
url: `${creds.baseUrl}${path}`,
|
|
214
|
+
apiKey: creds.apiKey,
|
|
215
|
+
fetch: ctx.fetch,
|
|
216
|
+
}),
|
|
217
|
+
},
|
|
218
|
+
creds,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
const route = sendRoute(next, creds.clusterId);
|
|
222
|
+
if (route.team && !creds.teamId) {
|
|
223
|
+
throw new UsageError("Missing team id. Pass --team, set POSTSHIBA_TEAM_ID, or save one with postshiba login.");
|
|
224
|
+
}
|
|
225
|
+
const body = await buildSendBody(next, ctx.stdin);
|
|
226
|
+
if (route.sandbox) body.sandbox = true;
|
|
227
|
+
/** @type {Record<string, string>} */
|
|
228
|
+
const headers = {};
|
|
229
|
+
if (route.team) {
|
|
230
|
+
if (route.idempotencyKey) headers["Idempotency-Key"] = route.idempotencyKey;
|
|
231
|
+
} else if (route.clusterId) {
|
|
232
|
+
headers["X-Capsule-Cluster-Id"] = String(route.clusterId);
|
|
233
|
+
}
|
|
234
|
+
const path = interpolatePath(route.path, { teamId: creds.teamId, clusterId: route.clusterId });
|
|
235
|
+
|
|
236
|
+
if (ctx.interactive && ctx.prompts) {
|
|
237
|
+
ctx.prompts.note(sendPreview(body, route), "Send");
|
|
238
|
+
const ok = await ctx.prompts.confirm({ message: "Send this email?" });
|
|
239
|
+
if (!ok) throw new CancelError();
|
|
240
|
+
const result = /** @type {Record<string, unknown>} */ (
|
|
241
|
+
await spinning(
|
|
242
|
+
ctx.prompts,
|
|
243
|
+
"Sending",
|
|
244
|
+
() => request({ method: "POST", url: `${creds.baseUrl}${path}`, apiKey: creds.apiKey, body, headers, fetch: ctx.fetch }),
|
|
245
|
+
() => (body.sandbox ? "Checked in sandbox. Nothing was delivered." : "Queued"),
|
|
246
|
+
)
|
|
247
|
+
);
|
|
248
|
+
ctx.prompts.outro(`Message id ${colorsFor(ctx).cyan(String(result.message_id ?? ""))}`);
|
|
249
|
+
return 0;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const result = await request({
|
|
253
|
+
method: "POST",
|
|
254
|
+
url: `${creds.baseUrl}${path}`,
|
|
255
|
+
apiKey: creds.apiKey,
|
|
256
|
+
body,
|
|
257
|
+
headers,
|
|
258
|
+
fetch: ctx.fetch,
|
|
259
|
+
});
|
|
260
|
+
writeJson(ctx.stdout, result);
|
|
261
|
+
return 0;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* @param {Record<string, any>} values
|
|
266
|
+
* @param {any} ctx
|
|
267
|
+
*/
|
|
268
|
+
async function doctor(values, ctx) {
|
|
269
|
+
const file = await readConfig(ctx.env, ctx.configDir);
|
|
270
|
+
const creds = resolveCredentials(values, ctx.env, file);
|
|
271
|
+
const report = await runDoctor(creds, ctx.fetch);
|
|
272
|
+
if (!ctx.interactive || values.json) {
|
|
273
|
+
writeJson(ctx.stdout, report);
|
|
274
|
+
return report.ok ? 0 : 1;
|
|
275
|
+
}
|
|
276
|
+
const c = colorsFor(ctx);
|
|
277
|
+
for (const check of report.checks) {
|
|
278
|
+
const mark = check.ok ? c.green("✔") : c.red("✖");
|
|
279
|
+
const extra = check.detail ? ` ${c.dim(check.detail)}` : "";
|
|
280
|
+
ctx.stdout.write(`${mark} ${doctorLabel(check)}${extra}\n`);
|
|
281
|
+
if (!check.ok && check.fix) ctx.stdout.write(` ${c.dim(check.fix)}\n`);
|
|
282
|
+
}
|
|
283
|
+
return report.ok ? 0 : 1;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* @param {string} resource
|
|
288
|
+
* @param {string[]} rest
|
|
289
|
+
* @param {Record<string, any>} values
|
|
290
|
+
* @param {any} ctx
|
|
291
|
+
*/
|
|
292
|
+
async function resourceCommand(resource, rest, values, ctx) {
|
|
293
|
+
const known = resources();
|
|
294
|
+
if (!known.includes(resource)) {
|
|
295
|
+
throw new UsageError(`Unknown command ${resource}`);
|
|
296
|
+
}
|
|
297
|
+
let action = rest[0];
|
|
298
|
+
if (!action) {
|
|
299
|
+
if (ctx.interactive && ctx.prompts) {
|
|
300
|
+
action = await ctx.prompts.select({
|
|
301
|
+
message: `${resource} action`,
|
|
302
|
+
options: actionsFor(resource).map((row) => ({ value: row.action, label: row.action })),
|
|
303
|
+
});
|
|
304
|
+
} else {
|
|
305
|
+
throw new UsageError(`Missing action for ${resource}`, { helpResource: resource });
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
const row = findCommand(resource, action);
|
|
309
|
+
if (!row) {
|
|
310
|
+
throw new UsageError(`Unknown action ${action} for ${resource}`, { helpResource: resource });
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const names = row.ids;
|
|
314
|
+
/** @type {string[]} */
|
|
315
|
+
let ids = rest.slice(1);
|
|
316
|
+
if (ctx.interactive && ctx.prompts) {
|
|
317
|
+
while (ids.length < names.length) {
|
|
318
|
+
const name = names[ids.length];
|
|
319
|
+
ids.push(await ctx.prompts.text({ message: name ?? "id" }));
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
if (ids.length < names.length) {
|
|
323
|
+
throw new UsageError(`Missing ${names[ids.length]}`, { helpResource: resource });
|
|
324
|
+
}
|
|
325
|
+
if (ids.length > names.length) {
|
|
326
|
+
throw new UsageError(`Unexpected extra argument ${ids[names.length]}`, { helpResource: resource });
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const accepted = new Set(row.query.map(queryFlag));
|
|
330
|
+
for (const flag of QUERY_FLAGS) {
|
|
331
|
+
if (values[flag] !== undefined && !accepted.has(flag)) {
|
|
332
|
+
throw new UsageError(`${resource} ${action} does not take --${flag}`, { helpResource: resource });
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
for (const name of row.required) {
|
|
336
|
+
const flag = queryFlag(name);
|
|
337
|
+
if (values[flag] !== undefined && values[flag] !== "") continue;
|
|
338
|
+
if (ctx.interactive && ctx.prompts) {
|
|
339
|
+
values = { ...values, [flag]: await ctx.prompts.text({ message: name }) };
|
|
340
|
+
} else {
|
|
341
|
+
throw new UsageError(`Missing --${flag}`, { helpResource: resource });
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const wizard =
|
|
346
|
+
ctx.interactive &&
|
|
347
|
+
resource === "sending-domains" &&
|
|
348
|
+
action === "create" &&
|
|
349
|
+
values.data === undefined;
|
|
350
|
+
if (row.data && values.data === undefined && !wizard) {
|
|
351
|
+
if (ctx.interactive && ctx.prompts) {
|
|
352
|
+
const raw = await ctx.prompts.text({ message: "--data JSON" });
|
|
353
|
+
values = { ...values, data: raw };
|
|
354
|
+
} else {
|
|
355
|
+
throw new UsageError(`Missing --data`, { helpResource: resource });
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (row.destructive && !values.yes) {
|
|
360
|
+
if (ctx.interactive && ctx.prompts) {
|
|
361
|
+
const ok = await ctx.prompts.confirm({ message: `Run ${resource} ${action}?` });
|
|
362
|
+
if (!ok) throw new CancelError();
|
|
363
|
+
} else {
|
|
364
|
+
throw new UsageError(`Refusing ${action} without --yes.`, { helpResource: resource });
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const creds = await credentials(values, ctx, { team: row.team });
|
|
369
|
+
|
|
370
|
+
if (wizard) {
|
|
371
|
+
const created = await createSendingDomainWizard(ctx, {
|
|
372
|
+
apiKey: creds.apiKey,
|
|
373
|
+
teamId: /** @type {string} */ (creds.teamId),
|
|
374
|
+
baseUrl: creds.baseUrl,
|
|
375
|
+
});
|
|
376
|
+
if (values.json) writeJson(ctx.stdout, created);
|
|
377
|
+
return 0;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** @type {Record<string, string | undefined>} */
|
|
381
|
+
const params = { teamId: creds.teamId };
|
|
382
|
+
names.forEach((name, i) => {
|
|
383
|
+
params[name] = ids[i];
|
|
384
|
+
});
|
|
385
|
+
const path = interpolatePath(row.path, params);
|
|
386
|
+
const query = queryString(row, values);
|
|
387
|
+
const body = row.data ? await loadData(values.data, ctx.stdin) : undefined;
|
|
388
|
+
/** @type {Record<string, string>} */
|
|
389
|
+
const headers = {};
|
|
390
|
+
if (row.cluster && creds.clusterId) headers["X-Capsule-Cluster-Id"] = String(creds.clusterId);
|
|
391
|
+
const result = await request({
|
|
392
|
+
method: row.method,
|
|
393
|
+
url: `${creds.baseUrl}${path}${query}`,
|
|
394
|
+
apiKey: creds.apiKey,
|
|
395
|
+
body,
|
|
396
|
+
headers,
|
|
397
|
+
binary: row.binary,
|
|
398
|
+
fetch: ctx.fetch,
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
if (row.binary) {
|
|
402
|
+
const bytes = /** @type {Buffer} */ (result);
|
|
403
|
+
if (values.output) await writeFile(values.output, bytes);
|
|
404
|
+
else ctx.stdout.write(bytes);
|
|
405
|
+
return 0;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
if (ctx.interactive && !values.json) {
|
|
409
|
+
renderResult(ctx, row, result);
|
|
410
|
+
return 0;
|
|
411
|
+
}
|
|
412
|
+
writeJson(ctx.stdout, result);
|
|
413
|
+
return 0;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Builds `?name=value&...` from the query flags the caller set, in the row's order.
|
|
418
|
+
* @param {import("./commands.js").CommandRow} row
|
|
419
|
+
* @param {Record<string, any>} values
|
|
420
|
+
*/
|
|
421
|
+
function queryString(row, values) {
|
|
422
|
+
const search = new URLSearchParams();
|
|
423
|
+
for (const name of row.query) {
|
|
424
|
+
const value = values[queryFlag(name)];
|
|
425
|
+
if (value === undefined) continue;
|
|
426
|
+
search.append(name, typeof value === "boolean" ? String(value) : value);
|
|
427
|
+
}
|
|
428
|
+
const text = search.toString();
|
|
429
|
+
return text ? `?${text}` : "";
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* @param {any} ctx
|
|
434
|
+
* @param {import("./commands.js").CommandRow} row
|
|
435
|
+
* @param {unknown} result
|
|
436
|
+
*/
|
|
437
|
+
function renderResult(ctx, row, result) {
|
|
438
|
+
const c = colorsFor(ctx);
|
|
439
|
+
const records = asRecords(result);
|
|
440
|
+
if (records.length && row.columns) {
|
|
441
|
+
ctx.stdout.write(`${formatTable(records, row.columns, c)}\n`);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
if (result && typeof result === "object" && !Array.isArray(result)) {
|
|
445
|
+
ctx.stdout.write(`${formatSummary(/** @type {Record<string, unknown>} */ (result), c)}\n`);
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
writeJson(ctx.stdout, result);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* @param {Record<string, any>} values
|
|
453
|
+
* @param {any} ctx
|
|
454
|
+
* @param {{ team: boolean }} opts
|
|
455
|
+
* @returns {Promise<{ apiKey: string, teamId?: string, clusterId?: string, baseUrl: string }>}
|
|
456
|
+
*/
|
|
457
|
+
async function credentials(values, ctx, opts) {
|
|
458
|
+
const file = await readConfig(ctx.env, ctx.configDir);
|
|
459
|
+
const creds = resolveCredentials(values, ctx.env, file);
|
|
460
|
+
if (!creds.apiKey) {
|
|
461
|
+
throw new UsageError("Missing API key. Run postshiba login or set POSTSHIBA_API_KEY.");
|
|
462
|
+
}
|
|
463
|
+
if (opts.team && !creds.teamId) {
|
|
464
|
+
throw new UsageError("Missing team id. Pass --team, set POSTSHIBA_TEAM_ID, or save one with postshiba login.");
|
|
465
|
+
}
|
|
466
|
+
return { apiKey: creds.apiKey, teamId: creds.teamId, clusterId: creds.clusterId, baseUrl: creds.baseUrl };
|
|
467
|
+
}
|
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
|
+
}
|