socialapi-cli 0.0.0-stage → 0.0.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.
@@ -0,0 +1,346 @@
1
+ // Runs one generated command: parses its arguments against the manifest,
2
+ // validates them, sends the request and prints the response.
3
+ import { readFileSync, writeFileSync } from 'node:fs';
4
+ import { basename } from 'node:path';
5
+ import { text } from 'node:stream/consumers';
6
+ import { noCredential, resolveCredential } from './credentials.mjs';
7
+ import { EXIT, usageError } from './errors.mjs';
8
+ import { GLOBAL_FLAGS } from './flags.mjs';
9
+ import { send } from './http.mjs';
10
+ import { writeJson } from './output.mjs';
11
+ import { nearest } from './suggest.mjs';
12
+
13
+ /**
14
+ * @typedef {import('../scripts/generate.mjs').Command} Command
15
+ * @typedef {import('../scripts/generate.mjs').Flag} Flag
16
+ * @typedef {import('./main.mjs').Context} Context
17
+ */
18
+
19
+ /** Base URL: --base-url, then SOCIALAPI_BASE_URL, then the spec's server URL. */
20
+ export function resolveBaseUrl(flag, env, manifest) {
21
+ return (flag || env.SOCIALAPI_BASE_URL || manifest.baseUrl).replace(/\/+$/, '');
22
+ }
23
+
24
+ /**
25
+ * The base URL to call, checked: --base-url, then SOCIALAPI_BASE_URL, then the spec's server URL.
26
+ * @returns {{ base: string, url: URL }} `base` has no trailing slash
27
+ */
28
+ export function parseBaseUrl(flag, env, manifest) {
29
+ const base = resolveBaseUrl(flag, env, manifest);
30
+ let url;
31
+ try {
32
+ url = new URL(base);
33
+ } catch {
34
+ throw usageError(`The base URL "${base}" is not a valid URL. Pass a full URL such as https://api.example.com/v1.`);
35
+ }
36
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') throw usageError(`The base URL "${base}" must start with https:// or http://.`);
37
+ return { base, url };
38
+ }
39
+
40
+ /** Seconds to wait for each response, from --timeout (default 60, 0 waits forever). */
41
+ export function parseTimeout(raw) {
42
+ if (raw === undefined) return 60;
43
+ const seconds = Number(raw);
44
+ if (raw.trim() === '' || !Number.isFinite(seconds) || seconds < 0) {
45
+ throw usageError(`--timeout takes a number of seconds (0 waits forever), not "${raw}".`);
46
+ }
47
+ return seconds;
48
+ }
49
+
50
+ /** The global flags a command accepts (`--all` only on paginated commands). */
51
+ export function globalFlagsFor(cmd) {
52
+ return GLOBAL_FLAGS.filter((g) => !g.paginatedOnly || cmd.pagination);
53
+ }
54
+
55
+ /**
56
+ * Splits argv into positionals, global flag values and operation flag values.
57
+ * @param {Command} cmd
58
+ * @param {string[]} argv
59
+ */
60
+ function parseArgv(cmd, argv) {
61
+ const globals = new Map(globalFlagsFor(cmd).map((g) => [g.flag, g]));
62
+ const flags = new Map(cmd.flags.map((f) => [f.flag, f]));
63
+ /** @type {string[]} */
64
+ const positionals = [];
65
+ /** @type {Record<string, string>} */
66
+ const global = {};
67
+ /** @type {Map<Flag, string[]>} */
68
+ const values = new Map();
69
+
70
+ for (let i = 0; i < argv.length; i++) {
71
+ const token = argv[i];
72
+ if (token === '--') {
73
+ positionals.push(...argv.slice(i + 1));
74
+ break;
75
+ }
76
+ if (!token.startsWith('--')) {
77
+ positionals.push(token);
78
+ continue;
79
+ }
80
+ const eq = token.indexOf('=');
81
+ const name = token.slice(2, eq === -1 ? undefined : eq);
82
+ const def = globals.get(name) ?? flags.get(name);
83
+ if (!def) {
84
+ const hint = nearest(name, [...globals.keys(), ...flags.keys()]).map((n) => `--${n}`);
85
+ throw usageError(`Unknown flag --${name} for ${cmd.name}.${hint.length ? ` Did you mean ${hint.join(', ')}?` : ''} Run socialapi ${cmd.name} --help to see its flags.`);
86
+ }
87
+ let value;
88
+ if (def.type === 'boolean') {
89
+ value = eq === -1 ? 'true' : token.slice(eq + 1);
90
+ if (value !== 'true' && value !== 'false') throw usageError(`--${name} takes true or false, not "${value}".`);
91
+ } else if (eq !== -1) {
92
+ value = token.slice(eq + 1);
93
+ } else if (i + 1 < argv.length) {
94
+ value = argv[++i];
95
+ } else {
96
+ throw usageError(`--${name} needs a value.`);
97
+ }
98
+ if ('in' in def) values.set(def, [...(values.get(def) ?? []), value]);
99
+ else global[name] = value;
100
+ }
101
+ return { positionals, global, values };
102
+ }
103
+
104
+ function parseJson(raw, what) {
105
+ try {
106
+ return JSON.parse(raw);
107
+ } catch (error) {
108
+ throw usageError(`${what} is not valid JSON (${error instanceof Error ? error.message : error}).`);
109
+ }
110
+ }
111
+
112
+ function checkEnum(value, values, what) {
113
+ if (values && !values.map(String).includes(String(value))) {
114
+ throw usageError(`${what} must be one of ${values.join(', ')}, not "${value}".`);
115
+ }
116
+ }
117
+
118
+ /** Converts one raw text value to the given scalar type. */
119
+ function scalar(raw, type, what) {
120
+ if (type === 'integer') {
121
+ if (!/^-?\d+$/.test(raw)) throw usageError(`${what} takes an integer, not "${raw}".`);
122
+ return Number(raw);
123
+ }
124
+ if (type === 'number') {
125
+ if (raw.trim() === '' || !Number.isFinite(Number(raw))) throw usageError(`${what} takes a number, not "${raw}".`);
126
+ return Number(raw);
127
+ }
128
+ if (type === 'boolean') {
129
+ if (raw !== 'true' && raw !== 'false') throw usageError(`${what} takes true or false, not "${raw}".`);
130
+ return raw === 'true';
131
+ }
132
+ if (type === 'json') return parseJson(raw, what);
133
+ return raw;
134
+ }
135
+
136
+ /**
137
+ * Converts the raw values of a flag to its typed value.
138
+ * @param {Flag} flag
139
+ * @param {string[]} raws
140
+ */
141
+ function convert(flag, raws) {
142
+ const what = `--${flag.flag}`;
143
+ if (flag.type === 'array') {
144
+ const items = [];
145
+ for (const raw of raws) {
146
+ if (raw.trimStart().startsWith('[')) {
147
+ const parsed = parseJson(raw, what);
148
+ if (!Array.isArray(parsed)) throw usageError(`${what} takes a JSON array.`);
149
+ items.push(...parsed);
150
+ } else if (flag.items === 'json') {
151
+ items.push(parseJson(raw, what));
152
+ } else {
153
+ items.push(...raw.split(',').map((part) => scalar(part, flag.items, what)));
154
+ }
155
+ }
156
+ for (const item of items) checkEnum(item, flag.enum, what);
157
+ return items;
158
+ }
159
+ const raw = raws[raws.length - 1];
160
+ if (flag.type === 'object') {
161
+ const parsed = parseJson(raw, what);
162
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw usageError(`${what} takes a JSON object.`);
163
+ return parsed;
164
+ }
165
+ const value = scalar(raw, flag.type, what);
166
+ checkEnum(value, flag.enum, what);
167
+ return value;
168
+ }
169
+
170
+ /** Reads --data: inline JSON, @file, or - for stdin. */
171
+ async function readData(raw, stdin) {
172
+ let source = raw;
173
+ if (raw === '-') source = await text(stdin);
174
+ else if (raw.startsWith('@')) {
175
+ try {
176
+ source = readFileSync(raw.slice(1), 'utf8');
177
+ } catch (error) {
178
+ throw usageError(`Could not read the --data file ${raw.slice(1)} (${error?.code ?? error}).`);
179
+ }
180
+ }
181
+ return parseJson(source, '--data');
182
+ }
183
+
184
+ /**
185
+ * Builds the multipart body; file fields hold a path to read.
186
+ * @param {Command} cmd
187
+ * @param {Record<string, any>} fields
188
+ */
189
+ function formData(cmd, fields) {
190
+ const form = new FormData();
191
+ for (const [name, value] of Object.entries(fields)) {
192
+ const flag = cmd.flags.find((f) => f.in === 'body' && f.name === name);
193
+ if (flag?.file) {
194
+ let bytes;
195
+ try {
196
+ bytes = readFileSync(String(value));
197
+ } catch (error) {
198
+ throw usageError(`Could not read the file ${value} for --${flag.flag} (${error?.code ?? error}).`);
199
+ }
200
+ form.append(name, new Blob([bytes]), basename(String(value)));
201
+ } else if (Array.isArray(value) && value.every((v) => typeof v !== 'object')) {
202
+ for (const item of value) form.append(name, String(item));
203
+ } else {
204
+ form.append(name, typeof value === 'string' ? value : JSON.stringify(value));
205
+ }
206
+ }
207
+ return form;
208
+ }
209
+
210
+ /**
211
+ * @param {Command} cmd
212
+ * @param {string[]} argv the arguments after the command name
213
+ * @param {Context} ctx
214
+ */
215
+ export async function runOperation(cmd, argv, ctx) {
216
+ const { positionals, global, values } = parseArgv(cmd, argv);
217
+ const usage = `Usage: socialapi ${[cmd.name, ...cmd.args.map((a) => `<${a.name}>`)].join(' ')} [flags]`;
218
+
219
+ if (positionals.length < cmd.args.length) {
220
+ throw usageError(`Missing argument <${cmd.args[positionals.length].name}>. ${usage}`);
221
+ }
222
+ if (positionals.length > cmd.args.length) {
223
+ throw usageError(`Unexpected argument "${positionals[cmd.args.length]}". ${usage}`);
224
+ }
225
+ cmd.args.forEach((arg, i) => checkEnum(positionals[i], arg.enum, `<${arg.name}>`));
226
+
227
+ /** @type {Record<'query' | 'header' | 'body', Record<string, any>>} */
228
+ const fields = { query: {}, header: {}, body: {} };
229
+ for (const [flag, raws] of values) fields[flag.in][flag.name] = convert(flag, raws);
230
+
231
+ let body;
232
+ if (global.data !== undefined) {
233
+ if (!cmd.body) throw usageError(`${cmd.name} takes no request body, so --data does not apply.`);
234
+ body = await readData(global.data, ctx.stdin);
235
+ }
236
+ if (Object.keys(fields.body).length) {
237
+ if (body !== undefined && (!body || typeof body !== 'object' || Array.isArray(body))) {
238
+ throw usageError('--data must be a JSON object when it is combined with body flags.');
239
+ }
240
+ body = { ...body, ...fields.body };
241
+ }
242
+ if (body === undefined && cmd.body?.required) body = {};
243
+
244
+ for (const flag of cmd.flags.filter((f) => f.required)) {
245
+ const present = flag.in === 'body' ? body && typeof body === 'object' && flag.name in body : flag.name in fields[flag.in];
246
+ if (!present) throw usageError(`Missing required ${flag.in === 'body' ? 'field' : 'flag'} --${flag.flag}${global.data !== undefined && flag.in === 'body' ? ` (or "${flag.name}" in --data)` : ''}. Run socialapi ${cmd.name} --help for details.`);
247
+ }
248
+
249
+ const timeoutSeconds = parseTimeout(global.timeout);
250
+ const { base, url: baseUrl } = parseBaseUrl(global['base-url'], ctx.env, ctx.manifest);
251
+
252
+ if (cmd.response === 'binary' && global.output === undefined && ctx.stdout.isTTY) {
253
+ throw usageError(`${cmd.name} returns binary data. Pass --output <file>, or pipe stdout to a file or another command.`);
254
+ }
255
+
256
+ let token;
257
+ if (cmd.auth) {
258
+ const credential = resolveCredential({ apiKeyFlag: global['api-key'], env: ctx.env, baseUrl: base });
259
+ if (!credential) throw noCredential();
260
+ token = credential.token;
261
+ }
262
+
263
+ const path = cmd.path.replace(/\{([^}]+)\}/g, (_, name) => encodeURIComponent(positionals[cmd.args.findIndex((a) => a.name === name)]));
264
+ const query = new URLSearchParams();
265
+ for (const [name, value] of Object.entries(fields.query)) {
266
+ for (const item of Array.isArray(value) ? value : [value]) query.append(name, typeof item === 'object' ? JSON.stringify(item) : String(item));
267
+ }
268
+ /** @type {Record<string, string>} */
269
+ const headers = {};
270
+ for (const [name, value] of Object.entries(fields.header)) headers[name] = Array.isArray(value) ? value.join(',') : typeof value === 'object' ? JSON.stringify(value) : String(value);
271
+
272
+ let payload;
273
+ if (body !== undefined) {
274
+ if (cmd.body?.kind === 'multipart') payload = formData(cmd, body);
275
+ else {
276
+ payload = JSON.stringify(body);
277
+ headers['content-type'] = 'application/json';
278
+ }
279
+ }
280
+
281
+ const request = (cursor) => {
282
+ const q = new URLSearchParams(query);
283
+ if (cursor !== undefined) q.set('cursor', cursor);
284
+ const url = new URL(`${baseUrl.href.replace(/\/+$/, '')}${path}${q.size ? `?${q}` : ''}`);
285
+ return send({ method: cmd.method, url, headers, body: payload, token, timeoutSeconds, verbose: global.verbose === 'true', stderr: ctx.stderr });
286
+ };
287
+ const pretty = global.pretty === 'true' || Boolean(ctx.stdout.isTTY);
288
+
289
+ const failed = (response) => {
290
+ const raw = response.body.toString('utf8');
291
+ ctx.stderr.write(raw.endsWith('\n') || raw === '' ? raw : `${raw}\n`);
292
+ return EXIT.apiError;
293
+ };
294
+
295
+ if (global.all === 'true' && cmd.pagination) {
296
+ const { list, cursor: cursorPath } = cmd.pagination;
297
+ const items = [];
298
+ const seen = new Set();
299
+ let cursor;
300
+ let last;
301
+ for (;;) {
302
+ const response = await request(cursor);
303
+ if (response.status >= 400) return failed(response);
304
+ last = response.body.length ? JSON.parse(response.body.toString('utf8')) : {};
305
+ items.push(...(Array.isArray(last?.[list]) ? last[list] : []));
306
+ const holder = cursorPath.length === 1 ? last : last?.[cursorPath[0]];
307
+ const next = holder?.next_cursor;
308
+ if (holder && typeof holder === 'object') delete holder.next_cursor;
309
+ if (!next || seen.has(next)) break;
310
+ seen.add(next);
311
+ cursor = String(next);
312
+ }
313
+ last[list] = items;
314
+ return output(Buffer.from(JSON.stringify(last)), last);
315
+ }
316
+
317
+ const response = await request(undefined);
318
+ if (response.status >= 400) return failed(response);
319
+ if (cmd.response === 'binary' || global.output !== undefined || response.body.length === 0) return output(response.body);
320
+ const raw = response.body.toString('utf8');
321
+ try {
322
+ return output(response.body, JSON.parse(raw));
323
+ } catch {
324
+ return output(response.body);
325
+ }
326
+
327
+ /**
328
+ * Writes the body to --output, or prints it: JSON formatted, anything else as is.
329
+ * @param {Buffer} bytes
330
+ * @param {any} [json]
331
+ */
332
+ function output(bytes, json) {
333
+ if (global.output !== undefined) {
334
+ try {
335
+ writeFileSync(global.output, bytes);
336
+ } catch (error) {
337
+ throw usageError(`Could not write to ${global.output} (${error?.code ?? error}).`);
338
+ }
339
+ } else if (json !== undefined) {
340
+ writeJson(ctx.stdout, json, pretty);
341
+ } else if (bytes.length) {
342
+ ctx.stdout.write(bytes);
343
+ }
344
+ return EXIT.ok;
345
+ }
346
+ }
package/src/output.mjs ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Prints a JSON value: indented with 2 spaces when pretty, one compact line otherwise.
3
+ * @param {{ write(chunk: string): any }} stream
4
+ * @param {any} value
5
+ * @param {boolean} pretty
6
+ */
7
+ export function writeJson(stream, value, pretty) {
8
+ stream.write(`${JSON.stringify(value, null, pretty ? 2 : undefined)}\n`);
9
+ }
10
+
11
+ /**
12
+ * Prints rows as two aligned columns.
13
+ * @param {string[][]} rows
14
+ * @param {string} [indent]
15
+ */
16
+ export function columns(rows, indent = ' ') {
17
+ const width = Math.max(0, ...rows.map(([left]) => left.length));
18
+ return rows.map(([left, right]) => (right ? `${indent}${left.padEnd(width)} ${right}` : `${indent}${left}`)).join('\n');
19
+ }
@@ -0,0 +1,40 @@
1
+ import { usageError } from './errors.mjs';
2
+
3
+ /** Levenshtein distance between two strings. */
4
+ function distance(a, b) {
5
+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
6
+ for (let i = 1; i <= a.length; i++) {
7
+ const current = [i];
8
+ for (let j = 1; j <= b.length; j++) {
9
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
10
+ }
11
+ previous = current;
12
+ }
13
+ return previous[b.length];
14
+ }
15
+
16
+ /**
17
+ * The nearest names to `input`: close in spelling, or containing it.
18
+ * @param {string} input
19
+ * @param {string[]} names
20
+ * @param {number} [max]
21
+ */
22
+ export function nearest(input, names, max = 5) {
23
+ const limit = Math.max(2, Math.floor(input.length / 3));
24
+ return names
25
+ .map((name) => ({ name, d: distance(input, name) }))
26
+ .filter(({ name, d }) => d <= limit || (input.length >= 3 && name.includes(input)))
27
+ .sort((a, b) => a.d - b.d || a.name.localeCompare(b.name))
28
+ .slice(0, max)
29
+ .map(({ name }) => name);
30
+ }
31
+
32
+ /**
33
+ * The error for a command name that is neither generated nor built in.
34
+ * @param {string} name
35
+ * @param {{ manifest: { commands: { name: string }[] }, builtins: { name: string }[] }} ctx
36
+ */
37
+ export function unknownCommand(name, ctx) {
38
+ const hint = nearest(name, [...ctx.manifest.commands.map((c) => c.name), ...ctx.builtins.map((b) => b.name)]);
39
+ return usageError(`Unknown command "${name}".${hint.length ? ` Did you mean ${hint.join(', ')}?` : ''} Run socialapi commands <text> to search the commands.`);
40
+ }
@@ -0,0 +1,4 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ /** The `version` of the package's own package.json. */
4
+ export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;