socialapi-cli 0.0.0-stage → 1.17.7
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 +279 -2
- package/SKILL.md +99 -0
- package/bin/socialapi.mjs +4 -0
- package/generated/commands.json +6891 -0
- package/package.json +41 -4
- package/src/auth/api.mjs +103 -0
- package/src/auth/config.mjs +62 -0
- package/src/auth/login.mjs +312 -0
- package/src/auth/logout.mjs +41 -0
- package/src/auth/whoami.mjs +13 -0
- package/src/builtins/commands.mjs +36 -0
- package/src/builtins/completion.mjs +106 -0
- package/src/builtins/help.mjs +17 -0
- package/src/builtins/index.mjs +18 -0
- package/src/builtins/skill.mjs +12 -0
- package/src/builtins/version.mjs +12 -0
- package/src/credentials.mjs +22 -0
- package/src/errors.mjs +46 -0
- package/src/flags.mjs +19 -0
- package/src/help.mjs +83 -0
- package/src/http.mjs +72 -0
- package/src/main.mjs +87 -0
- package/src/manifest.mjs +6 -0
- package/src/naming.mjs +15 -0
- package/src/operation.mjs +346 -0
- package/src/output.mjs +19 -0
- package/src/suggest.mjs +40 -0
- package/src/version.mjs +4 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Shell completion scripts built from the manifest: command names and each command's flags.
|
|
2
|
+
import { usageError } from '../errors.mjs';
|
|
3
|
+
import { globalFlagsFor } from '../operation.mjs';
|
|
4
|
+
|
|
5
|
+
const SHELLS = ['bash', 'zsh', 'fish'];
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Every completable entry: generated commands, then built-ins, each with its flags.
|
|
9
|
+
* @param {import('../main.mjs').Context} ctx
|
|
10
|
+
* @returns {{ name: string, summary: string, flags: string[], words?: string[] }[]}
|
|
11
|
+
*/
|
|
12
|
+
function entries(ctx) {
|
|
13
|
+
const generated = ctx.manifest.commands.map((c) => ({
|
|
14
|
+
name: c.name,
|
|
15
|
+
summary: c.summary,
|
|
16
|
+
flags: [...c.flags.map((f) => f.flag), ...globalFlagsFor(c).map((g) => g.flag)],
|
|
17
|
+
}));
|
|
18
|
+
const builtin = ctx.builtins.map((b) => ({
|
|
19
|
+
name: b.name,
|
|
20
|
+
summary: b.summary,
|
|
21
|
+
flags: [...b.usage.matchAll(/--([a-z-]+)/g)].map((m) => m[1]),
|
|
22
|
+
words: b.name === 'completion' ? SHELLS : b.name === 'help' ? ctx.manifest.commands.map((c) => c.name) : undefined,
|
|
23
|
+
}));
|
|
24
|
+
return [...generated, ...builtin];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const sq = (text) => `'${text.replace(/'/g, `'\\''`)}'`;
|
|
28
|
+
|
|
29
|
+
function bash(list) {
|
|
30
|
+
const cases = list.map((e) => ` ${e.name}) words="${[...(e.words ?? []), ...e.flags.map((f) => `--${f}`)].join(' ')}" ;;`);
|
|
31
|
+
return `# bash completion for socialapi. Load it with: source <(socialapi completion bash)
|
|
32
|
+
_socialapi_complete() {
|
|
33
|
+
local cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
34
|
+
local words=""
|
|
35
|
+
COMPREPLY=()
|
|
36
|
+
if [ "$COMP_CWORD" -eq 1 ]; then
|
|
37
|
+
words="${list.map((e) => e.name).join(' ')}"
|
|
38
|
+
else
|
|
39
|
+
case "\${COMP_WORDS[1]}" in
|
|
40
|
+
${cases.join('\n')}
|
|
41
|
+
esac
|
|
42
|
+
case "$cur" in
|
|
43
|
+
-*) ;;
|
|
44
|
+
*) [ "$COMP_CWORD" -eq 2 ] && [ "\${COMP_WORDS[1]}" = completion -o "\${COMP_WORDS[1]}" = help ] || return 0 ;;
|
|
45
|
+
esac
|
|
46
|
+
fi
|
|
47
|
+
COMPREPLY=($(compgen -W "$words" -- "$cur"))
|
|
48
|
+
}
|
|
49
|
+
complete -o default -F _socialapi_complete socialapi
|
|
50
|
+
`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function zsh(list) {
|
|
54
|
+
const described = list.map((e) => ` ${sq(`${e.name}:${e.summary}`)}`);
|
|
55
|
+
const cases = list.map((e) => ` ${e.name}) candidates=(${[...(e.words ?? []), ...e.flags.map((f) => `--${f}`)].join(' ')}) ;;`);
|
|
56
|
+
return `#compdef socialapi
|
|
57
|
+
# zsh completion for socialapi. Load it with: source <(socialapi completion zsh)
|
|
58
|
+
_socialapi() {
|
|
59
|
+
local -a commands candidates
|
|
60
|
+
commands=(
|
|
61
|
+
${described.join('\n')}
|
|
62
|
+
)
|
|
63
|
+
if (( CURRENT == 2 )); then
|
|
64
|
+
_describe 'command' commands
|
|
65
|
+
return
|
|
66
|
+
fi
|
|
67
|
+
case "\${words[2]}" in
|
|
68
|
+
${cases.join('\n')}
|
|
69
|
+
esac
|
|
70
|
+
if [[ "\${words[CURRENT]}" == -* || "\${words[2]}" == completion || "\${words[2]}" == help ]]; then
|
|
71
|
+
compadd -- "\${candidates[@]}"
|
|
72
|
+
else
|
|
73
|
+
_files
|
|
74
|
+
fi
|
|
75
|
+
}
|
|
76
|
+
compdef _socialapi socialapi
|
|
77
|
+
`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function fish(list) {
|
|
81
|
+
const q = (text) => `'${text.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
|
|
82
|
+
const lines = [
|
|
83
|
+
'# fish completion for socialapi. Load it with: socialapi completion fish | source',
|
|
84
|
+
...list.map((e) => `complete -c socialapi -n __fish_use_subcommand -f -a ${q(e.name)} -d ${q(e.summary)}`),
|
|
85
|
+
];
|
|
86
|
+
for (const e of list) {
|
|
87
|
+
const when = q(`__fish_seen_subcommand_from ${e.name}`);
|
|
88
|
+
if (e.words) lines.push(`complete -c socialapi -n ${when} -f -a ${q(e.words.join(' '))}`);
|
|
89
|
+
for (const flag of e.flags) lines.push(`complete -c socialapi -n ${when} -l ${q(flag)}`);
|
|
90
|
+
}
|
|
91
|
+
return `${lines.join('\n')}\n`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** @type {import('./index.mjs').Builtin} */
|
|
95
|
+
export const completion = {
|
|
96
|
+
name: 'completion',
|
|
97
|
+
usage: 'completion bash|zsh|fish',
|
|
98
|
+
summary: 'Print a shell completion script for command names and flags.',
|
|
99
|
+
run(args, ctx) {
|
|
100
|
+
const shell = args.find((a) => !a.startsWith('--'));
|
|
101
|
+
if (!shell || !SHELLS.includes(shell)) throw usageError('Name a shell: socialapi completion bash, socialapi completion zsh or socialapi completion fish.');
|
|
102
|
+
const list = entries(ctx);
|
|
103
|
+
ctx.stdout.write(shell === 'bash' ? bash(list) : shell === 'zsh' ? zsh(list) : fish(list));
|
|
104
|
+
return 0;
|
|
105
|
+
},
|
|
106
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { builtinHelp, commandHelp, globalHelp } from '../help.mjs';
|
|
2
|
+
import { unknownCommand } from '../suggest.mjs';
|
|
3
|
+
|
|
4
|
+
/** @type {import('./index.mjs').Builtin} */
|
|
5
|
+
export const help = {
|
|
6
|
+
name: 'help',
|
|
7
|
+
usage: 'help [command]',
|
|
8
|
+
summary: 'Show the list of commands, or the help of one command.',
|
|
9
|
+
run(args, ctx) {
|
|
10
|
+
const name = args.find((a) => !a.startsWith('--'));
|
|
11
|
+
const builtin = name && ctx.builtins.find((b) => b.name === name);
|
|
12
|
+
const cmd = name && ctx.manifest.commands.find((c) => c.name === name);
|
|
13
|
+
if (name && !builtin && !cmd) throw unknownCommand(name, ctx);
|
|
14
|
+
ctx.stdout.write(builtin ? builtinHelp(builtin) : cmd ? commandHelp(cmd) : globalHelp(ctx.manifest, ctx.builtins));
|
|
15
|
+
return 0;
|
|
16
|
+
},
|
|
17
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// The single table of built-in commands. Help, `commands` and completion read it.
|
|
2
|
+
import { login } from '../auth/login.mjs';
|
|
3
|
+
import { logout } from '../auth/logout.mjs';
|
|
4
|
+
import { whoami } from '../auth/whoami.mjs';
|
|
5
|
+
import { commands } from './commands.mjs';
|
|
6
|
+
import { completion } from './completion.mjs';
|
|
7
|
+
import { help } from './help.mjs';
|
|
8
|
+
import { skill } from './skill.mjs';
|
|
9
|
+
import { version } from './version.mjs';
|
|
10
|
+
|
|
11
|
+
/** Names no generated command may take. */
|
|
12
|
+
export const RESERVED_NAMES = ['login', 'logout', 'whoami', 'commands', 'completion', 'skill', 'help', 'version'];
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @typedef {{ name: string, usage: string, summary: string, run: (args: string[], ctx: import('../main.mjs').Context) => Promise<number> | number }} Builtin
|
|
16
|
+
* @type {Builtin[]}
|
|
17
|
+
*/
|
|
18
|
+
export const builtins = [login, logout, whoami, commands, completion, skill, help, version];
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
/** @type {import('./index.mjs').Builtin} */
|
|
4
|
+
export const skill = {
|
|
5
|
+
name: 'skill',
|
|
6
|
+
usage: 'skill',
|
|
7
|
+
summary: 'Print SKILL.md, the guide for AI agents that use socialapi.',
|
|
8
|
+
run(args, ctx) {
|
|
9
|
+
ctx.stdout.write(readFileSync(new URL('../../SKILL.md', import.meta.url), 'utf8'));
|
|
10
|
+
return 0;
|
|
11
|
+
},
|
|
12
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { VERSION } from '../version.mjs';
|
|
2
|
+
|
|
3
|
+
/** @type {import('./index.mjs').Builtin} */
|
|
4
|
+
export const version = {
|
|
5
|
+
name: 'version',
|
|
6
|
+
usage: 'version',
|
|
7
|
+
summary: 'Print the version of socialapi.',
|
|
8
|
+
run(args, ctx) {
|
|
9
|
+
ctx.stdout.write(`${VERSION}\n`);
|
|
10
|
+
return 0;
|
|
11
|
+
},
|
|
12
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Where the credential comes from, in order: --api-key, then SOCIALAPI_API_KEY, then the key
|
|
2
|
+
// stored by `socialapi login` (only for the base URL it was saved for).
|
|
3
|
+
import { readConfig } from './auth/config.mjs';
|
|
4
|
+
import { CliError } from './errors.mjs';
|
|
5
|
+
|
|
6
|
+
/** A base URL without its trailing slashes, for comparing two of them. */
|
|
7
|
+
export const sameBaseUrl = (a, b) => a.replace(/\/+$/, '') === b.replace(/\/+$/, '');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {{ apiKeyFlag?: string, env: Record<string, string | undefined>, baseUrl: string }} options
|
|
11
|
+
* @returns {{ token: string, source: 'flag' | 'env' | 'stored' } | null}
|
|
12
|
+
*/
|
|
13
|
+
export function resolveCredential({ apiKeyFlag, env, baseUrl }) {
|
|
14
|
+
if (apiKeyFlag) return { token: apiKeyFlag, source: 'flag' };
|
|
15
|
+
if (env.SOCIALAPI_API_KEY) return { token: env.SOCIALAPI_API_KEY, source: 'env' };
|
|
16
|
+
const stored = readConfig(env);
|
|
17
|
+
if (stored && sameBaseUrl(stored.base_url, baseUrl)) return { token: stored.api_key, source: 'stored' };
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const noCredential = () =>
|
|
22
|
+
new CliError('no_credential', 'No API key found. Run socialapi login, set the SOCIALAPI_API_KEY environment variable, or pass --api-key.');
|
package/src/errors.mjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Errors raised by the CLI itself. They print as {"error":{"code","message"}} on stderr,
|
|
2
|
+
// or as the API's error body unchanged when they carry one.
|
|
3
|
+
|
|
4
|
+
export const EXIT = { ok: 0, apiError: 1, usage: 2, unreachable: 3 };
|
|
5
|
+
|
|
6
|
+
export class CliError extends Error {
|
|
7
|
+
/**
|
|
8
|
+
* @param {'invalid_usage' | 'no_credential' | 'insecure_base_url' | 'network_error' | 'timeout' | string} code
|
|
9
|
+
* @param {string} message what happened and what to do
|
|
10
|
+
* @param {number} [exitCode]
|
|
11
|
+
*/
|
|
12
|
+
constructor(code, message, exitCode = EXIT.usage) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.code = code;
|
|
15
|
+
this.exitCode = exitCode;
|
|
16
|
+
/** @type {string | undefined} the API's error body, printed as is instead of the envelope */
|
|
17
|
+
this.body = undefined;
|
|
18
|
+
/** @type {number | undefined} the HTTP status of the API response this error comes from */
|
|
19
|
+
this.status = undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The error for a failed API response (exit 1): the API's error body unchanged, or an OAuth error
|
|
25
|
+
* (`{"error":"access_denied","error_description":"..."}`) turned into the CLI envelope.
|
|
26
|
+
* @param {{ status: number, body: Buffer }} response
|
|
27
|
+
*/
|
|
28
|
+
export function responseError(response) {
|
|
29
|
+
const raw = response.body.toString('utf8');
|
|
30
|
+
let parsed;
|
|
31
|
+
try {
|
|
32
|
+
parsed = JSON.parse(raw);
|
|
33
|
+
} catch {}
|
|
34
|
+
if (parsed && typeof parsed.error === 'string') {
|
|
35
|
+
const error = new CliError(parsed.error, parsed.error_description || `The server answered ${response.status} ${parsed.error}.`, EXIT.apiError);
|
|
36
|
+
error.status = response.status;
|
|
37
|
+
return error;
|
|
38
|
+
}
|
|
39
|
+
const error = new CliError(parsed?.error?.code ?? 'api_error', parsed?.error?.message ?? `The server answered ${response.status}.`, EXIT.apiError);
|
|
40
|
+
error.body = raw;
|
|
41
|
+
error.status = response.status;
|
|
42
|
+
return error;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param {string} message */
|
|
46
|
+
export const usageError = (message) => new CliError('invalid_usage', message);
|
package/src/flags.mjs
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Global flags, shared by the generator (collision rule) and the runtime.
|
|
2
|
+
|
|
3
|
+
/** @typedef {{ flag: string, type: 'string' | 'number' | 'boolean', value?: string, description: string, paginatedOnly?: boolean }} GlobalFlag */
|
|
4
|
+
|
|
5
|
+
/** @type {GlobalFlag[]} */
|
|
6
|
+
export const GLOBAL_FLAGS = [
|
|
7
|
+
{ flag: 'api-key', type: 'string', value: 'key', description: 'API key to send. Default: the SOCIALAPI_API_KEY environment variable, then the key stored by socialapi login.' },
|
|
8
|
+
{ flag: 'base-url', type: 'string', value: 'url', description: 'API base URL. Default: the SOCIALAPI_BASE_URL environment variable, then the URL from the API reference.' },
|
|
9
|
+
{ flag: 'data', type: 'string', value: 'json', description: 'Whole JSON request body: inline JSON, @file to read a file, or - to read stdin. Individual flags override its top-level fields.' },
|
|
10
|
+
{ flag: 'output', type: 'string', value: 'file', description: 'Write the response body to this file instead of stdout.' },
|
|
11
|
+
{ flag: 'pretty', type: 'boolean', description: 'Print JSON indented, even when stdout is not a terminal.' },
|
|
12
|
+
{ flag: 'timeout', type: 'number', value: 'seconds', description: 'Seconds to wait for each response (default 60, 0 waits forever).' },
|
|
13
|
+
{ flag: 'verbose', type: 'boolean', description: 'Print the request line, the status and the request id on stderr.' },
|
|
14
|
+
{ flag: 'help', type: 'boolean', description: 'Show help for the command.' },
|
|
15
|
+
{ flag: 'all', type: 'boolean', description: 'Follow next_cursor and print every page as one document.', paginatedOnly: true },
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
/** Names an operation flag can never take; `all` is reserved on every command. */
|
|
19
|
+
export const GLOBAL_FLAG_NAMES = GLOBAL_FLAGS.map((f) => f.flag);
|
package/src/help.mjs
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// Help text. Generated commands use only the summaries and descriptions of the spec.
|
|
2
|
+
import { kebabCase } from './naming.mjs';
|
|
3
|
+
import { globalFlagsFor } from './operation.mjs';
|
|
4
|
+
import { GLOBAL_FLAGS } from './flags.mjs';
|
|
5
|
+
import { columns } from './output.mjs';
|
|
6
|
+
|
|
7
|
+
/** @typedef {import('../scripts/generate.mjs').Command} Command */
|
|
8
|
+
|
|
9
|
+
/** @param {import('../scripts/generate.mjs').Flag} f */
|
|
10
|
+
function valueHint(f) {
|
|
11
|
+
if (f.file) return ' <file>';
|
|
12
|
+
if (f.type === 'boolean') return '';
|
|
13
|
+
if (f.type === 'array') return f.items === 'json' ? ' <json-array>' : ` <${f.items},...>`;
|
|
14
|
+
if (f.type === 'object' || f.type === 'json') return ' <json>';
|
|
15
|
+
return ` <${f.type}>`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Flag and argument rows stay on one line each. */
|
|
19
|
+
const oneLine = (text) => text.replace(/\s+/g, ' ').trim();
|
|
20
|
+
|
|
21
|
+
function globalRows(flags) {
|
|
22
|
+
return flags.map((g) => [`--${g.flag}${g.value ? ` <${g.value}>` : ''}`, g.description]);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {import('../scripts/generate.mjs').Manifest} manifest
|
|
27
|
+
* @param {import('./builtins/index.mjs').Builtin[]} builtins
|
|
28
|
+
*/
|
|
29
|
+
export function globalHelp(manifest, builtins) {
|
|
30
|
+
const sections = [
|
|
31
|
+
'socialapi: the command-line client for the SocialAPI REST API.',
|
|
32
|
+
'Usage: socialapi <command> [arguments] [flags]',
|
|
33
|
+
];
|
|
34
|
+
for (const tag of manifest.tags) {
|
|
35
|
+
const rows = manifest.commands.filter((c) => c.tag === tag).map((c) => [c.name, c.summary]);
|
|
36
|
+
sections.push(`${tag}:\n${columns(rows)}`);
|
|
37
|
+
}
|
|
38
|
+
sections.push(`Built-in commands:\n${columns(builtins.map((b) => [b.usage, b.summary]))}`);
|
|
39
|
+
sections.push(`Global flags:\n${columns(globalRows(GLOBAL_FLAGS))}`);
|
|
40
|
+
sections.push('Run socialapi <command> --help to see the arguments and flags of a command.');
|
|
41
|
+
return `${sections.join('\n\n')}\n`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** @param {Command} cmd */
|
|
45
|
+
export function commandHelp(cmd) {
|
|
46
|
+
const usage = [cmd.name, ...cmd.args.map((a) => `<${a.name}>`)].join(' ');
|
|
47
|
+
const sections = [`Usage: socialapi ${usage} [flags]`];
|
|
48
|
+
if (cmd.summary) sections.push(cmd.summary);
|
|
49
|
+
if (cmd.description && cmd.description !== cmd.summary) sections.push(cmd.description);
|
|
50
|
+
sections.push(`${cmd.method} ${cmd.path}`);
|
|
51
|
+
|
|
52
|
+
if (cmd.args.length) {
|
|
53
|
+
const rows = cmd.args.map((a) => [`<${a.name}>`, [`${a.type}, required.`, a.enum && `One of: ${a.enum.join(', ')}.`, a.description].filter(Boolean).join(' ')]).map(([k, v]) => [k, oneLine(v)]);
|
|
54
|
+
sections.push(`Arguments:\n${columns(rows)}`);
|
|
55
|
+
}
|
|
56
|
+
if (cmd.flags.length) {
|
|
57
|
+
const rows = cmd.flags.map((f) => {
|
|
58
|
+
const renamed = f.flag !== kebabCase(f.name);
|
|
59
|
+
const details = [
|
|
60
|
+
f.required && 'Required.',
|
|
61
|
+
f.enum && `One of: ${f.enum.join(', ')}.`,
|
|
62
|
+
f.description,
|
|
63
|
+
renamed && `(Sends the ${f.in} field "${f.name}": the flag is renamed because --${kebabCase(f.name)} is taken.)`,
|
|
64
|
+
];
|
|
65
|
+
return [`--${f.flag}${valueHint(f)}`, oneLine(details.filter(Boolean).join(' '))];
|
|
66
|
+
});
|
|
67
|
+
sections.push(`Flags:\n${columns(rows)}`);
|
|
68
|
+
}
|
|
69
|
+
if (cmd.body) {
|
|
70
|
+
sections.push(
|
|
71
|
+
cmd.body.kind === 'multipart'
|
|
72
|
+
? 'Request body: multipart/form-data. File flags take a file path.'
|
|
73
|
+
: 'Request body: JSON. Pass the whole body with --data; individual flags override its top-level fields.',
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
sections.push(`Global flags:\n${columns(globalRows(globalFlagsFor(cmd)))}`);
|
|
77
|
+
return `${sections.join('\n\n')}\n`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** @param {import('./builtins/index.mjs').Builtin} builtin */
|
|
81
|
+
export function builtinHelp(builtin) {
|
|
82
|
+
return `Usage: socialapi ${builtin.usage}\n\n${builtin.summary}\n`;
|
|
83
|
+
}
|
package/src/http.mjs
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// The single function every request goes through: credential rule, timeout,
|
|
2
|
+
// 429 retry, verbose log and User-Agent.
|
|
3
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
4
|
+
import { CliError, EXIT } from './errors.mjs';
|
|
5
|
+
import { VERSION } from './version.mjs';
|
|
6
|
+
|
|
7
|
+
export const MAX_RETRIES = 3;
|
|
8
|
+
const MAX_RETRY_WAIT_MS = 60_000;
|
|
9
|
+
const LOCAL_HOSTS = ['localhost', '127.0.0.1', '[::1]'];
|
|
10
|
+
|
|
11
|
+
/** A credential is sent only over https, or to localhost. */
|
|
12
|
+
export function isSecureBaseUrl(url) {
|
|
13
|
+
return url.protocol === 'https:' || (url.protocol === 'http:' && LOCAL_HOSTS.includes(url.hostname));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Milliseconds to wait for a Retry-After value (seconds or an HTTP date), capped at 60 seconds.
|
|
18
|
+
* Without a usable value the wait is 1 second.
|
|
19
|
+
* @param {string | null} value
|
|
20
|
+
*/
|
|
21
|
+
export function retryDelayMs(value, now = Date.now()) {
|
|
22
|
+
let ms = 1000;
|
|
23
|
+
if (value && /^\d+(\.\d+)?$/.test(value.trim())) ms = Number(value) * 1000;
|
|
24
|
+
else if (value && !Number.isNaN(Date.parse(value))) ms = Date.parse(value) - now;
|
|
25
|
+
return Math.min(Math.max(ms, 0), MAX_RETRY_WAIT_MS);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @typedef {{ status: number, headers: Headers, body: Buffer }} ApiResponse
|
|
30
|
+
* @param {{ method: string, url: URL, headers?: Record<string, string>, body?: string | FormData, token?: string,
|
|
31
|
+
* timeoutSeconds?: number, verbose?: boolean, stderr: { write(chunk: string): any } }} request
|
|
32
|
+
* @returns {Promise<ApiResponse>}
|
|
33
|
+
*/
|
|
34
|
+
export async function send({ method, url, headers = {}, body, token, timeoutSeconds = 60, verbose = false, stderr }) {
|
|
35
|
+
if (token && !isSecureBaseUrl(url)) {
|
|
36
|
+
throw new CliError(
|
|
37
|
+
'insecure_base_url',
|
|
38
|
+
`The API key is sent only to an https:// base URL or to localhost, and ${url.origin} is neither. Use an https:// base URL.`,
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
const log = (line) => {
|
|
42
|
+
if (verbose) stderr.write(`socialapi: ${token ? line.split(token).join('***') : line}\n`);
|
|
43
|
+
};
|
|
44
|
+
/** @type {Record<string, string>} */
|
|
45
|
+
const requestHeaders = { 'user-agent': `socialapi-cli/${VERSION}`, accept: 'application/json, */*', ...headers };
|
|
46
|
+
if (token) requestHeaders.authorization = `Bearer ${token}`;
|
|
47
|
+
|
|
48
|
+
for (let attempt = 0; ; attempt++) {
|
|
49
|
+
log(`> ${method} ${url.href}`);
|
|
50
|
+
const controller = new AbortController();
|
|
51
|
+
const timer = timeoutSeconds > 0 ? setTimeout(() => controller.abort(), timeoutSeconds * 1000) : undefined;
|
|
52
|
+
/** @type {ApiResponse} */
|
|
53
|
+
let response;
|
|
54
|
+
try {
|
|
55
|
+
const res = await fetch(url, { method, headers: requestHeaders, body, signal: controller.signal });
|
|
56
|
+
response = { status: res.status, headers: res.headers, body: Buffer.from(await res.arrayBuffer()) };
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (controller.signal.aborted) {
|
|
59
|
+
throw new CliError('timeout', `No response from ${url.origin} within ${timeoutSeconds} seconds. Try again, or raise --timeout.`, EXIT.unreachable);
|
|
60
|
+
}
|
|
61
|
+
const cause = error?.cause?.code ?? error?.cause?.message ?? error?.message ?? String(error);
|
|
62
|
+
throw new CliError('network_error', `Could not reach ${url.origin} (${cause}). Check the network connection and the base URL.`, EXIT.unreachable);
|
|
63
|
+
} finally {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
}
|
|
66
|
+
log(`< ${response.status} (request id ${response.headers.get('x-request-id') ?? 'none'})`);
|
|
67
|
+
if (response.status !== 429 || attempt >= MAX_RETRIES) return response;
|
|
68
|
+
const wait = retryDelayMs(response.headers.get('retry-after'));
|
|
69
|
+
log(`rate limited, retrying in ${wait / 1000} seconds`);
|
|
70
|
+
await sleep(wait);
|
|
71
|
+
}
|
|
72
|
+
}
|
package/src/main.mjs
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Entry point: finds the command in argv and runs a built-in or a generated command.
|
|
2
|
+
import { builtins } from './builtins/index.mjs';
|
|
3
|
+
import { CliError, EXIT, usageError } from './errors.mjs';
|
|
4
|
+
import { GLOBAL_FLAGS } from './flags.mjs';
|
|
5
|
+
import { builtinHelp, commandHelp, globalHelp } from './help.mjs';
|
|
6
|
+
import { loadManifest } from './manifest.mjs';
|
|
7
|
+
import { runOperation } from './operation.mjs';
|
|
8
|
+
import { unknownCommand } from './suggest.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @typedef {{ write(chunk: string | Uint8Array): any, isTTY?: boolean }} Output
|
|
12
|
+
* @typedef {{ env: Record<string, string | undefined>, stdin: NodeJS.ReadableStream, stdout: Output, stderr: Output,
|
|
13
|
+
* manifest: import('../scripts/generate.mjs').Manifest, builtins: import('./builtins/index.mjs').Builtin[], loginTimeoutMs: number }} Context
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const VALUE_GLOBALS = GLOBAL_FLAGS.filter((g) => g.type !== 'boolean').map((g) => `--${g.flag}`);
|
|
17
|
+
|
|
18
|
+
/** Index of the command name: the first token that is neither a flag nor the value of a global flag. */
|
|
19
|
+
function commandIndex(argv) {
|
|
20
|
+
for (let i = 0; i < argv.length; i++) {
|
|
21
|
+
if (argv[i] === '--') return i + 1 < argv.length ? i + 1 : -1;
|
|
22
|
+
if (VALUE_GLOBALS.includes(argv[i])) i++;
|
|
23
|
+
else if (!argv[i].startsWith('--')) return i;
|
|
24
|
+
}
|
|
25
|
+
return -1;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Runs the CLI and returns its exit code.
|
|
30
|
+
* @param {string[]} argv
|
|
31
|
+
* `loginTimeoutMs` is how long `socialapi login` waits for the browser (5 minutes; tests shorten it).
|
|
32
|
+
* @param {{ env?: Context['env'], stdin?: Context['stdin'], stdout?: Output, stderr?: Output, manifest?: Context['manifest'], loginTimeoutMs?: number }} [options]
|
|
33
|
+
*/
|
|
34
|
+
export async function main(argv, options = {}) {
|
|
35
|
+
/** @type {Context['manifest'] | undefined} */
|
|
36
|
+
let manifest = options.manifest;
|
|
37
|
+
/** @type {Context} */
|
|
38
|
+
const ctx = {
|
|
39
|
+
env: options.env ?? process.env,
|
|
40
|
+
stdin: options.stdin ?? process.stdin,
|
|
41
|
+
stdout: options.stdout ?? process.stdout,
|
|
42
|
+
stderr: options.stderr ?? process.stderr,
|
|
43
|
+
get manifest() {
|
|
44
|
+
manifest ??= loadManifest();
|
|
45
|
+
return manifest;
|
|
46
|
+
},
|
|
47
|
+
builtins,
|
|
48
|
+
loginTimeoutMs: options.loginTimeoutMs ?? 5 * 60 * 1000,
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
try {
|
|
52
|
+
const index = commandIndex(argv);
|
|
53
|
+
const wantsHelp = argv.includes('--help');
|
|
54
|
+
if (index === -1) {
|
|
55
|
+
if (argv.length && !wantsHelp) throw usageError('No command given. Run socialapi --help to list the commands.');
|
|
56
|
+
ctx.stdout.write(globalHelp(ctx.manifest, ctx.builtins));
|
|
57
|
+
return EXIT.ok;
|
|
58
|
+
}
|
|
59
|
+
const name = argv[index];
|
|
60
|
+
const rest = [...argv.slice(0, index), ...argv.slice(index + 1)];
|
|
61
|
+
|
|
62
|
+
const builtin = ctx.builtins.find((b) => b.name === name);
|
|
63
|
+
if (builtin) {
|
|
64
|
+
if (wantsHelp) {
|
|
65
|
+
ctx.stdout.write(builtinHelp(builtin));
|
|
66
|
+
return EXIT.ok;
|
|
67
|
+
}
|
|
68
|
+
return await builtin.run(rest, ctx);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const cmd = ctx.manifest.commands.find((c) => c.name === name);
|
|
72
|
+
if (cmd) {
|
|
73
|
+
if (wantsHelp) {
|
|
74
|
+
ctx.stdout.write(commandHelp(cmd));
|
|
75
|
+
return EXIT.ok;
|
|
76
|
+
}
|
|
77
|
+
return await runOperation(cmd, rest, ctx);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
throw unknownCommand(name, ctx);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (!(error instanceof CliError)) throw error;
|
|
83
|
+
const body = error.body ?? JSON.stringify({ error: { code: error.code, message: error.message } });
|
|
84
|
+
ctx.stderr.write(body.endsWith('\n') ? body : `${body}\n`);
|
|
85
|
+
return error.exitCode;
|
|
86
|
+
}
|
|
87
|
+
}
|
package/src/manifest.mjs
ADDED
package/src/naming.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Kebab case: a hyphen goes before each capital that follows a lowercase letter or a digit,
|
|
3
|
+
* and before the last capital of a run of capitals followed by a lowercase letter
|
|
4
|
+
* (`getAPIKey` gives `get-api-key`). Digits stay with the letters before them
|
|
5
|
+
* (`oauth2Token` gives `oauth2-token`). Any other character becomes a hyphen.
|
|
6
|
+
* @param {string} text
|
|
7
|
+
*/
|
|
8
|
+
export function kebabCase(text) {
|
|
9
|
+
return text
|
|
10
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
11
|
+
.replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')
|
|
12
|
+
.replace(/[^A-Za-z0-9]+/g, '-')
|
|
13
|
+
.replace(/^-+|-+$/g, '')
|
|
14
|
+
.toLowerCase();
|
|
15
|
+
}
|