@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.
Files changed (78) hide show
  1. package/README.md +16 -2
  2. package/bin/superpanel.mjs +23 -0
  3. package/dist/api/platform.d.ts +31 -0
  4. package/dist/api/platform.js +39 -0
  5. package/dist/auth/auth.d.ts +162 -0
  6. package/dist/auth/auth.js +923 -0
  7. package/dist/auth/backend-url.d.ts +7 -0
  8. package/dist/auth/backend-url.js +41 -0
  9. package/dist/auth/cli-login.d.ts +8 -0
  10. package/dist/auth/cli-login.js +92 -0
  11. package/dist/auth/clipboard.d.ts +8 -0
  12. package/dist/auth/clipboard.js +42 -0
  13. package/dist/auth/file-lock.d.ts +25 -0
  14. package/dist/auth/file-lock.js +173 -0
  15. package/dist/auth/http.d.ts +34 -0
  16. package/dist/auth/http.js +48 -0
  17. package/dist/auth/index.d.ts +13 -0
  18. package/dist/auth/index.js +117 -0
  19. package/dist/auth/origin-guard.d.ts +4 -0
  20. package/dist/auth/origin-guard.js +9 -0
  21. package/dist/auth/origin.d.ts +17 -0
  22. package/dist/auth/origin.js +142 -0
  23. package/dist/auth/pending-login.d.ts +5 -0
  24. package/dist/auth/pending-login.js +67 -0
  25. package/dist/commands/auth-token.d.ts +26 -0
  26. package/dist/commands/auth-token.js +71 -0
  27. package/dist/commands/git-method.d.ts +54 -0
  28. package/dist/commands/git-method.js +180 -0
  29. package/dist/commands/setup.d.ts +88 -0
  30. package/dist/commands/setup.js +366 -0
  31. package/dist/commands/skill.d.ts +29 -0
  32. package/dist/commands/skill.js +169 -0
  33. package/dist/commands/ssh-key.d.ts +13 -0
  34. package/dist/commands/ssh-key.js +83 -0
  35. package/dist/git/credential.d.ts +7 -0
  36. package/dist/git/credential.js +66 -0
  37. package/dist/git/index.d.ts +36 -0
  38. package/dist/git/index.js +119 -0
  39. package/dist/git/run.d.ts +13 -0
  40. package/dist/git/run.js +32 -0
  41. package/dist/git/setup.d.ts +97 -0
  42. package/dist/git/setup.js +471 -0
  43. package/dist/handover/clone.d.ts +8 -0
  44. package/dist/handover/clone.js +39 -0
  45. package/dist/handover/repo-help.d.ts +7 -0
  46. package/dist/handover/repo-help.js +55 -0
  47. package/dist/handover/run.d.ts +5 -0
  48. package/dist/handover/run.js +67 -0
  49. package/dist/inbound/index.d.ts +44 -0
  50. package/dist/inbound/index.js +129 -0
  51. package/dist/index.d.ts +3 -0
  52. package/dist/index.js +251 -0
  53. package/dist/logs/index.d.ts +19 -0
  54. package/dist/logs/index.js +132 -0
  55. package/dist/npm-launch.d.ts +19 -0
  56. package/dist/npm-launch.js +80 -0
  57. package/dist/ops/agent.d.ts +3 -0
  58. package/dist/ops/agent.js +14 -0
  59. package/dist/ops/cache.d.ts +18 -0
  60. package/dist/ops/cache.js +92 -0
  61. package/dist/ops/parse.d.ts +6 -0
  62. package/dist/ops/parse.js +106 -0
  63. package/dist/ops/register.d.ts +18 -0
  64. package/dist/ops/register.js +174 -0
  65. package/dist/ops/run.d.ts +20 -0
  66. package/dist/ops/run.js +127 -0
  67. package/dist/ops/types.d.ts +41 -0
  68. package/dist/ops/types.js +16 -0
  69. package/dist/protocol.d.ts +4 -0
  70. package/dist/protocol.js +17 -0
  71. package/dist/reserved.d.ts +4 -0
  72. package/dist/reserved.js +25 -0
  73. package/dist/turns/index.d.ts +20 -0
  74. package/dist/turns/index.js +108 -0
  75. package/dist/version.d.ts +2 -0
  76. package/dist/version.js +11 -0
  77. package/package.json +48 -4
  78. package/skill/SKILL.md +17 -0
