Repository navigation
Expand file tree
/
Copy pathvite.config.ts
More file actions
88 lines (77 loc) · 2.48 KB
/
Copy pathvite.config.ts
File metadata and controls
88 lines (77 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import path from 'path';
import { defineConfig, loadEnv, type Plugin } from 'vite';
import react from '@vitejs/plugin-react';
import { handleGeminiRequest } from './server/gemini';
function geminiDevApi(apiKey: string | undefined): Plugin {
return {
name: 'gemini-dev-api',
apply: 'serve',
configureServer(server) {
server.middlewares.use('/api/gemini', (req, res) => {
let aborted = false;
req.on('aborted', () => {
aborted = true;
});
req.on('error', () => {
if (!res.headersSent) {
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json');
}
if (!res.writableEnded) {
res.end(JSON.stringify({ error: 'Request stream error' }));
}
});
res.on('error', () => {
// Ignore response stream errors to avoid crashing the dev server
});
if (!apiKey) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Missing GEMINI_API_KEY env var' }));
return;
}
if (req.method !== 'POST') {
res.statusCode = 405;
res.setHeader('Allow', 'POST');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
return;
}
let raw = '';
req.on('data', (chunk) => {
raw += chunk;
});
req.on('end', async () => {
try {
if (aborted || res.writableEnded) return;
const body = raw ? JSON.parse(raw) : {};
const result = await handleGeminiRequest(body, apiKey);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(result));
} catch (error) {
const message = error instanceof Error ? error.message : 'Gemini request failed';
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: message }));
}
});
});
},
};
}
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, '.', '');
return {
server: {
port: 3000,
host: '0.0.0.0',
},
plugins: [react(), geminiDevApi(env.GEMINI_API_KEY)],
resolve: {
alias: {
'@': path.resolve(__dirname, '.'),
}
}
};
});