import { defineConfig, type Plugin } from 'vite' import vue from '@vitejs/plugin-vue' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { spawn } from 'node:child_process' import { fileURLToPath } from 'node:url' const here = path.dirname(fileURLToPath(import.meta.url)) function agentFile() { if (process.env.TAPREMLY_HOME) return path.join(process.env.TAPREMLY_HOME, 'agent.json') const local = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local') return path.join(local, 'TapRemly', 'agent.json') } function alive(pid: number) { if (!pid) return false try { process.kill(pid, 0) return true } catch (err) { return (err as NodeJS.ErrnoException).code === 'EPERM' } } function readInfo() { try { const info = JSON.parse(fs.readFileSync(agentFile(), 'utf8')) as { addr?: string; token?: string; pid?: number } const pid = Number(info.pid || 0) if (!info.addr || !info.token || !alive(pid)) return { running: false, addr: '', token: '', pid: 0 } return { running: true, addr: info.addr, token: info.token, pid } } catch { return { running: false, addr: '', token: '', pid: 0 } } } function agentDev(): Plugin { return { name: 'tapremly-agent-dev', configureServer(server) { server.middlewares.use('/__agent', (req, res) => { if (req.method === 'POST' && req.url?.startsWith('/start')) { const exe = path.resolve(here, '../agent/tapremly-agent.exe') if (!fs.existsSync(exe)) { res.statusCode = 404 res.end('找不到被控程序') return } const child = spawn(exe, [], { detached: true, stdio: 'ignore', windowsHide: true }) child.unref() res.end('ok') return } if (req.method === 'POST' && req.url?.startsWith('/stop')) { const info = readInfo() if (info.running) { fetch(`http://${info.addr}/v1/stop`, { method: 'POST', headers: { Authorization: `Bearer ${info.token}` }, }).catch(() => undefined) } res.end('ok') return } res.setHeader('content-type', 'application/json') res.end(JSON.stringify(readInfo())) }) }, } } export default defineConfig({ plugins: [vue(), agentDev()], clearScreen: false, server: { host: '127.0.0.1', port: 1420, strictPort: true, }, envPrefix: ['VITE_', 'TAURI_'], })