@@ -0,0 +1,142 @@
1
+ import { cliCommand } from './auth.js';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { homedir } from 'node:os';
4
+ export function orgFromCloneUrl(cloneUrl) {
5
+ const slash = cloneUrl.includes('://') ? cloneUrl : `ssh://${cloneUrl.replace(':', '/')}`;
6
+ try {
7
+ const parts = new URL(slash).pathname.split('/').filter(Boolean);
8
+ const repo = parts.at(-1)?.replace(/\.git$/, '');
9
+ const org = parts.at(-2);
10
+ return repo && org ? org : null;
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
16
+ export function parseRemote(value) {
17
+ const trimmed = value.trim();
18
+ const scp = /^[^@/\s]+@([^:\s]+):(.+)$/.exec(trimmed);
19
+ try {
20
+ const url = new URL(scp ? 'ssh://' + scp[1] + '/' + scp[2] : trimmed);
21
+ if (!['https:', 'http:', 'ssh:'].includes(url.protocol) || url.search || url.hash)
22
+ return null;
23
+ const repoPath = url.pathname.replace(/^\/+|\/+$/g, '').replace(/\.git$/, '');
24
+ if (!repoPath.includes('/'))
25
+ return null;
26
+ const parts = repoPath.split('/');
27
+ const repository = parts.splice(-2).join('/').toLowerCase();
28
+ return {
29
+ protocol: url.protocol,
30
+ host: url.hostname.toLowerCase(),
31
+ port: url.port,
32
+ path: [...parts, repository].join('/'),
33
+ };
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ function sshEndpoint(raw, parsed, configFile) {
40
+ const host = parsed.host.replace(/^\[|\]$/g, '');
41
+ const address = raw.trim();
42
+ const login = /^ssh:\/\//i.test(address) ? new URL(address).username : address.split('@')[0];
43
+ if (!/^[a-z0-9.:_-]+$/i.test(host) || (login && !/^[a-z0-9._-]+$/i.test(login)))
44
+ return null;
45
+ const args = [
46
+ '-G',
47
+ ...(configFile ? ['-F', configFile] : []),
48
+ ...(login ? ['-l', login] : []),
49
+ ...(parsed.port ? ['-p', parsed.port] : []),
50
+ '--',
51
+ host,
52
+ ];
53
+ const result = spawnSync('ssh', args, { cwd: homedir(), encoding: 'utf8', timeout: 5000 });
54
+ if (result.status !== 0)
55
+ return null;
56
+ const name = /^hostname (.+)$/m.exec(result.stdout)?.[1]?.trim().toLowerCase();
57
+ const port = /^port (\d+)$/m.exec(result.stdout)?.[1];
58
+ if (!name || !port)
59
+ return null;
60
+ return { ...parsed, host: name.replace(/^\[|\]$/g, ''), port };
61
+ }
62
+ export function remotesMatch(origin, identity, sshConfigFile) {
63
+ const parsed = parseRemote(origin);
64
+ const actual = parsed?.protocol === 'ssh:' ? sshEndpoint(origin, parsed, sshConfigFile) : parsed;
65
+ if (!actual)
66
+ return false;
67
+ for (const candidate of [identity.httpsCloneUrl, identity.sshCloneUrl]) {
68
+ if (!candidate)
69
+ continue;
70
+ const expected = parseRemote(candidate);
71
+ if (!expected)
72
+ continue;
73
+ if (expected.protocol === 'ssh:') {
74
+ expected.port ||= '22';
75
+ expected.host = expected.host.replace(/^\[|\]$/g, '');
76
+ }
77
+ if (actual.protocol === expected.protocol &&
78
+ actual.host === expected.host &&
79
+ actual.port === expected.port &&
80
+ actual.path === expected.path)
81
+ return true;
82
+ }
83
+ return false;
84
+ }
85
+ export { findCloneRoot as findCompanyRepo } from '../handover/clone.js';
86
+ function gitOutput(args) {
87
+ return new Promise((resolve) => {
88
+ const env = { ...process.env };
89
+ delete env.GIT_DIR;
90
+ delete env.GIT_WORK_TREE;
91
+ delete env.GIT_COMMON_DIR;
92
+ const child = spawn('git', args, { env, stdio: ['ignore', 'pipe', 'ignore'] });
93
+ const out = [];
94
+ child.stdout.on('data', (chunk) => out.push(chunk));
95
+ child.on('error', () => resolve(''));
96
+ child.on('close', (status) => {
97
+ resolve(status === 0 ? Buffer.concat(out).toString('utf8') : '');
98
+ });
99
+ });
100
+ }
101
+ async function gitOrigin(root) {
102
+ const url = (await gitOutput(['-C', root, 'remote', 'get-url', '--', 'origin'])).trim();
103
+ await checkSshCommand(root, [url]);
104
+ return url || null;
105
+ }
106
+ async function checkSshCommand(root, urls) {
107
+ if (urls.some((url) => parseRemote(url)?.protocol === 'ssh:')) {
108
+ const setting = async (key, fallback) => (await gitOutput(['-C', root, 'config', '--default', fallback, '--get', key])).trim();
109
+ const command = process.env.GIT_SSH_COMMAND ?? (await setting('core.sshCommand', process.env.GIT_SSH ?? 'ssh'));
110
+ const variant = process.env.GIT_SSH_VARIANT ?? (await setting('ssh.variant', 'auto'));
111
+ if (command !== 'ssh' || !['ssh', 'auto'].includes(variant))
112
+ throw new Error('Cannot verify the repository with a custom Git SSH command or variant. Use standard OpenSSH configuration or the company HTTPS URL.');
113
+ }
114
+ }
115
+ async function effectiveOriginUrls(root) {
116
+ const read = async (flags) => {
117
+ const output = await gitOutput(['-C', root, 'remote', 'get-url', ...flags, '--all', '--', 'origin']);
118
+ return output.trimEnd().split(/\r?\n/);
119
+ };
120
+ const urls = [...(await read([])), ...(await read(['--push']))];
121
+ await checkSshCommand(root, urls);
122
+ return urls;
123
+ }
124
+ export async function companyCloneStatus(root, identity) {
125
+ const location = await gitOutput(['-C', root, 'rev-parse', '--is-inside-work-tree', '--show-prefix']);
126
+ if (!/^true\r?\n\r?\n$/.test(location))
127
+ return 'missing';
128
+ const urls = await effectiveOriginUrls(root);
129
+ if (!urls.every((url) => remotesMatch(url, identity)))
130
+ return 'different';
131
+ return 'matches';
132
+ }
133
+ export async function assertRepoMatchesLogin(root, identity, backendUrl) {
134
+ const recover = `Run \`${cliCommand('logout', backendUrl)}\`, then \`${cliCommand('login', backendUrl)}\` for this company.`;
135
+ const origin = await gitOrigin(root);
136
+ if (!origin || !parseRemote(origin))
137
+ throw new Error(`This directory has no git origin this login can check. Open the company repo. ${recover}`);
138
+ if (!identity.httpsCloneUrl && !identity.sshCloneUrl)
139
+ throw new Error(`This login has no company repo to compare with this directory. ${recover}`);
140
+ if (!remotesMatch(origin, identity))
141
+ throw new Error(`This directory's git origin is not the company you are logged in to. Open that company's repo. ${recover}`);
142
+ }
@@ -0,0 +1,5 @@
1
+ import { type DeviceLogin } from './auth.js';
2
+ export declare function readPendingLogin(backendUrl: string, epoch: number, file?: string): DeviceLogin | null;
3
+ export declare function savePendingLogin(backendUrl: string, login: DeviceLogin, epoch: number, file?: string): Promise<void>;
4
+ export declare function clearPendingLogin(backendUrl: string, file?: string, epoch?: number): Promise<void>;
5
+ //# sourceMappingURL=pending-login.d.ts.map
@@ -0,0 +1,67 @@
1
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { backendCacheKey, withCacheLock } from './auth.js';
5
+ function pendingPath(file) {
6
+ return file ?? path.join(homedir(), '.superpanel', 'pending-login.json');
7
+ }
8
+ function readFile(file) {
9
+ try {
10
+ const parsed = JSON.parse(readFileSync(pendingPath(file), 'utf8'));
11
+ if (parsed?.version !== 1 || !parsed.backends)
12
+ return { version: 1, backends: {} };
13
+ return parsed;
14
+ }
15
+ catch {
16
+ return { version: 1, backends: {} };
17
+ }
18
+ }
19
+ function writeFile(pending, file) {
20
+ const target = pendingPath(file);
21
+ const dir = path.dirname(target);
22
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
23
+ chmodSync(dir, 0o700);
24
+ const tmp = `${target}.${process.pid}.tmp`;
25
+ writeFileSync(tmp, JSON.stringify(pending), { mode: 0o600 });
26
+ chmodSync(tmp, 0o600);
27
+ renameSync(tmp, target);
28
+ chmodSync(target, 0o600);
29
+ }
30
+ function backendRows(pending, backendUrl) {
31
+ const key = backendCacheKey(backendUrl);
32
+ return Object.entries(pending.backends).filter(([stored]) => {
33
+ try {
34
+ return backendCacheKey(stored) === key;
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ });
40
+ }
41
+ export function readPendingLogin(backendUrl, epoch, file) {
42
+ const rows = backendRows(readFile(file), backendUrl)
43
+ .map(([, row]) => row)
44
+ .filter((row) => (row.epoch ?? 0) === epoch && row.expiresAt > Date.now());
45
+ return rows.sort((a, b) => b.expiresAt - a.expiresAt)[0] ?? null;
46
+ }
47
+ export async function savePendingLogin(backendUrl, login, epoch, file) {
48
+ await withCacheLock(pendingPath(file), async () => {
49
+ const pending = readFile(file);
50
+ const key = backendCacheKey(backendUrl);
51
+ for (const [alias] of backendRows(pending, backendUrl))
52
+ delete pending.backends[alias];
53
+ pending.backends[key] = { ...login, backendUrl: key, epoch };
54
+ writeFile(pending, file);
55
+ });
56
+ }
57
+ export async function clearPendingLogin(backendUrl, file, epoch) {
58
+ await withCacheLock(pendingPath(file), async () => {
59
+ const pending = readFile(file);
60
+ const rows = backendRows(pending, backendUrl).filter(([, row]) => epoch === undefined || (row.epoch ?? 0) === epoch);
61
+ if (!rows.length)
62
+ return;
63
+ for (const [key] of rows)
64
+ delete pending.backends[key];
65
+ writeFile(pending, file);
66
+ });
67
+ }
@@ -0,0 +1,26 @@
1
+ export type TokenSuccess = {
2
+ version: number;
3
+ backendUrl: string;
4
+ accessToken: string;
5
+ expiresAt: string;
6
+ login: {
7
+ userId: string;
8
+ email: string;
9
+ companyId: string;
10
+ companyName: string | null;
11
+ };
12
+ identity: {
13
+ userId: string;
14
+ companyId: string;
15
+ companyName: string | null;
16
+ giteaOrg: string | null;
17
+ httpsCloneUrl: string | null;
18
+ sshCloneUrl: string | null;
19
+ };
20
+ };
21
+ export declare function runAuthToken(options: {
22
+ json?: boolean;
23
+ protocol?: string;
24
+ url?: string;
25
+ }): Promise<void>;
26
+ //# sourceMappingURL=auth-token.d.ts.map
@@ -0,0 +1,71 @@
1
+ import { orgFromCloneUrl } from '../auth/origin.js';
2
+ import { CliLoginRejectedError, getValidCliAuthorization, loginCommand, resolveBackendUrl } from '../auth/auth.js';
3
+ import { getGitAccount } from '../api/platform.js';
4
+ import { negotiateProtocol, parseProtocolList } from '../protocol.js';
5
+ function fail(error, message, json) {
6
+ if (json)
7
+ console.log(JSON.stringify({ error, message }));
8
+ else
9
+ console.error(message);
10
+ process.exit(1);
11
+ }
12
+ export async function runAuthToken(options) {
13
+ const asked = options.protocol ? parseProtocolList(options.protocol) : [1];
14
+ const version = negotiateProtocol(asked);
15
+ if (version === null) {
16
+ fail('protocol_mismatch', 'This CLI does not speak a protocol the caller asked for. Update the CLI.', Boolean(options.json));
17
+ }
18
+ let backendUrl;
19
+ try {
20
+ backendUrl = resolveBackendUrl(options.url);
21
+ }
22
+ catch (error) {
23
+ fail('not_logged_in', error instanceof Error ? error.message : String(error), Boolean(options.json));
24
+ }
25
+ const recover = `Run \`${loginCommand(backendUrl)}\`.`;
26
+ let authorization;
27
+ try {
28
+ authorization = await getValidCliAuthorization(backendUrl);
29
+ }
30
+ catch (error) {
31
+ if (error instanceof CliLoginRejectedError) {
32
+ fail('login_ended', `The login has ended. ${recover}`, Boolean(options.json));
33
+ }
34
+ fail('backend_error', error instanceof Error ? error.message : String(error), Boolean(options.json));
35
+ }
36
+ if (!authorization)
37
+ fail('not_logged_in', `Not logged in. ${recover}`, Boolean(options.json));
38
+ let account;
39
+ try {
40
+ account = await getGitAccount(backendUrl, authorization.accessToken, { cliVersion: false });
41
+ }
42
+ catch (error) {
43
+ if (error instanceof CliLoginRejectedError)
44
+ fail('login_ended', `${error.message}. ${recover}`, Boolean(options.json));
45
+ fail('backend_error', error instanceof Error ? error.message : String(error), Boolean(options.json));
46
+ }
47
+ const body = {
48
+ version,
49
+ backendUrl,
50
+ accessToken: authorization.accessToken,
51
+ expiresAt: new Date(authorization.accessTokenExpiresAt).toISOString(),
52
+ login: {
53
+ userId: authorization.user.id,
54
+ email: authorization.user.email,
55
+ companyId: authorization.companyId,
56
+ companyName: authorization.companyName,
57
+ },
58
+ identity: {
59
+ userId: authorization.user.id,
60
+ companyId: authorization.companyId,
61
+ companyName: authorization.companyName,
62
+ giteaOrg: orgFromCloneUrl(account?.httpsCloneUrl ?? account?.sshCloneUrl ?? ''),
63
+ httpsCloneUrl: account?.httpsCloneUrl ?? null,
64
+ sshCloneUrl: account?.sshCloneUrl ?? null,
65
+ },
66
+ };
67
+ if (options.json)
68
+ console.log(JSON.stringify(body));
69
+ else
70
+ console.log(authorization.accessToken);
71
+ }
@@ -0,0 +1,54 @@
1
+ export type GitProtocol = 'https' | 'ssh';
2
+ export declare const GLOBAL_INSTALL_AGENT_PROMPT: string;
3
+ export declare function chooseGitProtocol(input: {
4
+ requested?: GitProtocol;
5
+ preferSsh: boolean;
6
+ installCli?: boolean;
7
+ }, globalCli?: () => string | null): GitProtocol | 'ask-install' | 'https-refused';
8
+ export declare function installFallback(requested?: GitProtocol): 'ssh' | 'stop';
9
+ export declare function gitSetupRefusal(git: {
10
+ ok: boolean;
11
+ message: string;
12
+ ssh?: {
13
+ status: string;
14
+ };
15
+ }, input: {
16
+ allowSshConfig: boolean;
17
+ command: 'setup' | 'setup-git';
18
+ backendUrl: string;
19
+ }): Error | null;
20
+ export declare function defaultCloneUsesSsh(role: string | undefined): boolean;
21
+ export declare function confirm(question: string, agent: boolean): Promise<boolean>;
22
+ export declare function globalCliInstalled(): boolean;
23
+ export declare function globalCliPath(): string | null;
24
+ export declare function prepareGitMethod(input: {
25
+ command: 'setup' | 'setup-git';
26
+ requested?: GitProtocol;
27
+ preferSsh: boolean;
28
+ installCli?: boolean;
29
+ onInstallAnswer?: (answer: boolean) => void;
30
+ backendUrl: string;
31
+ token: string;
32
+ agent: boolean;
33
+ ask?: (question: string) => Promise<boolean>;
34
+ globalCli?: () => string | null;
35
+ installArgs?: () => Promise<string[]>;
36
+ install?: (args: string[]) => {
37
+ ok: boolean;
38
+ text: string;
39
+ };
40
+ }): Promise<'https' | 'ssh'>;
41
+ export declare function offerGlobalCli(input: {
42
+ installCli?: boolean;
43
+ backendUrl: string;
44
+ token: string;
45
+ agent: boolean;
46
+ ask?: (question: string) => Promise<boolean>;
47
+ globalCli?: () => string | null;
48
+ installArgs?: () => Promise<string[]>;
49
+ install?: (args: string[]) => {
50
+ ok: boolean;
51
+ text: string;
52
+ };
53
+ }): Promise<void>;
54
+ //# sourceMappingURL=git-method.d.ts.map
@@ -0,0 +1,180 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { stdin as input, stdout as output } from 'node:process';
6
+ import { cliCommand } from '../auth/auth.js';
7
+ import { apiUrl, getJson, requestJson } from '../auth/http.js';
8
+ import { cliVersion } from '../version.js';
9
+ import { npmLaunch } from '../npm-launch.js';
10
+ import { NeedsPersonError } from '../ops/types.js';
11
+ const GLOBAL_INSTALL_QUESTION = 'We recommend installing the Superpanel CLI globally for your user account so you can run superpanel from any folder. Install it now?';
12
+ export const GLOBAL_INSTALL_AGENT_PROMPT = GLOBAL_INSTALL_QUESTION +
13
+ ' Ask the person, then rerun with --install-cli or --no-install-cli according to their reply.';
14
+ export function chooseGitProtocol(input, globalCli = globalCliPath) {
15
+ if (input.requested === 'ssh' || (!input.requested && input.preferSsh))
16
+ return 'ssh';
17
+ if (input.installCli === false)
18
+ return input.requested === 'https' ? 'https-refused' : 'ssh';
19
+ if (input.installCli === true || globalCli())
20
+ return 'https';
21
+ return 'ask-install';
22
+ }
23
+ export function installFallback(requested) {
24
+ return requested === 'https' || requested === 'ssh' ? 'stop' : 'ssh';
25
+ }
26
+ export function gitSetupRefusal(git, input) {
27
+ if (git.ssh?.status === 'needs-confirmation' && !input.allowSshConfig) {
28
+ const rerun = cliCommand(`${input.command} --git-protocol ssh --allow-ssh-config "<their words>"`, input.backendUrl);
29
+ return new NeedsPersonError(`${git.message}\nAsk the person, then rerun: ${rerun}`);
30
+ }
31
+ if (git.ssh?.status === 'needs-ssh-add') {
32
+ return new NeedsPersonError(`${git.message}\nThen run the setup command again.`);
33
+ }
34
+ if (!git.ok)
35
+ return new Error(git.message);
36
+ return null;
37
+ }
38
+ export function defaultCloneUsesSsh(role) {
39
+ return role === 'orgAdmin' || role === 'superAdmin';
40
+ }
41
+ export async function confirm(question, agent) {
42
+ if (agent)
43
+ return false;
44
+ const rl = createInterface({ input, output });
45
+ try {
46
+ const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
47
+ return answer === 'y' || answer === 'yes';
48
+ }
49
+ finally {
50
+ rl.close();
51
+ }
52
+ }
53
+ function runNpm(args) {
54
+ const launched = npmLaunch(args);
55
+ const result = spawnSync(launched.command, launched.args, {
56
+ encoding: 'utf8',
57
+ windowsVerbatimArguments: launched.verbatim === true,
58
+ });
59
+ return {
60
+ ok: result.status === 0,
61
+ stdout: (result.stdout ?? '').trim(),
62
+ stderr: (result.stderr || result.error?.message || '').trim(),
63
+ text: `${result.stdout ?? ''}${result.stderr ?? ''}`.trim(),
64
+ };
65
+ }
66
+ export function globalCliInstalled() {
67
+ return globalCliPath() !== null;
68
+ }
69
+ export function globalCliPath() {
70
+ const root = runNpm(['root', '-g']);
71
+ if (!root.ok) {
72
+ console.error('Could not locate the global npm directory' + (root.stderr ? ': ' + root.stderr : '.'));
73
+ return null;
74
+ }
75
+ if (!path.isAbsolute(root.stdout))
76
+ return null;
77
+ const entry = path.join(root.stdout, '@superpanel-sdk', 'cli', 'bin', 'superpanel.mjs');
78
+ return existsSync(entry) ? entry : null;
79
+ }
80
+ async function globalCliNeedsUpgrade(entry, backendUrl, token) {
81
+ const manifest = JSON.parse(readFileSync(path.resolve(path.dirname(entry), '../package.json'), 'utf8'));
82
+ if (manifest.version === cliVersion())
83
+ return false;
84
+ const { response } = await requestJson(apiUrl(backendUrl, 'me'), {
85
+ headers: { Authorization: 'Bearer ' + token, 'Superpanel-Cli-Version': manifest.version ?? '' },
86
+ });
87
+ if (response.status === 426)
88
+ return true;
89
+ if (!response.ok)
90
+ throw new Error('Could not verify the global CLI with the target backend (HTTP ' + response.status + ').');
91
+ return false;
92
+ }
93
+ async function npmInstallArgs(backendUrl, token) {
94
+ const args = ['install', '-g', '@superpanel-sdk/cli@latest'];
95
+ try {
96
+ const { response, payload } = await getJson(apiUrl(backendUrl, 'cli/info'), token);
97
+ if (!response.ok)
98
+ throw new Error('HTTP ' + response.status);
99
+ const registry = payload.registry;
100
+ if (registry !== null && registry !== '') {
101
+ if (typeof registry !== 'string' || !['https:', 'http:'].includes(new URL(registry).protocol))
102
+ throw new Error('Invalid registry address');
103
+ args.push('--@superpanel-sdk:registry=' + registry.replace(/\/+$/, ''));
104
+ }
105
+ }
106
+ catch (error) {
107
+ throw new Error('Could not determine the CLI registry from the target backend. Retry setup when it is reachable.', {
108
+ cause: error,
109
+ });
110
+ }
111
+ return args;
112
+ }
113
+ export async function prepareGitMethod(input) {
114
+ const ask = input.ask ?? ((question) => confirm(question, input.agent));
115
+ const globalCli = input.globalCli ?? globalCliPath;
116
+ const install = input.install ?? runNpm;
117
+ const installArgs = input.installArgs ?? (() => npmInstallArgs(input.backendUrl, input.token));
118
+ let installCli = input.installCli;
119
+ const choice = chooseGitProtocol({
120
+ requested: input.requested,
121
+ preferSsh: input.preferSsh,
122
+ installCli,
123
+ }, globalCli);
124
+ if (choice === 'https' && installCli === undefined)
125
+ return 'https';
126
+ if (input.command === 'setup' && choice === 'ssh')
127
+ return 'ssh';
128
+ if (choice === 'ask-install') {
129
+ const yes = await ask('Git over HTTPS needs the global CLI. ' + GLOBAL_INSTALL_QUESTION);
130
+ if (!yes && input.agent) {
131
+ throw new NeedsPersonError(`${input.command}: ${GLOBAL_INSTALL_AGENT_PROMPT}`);
132
+ }
133
+ installCli = yes;
134
+ input.onInstallAnswer?.(yes);
135
+ }
136
+ const entry = installCli === true ? globalCli() : null;
137
+ if (installCli === true &&
138
+ (!entry || (choice === 'https' && (await globalCliNeedsUpgrade(entry, input.backendUrl, input.token))))) {
139
+ const installed = install(await installArgs());
140
+ if (!installed.ok || !globalCli()) {
141
+ if (installFallback(input.requested) === 'stop') {
142
+ throw new Error(installed.text ||
143
+ 'Could not install @superpanel-sdk/cli for this user. HTTPS git needs that install. Use --git-protocol ssh to skip it.');
144
+ }
145
+ console.error('The global CLI did not install, so git will use SSH.');
146
+ installCli = false;
147
+ input.onInstallAnswer?.(false);
148
+ }
149
+ }
150
+ const method = chooseGitProtocol({
151
+ requested: input.requested,
152
+ preferSsh: input.preferSsh,
153
+ installCli,
154
+ }, globalCli);
155
+ if (method === 'https-refused') {
156
+ throw new Error('HTTPS git needs the CLI installed for this user. Rerun with --install-cli, or use --git-protocol ssh.');
157
+ }
158
+ if (method !== 'https' && method !== 'ssh')
159
+ throw new Error('Could not choose a git protocol.');
160
+ return method;
161
+ }
162
+ export async function offerGlobalCli(input) {
163
+ const globalCli = input.globalCli ?? globalCliPath;
164
+ if (input.installCli === false)
165
+ return;
166
+ const entry = globalCli();
167
+ if (entry && (input.installCli !== true || !(await globalCliNeedsUpgrade(entry, input.backendUrl, input.token))))
168
+ return;
169
+ const yes = input.installCli ??
170
+ (await (input.ask ?? ((question) => confirm(question, input.agent)))(GLOBAL_INSTALL_QUESTION));
171
+ if (!yes) {
172
+ if (input.agent && input.installCli === undefined) {
173
+ throw new NeedsPersonError(GLOBAL_INSTALL_AGENT_PROMPT);
174
+ }
175
+ return;
176
+ }
177
+ const installed = (input.install ?? runNpm)(await (input.installArgs ?? (() => npmInstallArgs(input.backendUrl, input.token)))());
178
+ if (!installed.ok || !globalCli())
179
+ throw new Error(installed.text || 'Could not install @superpanel-sdk/cli for this user.');
180
+ }
@@ -0,0 +1,88 @@
1
+ import { chooseGitProtocol, type GitProtocol } from './git-method.js';
2
+ export { chooseGitProtocol, defaultCloneUsesSsh, gitSetupRefusal, installFallback, type GitProtocol, } from './git-method.js';
3
+ export type SetupAnswers = {
4
+ company?: string;
5
+ gitProtocol?: GitProtocol;
6
+ installCli?: boolean;
7
+ installSkill?: boolean;
8
+ allowSshConfig?: string;
9
+ allowBackendChange?: boolean;
10
+ allowAgentInstructions?: string;
11
+ noAgentInstructions?: boolean;
12
+ url?: string;
13
+ waitSeconds?: number;
14
+ };
15
+ export declare function answersFromSetupOptions(options: {
16
+ url?: string;
17
+ company?: string;
18
+ gitProtocol?: string;
19
+ installCli?: boolean;
20
+ installSkill?: boolean;
21
+ agentInstructions?: boolean;
22
+ allowSshConfig?: string;
23
+ allowBackendChange?: boolean;
24
+ allowAgentInstructions?: string;
25
+ waitSeconds?: string;
26
+ }): SetupAnswers;
27
+ export declare function sameCompanyClone(origin: string, identity: {
28
+ httpsCloneUrl: string | null;
29
+ sshCloneUrl: string | null;
30
+ }): boolean;
31
+ export declare function companyFolder(org: string): string;
32
+ export declare function setupQuestionsForAgent(input: {
33
+ protocol: ReturnType<typeof chooseGitProtocol> | null;
34
+ backendChangePath: string | null;
35
+ instructions: boolean;
36
+ }): string[];
37
+ export type SetupConfigRead = {
38
+ status: 'absent';
39
+ } | {
40
+ status: 'ok';
41
+ config: Record<string, unknown>;
42
+ } | {
43
+ status: 'unreadable';
44
+ message: string;
45
+ };
46
+ export declare function setupConfigPlan(input: {
47
+ path: string;
48
+ read: SetupConfigRead;
49
+ backendUrl: string;
50
+ shellUrl?: string;
51
+ allowBackendChange?: boolean;
52
+ }): {
53
+ action: 'stop';
54
+ message: string;
55
+ } | {
56
+ action: 'shell';
57
+ } | {
58
+ action: 'keep';
59
+ } | {
60
+ action: 'write';
61
+ text: string | null;
62
+ confirm: boolean;
63
+ };
64
+ export type InstructionAgent = 'claude' | 'codex';
65
+ export declare function instructionAgent(env?: NodeJS.ProcessEnv): InstructionAgent | null;
66
+ export declare function instructionFiles(input: {
67
+ home: string;
68
+ runningAsAgent: boolean;
69
+ env?: NodeJS.ProcessEnv;
70
+ directoryExists: (dir: string) => boolean;
71
+ }): string[];
72
+ export { orgFromCloneUrl } from '../auth/origin.js';
73
+ export declare function instructionBlock(existing: string, org: string, display: string, folder: string): string;
74
+ export declare function configBackendChange(config: Record<string, unknown> | null, backendUrl: string, shellUrl: string | undefined): {
75
+ kind: 'shell';
76
+ } | {
77
+ kind: 'keep';
78
+ } | {
79
+ kind: 'write';
80
+ text: string | null;
81
+ };
82
+ export declare function supportedSetupNode(version: string): boolean;
83
+ export declare function runSetup(options: SetupAnswers): Promise<void>;
84
+ export declare function offerSkill(options: Pick<SetupAnswers, 'installSkill'>, deps?: {
85
+ globalCli?: () => boolean;
86
+ homes?: string[];
87
+ }): Promise<void>;
88
+ //# sourceMappingURL=setup.d.ts.map