feat: 部署 TUI 支持多选服务与分层返回

This commit is contained in:
2026-09-17 10:04:23 +08:00
parent 8c56cfb0b5
commit 2ff2407e05
4 changed files with 425 additions and 247 deletions
+6 -4
View File
@@ -64,13 +64,15 @@ cd deploy
pnpm dev pnpm dev
``` ```
进入 **部署服务**,选择: 进入 **部署**,选择:
| 选项 | 说明 | | 选项 | 说明 |
|------|------| |------|------|
| 自动部署 | 编译 → 上传到服务器 → 重启容器 | | 自动部署 | 编译 → 上传 → 重启 |
| 仅编译产物 | 只编译到 `artifacts/`,不上传 | | 仅编译 | 只编译到 `artifacts/`,不上传 |
| 上传产物并重启 | 从 `artifacts/` 上传并重启,不重新编译 | | 仅上传重启 | 从 `artifacts/` 上传并重启,不重新编译 |
服务范围可选「全部」或「指定服务…」(空格多选)。子菜单按 **← 左方向键** 返回上一步。
--- ---
+349 -239
View File
@@ -1,7 +1,16 @@
#!/usr/bin/env node #!/usr/bin/env node
import { input, password as pwPrompt, select } from '@inquirer/prompts'; import { input, password as pwPrompt, select } from '@inquirer/prompts';
import { loadConfig, saveConfig, updateServiceServerConfig, getServiceConfig, getSshKeyPath, syncServerKeyAuth, resolveServiceDeployPath } from './config.js'; import {
loadConfig,
saveConfig,
updateServiceServerConfig,
getServiceConfig,
getSshKeyPath,
syncServerKeyAuth,
resolveServiceDeployPath,
getArtifactsRoot,
} from './config.js';
import { import {
buildAndDeployServices, buildAndDeployServices,
buildServicesOnly, buildServicesOnly,
@@ -12,59 +21,75 @@ import {
serviceStatus, serviceStatus,
stopService, stopService,
} from './deploy/index.js'; } from './deploy/index.js';
import { getArtifactsRoot } from './config.js';
import { ensureKeyPair, setupSSHKey, testConnection } from './ssh.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 { printBanner, printBox, printError, printInfo, printSuccess } from './ui/render.js';
import { ENV_LABELS, SERVICE_LABELS } from './types.js'; import { ENV_LABELS, SERVICE_LABELS } from './types.js';
import type { Environment, Service } from './types.js'; import type { DeployConfig, Environment, Service } from './types.js';
const ALL_SERVICES: Service[] = ['frontend', 'backend', 'license'];
async function pause() { async function pause() {
await input({ message: '按 Enter 返回' }); await input({ message: '按 Enter 返回主菜单' });
} }
async function selectEnv(): Promise<Environment> { function isExitPrompt(e: unknown): boolean {
return (e as { name?: string })?.name === 'ExitPromptError';
}
async function selectEnv(): Promise<Environment | Nav> {
const config = await loadConfig(); const config = await loadConfig();
const env = await select({ const env = await selectNav({
message: '选择环境', message: '选择环境',
choices: (['test', 'pre', 'prod'] as Environment[]).map((e) => ({ choices: (['test', 'pre', 'prod'] as Environment[]).map((e) => ({
name: `${e === config.currentEnv ? '● ' : ' '}${ENV_LABELS[e]}`, name: `${e === config.currentEnv ? '● ' : ' '}${ENV_LABELS[e]}`,
value: e, value: e,
})), })),
}); });
if (env === BACK) return BACK;
config.currentEnv = env; config.currentEnv = env;
await saveConfig(config); await saveConfig(config);
return env; return env;
} }
async function selectService(): Promise<Service> { async function selectService(): Promise<Service | Nav> {
return await select({ return await selectNav({
message: '选择服务', message: '选择服务',
choices: [ choices: [
{ name: '前端', value: 'frontend' }, { name: '前端', value: 'frontend' as Service },
{ name: '后端', value: 'backend' }, { name: '后端', value: 'backend' as Service },
{ name: '许可证服务', value: 'license' }, { name: '许可证', value: 'license' as Service },
],
}) as Service;
}
async function selectServices(): Promise<Service[]> {
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<ReturnType<typeof loadConfig>>): string { /** 空格多选服务;← 返回上一步 */
async function selectServicesMulti(): Promise<Service[] | Nav> {
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 },
],
required: true,
});
return picked;
}
function showServiceHosts(config: DeployConfig): string {
const env = config.currentEnv; const env = config.currentEnv;
const services: Service[] = ['frontend', 'backend', 'license']; return ALL_SERVICES.map((s) => {
return services.map((s) => {
const cfg = config.services[s][env]; const cfg = config.services[s][env];
const resolved = resolveServiceDeployPath(cfg, s, env); const resolved = resolveServiceDeployPath(cfg, s, env);
return ` ${SERVICE_LABELS[s]}: ${cfg.server.host} → ${resolved}`; return ` ${SERVICE_LABELS[s]}: ${cfg.server.host} → ${resolved}`;
@@ -72,241 +97,302 @@ function showServiceHosts(config: Awaited<ReturnType<typeof loadConfig>>): strin
} }
async function configureService() { async function configureService() {
const config = await loadConfig(); while (true) {
const service = await selectService(); const service = await selectService();
const env = await selectEnv(); if (service === BACK) return;
const cfg = config.services[service][env];
const srv = cfg.server;
console.clear(); const env = await selectEnv();
printBox(`${SERVICE_LABELS[service]} · ${ENV_LABELS[env]} 配置`, [ if (env === BACK) continue;
`服务器: ${srv.host}:${srv.port}`,
`用户: ${srv.username}`,
`部署根目录: ${srv.deployPath}`,
`实际目录: ${resolveServiceDeployPath(cfg, service, env)}`,
`端口: ${cfg.port}`,
`认证方式: ${srv.authType === 'key' ? '密钥' : '密码'}`,
].join('\n'));
const action = await select({ while (true) {
message: '配置操作', const config = await loadConfig();
choices: [ const cfg = config.services[service][env];
{ name: '修改服务器地址', value: 'host' }, const srv = cfg.server;
{ 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) { console.clear();
case 'host': { printBox(`${SERVICE_LABELS[service]} · ${ENV_LABELS[env]}`, [
const host = await input({ message: '服务器地址', default: srv.host }); `服务器: ${srv.host}:${srv.port}`,
await updateServiceServerConfig(service, env, { host }); `用户: ${srv.username}`,
break; `部署根: ${srv.deployPath}`,
} `实际目录: ${resolveServiceDeployPath(cfg, service, env)}`,
case 'port': { `端口: ${cfg.port}`,
const p = await input({ message: 'SSH 端口', default: String(srv.port) }); `认证: ${srv.authType === 'key' ? '密钥' : '密码'}`,
await updateServiceServerConfig(service, env, { port: Number(p) }); ].join('\n'));
break;
} const action = await selectNav({
case 'svcPort': { message: '配置项',
const p = await input({ message: '服务端口', default: String(cfg.port) }); choices: [
const { updateServiceEnvConfig } = await import('./config.js'); { name: '服务器地址', value: 'host' as const },
await updateServiceEnvConfig(service, env, { port: Number(p) }); { name: 'SSH 端口', value: 'port' as const },
break; { name: '服务端口', value: 'svcPort' as const },
} { name: '用户名', value: 'username' as const },
case 'username': { { name: '部署根目录', value: 'deployPath' as const },
const u = await input({ message: 'SSH 用户', default: srv.username }); { name: '测试 SSH', value: 'test' as const },
await updateServiceServerConfig(service, env, { username: u }); { name: '配置免密密钥', value: 'setupKey' as const, description: '首次上传公钥' },
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 }); if (action === BACK) break;
break;
} switch (action) {
case 'test': { case 'host': {
const ok = await testConnection(srv); const host = await input({ message: '服务器地址', default: srv.host });
if (ok) printSuccess('SSH 连接成功'); await updateServiceServerConfig(service, env, { host });
else printError('SSH 连接失败'); break;
break; }
} case 'port': {
case 'setupKey': { const p = await input({ message: 'SSH 端口', default: String(srv.port) });
const pwd = await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true }); await updateServiceServerConfig(service, env, { port: Number(p) });
try { break;
await setupSSHKey(srv, pwd); }
await syncServerKeyAuth(srv.host, srv.username, { authType: 'key', keyPath: getSshKeyPath() }); case 'svcPort': {
} catch (e: any) { const p = await input({ message: '服务端口', default: String(cfg.port) });
printError(`密钥配置失败: ${e.message}`); 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;
}
} }
break;
} }
} }
} }
async function deployMenu() { 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 config = await loadConfig();
const env = config.currentEnv; const env = config.currentEnv;
printBox('当前环境', `${ENV_LABELS[env]}\n${showServiceHosts(config)}`, 'yellow'); printBox('当前环境', `${ENV_LABELS[env]}\n${showServiceHosts(config)}`, 'yellow');
const deployMode = await select({ while (true) {
message: '部署方式', if (step === 'mode') {
choices: [ const mode = await selectNav({
{ name: '自动部署(编译 + 上传 + 重启)', value: 'auto' }, message: '部署方式',
{ name: '仅编译产物(不上传,输出到 artifacts/)', value: 'buildOnly' }, choices: [
{ name: '上传产物并重启(从 artifacts/,不编译)', value: 'uploadOnly' }, { name: '自动部署', value: 'auto' as const, description: '编译 → 上传 → 重启' },
{ name: '取消', value: 'cancel' }, { name: '仅编译', value: 'buildOnly' as const, description: '产物到 artifacts/,不上传' },
], { name: '仅上传重启', value: 'uploadOnly' as const, description: '用已有 artifacts/,不编译' },
}); ],
if (deployMode === 'cancel') return; });
if (mode === BACK) return;
const services = await selectServices(); deployMode = mode;
printBox('待部署服务', services.map((s) => `${SERVICE_LABELS[s]} → ${config.services[s][env].server.host}`).join('\n'), 'cyan'); step = 'services';
continue;
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}`); 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() { async function serviceMenu() {
const service = await selectService(); while (true) {
const config = await loadConfig(); const service = await selectService();
const cfg = getServiceConfig(config, service); if (service === BACK) return;
const srv = cfg.server;
const action = await select({ const config = await loadConfig();
message: `${SERVICE_LABELS[service]} 管理 (${srv.host})`, const cfg = getServiceConfig(config, service);
choices: [ const srv = cfg.server;
{ 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(); while (true) {
const onPassword = async () => await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: 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;
try { console.clear();
switch (action) { const onPassword = async () =>
case 'status': { await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true });
const ps = await serviceStatus(service, onPassword);
console.log(ps || '暂无运行的服务'); try {
break; 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}`);
} }
case 'logs': { await pause();
const lines = await input({ message: '日志行数', default: '50' }); console.clear();
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() { async function sshMenu() {
const config = await loadConfig(); while (true) {
const service = await selectService(); const service = await selectService();
const env = config.currentEnv; if (service === BACK) return;
const srv = config.services[service][env].server;
const action = await select({ const config = await loadConfig();
message: `${SERVICE_LABELS[service]} SSH 管理 (${srv.host})`, const env = config.currentEnv;
choices: [ const srv = config.services[service][env].server;
{ name: '查看 SSH 密钥状态', value: 'status' },
{ name: '生成 SSH 密钥对', value: 'genKey' },
{ name: '上传公钥到服务器', value: 'uploadKey' },
{ name: '测试连接', value: 'test' },
{ name: '返回', value: 'back' },
],
});
if (action === 'back') return;
console.clear(); while (true) {
switch (action) { const action = await selectNav({
case 'status': { message: `SSH · ${SERVICE_LABELS[service]} (${srv.host})`,
const { existsSync } = await import('fs'); choices: [
if (existsSync(getSshKeyPath())) printSuccess(`密钥存在: ${getSshKeyPath()}`); { name: '密钥状态', value: 'status' as const },
else printInfo('尚未生成 SSH 密钥对'); { name: '生成密钥对', value: 'genKey' as const },
break; { name: '上传公钥', value: 'uploadKey' as const },
} { name: '测试连接', value: 'test' as const },
case 'genKey': { ],
ensureKeyPair(); });
printSuccess('SSH 密钥对已生成'); if (action === BACK) break;
break;
} console.clear();
case 'uploadKey': { switch (action) {
const pwd = await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true }); case 'status': {
try { const { existsSync } = await import('fs');
await setupSSHKey(srv, pwd); if (existsSync(getSshKeyPath())) printSuccess(`密钥存在: ${getSshKeyPath()}`);
await syncServerKeyAuth(srv.host, srv.username, { authType: 'key', keyPath: getSshKeyPath() }); else printInfo('尚未生成 SSH 密钥对');
} catch (e: any) { break;
printError(`上传失败: ${e.message}`); }
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;
}
} }
break; await pause();
} console.clear();
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() { async function mainMenu(): Promise<'continue' | 'exit'> {
console.clear(); console.clear();
printBanner(); printBanner();
@@ -314,40 +400,64 @@ async function mainMenu() {
const env = config.currentEnv; const env = config.currentEnv;
printInfo(`当前环境: ${ENV_LABELS[env]}`); printInfo(`当前环境: ${ENV_LABELS[env]}`);
console.log(showServiceHosts(config)); console.log(showServiceHosts(config));
printInfo('提示: 子菜单按 ← 返回上一步');
const action = await select({ const action = await select({
message: '主菜单', message: '主菜单',
choices: [ choices: [
{ name: '部署服务', value: 'deploy' }, { name: '部署', value: 'deploy' },
{ name: '服务管理', value: 'service' }, { name: '服务管理', value: 'service' },
{ name: '配置服务', value: 'config' }, { name: '配置', value: 'config' },
{ name: 'SSH 密钥管理', value: 'ssh' }, { name: 'SSH', value: 'ssh' },
{ name: '切换环境', value: 'switchEnv' }, { name: '切换环境', value: 'switchEnv' },
{ name: '退出', value: 'exit' }, { name: '退出', value: 'exit' },
], ],
theme: {
style: {
keysHelpTip: () => '↑↓ 选择 · ⏎ 确认',
},
},
}); });
switch (action) { switch (action) {
case 'deploy': console.clear(); await deployMenu(); break; case 'deploy':
case 'service': console.clear(); await serviceMenu(); break; console.clear();
case 'config': await configureService(); break; await deployMenu();
case 'ssh': await sshMenu(); break; break;
case 'service':
console.clear();
await serviceMenu();
break;
case 'config':
await configureService();
break;
case 'ssh':
await sshMenu();
break;
case 'switchEnv': { case 'switchEnv': {
const newEnv = await selectEnv(); const newEnv = await selectEnv();
printSuccess(`已切换到: ${ENV_LABELS[newEnv]}`); if (newEnv !== BACK) {
printSuccess(`已切换到: ${ENV_LABELS[newEnv]}`);
}
break; break;
} }
case 'exit': process.exit(0); case 'exit':
return 'exit';
} }
return 'continue';
} }
async function main() { async function main() {
while (true) { while (true) {
try { try {
await mainMenu(); const result = await mainMenu();
if (result === 'exit') process.exit(0);
await pause(); await pause();
} catch (e: any) { } catch (e: any) {
if (e?.name === 'ExitPromptError') process.exit(0); if (isExitPrompt(e)) {
printInfo('已取消');
continue;
}
printError(String(e?.message || e)); printError(String(e?.message || e));
await pause(); await pause();
} }
+4 -4
View File
@@ -34,11 +34,11 @@ export interface DeployConfig {
export const SERVICE_LABELS: Record<Service, string> = { export const SERVICE_LABELS: Record<Service, string> = {
frontend: '前端', frontend: '前端',
backend: '后端', backend: '后端',
license: '许可证服务', license: '许可证',
}; };
export const ENV_LABELS: Record<Environment, string> = { export const ENV_LABELS: Record<Environment, string> = {
test: '测试环境', test: '测试',
pre: '预发布环境', pre: '预发',
prod: '生产环境', prod: '生产',
}; };
+66
View File
@@ -0,0 +1,66 @@
import { checkbox, select } from '@inquirer/prompts';
import type { Key } from 'node:readline';
/** 导航:左方向键返回 */
export const BACK = '__back__' as const;
export type Nav = typeof BACK;
type Cancellable<T> = Promise<T> & { cancel: () => void };
function isCancelPrompt(e: unknown): boolean {
return (e as { name?: string })?.name === 'CancelPromptError';
}
/**
* 运行可取消的 inquirer prompt:← 左键 → cancel → 返回 BACK。
*/
export async function withLeftBack<T>(start: () => Cancellable<T>): Promise<T | Nav> {
const prompt = start();
const onKeypress = (_input: string, key: Key) => {
// 左方向键;忽略带修饰键,避免误触
if (key?.name === 'left' && !key.ctrl && !key.meta && !key.shift) {
prompt.cancel();
}
};
process.stdin.on('keypress', onKeypress);
try {
return await prompt;
} catch (e) {
if (isCancelPrompt(e)) return BACK;
throw e;
} finally {
process.stdin.off('keypress', onKeypress);
}
}
const selectHelp = {
style: {
keysHelpTip: () => '↑↓ 选择 · ⏎ 确认 · ← 返回',
},
} as const;
const checkboxHelp = {
style: {
keysHelpTip: () => '↑↓ 移动 · 空格 勾选 · a 全选 · ⏎ 确认 · ← 返回',
},
} as const;
/** select:← 返回 BACK */
export function selectNav<Value>(config: Parameters<typeof select<Value>>[0]) {
return withLeftBack(() =>
select({
...config,
theme: { ...selectHelp, ...(config.theme as object | undefined) },
}),
);
}
/** checkbox:← 返回 BACK */
export function checkboxNav<Value>(config: Parameters<typeof checkbox<Value>>[0]) {
return withLeftBack(() =>
checkbox({
...config,
theme: { ...checkboxHelp, ...(config.theme as object | undefined) },
}),
);
}