#!/usr/bin/env node /** * 一键启动:环境自检 → 装依赖(缺什么装什么)→ 拉起 Python 工具服务 → 拉起 BFF → 打开浏览器。 * * node scripts/start.mjs # 正常启动 * node scripts/start.mjs --no-open # 不自动开浏览器 * node scripts/start.mjs --skip-install # 跳过依赖安装检查(离线环境) * node scripts/start.mjs --rebuild # 强制重新构建前端/BFF * * 退出码:0 正常;1 环境不满足;2 依赖安装失败;3 服务启动失败。 */ import { spawn, spawnSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import net from 'node:net'; import os from 'node:os'; import path from 'node:path'; const ROOT = path.resolve(import.meta.dirname, '..'); const RUN_DIR = path.join(ROOT, '.run'); const PID_FILE = path.join(RUN_DIR, 'pids.json'); const args = new Set(process.argv.slice(2)); const IS_WINDOWS = process.platform === 'win32'; const PYTHON = process.env.CDA_PYTHON ?? (IS_WINDOWS ? 'python' : 'python3'); // --------------------------------------------------------------------- 输出 const C = { reset: '\u001b[0m', dim: '\u001b[2m', green: '\u001b[32m', yellow: '\u001b[33m', red: '\u001b[31m', cyan: '\u001b[36m', bold: '\u001b[1m', }; const paint = (color, text) => `${C[color]}${text}${C.reset}`; const step = (index, total, text) => console.log(`${paint('cyan', `[${index}/${total}]`)} ${text}`); const info = (text) => console.log(` ${C.dim}${text}${C.reset}`); const ok = (text) => console.log(` ${paint('green', '✓')} ${text}`); const warn = (text) => console.log(` ${paint('yellow', '!')} ${text}`); const fail = (text) => console.error(` ${paint('red', '✗')} ${text}`); function loadDotEnv() { const file = path.join(ROOT, '.env'); if (!existsSync(file)) return; for (const rawLine of readFileSync(file, 'utf8').split(/\r?\n/)) { const line = rawLine.trim(); if (!line || line.startsWith('#')) continue; const index = line.indexOf('='); if (index <= 0) continue; const key = line.slice(0, index).trim(); let value = line.slice(index + 1).trim(); if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { value = value.slice(1, -1); } if (process.env[key] === undefined) process.env[key] = value; } } function needsShell(command) { // 只有 .cmd/.bat 需要走 cmd.exe;python/node 直接 spawn 更安全(也避免 DEP0190 警告) return IS_WINDOWS && /\.(cmd|bat)$/i.test(command); } function run(command, argv, options = {}) { const result = spawnSync(command, argv, { cwd: options.cwd ?? ROOT, stdio: options.capture ? 'pipe' : 'inherit', shell: needsShell(command), env: { ...process.env, ...(options.env ?? {}) }, encoding: 'utf8', }); return { code: result.status ?? 1, stdout: result.stdout ?? '', stderr: result.stderr ?? '' }; } function probePython() { const result = run(PYTHON, ['--version'], { capture: true }); if (result.code !== 0) return null; return (result.stdout || result.stderr).trim(); } function pythonHasDeps() { const code = 'import fastapi, uvicorn, openpyxl, multipart, pydantic; print("ok")'; const result = run(PYTHON, ['-c', code], { capture: true, cwd: path.join(ROOT, 'tools-service') }); return result.code === 0 && result.stdout.includes('ok'); } function portFree(port) { return new Promise((resolve) => { const server = net.createServer(); server.once('error', () => resolve(false)); server.once('listening', () => server.close(() => resolve(true))); server.listen(port, '127.0.0.1'); }); } async function waitFor(url, timeoutMs, label) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { try { const response = await fetch(url, { signal: AbortSignal.timeout(2500) }); if (response.ok) return true; } catch { /* 还没起来 */ } await new Promise((resolve) => setTimeout(resolve, 600)); } fail(`${label} 在 ${Math.round(timeoutMs / 1000)} 秒内没有就绪:${url}`); return false; } function openBrowser(url) { if (IS_WINDOWS) { spawn('cmd', ['/c', 'start', '""', url], { detached: true, stdio: 'ignore' }).unref(); } else if (process.platform === 'darwin') { spawn('open', [url], { detached: true, stdio: 'ignore' }).unref(); } else { spawn('xdg-open', [url], { detached: true, stdio: 'ignore' }).unref(); } } const children = []; function startProcess(name, command, argv, options = {}) { const child = spawn(command, argv, { cwd: options.cwd ?? ROOT, env: { ...process.env, ...(options.env ?? {}) }, stdio: options.silent ? 'ignore' : 'inherit', shell: needsShell(command), }); child.on('exit', (code, signal) => { if (!shuttingDown && name !== 'X') { console.log(`\n${paint('yellow', `[${name}] 进程退出 code=${code} signal=${signal}`)}`); if (!options.optional) shutdown(1); } }); children.push({ name, child }); return child; } let shuttingDown = false; function shutdown(code = 0) { if (shuttingDown) return; shuttingDown = true; console.log(`\n${paint('dim', '正在停止服务…')}`); for (const { name, child } of children.slice().reverse()) { try { if (IS_WINDOWS) { spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }); } else { child.kill('SIGTERM'); } console.log(` ${paint('dim', '已停止')} ${name}`); } catch { /* 忽略 */ } } try { if (existsSync(PID_FILE)) writeFileSync(PID_FILE, JSON.stringify({ stoppedAt: new Date().toISOString() }, null, 2)); } catch { /* 忽略 */ } setTimeout(() => process.exit(code), 300); } process.on('SIGINT', () => shutdown(0)); process.on('SIGTERM', () => shutdown(0)); // --------------------------------------------------------------------- main async function main() { console.log(paint('bold', '\n海关问数 Agent · 一键启动\n')); const total = 7; loadDotEnv(); mkdirSync(RUN_DIR, { recursive: true }); // 1. Node step(1, total, '检查运行环境'); const nodeMajor = Number(process.versions.node.split('.')[0]); if (nodeMajor < 22) { fail(`Node 版本过低:${process.version},需要 >= 22.5(推荐 24.x)`); return 1; } ok(`Node ${process.version}`); const pythonVersion = probePython(); if (!pythonVersion) { fail(`找不到 Python(命令:${PYTHON})。请安装 Python 3.11+ 并加入 PATH,或用 CDA_PYTHON 指定路径。`); return 1; } ok(`${pythonVersion}(${PYTHON})`); // 2. 端口 step(2, total, '检查端口占用'); const port = Number(process.env.CDA_PORT ?? 8787); const toolsPort = Number(process.env.CDA_TOOLS_PORT ?? 8788); for (const [label, value] of [ ['BFF', port], ['工具服务', toolsPort], ]) { if (!(await portFree(value))) { warn(`${label} 端口 ${value} 已被占用,可能已经启动过(可直接访问 http://127.0.0.1:${port})`); } else { ok(`${label} 端口 ${value} 可用`); } } // 3. Python 依赖 step(3, total, '检查 Python 依赖'); if (args.has('--skip-install')) { warn('按 --skip-install 跳过依赖安装'); } else if (pythonHasDeps()) { ok('fastapi / uvicorn / openpyxl / python-multipart 已安装'); } else { const wheels = path.join(ROOT, 'offline', 'wheels'); const offline = existsSync(wheels); info(offline ? `离线安装:使用 ${wheels}` : '在线安装:从 PyPI 拉取'); const installArgs = ['-m', 'pip', 'install', '-r', 'requirements.txt']; if (offline) installArgs.push('--no-index', '--find-links', wheels); const result = run(PYTHON, installArgs, { cwd: path.join(ROOT, 'tools-service') }); if (result.code !== 0) { fail('Python 依赖安装失败。离线环境请把 wheel 放进 offline/wheels 后重试。'); return 2; } ok('Python 依赖安装完成'); } // 4. BFF / 前端构建 step(4, total, '检查构建产物'); const bffEntry = path.join(ROOT, 'bff', 'dist', 'src', 'index.js'); const webEntry = path.join(ROOT, 'web', 'dist', 'index.html'); const needBuild = args.has('--rebuild') || !existsSync(bffEntry) || !existsSync(webEntry); if (!needBuild) { ok('BFF 与前端已构建(web/dist 存在)'); } else if (args.has('--skip-install')) { if (!existsSync(bffEntry)) { fail('缺少 bff/dist,且指定了 --skip-install。请先执行 npm install && npm run build。'); return 2; } warn('缺少前端构建产物,将只提供 API(页面无法打开)'); } else { for (const [name, dir] of [ ['BFF', path.join(ROOT, 'bff')], ['前端', path.join(ROOT, 'web')], ]) { if (!existsSync(path.join(dir, 'node_modules'))) { info(`${name}:安装 npm 依赖(首次较慢)`); const npmCommand = IS_WINDOWS ? 'npm.cmd' : 'npm'; const installed = run(npmCommand, ['install', '--no-audit', '--no-fund'], { cwd: dir }); if (installed.code !== 0) { fail(`${name} npm install 失败`); return 2; } } info(`${name}:构建`); const npmCommand = IS_WINDOWS ? 'npm.cmd' : 'npm'; const built = run(npmCommand, ['run', 'build'], { cwd: dir }); if (built.code !== 0) { fail(`${name} 构建失败`); return 2; } ok(`${name} 构建完成`); } } // 5. 工具服务 step(5, total, '启动 Python 工具服务'); if (!(await portFree(toolsPort))) { warn(`工具服务端口 ${toolsPort} 已被占用,跳过启动(复用已有进程)`); } else { startProcess('tools', PYTHON, ['-m', 'toolsvc'], { cwd: path.join(ROOT, 'tools-service'), env: { CDA_DATA_DIR: process.env.CDA_DATA_DIR ?? path.join(ROOT, 'data'), CDA_TOOLS_PORT: String(toolsPort) }, }); if (!(await waitFor(`http://127.0.0.1:${toolsPort}/health`, 90_000, '工具服务'))) return 3; ok(`工具服务就绪:http://127.0.0.1:${toolsPort}`); } // 6. BFF step(6, total, '启动 BFF(Web/API)'); if (!(await portFree(port))) { warn(`BFF 端口 ${port} 已被占用;如果你刚启动过,直接打开页面即可`); } else { startProcess('bff', process.execPath, [bffEntry], { env: { CDA_TOOLS_URL: process.env.CDA_TOOLS_URL ?? `http://127.0.0.1:${toolsPort}`, CDA_PORT: String(port), CDA_BFF_DATA_DIR: process.env.CDA_BFF_DATA_DIR ?? path.join(ROOT, 'data', 'bff'), }, }); if (!(await waitFor(`http://127.0.0.1:${port}/api/health`, 60_000, 'BFF'))) return 3; ok(`BFF 就绪:http://127.0.0.1:${port}`); } // 7. 完成 step(7, total, '启动完成'); const url = `http://127.0.0.1:${port}`; console.log(`\n ${paint('green', paint('bold', '海关问数 Agent 已启动'))}`); console.log(` 地址:${paint('cyan', url)}`); console.log(` 数据目录:${paint('dim', path.join(ROOT, 'data'))}`); if (!process.env.DEEPSEEK_API_KEY) { console.log(` ${paint('yellow', '注意:未配置 DEEPSEEK_API_KEY,对话功能不可用(数据处理仍可用)')}`); console.log(` ${paint('dim', '在项目根目录创建 .env,写入 DEEPSEEK_API_KEY=sk-xxx 后重启')}`); } console.log(` ${paint('dim', '按 Ctrl+C 停止全部服务')}\n`); writeFileSync( PID_FILE, JSON.stringify({ startedAt: new Date().toISOString(), url, children: children.map((item) => ({ name: item.name, pid: item.child.pid })) }, null, 2), ); if (!args.has('--no-open')) openBrowser(url); // 保持前台运行(Ctrl+C 停止) await new Promise(() => {}); } main() .then((code) => { if (typeof code === 'number') shutdown(code); }) .catch((error) => { fail(`启动失败:${error?.stack ?? error}`); shutdown(3); });