|
| 1 | +// dev-all.ts — 多进程输出流复用器:同时启动所有 dev 命令,按键切换输出流 |
| 2 | +import { execa } from 'execa' |
| 3 | +import chalk from 'chalk' |
| 4 | +import { t } from './i18n.js' |
| 5 | + |
| 6 | +const MAX_BUFFER_LINES = 5000 |
| 7 | + |
| 8 | +class OutputBuffer { |
| 9 | + private lines: string[] = [] |
| 10 | + private partial = '' |
| 11 | + |
| 12 | + append(data: string) { |
| 13 | + const text = this.partial + data |
| 14 | + const parts = text.split('\n') |
| 15 | + this.partial = parts.pop()! |
| 16 | + this.lines.push(...parts) |
| 17 | + if (this.lines.length > MAX_BUFFER_LINES) { |
| 18 | + this.lines = this.lines.slice(-MAX_BUFFER_LINES) |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + getRecent(n: number): string { |
| 23 | + const recent = this.lines.slice(-n) |
| 24 | + let result = recent.join('\n') |
| 25 | + if (this.partial) result += '\n' + this.partial |
| 26 | + return result |
| 27 | + } |
| 28 | + |
| 29 | + clear() { |
| 30 | + this.lines = [] |
| 31 | + this.partial = '' |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +export interface DevProcessDef { |
| 36 | + name: string |
| 37 | + cmd: string |
| 38 | + cwd: string |
| 39 | + envs?: Record<string, string> |
| 40 | +} |
| 41 | + |
| 42 | +interface ManagedProcess { |
| 43 | + name: string |
| 44 | + def: DevProcessDef |
| 45 | + child: any |
| 46 | + buffer: OutputBuffer |
| 47 | + status: 'running' | 'exited' | 'crashed' |
| 48 | + exitCode?: number |
| 49 | +} |
| 50 | + |
| 51 | +export async function runDevMultiplexer(defs: DevProcessDef[]): Promise<void> { |
| 52 | + const processes: ManagedProcess[] = [] |
| 53 | + let activeIndex = 0 |
| 54 | + let shuttingDown = false |
| 55 | + const isTTY = !!(process.stdout.isTTY && process.stdin.isTTY) |
| 56 | + |
| 57 | + function spawnOne(def: DevProcessDef): ManagedProcess { |
| 58 | + const child = execa('sh', ['-c', def.cmd], { |
| 59 | + cwd: def.cwd, |
| 60 | + stdio: ['ignore', 'pipe', 'pipe'], |
| 61 | + env: def.envs, |
| 62 | + reject: false, |
| 63 | + }) |
| 64 | + |
| 65 | + return { |
| 66 | + name: def.name, |
| 67 | + def, |
| 68 | + child, |
| 69 | + buffer: new OutputBuffer(), |
| 70 | + status: 'running', |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + function attachOutput(proc: ManagedProcess) { |
| 75 | + const onData = (chunk: Buffer) => { |
| 76 | + if (!processes.includes(proc)) return |
| 77 | + const text = chunk.toString() |
| 78 | + proc.buffer.append(text) |
| 79 | + const idx = processes.indexOf(proc) |
| 80 | + |
| 81 | + if (isTTY) { |
| 82 | + if (idx === activeIndex) process.stdout.write(chunk) |
| 83 | + } else { |
| 84 | + const prefix = chalk.dim(`[${proc.name}] `) |
| 85 | + for (const line of text.split('\n')) { |
| 86 | + if (line) process.stdout.write(prefix + line + '\n') |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + proc.child.stdout?.on('data', onData) |
| 92 | + proc.child.stderr?.on('data', onData) |
| 93 | + |
| 94 | + proc.child.then( |
| 95 | + (result: any) => { |
| 96 | + if (!processes.includes(proc)) return |
| 97 | + proc.exitCode = result.exitCode ?? 0 |
| 98 | + proc.status = result.exitCode === 0 ? 'exited' : 'crashed' |
| 99 | + onProcDone(proc) |
| 100 | + }, |
| 101 | + (error: any) => { |
| 102 | + if (!processes.includes(proc)) return |
| 103 | + proc.exitCode = 1 |
| 104 | + proc.status = 'crashed' |
| 105 | + proc.buffer.append(`\n${chalk.red(error.message ?? String(error))}\n`) |
| 106 | + onProcDone(proc) |
| 107 | + }, |
| 108 | + ) |
| 109 | + } |
| 110 | + |
| 111 | + function onProcDone(proc: ManagedProcess) { |
| 112 | + if (isTTY && processes.indexOf(proc) === activeIndex) { |
| 113 | + const label = proc.status === 'crashed' |
| 114 | + ? chalk.red(`\n ✗ ${proc.name} exited with code ${proc.exitCode}`) |
| 115 | + : chalk.dim(`\n ○ ${proc.name} ${t('devAllExited')}`) |
| 116 | + process.stdout.write(label + '\n') |
| 117 | + } |
| 118 | + |
| 119 | + if (!shuttingDown && processes.every(p => p.status !== 'running')) { |
| 120 | + shutdown() |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + // ─── Spawn all ─── |
| 125 | + for (const def of defs) { |
| 126 | + const proc = spawnOne(def) |
| 127 | + processes.push(proc) |
| 128 | + attachOutput(proc) |
| 129 | + } |
| 130 | + |
| 131 | + const names = processes.map(p => p.name).join(', ') |
| 132 | + console.log(chalk.cyan(`\n ${t('devAllStarting')} ${processes.length} ${t('devAllServices')}: ${names}\n`)) |
| 133 | + |
| 134 | + // Non-TTY: prefixed output, wait for all |
| 135 | + if (!isTTY) { |
| 136 | + await Promise.allSettled(processes.map(p => p.child)) |
| 137 | + process.exit(0) |
| 138 | + } |
| 139 | + |
| 140 | + // TTY: status bar + keyboard switching |
| 141 | + printStatusBar() |
| 142 | + |
| 143 | + process.stdin.setRawMode(true) |
| 144 | + process.stdin.resume() |
| 145 | + process.stdin.setEncoding('utf8') |
| 146 | + |
| 147 | + process.stdin.on('data', (key: string) => { |
| 148 | + if (shuttingDown) return |
| 149 | + |
| 150 | + const num = parseInt(key) |
| 151 | + if (num >= 1 && num <= processes.length && num - 1 !== activeIndex) { |
| 152 | + activeIndex = num - 1 |
| 153 | + redraw() |
| 154 | + return |
| 155 | + } |
| 156 | + |
| 157 | + if (key === 'q' || key === '\x03') { |
| 158 | + shutdown() |
| 159 | + return |
| 160 | + } |
| 161 | + |
| 162 | + if (key === 'r') { |
| 163 | + restartCurrent() |
| 164 | + return |
| 165 | + } |
| 166 | + }) |
| 167 | + |
| 168 | + process.stdout.on('resize', () => { |
| 169 | + if (!shuttingDown) redraw() |
| 170 | + }) |
| 171 | + |
| 172 | + process.on('SIGTERM', () => shutdown()) |
| 173 | + |
| 174 | + function printStatusBar() { |
| 175 | + const indicators = processes.map((p, i) => { |
| 176 | + const dot = p.status === 'running' ? chalk.green('●') |
| 177 | + : p.status === 'exited' ? chalk.dim('○') |
| 178 | + : chalk.red('✗') |
| 179 | + const name = i === activeIndex ? chalk.bold.white(p.name) : chalk.dim(p.name) |
| 180 | + return `${chalk.dim(`[${i + 1}]`)} ${name} ${dot}` |
| 181 | + }).join(' ') |
| 182 | + |
| 183 | + const hint = chalk.dim( |
| 184 | + `[1-${processes.length}: ${t('devAllSwitch')} | q: ${t('devAllQuit')} | r: ${t('devAllRestart')}]`, |
| 185 | + ) |
| 186 | + const cols = process.stdout.columns ?? 80 |
| 187 | + const sep = chalk.dim('─'.repeat(cols)) |
| 188 | + |
| 189 | + process.stdout.write(` ${indicators}\n ${hint}\n${sep}\n`) |
| 190 | + } |
| 191 | + |
| 192 | + function redraw() { |
| 193 | + const rows = process.stdout.rows ?? 24 |
| 194 | + process.stdout.write('\x1b[2J\x1b[H') |
| 195 | + printStatusBar() |
| 196 | + const available = Math.max(rows - 5, 10) |
| 197 | + const recent = processes[activeIndex]!.buffer.getRecent(available) |
| 198 | + if (recent) { |
| 199 | + process.stdout.write('\x1b[0m' + recent) |
| 200 | + if (!recent.endsWith('\n')) process.stdout.write('\n') |
| 201 | + } |
| 202 | + } |
| 203 | + |
| 204 | + async function restartCurrent() { |
| 205 | + const old = processes[activeIndex]! |
| 206 | + if (old.status === 'running') { |
| 207 | + old.child.kill('SIGTERM') |
| 208 | + } |
| 209 | + try { await old.child } catch {} |
| 210 | + |
| 211 | + const newProc = spawnOne(old.def) |
| 212 | + processes[activeIndex] = newProc |
| 213 | + attachOutput(newProc) |
| 214 | + redraw() |
| 215 | + } |
| 216 | + |
| 217 | + function shutdown() { |
| 218 | + if (shuttingDown) return |
| 219 | + shuttingDown = true |
| 220 | + |
| 221 | + if (isTTY) { |
| 222 | + process.stdin.setRawMode(false) |
| 223 | + process.stdin.pause() |
| 224 | + } |
| 225 | + |
| 226 | + for (const p of processes) { |
| 227 | + if (p.status === 'running') { |
| 228 | + p.child.kill('SIGTERM') |
| 229 | + } |
| 230 | + } |
| 231 | + |
| 232 | + process.stdout.write('\x1b[0m') |
| 233 | + console.log(chalk.dim(`\n ${t('devAllStopped')}\n`)) |
| 234 | + process.exit(0) |
| 235 | + } |
| 236 | + |
| 237 | + await new Promise<never>(() => {}) |
| 238 | +} |
0 commit comments