import tailwindcss from '@tailwindcss/vite'; import react from '@vitejs/plugin-react'; import path from 'path'; import {defineConfig, loadEnv} from 'vite'; import fs from 'fs'; function apiMiddleware() { return { name: 'api-middleware', configureServer(server: any) { server.middlewares.use('/api/save-local-md', (req: any, res: any, next: any) => { if (req.method === 'POST') { let body = ''; req.on('data', (chunk: string) => { body += chunk.toString(); }); req.on('end', () => { try { const parsed = JSON.parse(body); const userName = parsed.userName; const content = parsed.content; if (!userName || !content) { res.statusCode = 400; res.end(JSON.stringify({ error: 'Missing userName or content' })); return; } const docsDir = path.resolve(__dirname, 'docs'); let overRidden = false; if (fs.existsSync(docsDir)) { const files = fs.readdirSync(docsDir); for (const file of files) { if (file.endsWith('.md')) { const filePath = path.join(docsDir, file); const fileContent = fs.readFileSync(filePath, 'utf-8'); if (fileContent.includes(`**User**: ${userName}`)) { fs.writeFileSync(filePath, content, 'utf-8'); overRidden = true; console.log(`[Vite API] Successfully updated local file: ${file}`); } } } } if (overRidden) { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ success: true })); } else { res.statusCode = 404; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ error: `Could not find an .md file in docs/ for user: ${userName}` })); } } catch (e: any) { res.statusCode = 500; res.end(JSON.stringify({ error: e.message })); } }); } else { next(); } }); } }; } export default defineConfig(({mode}) => { const env = loadEnv(mode, '.', ''); return { plugins: [react(), tailwindcss(), apiMiddleware()], define: { 'process.env.GEMINI_API_KEY': JSON.stringify(process.env.GEMINI_API_KEY || env.GEMINI_API_KEY || ''), }, resolve: { alias: { '@': path.resolve(__dirname, '.'), }, }, server: { // HMR is disabled in AI Studio via DISABLE_HMR env var. // Do not modify—file watching is disabled to prevent flickering during agent edits. hmr: process.env.DISABLE_HMR !== 'true', }, }; });