#!/usr/bin/env node import { input, password as pwPrompt, select } from '@inquirer/prompts'; import { loadConfig, saveConfig, updateServiceServerConfig, getServiceConfig, getSshKeyPath, syncServerKeyAuth, resolveServiceDeployPath } from './config.js'; import { buildAndDeployServices, buildServicesOnly, deployArtifactsOnly, checkRemoteDocker, restartService, serviceLogs, serviceStatus, stopService, } from './deploy/index.js'; import { getArtifactsRoot } from './config.js'; import { ensureKeyPair, setupSSHKey, testConnection } from './ssh.js'; import { printBanner, printBox, printError, printInfo, printSuccess } from './ui/render.js'; import { ENV_LABELS, SERVICE_LABELS } from './types.js'; import type { Environment, Service } from './types.js'; async function pause() { await input({ message: '按 Enter 返回' }); } async function selectEnv(): Promise { const config = await loadConfig(); const env = await select({ message: '选择环境', choices: (['test', 'pre', 'prod'] as Environment[]).map((e) => ({ name: `${e === config.currentEnv ? '● ' : ' '}${ENV_LABELS[e]}`, value: e, })), }); config.currentEnv = env; await saveConfig(config); return env; } async function selectService(): Promise { return await select({ message: '选择服务', choices: [ { name: '前端', value: 'frontend' }, { name: '后端', value: 'backend' }, { name: '许可证服务', value: 'license' }, ], }) as Service; } async function selectServices(): Promise { const selected = await select({ message: '选择服务', choices: [ { name: '全部服务', value: 'all' as any }, { name: '前端', value: 'frontend' }, { name: '后端', value: 'backend' }, { name: '许可证服务', value: 'license' }, ], }); if (selected === 'all') return ['frontend', 'backend', 'license']; return [selected as Service]; } function showServiceHosts(config: Awaited>): string { const env = config.currentEnv; const services: Service[] = ['frontend', 'backend', 'license']; return 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() { const config = await loadConfig(); const service = await selectService(); const env = await selectEnv(); 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 select({ message: '配置操作', choices: [ { name: '修改服务器地址', value: 'host' }, { name: '修改端口', value: 'port' }, { name: '修改服务端口', value: 'svcPort' }, { name: '修改用户名', value: 'username' }, { name: '修改部署根目录', value: 'deployPath' }, { name: '测试 SSH 连接', value: 'test' }, { name: '配置 SSH 密钥 (首次免密)', value: 'setupKey' }, { name: '返回', value: 'back' }, ], }); 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 连接失败'); 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}`); } break; } } } async function deployMenu() { const config = await loadConfig(); const env = config.currentEnv; printBox('当前环境', `${ENV_LABELS[env]}\n${showServiceHosts(config)}`, 'yellow'); const deployMode = await select({ message: '部署方式', choices: [ { name: '自动部署(编译 + 上传 + 重启)', value: 'auto' }, { name: '仅编译产物(不上传,输出到 artifacts/)', value: 'buildOnly' }, { name: '上传产物并重启(从 artifacts/,不编译)', value: 'uploadOnly' }, { name: '取消', value: 'cancel' }, ], }); if (deployMode === 'cancel') return; const services = await selectServices(); printBox('待部署服务', services.map((s) => `${SERVICE_LABELS[s]} → ${config.services[s][env].server.host}`).join('\n'), 'cyan'); if (deployMode === 'buildOnly') { printInfo(`产物目录: ${getArtifactsRoot()}`); } const ok = await select({ message: '确认执行?', choices: [{ name: '开始', value: 'go' }, { name: '取消', value: 'cancel' }], }); 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}`); } } async function serviceMenu() { const service = await selectService(); const config = await loadConfig(); const cfg = getServiceConfig(config, service); const srv = cfg.server; const action = await select({ message: `${SERVICE_LABELS[service]} 管理 (${srv.host})`, choices: [ { name: '查看状态', value: 'status' }, { name: '查看日志', value: 'logs' }, { name: '重启服务', value: 'restart' }, { name: '停止服务', value: 'stop' }, { name: '检查 Docker 环境', value: 'checkDocker' }, { name: '返回', value: 'back' }, ], }); if (action === 'back') return; 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}`); } } async function sshMenu() { const config = await loadConfig(); const service = await selectService(); const env = config.currentEnv; const srv = config.services[service][env].server; const action = await select({ message: `${SERVICE_LABELS[service]} SSH 管理 (${srv.host})`, choices: [ { name: '查看 SSH 密钥状态', value: 'status' }, { name: '生成 SSH 密钥对', value: 'genKey' }, { name: '上传公钥到服务器', value: 'uploadKey' }, { name: '测试连接', value: 'test' }, { name: '返回', value: 'back' }, ], }); if (action === 'back') return; 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; } } } async function mainMenu() { console.clear(); printBanner(); const config = await loadConfig(); const env = config.currentEnv; printInfo(`当前环境: ${ENV_LABELS[env]}`); console.log(showServiceHosts(config)); 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' }, ], }); 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(); printSuccess(`已切换到: ${ENV_LABELS[newEnv]}`); break; } case 'exit': process.exit(0); } } async function main() { while (true) { try { await mainMenu(); await pause(); } catch (e: any) { if (e?.name === 'ExitPromptError') process.exit(0); printError(String(e?.message || e)); await pause(); } } } main();