import { defineConfig, type Plugin } from 'vite' import react from '@vitejs/plugin-react' import { writeFileSync, mkdirSync } from 'node:fs' import { join, dirname } from 'node:path' import { fileURLToPath } from 'node:url' /** P 层闭环的写盘中间件:浏览器 POST 源码 → 落盘 pages/(HMR 自动生效) */ function savePagePlugin(): Plugin { const root = dirname(fileURLToPath(import.meta.url)) return { name: 'vr-save-page', configureServer(server) { server.middlewares.use('/__vr-save', (req, res) => { let body = '' req.on('data', (c) => (body += c)) req.on('end', () => { try { const { filename, content } = JSON.parse(body) as { filename: string; content: string } if (!/^[a-z0-9-]+\.tsx?$/.test(filename)) { res.statusCode = 400 res.end('bad filename') return } const target = join(root, 'pages', filename) mkdirSync(dirname(target), { recursive: true }) writeFileSync(target, content, 'utf8') res.setHeader('Content-Type', 'application/json') res.end(JSON.stringify({ ok: true, path: `pages/${filename}` })) } catch (e) { res.statusCode = 500 res.end(JSON.stringify({ ok: false, error: String(e) })) } }) }) }, } } export default defineConfig({ plugins: [react(), savePagePlugin()], server: { port: 5183, open: false }, })