#!/usr/bin/env node import { input, password as pwPrompt, select } from '@inquirer/prompts'; import { loadConfig, saveConfig, updateServiceServerConfig, getServiceConfig, getSshKeyPath, syncServerKeyAuth, resolveServiceDeployPath, getArtifactsRoot, } from './config.js'; import { buildAndDeployServices, buildServicesOnly, deployArtifactsOnly, checkRemoteDocker, restartService, serviceLogs, serviceStatus, stopService, } from './deploy/index.js'; import { ensureKeyPair, setupSSHKey, testConnection } from './ssh.js'; import { BACK, checkboxNav, selectNav, type Nav } from './ui/nav-prompt.js'; import { printBanner, printBox, printError, printInfo, printSuccess } from './ui/render.js'; import { ENV_LABELS, SERVICE_LABELS } from './types.js'; import type { DeployConfig, Environment, Service } from './types.js'; const ALL_SERVICES: Service[] = ['frontend', 'backend', 'license', 'agent']; async function pause() { await input({ message: '按 Enter 返回主菜单' }); } function isExitPrompt(e: unknown): boolean { return (e as { name?: string })?.name === 'ExitPromptError'; } async function selectEnv(): Promise { const config = await loadConfig(); const env = await selectNav({ message: '选择环境', choices: (['test', 'pre', 'prod'] as Environment[]).map((e) => ({ name: `${e === config.currentEnv ? '● ' : ' '}${ENV_LABELS[e]}`, value: e, })), }); if (env === BACK) return BACK; config.currentEnv = env; await saveConfig(config); return env; } async function selectService(): Promise { return await selectNav({ message: '选择服务', choices: [ { name: '前端', value: 'frontend' as Service }, { name: '后端', value: 'backend' as Service }, { name: '许可证', value: 'license' as Service }, { name: '智能体', value: 'agent' as Service }, ], }); } /** 空格多选服务;← 返回上一步 */ async function selectServicesMulti(): Promise { const scope = await selectNav({ message: '部署范围', choices: [ { name: '全部服务', value: 'all' as const, description: '前端 + 后端 + 许可证 + 智能体' }, { name: '指定服务…', value: 'pick' as const, description: '空格多选' }, ], }); if (scope === BACK) return BACK; if (scope === 'all') return [...ALL_SERVICES]; const picked = await checkboxNav({ message: '勾选服务', choices: [ { name: '前端', value: 'frontend' as Service }, { name: '后端', value: 'backend' as Service }, { name: '许可证', value: 'license' as Service }, { name: '智能体', value: 'agent' as Service }, ], required: true, }); return picked; } function showServiceHosts(config: DeployConfig): string { const env = config.currentEnv; return ALL_SERVICES.map((s) => { const cfg = config.services[s][env]; const resolved = resolveServiceDeployPath(cfg, s, env); return ` ${SERVICE_LABELS[s]}: ${cfg.server.host} → ${resolved}`; }).join('\n'); } async function configureService() { while (true) { const service = await selectService(); if (service === BACK) return; const env = await selectEnv(); if (env === BACK) continue; while (true) { const config = await loadConfig(); const cfg = config.services[service][env]; const srv = cfg.server; console.clear(); printBox(`${SERVICE_LABELS[service]} · ${ENV_LABELS[env]}`, [ `服务器: ${srv.host}:${srv.port}`, `用户: ${srv.username}`, `部署根: ${srv.deployPath}`, `实际目录: ${resolveServiceDeployPath(cfg, service, env)}`, `端口: ${cfg.port}`, `认证: ${srv.authType === 'key' ? '密钥' : '密码'}`, ].join('\n')); const action = await selectNav({ message: '配置项', choices: [ { name: '服务器地址', value: 'host' as const }, { name: 'SSH 端口', value: 'port' as const }, { name: '服务端口', value: 'svcPort' as const }, { name: '用户名', value: 'username' as const }, { name: '部署根目录', value: 'deployPath' as const }, { name: '测试 SSH', value: 'test' as const }, { name: '配置免密密钥', value: 'setupKey' as const, description: '首次上传公钥' }, ], }); if (action === BACK) break; switch (action) { case 'host': { const host = await input({ message: '服务器地址', default: srv.host }); await updateServiceServerConfig(service, env, { host }); break; } case 'port': { const p = await input({ message: 'SSH 端口', default: String(srv.port) }); await updateServiceServerConfig(service, env, { port: Number(p) }); break; } case 'svcPort': { const p = await input({ message: '服务端口', default: String(cfg.port) }); const { updateServiceEnvConfig } = await import('./config.js'); await updateServiceEnvConfig(service, env, { port: Number(p) }); break; } case 'username': { const u = await input({ message: 'SSH 用户', default: srv.username }); await updateServiceServerConfig(service, env, { username: u }); break; } case 'deployPath': { const hint = service === 'frontend' ? '部署根(实际为 根/ecom-dmb-{env}/index)' : '部署根(实际为 根/ecom-dmb/{service}/{env})'; const d = await input({ message: hint, default: srv.deployPath }); await updateServiceServerConfig(service, env, { deployPath: d }); break; } case 'test': { const ok = await testConnection(srv); if (ok) printSuccess('SSH 连接成功'); else printError('SSH 连接失败'); await pause(); break; } case 'setupKey': { const pwd = await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true }); try { await setupSSHKey(srv, pwd); await syncServerKeyAuth(srv.host, srv.username, { authType: 'key', keyPath: getSshKeyPath(), }); } catch (e: any) { printError(`密钥配置失败: ${e.message}`); } await pause(); break; } } } } } async function deployMenu() { type DeployMode = 'auto' | 'buildOnly' | 'uploadOnly'; type Step = 'mode' | 'services' | 'confirm'; let step: Step = 'mode'; let deployMode: DeployMode = 'auto'; let services: Service[] = []; const config = await loadConfig(); const env = config.currentEnv; printBox('当前环境', `${ENV_LABELS[env]}\n${showServiceHosts(config)}`, 'yellow'); while (true) { if (step === 'mode') { const mode = await selectNav({ message: '部署方式', choices: [ { name: '自动部署', value: 'auto' as const, description: '编译 → 上传 → 重启' }, { name: '仅编译', value: 'buildOnly' as const, description: '产物到 artifacts/,不上传' }, { name: '仅上传重启', value: 'uploadOnly' as const, description: '用已有 artifacts/,不编译' }, ], }); if (mode === BACK) return; deployMode = mode; step = 'services'; continue; } if (step === 'services') { const picked = await selectServicesMulti(); if (picked === BACK) { step = 'mode'; continue; } services = picked; printBox( '待部署', services.map((s) => `${SERVICE_LABELS[s]} → ${config.services[s][env].server.host}`).join('\n'), 'cyan', ); if (deployMode === 'buildOnly') { printInfo(`产物目录: ${getArtifactsRoot()}`); } step = 'confirm'; continue; } const ok = await selectNav({ message: '确认执行?', choices: [ { name: '开始', value: 'go' as const }, { name: '取消', value: 'cancel' as const }, ], }); if (ok === BACK) { step = 'services'; continue; } if (ok === 'cancel') return; const onPassword = async (s: Service) => { const cfg = config.services[s][env]; return await pwPrompt({ message: `输入 ${cfg.server.host} 的 SSH 密码`, mask: true }); }; try { console.clear(); if (deployMode === 'auto') { await buildAndDeployServices(services, onPassword); } else if (deployMode === 'buildOnly') { await buildServicesOnly(services); printSuccess(`编译完成,产物位于 ${getArtifactsRoot()}`); } else { await deployArtifactsOnly(services, onPassword); } } catch (e: any) { printError(`操作失败: ${e.message}`); } return; } } async function serviceMenu() { while (true) { const service = await selectService(); if (service === BACK) return; const config = await loadConfig(); const cfg = getServiceConfig(config, service); const srv = cfg.server; while (true) { const action = await selectNav({ message: `${SERVICE_LABELS[service]} · ${srv.host}`, choices: [ { name: '状态', value: 'status' as const }, { name: '日志', value: 'logs' as const }, { name: '重启', value: 'restart' as const }, { name: '停止', value: 'stop' as const }, { name: '检查 Docker', value: 'checkDocker' as const }, ], }); if (action === BACK) break; console.clear(); const onPassword = async () => await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true }); try { switch (action) { case 'status': { const ps = await serviceStatus(service, onPassword); console.log(ps || '暂无运行的服务'); break; } case 'logs': { const lines = await input({ message: '日志行数', default: '50' }); const logs = await serviceLogs(service, Number(lines) || 50, onPassword); console.log(logs || '(无日志)'); break; } case 'restart': await restartService(service, onPassword); break; case 'stop': await stopService(service, onPassword); break; case 'checkDocker': await checkRemoteDocker(service, onPassword); break; } } catch (e: any) { printError(`操作失败: ${e.message}`); } await pause(); console.clear(); } } } async function sshMenu() { while (true) { const service = await selectService(); if (service === BACK) return; const config = await loadConfig(); const env = config.currentEnv; const srv = config.services[service][env].server; while (true) { const action = await selectNav({ message: `SSH · ${SERVICE_LABELS[service]} (${srv.host})`, choices: [ { name: '密钥状态', value: 'status' as const }, { name: '生成密钥对', value: 'genKey' as const }, { name: '上传公钥', value: 'uploadKey' as const }, { name: '测试连接', value: 'test' as const }, ], }); if (action === BACK) break; console.clear(); switch (action) { case 'status': { const { existsSync } = await import('fs'); if (existsSync(getSshKeyPath())) printSuccess(`密钥存在: ${getSshKeyPath()}`); else printInfo('尚未生成 SSH 密钥对'); break; } case 'genKey': { ensureKeyPair(); printSuccess('SSH 密钥对已生成'); break; } case 'uploadKey': { const pwd = await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true }); try { await setupSSHKey(srv, pwd); await syncServerKeyAuth(srv.host, srv.username, { authType: 'key', keyPath: getSshKeyPath(), }); } catch (e: any) { printError(`上传失败: ${e.message}`); } break; } case 'test': { const pwd = srv.authType === 'password' ? await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true }) : undefined; const ok = await testConnection(srv, pwd); if (ok) printSuccess('SSH 连接成功'); else printError('SSH 连接失败'); break; } } await pause(); console.clear(); } } } async function mainMenu(): Promise<'continue' | 'exit'> { console.clear(); printBanner(); const config = await loadConfig(); const env = config.currentEnv; printInfo(`当前环境: ${ENV_LABELS[env]}`); console.log(showServiceHosts(config)); printInfo('提示: 子菜单按 ← 返回上一步'); const action = await select({ message: '主菜单', choices: [ { name: '部署', value: 'deploy' }, { name: '服务管理', value: 'service' }, { name: '配置', value: 'config' }, { name: 'SSH', value: 'ssh' }, { name: '切换环境', value: 'switchEnv' }, { name: '退出', value: 'exit' }, ], theme: { style: { keysHelpTip: () => '↑↓ 选择 · ⏎ 确认', }, }, }); switch (action) { case 'deploy': console.clear(); await deployMenu(); break; case 'service': console.clear(); await serviceMenu(); break; case 'config': await configureService(); break; case 'ssh': await sshMenu(); break; case 'switchEnv': { const newEnv = await selectEnv(); if (newEnv !== BACK) { printSuccess(`已切换到: ${ENV_LABELS[newEnv]}`); } break; } case 'exit': return 'exit'; } return 'continue'; } async function main() { while (true) { try { const result = await mainMenu(); if (result === 'exit') process.exit(0); await pause(); } catch (e: any) { if (isExitPrompt(e)) { printInfo('已取消'); continue; } printError(String(e?.message || e)); await pause(); } } } main();