@superpanel-sdk/cli 0.0.0-stage → 0.1.1
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/README.md +16 -2
- package/bin/superpanel.mjs +23 -0
- package/dist/api/platform.d.ts +31 -0
- package/dist/api/platform.js +39 -0
- package/dist/auth/auth.d.ts +162 -0
- package/dist/auth/auth.js +923 -0
- package/dist/auth/backend-url.d.ts +7 -0
- package/dist/auth/backend-url.js +41 -0
- package/dist/auth/cli-login.d.ts +8 -0
- package/dist/auth/cli-login.js +92 -0
- package/dist/auth/clipboard.d.ts +8 -0
- package/dist/auth/clipboard.js +42 -0
- package/dist/auth/file-lock.d.ts +25 -0
- package/dist/auth/file-lock.js +173 -0
- package/dist/auth/http.d.ts +34 -0
- package/dist/auth/http.js +48 -0
- package/dist/auth/index.d.ts +13 -0
- package/dist/auth/index.js +117 -0
- package/dist/auth/origin-guard.d.ts +4 -0
- package/dist/auth/origin-guard.js +9 -0
- package/dist/auth/origin.d.ts +17 -0
- package/dist/auth/origin.js +142 -0
- package/dist/auth/pending-login.d.ts +5 -0
- package/dist/auth/pending-login.js +67 -0
- package/dist/commands/auth-token.d.ts +26 -0
- package/dist/commands/auth-token.js +71 -0
- package/dist/commands/git-method.d.ts +54 -0
- package/dist/commands/git-method.js +180 -0
- package/dist/commands/setup.d.ts +88 -0
- package/dist/commands/setup.js +366 -0
- package/dist/commands/skill.d.ts +29 -0
- package/dist/commands/skill.js +169 -0
- package/dist/commands/ssh-key.d.ts +13 -0
- package/dist/commands/ssh-key.js +83 -0
- package/dist/git/credential.d.ts +7 -0
- package/dist/git/credential.js +66 -0
- package/dist/git/index.d.ts +36 -0
- package/dist/git/index.js +119 -0
- package/dist/git/run.d.ts +13 -0
- package/dist/git/run.js +32 -0
- package/dist/git/setup.d.ts +97 -0
- package/dist/git/setup.js +471 -0
- package/dist/handover/clone.d.ts +8 -0
- package/dist/handover/clone.js +39 -0
- package/dist/handover/repo-help.d.ts +7 -0
- package/dist/handover/repo-help.js +55 -0
- package/dist/handover/run.d.ts +5 -0
- package/dist/handover/run.js +67 -0
- package/dist/inbound/index.d.ts +44 -0
- package/dist/inbound/index.js +129 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +251 -0
- package/dist/logs/index.d.ts +19 -0
- package/dist/logs/index.js +132 -0
- package/dist/npm-launch.d.ts +19 -0
- package/dist/npm-launch.js +80 -0
- package/dist/ops/agent.d.ts +3 -0
- package/dist/ops/agent.js +14 -0
- package/dist/ops/cache.d.ts +18 -0
- package/dist/ops/cache.js +92 -0
- package/dist/ops/parse.d.ts +6 -0
- package/dist/ops/parse.js +106 -0
- package/dist/ops/register.d.ts +18 -0
- package/dist/ops/register.js +174 -0
- package/dist/ops/run.d.ts +20 -0
- package/dist/ops/run.js +127 -0
- package/dist/ops/types.d.ts +41 -0
- package/dist/ops/types.js +16 -0
- package/dist/protocol.d.ts +4 -0
- package/dist/protocol.js +17 -0
- package/dist/reserved.d.ts +4 -0
- package/dist/reserved.js +25 -0
- package/dist/turns/index.d.ts +20 -0
- package/dist/turns/index.js +108 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +11 -0
- package/package.json +48 -4
- package/skill/SKILL.md +17 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
function pathFor(platform) {
|
|
4
|
+
return platform === 'win32' ? path.win32 : path.posix;
|
|
5
|
+
}
|
|
6
|
+
function expandShimPath(raw, dir, paths) {
|
|
7
|
+
const base = dir.endsWith(paths.sep) ? dir : `${dir}${paths.sep}`;
|
|
8
|
+
const expanded = raw
|
|
9
|
+
.replace(/%~dp0%/gi, base)
|
|
10
|
+
.replace(/%dp0%/gi, base)
|
|
11
|
+
.replace(/%~dp0/gi, base);
|
|
12
|
+
return paths.normalize(paths.resolve(dir, expanded));
|
|
13
|
+
}
|
|
14
|
+
export function jsEntryFromCmd(cmdFile, paths, exists, readFile, sibling) {
|
|
15
|
+
let text = '';
|
|
16
|
+
try {
|
|
17
|
+
text = readFile(cmdFile);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
text = '';
|
|
21
|
+
}
|
|
22
|
+
const dir = paths.dirname(cmdFile);
|
|
23
|
+
for (const match of text.matchAll(/"([^"\r\n]+\.(?:mjs|cjs|js))"/gi)) {
|
|
24
|
+
const raw = match[1];
|
|
25
|
+
if (!raw)
|
|
26
|
+
continue;
|
|
27
|
+
const entry = expandShimPath(raw, dir, paths);
|
|
28
|
+
if (exists(entry))
|
|
29
|
+
return entry;
|
|
30
|
+
}
|
|
31
|
+
if (sibling && exists(sibling))
|
|
32
|
+
return sibling;
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
function skippedPathDir(dir, sep) {
|
|
36
|
+
const parts = dir.split(sep);
|
|
37
|
+
for (let i = 1; i < parts.length; i += 1) {
|
|
38
|
+
if (parts[i] === '.bin' && parts[i - 1] === 'node_modules')
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
return parts.includes('_npx');
|
|
42
|
+
}
|
|
43
|
+
export function globalBinDir(prefix, platform = process.platform) {
|
|
44
|
+
const root = prefix.trim();
|
|
45
|
+
return platform === 'win32' ? root : path.join(root, 'bin');
|
|
46
|
+
}
|
|
47
|
+
function quoteCmd(arg) {
|
|
48
|
+
if (arg.length === 0)
|
|
49
|
+
return '""';
|
|
50
|
+
if (!/[\s"&|<>^%]/.test(arg))
|
|
51
|
+
return arg;
|
|
52
|
+
return `"${arg.replace(/"/g, '""')}"`;
|
|
53
|
+
}
|
|
54
|
+
export function npmLaunch(args, input = {}) {
|
|
55
|
+
const platform = input.platform ?? process.platform;
|
|
56
|
+
const paths = pathFor(platform);
|
|
57
|
+
const execPath = input.execPath ?? process.execPath;
|
|
58
|
+
const exists = input.exists ?? existsSync;
|
|
59
|
+
const readFile = input.readFile ?? ((file) => readFileSync(file, 'utf8'));
|
|
60
|
+
const besideNode = paths.join(paths.dirname(execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js');
|
|
61
|
+
if (exists(besideNode))
|
|
62
|
+
return { command: execPath, args: [besideNode, ...args] };
|
|
63
|
+
if (platform === 'win32') {
|
|
64
|
+
for (const dir of (input.env?.PATH ?? process.env.PATH ?? '').split(paths.delimiter)) {
|
|
65
|
+
if (!dir || skippedPathDir(dir, paths.sep))
|
|
66
|
+
continue;
|
|
67
|
+
for (const name of ['npm.cmd', 'npm.bat']) {
|
|
68
|
+
const cmd = paths.join(dir, name);
|
|
69
|
+
if (!exists(cmd))
|
|
70
|
+
continue;
|
|
71
|
+
const entry = jsEntryFromCmd(cmd, paths, exists, readFile, paths.join(dir, 'node_modules', 'npm', 'bin', 'npm-cli.js'));
|
|
72
|
+
if (entry)
|
|
73
|
+
return { command: execPath, args: [entry, ...args] };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const comspec = input.env?.ComSpec || input.env?.COMSPEC || 'cmd.exe';
|
|
77
|
+
return { command: comspec, args: ['/d', '/s', '/c', ['npm', ...args.map(quoteCmd)].join(' ')], verbatim: true };
|
|
78
|
+
}
|
|
79
|
+
return { command: 'npm', args };
|
|
80
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export function runningAsAgent(env = process.env) {
|
|
2
|
+
if (env.AI_AGENT)
|
|
3
|
+
return true;
|
|
4
|
+
if (env.CLAUDECODE || env.GEMINI_CLI || env.CURSOR_AGENT)
|
|
5
|
+
return true;
|
|
6
|
+
if (env.CODEX_SANDBOX || env.CODEX_CI || env.CODEX_THREAD_ID)
|
|
7
|
+
return true;
|
|
8
|
+
if (env.OR_APP_NAME === 'Aider' || env.REPLIT_CLI)
|
|
9
|
+
return true;
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
export function hasTerminal() {
|
|
13
|
+
return Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
14
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { OpsList } from './types.js';
|
|
2
|
+
export type OpsCacheFile = {
|
|
3
|
+
version: 1;
|
|
4
|
+
backends: Record<string, OpsList>;
|
|
5
|
+
};
|
|
6
|
+
export declare function opsCachePath(): string;
|
|
7
|
+
export declare function readOpsCache(file?: string): Promise<OpsCacheFile>;
|
|
8
|
+
export declare function rememberOpsList(backendUrl: string, list: OpsList, file?: string): Promise<void>;
|
|
9
|
+
export declare function cachedOpsList(backendUrl: string, file?: string): Promise<OpsList | null>;
|
|
10
|
+
export declare function fetchOpsList(backendUrl: string, fetchImpl?: typeof fetch): Promise<OpsList>;
|
|
11
|
+
export type OpReply = {
|
|
12
|
+
status: number;
|
|
13
|
+
text?: string;
|
|
14
|
+
data?: unknown;
|
|
15
|
+
error?: string;
|
|
16
|
+
};
|
|
17
|
+
export declare function postOp(backendUrl: string, name: string, args: Record<string, unknown>, token: string, backendVersion: string, fetchImpl?: typeof fetch, terminalConfirmed?: boolean): Promise<OpReply>;
|
|
18
|
+
//# sourceMappingURL=cache.d.ts.map
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { apiUrl } from '../auth/http.js';
|
|
6
|
+
import { backendCacheKey } from '../auth/auth.js';
|
|
7
|
+
import { cliVersion } from '../version.js';
|
|
8
|
+
const TIMEOUT_MS = 15_000;
|
|
9
|
+
export function opsCachePath() {
|
|
10
|
+
return path.join(homedir(), '.superpanel', 'ops-cache.json');
|
|
11
|
+
}
|
|
12
|
+
function isList(value) {
|
|
13
|
+
if (!value || typeof value !== 'object')
|
|
14
|
+
return false;
|
|
15
|
+
const record = value;
|
|
16
|
+
return (typeof record.formatVersion === 'number' && typeof record.backendVersion === 'string' && Array.isArray(record.ops));
|
|
17
|
+
}
|
|
18
|
+
export async function readOpsCache(file = opsCachePath()) {
|
|
19
|
+
try {
|
|
20
|
+
const raw = JSON.parse(await readFile(file, 'utf8'));
|
|
21
|
+
const backends = {};
|
|
22
|
+
for (const [key, value] of Object.entries(raw.backends ?? {})) {
|
|
23
|
+
if (isList(value))
|
|
24
|
+
backends[key] = value;
|
|
25
|
+
}
|
|
26
|
+
return { version: 1, backends };
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
|
|
30
|
+
if (code === 'ENOENT' || error instanceof SyntaxError)
|
|
31
|
+
return { version: 1, backends: {} };
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
async function writeOpsCache(cache, file) {
|
|
36
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
37
|
+
const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
38
|
+
await writeFile(temporary, `${JSON.stringify(cache, null, 2)}\n`, { mode: 0o600 });
|
|
39
|
+
try {
|
|
40
|
+
await rename(temporary, file);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
await rm(temporary, { force: true });
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
await chmod(file, 0o600).catch(() => undefined);
|
|
47
|
+
}
|
|
48
|
+
function backendCacheFile(file, key) {
|
|
49
|
+
return path.join(file + '.d', createHash('sha256').update(key).digest('hex') + '.json');
|
|
50
|
+
}
|
|
51
|
+
export async function rememberOpsList(backendUrl, list, file = opsCachePath()) {
|
|
52
|
+
const key = backendCacheKey(backendUrl);
|
|
53
|
+
await writeOpsCache({ version: 1, backends: { [key]: list } }, backendCacheFile(file, key));
|
|
54
|
+
}
|
|
55
|
+
export async function cachedOpsList(backendUrl, file = opsCachePath()) {
|
|
56
|
+
const key = backendCacheKey(backendUrl);
|
|
57
|
+
const own = await readOpsCache(backendCacheFile(file, key));
|
|
58
|
+
return own.backends[key] ?? (await readOpsCache(file)).backends[key] ?? null;
|
|
59
|
+
}
|
|
60
|
+
export async function fetchOpsList(backendUrl, fetchImpl = fetch) {
|
|
61
|
+
const response = await fetchImpl(apiUrl(backendUrl, 'ops'), {
|
|
62
|
+
headers: { 'Superpanel-Cli-Version': cliVersion() },
|
|
63
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
64
|
+
});
|
|
65
|
+
const payload = (await response.json().catch(() => ({})));
|
|
66
|
+
if (response.status === 426)
|
|
67
|
+
throw new Error(payload.error || 'This CLI is too old. Update it.');
|
|
68
|
+
if (!response.ok || !Array.isArray(payload.ops) || typeof payload.formatVersion !== 'number') {
|
|
69
|
+
throw new Error(payload.error || `Could not read the operation list (${response.status}).`);
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
formatVersion: payload.formatVersion,
|
|
73
|
+
backendVersion: response.headers.get('superpanel-backend-version') ?? '',
|
|
74
|
+
ops: payload.ops,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
export async function postOp(backendUrl, name, args, token, backendVersion, fetchImpl = fetch, terminalConfirmed = false) {
|
|
78
|
+
const response = await fetchImpl(apiUrl(backendUrl, `ops/${name}`), {
|
|
79
|
+
method: 'POST',
|
|
80
|
+
headers: {
|
|
81
|
+
'Content-Type': 'application/json',
|
|
82
|
+
Authorization: `Bearer ${token}`,
|
|
83
|
+
'Superpanel-Backend-Version': backendVersion,
|
|
84
|
+
...(terminalConfirmed ? { 'Superpanel-Terminal-Confirmed': 'true' } : {}),
|
|
85
|
+
'Superpanel-Cli-Version': cliVersion(),
|
|
86
|
+
},
|
|
87
|
+
body: JSON.stringify(args),
|
|
88
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
89
|
+
});
|
|
90
|
+
const payload = (await response.json().catch(() => ({})));
|
|
91
|
+
return { status: response.status, text: payload.text, data: payload.data, error: payload.error };
|
|
92
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type PublicOp } from './types.js';
|
|
2
|
+
export declare function commandWords(command: string): string[];
|
|
3
|
+
export declare function flagOf(name: string): string;
|
|
4
|
+
export declare function refusal(op: PublicOp, formatVersion: number): string | null;
|
|
5
|
+
export declare function buildArgs(op: PublicOp, positionals: string[], options: Record<string, unknown>): Record<string, unknown>;
|
|
6
|
+
//# sourceMappingURL=parse.d.ts.map
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { isReservedCommand } from '../reserved.js';
|
|
2
|
+
import { KNOWN_OPS_FORMAT, KNOWN_PARAM_TYPES } from './types.js';
|
|
3
|
+
const UPDATE = 'This CLI does not understand this command. Update it: npm install -g @superpanel-sdk/cli@latest';
|
|
4
|
+
export function commandWords(command) {
|
|
5
|
+
return command
|
|
6
|
+
.trim()
|
|
7
|
+
.split(/\s+/)
|
|
8
|
+
.filter((word) => word.length > 0 && !word.startsWith('-') && !word.startsWith('<') && !word.startsWith('['));
|
|
9
|
+
}
|
|
10
|
+
export function flagOf(name) {
|
|
11
|
+
return `--${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`;
|
|
12
|
+
}
|
|
13
|
+
export function refusal(op, formatVersion) {
|
|
14
|
+
if (formatVersion !== KNOWN_OPS_FORMAT) {
|
|
15
|
+
return `This CLI does not understand operation list format ${formatVersion}. Update it: npm install -g @superpanel-sdk/cli@latest`;
|
|
16
|
+
}
|
|
17
|
+
const words = commandWords(op.command);
|
|
18
|
+
if (words.length === 0 || !isReservedCommand(words[0]))
|
|
19
|
+
return 'ignored';
|
|
20
|
+
if (op.confirm && op.confirm.when !== 'environment-is-prod')
|
|
21
|
+
return UPDATE;
|
|
22
|
+
for (const param of op.params) {
|
|
23
|
+
if (!KNOWN_PARAM_TYPES.includes(param.type))
|
|
24
|
+
return UPDATE;
|
|
25
|
+
if (param.place !== 'positional' && param.place !== 'option' && param.place !== 'repeat')
|
|
26
|
+
return UPDATE;
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
function integer(value, name) {
|
|
31
|
+
if (!/^-?\d+$/.test(value))
|
|
32
|
+
throw new Error(`--${name} must be an integer`);
|
|
33
|
+
return Number(value);
|
|
34
|
+
}
|
|
35
|
+
function pair(value, flag) {
|
|
36
|
+
const index = value.indexOf('=');
|
|
37
|
+
if (index <= 0)
|
|
38
|
+
throw new Error(`${flag} needs key=value`);
|
|
39
|
+
return [value.slice(0, index), value.slice(index + 1)];
|
|
40
|
+
}
|
|
41
|
+
function one(param, raw) {
|
|
42
|
+
if (raw === undefined || raw === null || raw === '')
|
|
43
|
+
return undefined;
|
|
44
|
+
if (param.type === 'boolean')
|
|
45
|
+
return Boolean(raw);
|
|
46
|
+
if (param.type === 'integer')
|
|
47
|
+
return integer(String(raw), param.name);
|
|
48
|
+
if (param.type === 'enum') {
|
|
49
|
+
const value = String(raw);
|
|
50
|
+
if (param.enum && !param.enum.includes(value)) {
|
|
51
|
+
throw new Error(`${param.name} must be one of ${param.enum.join(', ')}`);
|
|
52
|
+
}
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
if (param.type === 'kv' && param.place === 'repeat') {
|
|
56
|
+
const values = {};
|
|
57
|
+
for (const item of raw) {
|
|
58
|
+
const [key, value] = pair(item, flagOf(param.name));
|
|
59
|
+
values[key] = value;
|
|
60
|
+
}
|
|
61
|
+
return values;
|
|
62
|
+
}
|
|
63
|
+
if (param.type === 'json' && param.place === 'repeat') {
|
|
64
|
+
const values = {};
|
|
65
|
+
for (const item of raw) {
|
|
66
|
+
const [key, value] = pair(item, flagOf(param.name));
|
|
67
|
+
try {
|
|
68
|
+
values[key] = JSON.parse(value);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
throw new Error(`${flagOf(param.name)} ${key} is not JSON`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return values;
|
|
75
|
+
}
|
|
76
|
+
if (param.place === 'repeat')
|
|
77
|
+
return raw;
|
|
78
|
+
return String(raw);
|
|
79
|
+
}
|
|
80
|
+
export function buildArgs(op, positionals, options) {
|
|
81
|
+
const args = {};
|
|
82
|
+
let index = 0;
|
|
83
|
+
for (const param of op.params) {
|
|
84
|
+
if (param.place === 'positional') {
|
|
85
|
+
const raw = positionals[index];
|
|
86
|
+
index += 1;
|
|
87
|
+
if (raw === undefined) {
|
|
88
|
+
if (param.required)
|
|
89
|
+
throw new Error(`${param.name} is required`);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
args[param.name] = one(param, raw);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const raw = options[param.name];
|
|
96
|
+
if (raw === undefined || (Array.isArray(raw) && raw.length === 0)) {
|
|
97
|
+
if (param.required)
|
|
98
|
+
throw new Error(`${flagOf(param.name)} is required`);
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const value = one(param, raw);
|
|
102
|
+
if (value !== undefined)
|
|
103
|
+
args[param.name] = value;
|
|
104
|
+
}
|
|
105
|
+
return args;
|
|
106
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
export declare const CATALOG_ROOTS: readonly ['env', 'config', 'connection', 'webhook', 'release', 'pr', 'platform'];
|
|
3
|
+
export type RegisterOptions = {
|
|
4
|
+
url?: string;
|
|
5
|
+
fetchImpl?: typeof fetch;
|
|
6
|
+
cacheFile?: string;
|
|
7
|
+
token?: string;
|
|
8
|
+
isAgent?: boolean;
|
|
9
|
+
isTerminal?: boolean;
|
|
10
|
+
ask?: (message: string) => Promise<boolean>;
|
|
11
|
+
};
|
|
12
|
+
export declare function splitActionInputs(inputs: unknown[]): {
|
|
13
|
+
positionals: string[];
|
|
14
|
+
options: Record<string, unknown>;
|
|
15
|
+
};
|
|
16
|
+
export declare function registerPlatformCommands(program: Command, options?: RegisterOptions): Promise<void>;
|
|
17
|
+
export declare function backendWhoamiText(backendUrl: string): Promise<string | null>;
|
|
18
|
+
//# sourceMappingURL=register.d.ts.map
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline/promises';
|
|
2
|
+
import { CliLoginRejectedError, getValidCliAuthorization, loginCommand, resolveBackendUrl } from '../auth/auth.js';
|
|
3
|
+
import { guardNetworkedClone } from '../auth/origin-guard.js';
|
|
4
|
+
import { hasTerminal, runningAsAgent } from './agent.js';
|
|
5
|
+
import { fetchOpsList, rememberOpsList } from './cache.js';
|
|
6
|
+
import { buildArgs, commandWords, flagOf, refusal } from './parse.js';
|
|
7
|
+
import { catalogForHelp, executeOp } from './run.js';
|
|
8
|
+
import { confirmationOptionHelp, NeedsPersonError } from './types.js';
|
|
9
|
+
export const CATALOG_ROOTS = ['env', 'config', 'connection', 'webhook', 'release', 'pr', 'platform'];
|
|
10
|
+
const GROUP_DESCRIPTION = {
|
|
11
|
+
env: 'Environments',
|
|
12
|
+
config: 'Phone numbers, mailboxes and connections',
|
|
13
|
+
connection: 'Env connection values',
|
|
14
|
+
webhook: 'Webhook URLs',
|
|
15
|
+
release: 'Releases',
|
|
16
|
+
pr: 'Pull requests',
|
|
17
|
+
platform: 'Platform commands',
|
|
18
|
+
};
|
|
19
|
+
function collect(value, previous) {
|
|
20
|
+
return previous.concat(value);
|
|
21
|
+
}
|
|
22
|
+
async function askTerminal(message) {
|
|
23
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
24
|
+
try {
|
|
25
|
+
const answer = await rl.question(`${message} [y/N] `);
|
|
26
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
rl.close();
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async function tokenFor(backendUrl, given) {
|
|
33
|
+
if (given)
|
|
34
|
+
return given;
|
|
35
|
+
try {
|
|
36
|
+
const authorization = await getValidCliAuthorization(backendUrl);
|
|
37
|
+
if (!authorization)
|
|
38
|
+
throw new Error(`Not logged in. Run \`${loginCommand(backendUrl)}\`.`);
|
|
39
|
+
return authorization.accessToken;
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (error instanceof CliLoginRejectedError)
|
|
43
|
+
throw new Error(`The login ended. Run \`${loginCommand(backendUrl)}\`.`);
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function addParams(leaf, op) {
|
|
48
|
+
for (const param of op.params) {
|
|
49
|
+
const description = param.name === op.confirm?.argument ? confirmationOptionHelp(param.description) : param.description;
|
|
50
|
+
if (param.place === 'positional') {
|
|
51
|
+
leaf.argument(param.required === false ? `[${param.name}]` : `<${param.name}>`, description);
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const flag = flagOf(param.name);
|
|
55
|
+
if (param.place === 'repeat') {
|
|
56
|
+
const hint = param.type === 'kv' || param.type === 'json' ? '<key=value>' : '<value>';
|
|
57
|
+
leaf.option(`${flag} ${hint}`, description, collect, []);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (param.type === 'boolean') {
|
|
61
|
+
if (param.required)
|
|
62
|
+
leaf.requiredOption(flag, description);
|
|
63
|
+
else
|
|
64
|
+
leaf.option(flag, description);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const spec = `${flag} <value>`;
|
|
68
|
+
if (param.required)
|
|
69
|
+
leaf.requiredOption(spec, description);
|
|
70
|
+
else
|
|
71
|
+
leaf.option(spec, description);
|
|
72
|
+
}
|
|
73
|
+
leaf.option('--json', 'Print the data as JSON');
|
|
74
|
+
leaf.option('--url <url>', 'Backend URL');
|
|
75
|
+
}
|
|
76
|
+
function parentFor(program, groups) {
|
|
77
|
+
let parent = program;
|
|
78
|
+
for (const segment of groups) {
|
|
79
|
+
parent =
|
|
80
|
+
parent.commands.find((command) => command.name() === segment) ??
|
|
81
|
+
parent.command(segment).description(GROUP_DESCRIPTION[segment] ?? segment);
|
|
82
|
+
}
|
|
83
|
+
return parent;
|
|
84
|
+
}
|
|
85
|
+
export function splitActionInputs(inputs) {
|
|
86
|
+
const rest = inputs.slice(0, -1);
|
|
87
|
+
const options = (rest.pop() ?? {});
|
|
88
|
+
return {
|
|
89
|
+
positionals: rest.flatMap((value) => (typeof value === 'string' ? [value] : [])),
|
|
90
|
+
options,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function registerOp(program, op, options) {
|
|
94
|
+
const words = commandWords(op.command);
|
|
95
|
+
if (words.length === 0)
|
|
96
|
+
return;
|
|
97
|
+
const parent = parentFor(program, words.slice(0, -1));
|
|
98
|
+
const leafName = words[words.length - 1];
|
|
99
|
+
if (parent.commands.some((command) => command.name() === leafName))
|
|
100
|
+
return;
|
|
101
|
+
const leaf = parent.command(leafName).description(op.description);
|
|
102
|
+
addParams(leaf, op);
|
|
103
|
+
leaf.action(async (...inputs) => {
|
|
104
|
+
const { positionals, options: raw } = splitActionInputs(inputs);
|
|
105
|
+
try {
|
|
106
|
+
const url = resolveBackendUrl(typeof raw.url === 'string' ? raw.url : options.url);
|
|
107
|
+
const fetchImpl = options.fetchImpl;
|
|
108
|
+
const catalog = await fetchOpsList(url, fetchImpl);
|
|
109
|
+
await rememberOpsList(url, catalog, options.cacheFile);
|
|
110
|
+
const current = catalog.ops.find((item) => item.name === op.name && item.entrances.includes('cli'));
|
|
111
|
+
if (!current)
|
|
112
|
+
throw new Error(`This backend does not have "${op.name}" yet.`);
|
|
113
|
+
const args = buildArgs(current, positionals, raw);
|
|
114
|
+
const token = await tokenFor(url, options.token);
|
|
115
|
+
await guardNetworkedClone(process.cwd(), url, token);
|
|
116
|
+
const result = await executeOp({
|
|
117
|
+
op: current,
|
|
118
|
+
args,
|
|
119
|
+
catalog,
|
|
120
|
+
backendUrl: url,
|
|
121
|
+
token,
|
|
122
|
+
fetchImpl,
|
|
123
|
+
cacheFile: options.cacheFile,
|
|
124
|
+
isAgent: options.isAgent ?? runningAsAgent(),
|
|
125
|
+
isTerminal: options.isTerminal ?? hasTerminal(),
|
|
126
|
+
ask: options.ask ?? askTerminal,
|
|
127
|
+
});
|
|
128
|
+
if (raw.json)
|
|
129
|
+
console.log(JSON.stringify(result.data ?? { text: result.text }));
|
|
130
|
+
else
|
|
131
|
+
console.log(result.text);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
if (error instanceof NeedsPersonError) {
|
|
135
|
+
console.error(error.message);
|
|
136
|
+
console.log(JSON.stringify({ reason: error.reason }));
|
|
137
|
+
process.exit(2);
|
|
138
|
+
}
|
|
139
|
+
console.error(error instanceof Error ? error.message : error);
|
|
140
|
+
process.exit(1);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
export async function registerPlatformCommands(program, options = {}) {
|
|
145
|
+
const backendUrl = resolveBackendUrl(options.url);
|
|
146
|
+
const catalog = await catalogForHelp(backendUrl, options.fetchImpl, options.cacheFile);
|
|
147
|
+
if (!catalog)
|
|
148
|
+
return;
|
|
149
|
+
for (const op of catalog.ops) {
|
|
150
|
+
if (!op.entrances.includes('cli'))
|
|
151
|
+
continue;
|
|
152
|
+
if (refusal(op, catalog.formatVersion) === 'ignored')
|
|
153
|
+
continue;
|
|
154
|
+
registerOp(program, op, options);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
export async function backendWhoamiText(backendUrl) {
|
|
158
|
+
const catalog = await fetchOpsList(backendUrl);
|
|
159
|
+
const op = catalog.ops.find((item) => item.name === 'whoami' && item.entrances.includes('cli'));
|
|
160
|
+
if (!op)
|
|
161
|
+
return null;
|
|
162
|
+
const token = await tokenFor(backendUrl, undefined);
|
|
163
|
+
const result = await executeOp({
|
|
164
|
+
op,
|
|
165
|
+
args: {},
|
|
166
|
+
catalog,
|
|
167
|
+
backendUrl,
|
|
168
|
+
token,
|
|
169
|
+
isAgent: false,
|
|
170
|
+
isTerminal: true,
|
|
171
|
+
ask: async () => false,
|
|
172
|
+
});
|
|
173
|
+
return result.text;
|
|
174
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type ListedEnvironment, type OpsList, type PublicOp } from './types.js';
|
|
2
|
+
export type ExecuteInput = {
|
|
3
|
+
op: PublicOp;
|
|
4
|
+
args: Record<string, unknown>;
|
|
5
|
+
catalog: OpsList;
|
|
6
|
+
backendUrl: string;
|
|
7
|
+
token: string;
|
|
8
|
+
fetchImpl?: typeof fetch;
|
|
9
|
+
cacheFile?: string;
|
|
10
|
+
isAgent: boolean;
|
|
11
|
+
isTerminal: boolean;
|
|
12
|
+
ask: (message: string) => Promise<boolean>;
|
|
13
|
+
};
|
|
14
|
+
export declare function treatAsProd(environments: ListedEnvironment[] | null, name: string): boolean;
|
|
15
|
+
export declare function executeOp(input: ExecuteInput): Promise<{
|
|
16
|
+
text: string;
|
|
17
|
+
data: unknown;
|
|
18
|
+
}>;
|
|
19
|
+
export declare function catalogForHelp(backendUrl: string, fetchImpl?: typeof fetch, cacheFile?: string): Promise<OpsList | null>;
|
|
20
|
+
//# sourceMappingURL=run.d.ts.map
|
package/dist/ops/run.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { cachedOpsList, fetchOpsList, postOp, rememberOpsList } from './cache.js';
|
|
2
|
+
import { flagOf, refusal } from './parse.js';
|
|
3
|
+
import { NeedsPersonError } from './types.js';
|
|
4
|
+
function environmentsOf(data) {
|
|
5
|
+
if (!data || typeof data !== 'object' || !('environments' in data))
|
|
6
|
+
return null;
|
|
7
|
+
const list = data.environments;
|
|
8
|
+
if (!Array.isArray(list))
|
|
9
|
+
return null;
|
|
10
|
+
const environments = [];
|
|
11
|
+
for (const item of list) {
|
|
12
|
+
if (!item || typeof item !== 'object')
|
|
13
|
+
return null;
|
|
14
|
+
const row = item;
|
|
15
|
+
if (typeof row.id !== 'string' || typeof row.name !== 'string' || typeof row.prod !== 'boolean')
|
|
16
|
+
return null;
|
|
17
|
+
environments.push({ id: row.id, name: row.name, prod: row.prod });
|
|
18
|
+
}
|
|
19
|
+
return environments;
|
|
20
|
+
}
|
|
21
|
+
export function treatAsProd(environments, name) {
|
|
22
|
+
if (!environments)
|
|
23
|
+
return true;
|
|
24
|
+
const found = environments.find((environment) => environment.name === name || environment.id === name);
|
|
25
|
+
if (!found)
|
|
26
|
+
return true;
|
|
27
|
+
return found.prod;
|
|
28
|
+
}
|
|
29
|
+
function confirmMessage(op, environment, unknown, args) {
|
|
30
|
+
const flag = flagOf(op.confirm?.argument ?? 'allow-prod');
|
|
31
|
+
const where = unknown
|
|
32
|
+
? `The environment "${environment}" could not be checked, so it is treated as prod.`
|
|
33
|
+
: `This changes "${environment}", which is prod.`;
|
|
34
|
+
const changes = [];
|
|
35
|
+
if (op.name === 'set_connection') {
|
|
36
|
+
changes.push('Connection ' + JSON.stringify(args.name));
|
|
37
|
+
const setKeys = [...Object.keys(args.set ?? {}), ...Object.keys(args.setJson ?? {})];
|
|
38
|
+
if (setKeys.length)
|
|
39
|
+
changes.push('Set keys ' + JSON.stringify(setKeys));
|
|
40
|
+
if (Array.isArray(args.unset) && args.unset.length)
|
|
41
|
+
changes.push('Remove keys ' + JSON.stringify(args.unset));
|
|
42
|
+
}
|
|
43
|
+
return [
|
|
44
|
+
...changes,
|
|
45
|
+
`${where} It takes effect for live calls and messages at once, and the old values cannot be read back.`,
|
|
46
|
+
'Stop and ask the person. If they agree, append this option to the original command and rerun it:',
|
|
47
|
+
` ${flag} "<their words>"`,
|
|
48
|
+
'A vague answer is not agreement: ask again.',
|
|
49
|
+
].join('\n');
|
|
50
|
+
}
|
|
51
|
+
async function environmentKind(input, name, catalog) {
|
|
52
|
+
const reply = await postOp(input.backendUrl, 'list_environments', {}, input.token, catalog.backendVersion, input.fetchImpl);
|
|
53
|
+
if (reply.status !== 200)
|
|
54
|
+
return 'unknown';
|
|
55
|
+
const environments = environmentsOf(reply.data);
|
|
56
|
+
if (!environments)
|
|
57
|
+
return 'unknown';
|
|
58
|
+
const found = environments.find((environment) => environment.name === name || environment.id === name);
|
|
59
|
+
if (!found)
|
|
60
|
+
return 'unknown';
|
|
61
|
+
return found.prod ? 'prod' : 'other';
|
|
62
|
+
}
|
|
63
|
+
async function ensureConfirmed(input, op, catalog) {
|
|
64
|
+
if (!op.confirm)
|
|
65
|
+
return false;
|
|
66
|
+
if (op.confirm.when !== 'environment-is-prod') {
|
|
67
|
+
throw new Error('This CLI does not understand this command. Update it: npm install -g @superpanel-sdk/cli@latest');
|
|
68
|
+
}
|
|
69
|
+
const quote = input.args[op.confirm.argument];
|
|
70
|
+
if (typeof quote === 'string' && quote.trim())
|
|
71
|
+
return false;
|
|
72
|
+
const environment = String(input.args[op.confirm.param] ?? '');
|
|
73
|
+
const kind = await environmentKind(input, environment, catalog);
|
|
74
|
+
if (kind === 'other')
|
|
75
|
+
return false;
|
|
76
|
+
const message = confirmMessage(op, environment, kind === 'unknown', input.args);
|
|
77
|
+
if (input.isAgent || !input.isTerminal)
|
|
78
|
+
throw new NeedsPersonError(message);
|
|
79
|
+
const yes = await input.ask(`${message}\nProceed?`);
|
|
80
|
+
if (!yes)
|
|
81
|
+
throw new Error('Not changed.');
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
function resultOf(reply, name) {
|
|
85
|
+
if (reply.status === 200 && typeof reply.text === 'string')
|
|
86
|
+
return { text: reply.text, data: reply.data };
|
|
87
|
+
if (reply.status === 404 && reply.error === 'unknown_operation') {
|
|
88
|
+
throw new Error(`This backend does not have "${name}" yet.`);
|
|
89
|
+
}
|
|
90
|
+
throw new Error(reply.error || `The operation failed (${reply.status}).`);
|
|
91
|
+
}
|
|
92
|
+
export async function executeOp(input) {
|
|
93
|
+
const blocked = refusal(input.op, input.catalog.formatVersion);
|
|
94
|
+
if (blocked && blocked !== 'ignored')
|
|
95
|
+
throw new Error(blocked);
|
|
96
|
+
const confirmed = await ensureConfirmed(input, input.op, input.catalog);
|
|
97
|
+
const fetchImpl = input.fetchImpl;
|
|
98
|
+
let reply = await postOp(input.backendUrl, input.op.name, input.args, input.token, input.catalog.backendVersion, fetchImpl, confirmed);
|
|
99
|
+
if (reply.status !== 409)
|
|
100
|
+
return resultOf(reply, input.op.name);
|
|
101
|
+
const fresh = await fetchOpsList(input.backendUrl, fetchImpl);
|
|
102
|
+
await rememberOpsList(input.backendUrl, fresh, input.cacheFile);
|
|
103
|
+
const next = fresh.ops.find((op) => op.name === input.op.name);
|
|
104
|
+
if (!next || !next.entrances.includes('cli'))
|
|
105
|
+
throw new Error(`This backend does not have "${input.op.name}" yet.`);
|
|
106
|
+
const again = refusal(next, fresh.formatVersion);
|
|
107
|
+
if (again && again !== 'ignored')
|
|
108
|
+
throw new Error(again);
|
|
109
|
+
const reconfirmed = await ensureConfirmed({ ...input, op: next }, next, fresh);
|
|
110
|
+
reply = await postOp(input.backendUrl, next.name, input.args, input.token, fresh.backendVersion, fetchImpl, reconfirmed);
|
|
111
|
+
if (reply.status === 409)
|
|
112
|
+
throw new Error(reply.error || 'The operation list changed. Nothing was changed.');
|
|
113
|
+
return resultOf(reply, next.name);
|
|
114
|
+
}
|
|
115
|
+
export async function catalogForHelp(backendUrl, fetchImpl = fetch, cacheFile) {
|
|
116
|
+
try {
|
|
117
|
+
const fresh = await fetchOpsList(backendUrl, fetchImpl);
|
|
118
|
+
await rememberOpsList(backendUrl, fresh, cacheFile);
|
|
119
|
+
return fresh;
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
const cached = await cachedOpsList(backendUrl, cacheFile);
|
|
123
|
+
if (cached)
|
|
124
|
+
return cached;
|
|
125
|
+
throw error;
|
|
126
|
+
}
|
|
127
|
+
}
|