-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
261 lines (231 loc) · 8.41 KB
/
Copy pathserver.js
File metadata and controls
261 lines (231 loc) · 8.41 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
let WebSocket = null;
let isWebSocketAvailable = false;
try {
WebSocket = require('ws');
isWebSocketAvailable = true;
console.log('WebSocket support enabled');
} catch (error) {
console.log('WebSocket support disabled (ws package not installed)');
}
const DIST_DIR = path.join(__dirname, 'dist');
const STATIC_DIR = process.env.SERVE_DIR
? path.join(__dirname, process.env.SERVE_DIR)
: DIST_DIR;
const isProduction = process.env.IS_PRODUCTION === 'true';
if (isProduction && !fs.existsSync(STATIC_DIR)) {
throw new Error(`Production mode enabled but serve directory does not exist: ${STATIC_DIR}`);
}
const PORT = process.env.PORT || 3000;
const OPENAI_BASE_URL = (process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1').replace(/\/+$/, '');
const wsClients = new Set();
const LOG_DIR = path.join(__dirname, 'logs');
const LOG_FILE = path.join(LOG_DIR, 'events.jsonl');
if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });
const mimeTypes = {
'.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css',
'.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml',
'.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2',
'.ttf': 'font/ttf', '.eot': 'application/vnd.ms-fontobject'
};
function getMimeType(filePath) {
const ext = path.extname(filePath).toLowerCase();
return mimeTypes[ext] || 'text/plain';
}
function serveFile(filePath, res) {
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File not found');
return;
}
res.writeHead(200, { 'Content-Type': getMimeType(filePath) });
res.end(data);
});
}
function readBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', chunk => { body += chunk.toString(); });
req.on('end', () => {
try { resolve(JSON.parse(body)); }
catch (e) { reject(e); }
});
req.on('error', reject);
});
}
async function handleChatRequest(req, res) {
try {
const data = await readBody(req);
const { messages, persona } = data;
if (!messages || !Array.isArray(messages)) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'messages array is required' }));
return;
}
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
const fallback = generateFallbackResponse(persona);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ response: fallback }));
return;
}
const systemMessage = {
role: 'system',
content: persona || 'You are a helpful coworker in a workplace chat. Keep responses brief, friendly, and conversational (1-3 sentences).'
};
const apiRes = await fetch(`${OPENAI_BASE_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [systemMessage, ...messages],
max_tokens: 200,
temperature: 0.8
})
});
if (!apiRes.ok) {
const errBody = await apiRes.text();
console.error('OpenAI API error:', apiRes.status, errBody);
const fallback = generateFallbackResponse(persona);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ response: fallback }));
return;
}
const result = await apiRes.json();
const reply = result.choices?.[0]?.message?.content || 'Sorry, I didn\'t catch that.';
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ response: reply }));
} catch (error) {
console.error('Chat endpoint error:', error);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Internal server error' }));
}
}
function generateFallbackResponse(persona) {
const responses = [
'Sounds good, let me look into that!',
'Got it, thanks for the update!',
'Makes sense. Let me know if you need anything else.',
'Good point! I\'ll follow up on that.',
'Sure thing, I\'ll get back to you shortly.',
'That works for me. Talk soon!',
'Interesting, I hadn\'t thought of it that way.',
'Appreciate the heads up! I\'ll take care of it.'
];
return responses[Math.floor(Math.random() * responses.length)];
}
async function handleLogRequest(req, res) {
try {
const data = await readBody(req);
const entries = data.entries;
if (!Array.isArray(entries) || entries.length === 0) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'entries array is required' }));
return;
}
const lines = entries.map(e => JSON.stringify(e)).join('\n') + '\n';
fs.appendFile(LOG_FILE, lines, (err) => {
if (err) console.error('Failed to write log:', err);
});
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true, count: entries.length }));
} catch (error) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
}
function handlePostRequest(req, res, parsedUrl) {
if (parsedUrl.pathname === '/api/log') {
handleLogRequest(req, res);
return;
}
if (parsedUrl.pathname === '/api/chat') {
handleChatRequest(req, res);
return;
}
if (parsedUrl.pathname === '/message') {
let body = '';
req.on('data', chunk => { body += chunk.toString(); });
req.on('end', () => {
try {
const data = JSON.parse(body);
if (!data.message) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Message is required' }));
return;
}
if (!isWebSocketAvailable) {
res.writeHead(503, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'WebSocket not available' }));
return;
}
wsClients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: 'message', message: data.message }));
}
});
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true, clientCount: wsClients.size }));
} catch (error) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
let pathName = parsedUrl.pathname === '/' ? '/index.html' : parsedUrl.pathname;
if (req.method === 'POST') {
handlePostRequest(req, res, parsedUrl);
return;
}
if (isProduction) {
let filePath = path.join(STATIC_DIR, pathName.replace(/^\/+/, ''));
const resolvedStaticDir = path.resolve(STATIC_DIR);
const resolvedFilePath = path.resolve(filePath);
if (path.relative(resolvedStaticDir, resolvedFilePath).startsWith('..')) {
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Forbidden');
return;
}
serveFile(filePath, res);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found (development mode - use Vite dev server)');
}
});
if (isWebSocketAvailable) {
const wss = new WebSocket.Server({ server, path: '/ws' });
wss.on('connection', (ws) => {
console.log('WebSocket client connected');
wsClients.add(ws);
ws.on('close', () => { wsClients.delete(ws); });
ws.on('error', () => { wsClients.delete(ws); });
});
}
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
if (isProduction) console.log(`Serving static files from: ${STATIC_DIR}`);
else console.log('Development mode - static files served by Vite');
});
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') console.error(`Port ${PORT} is already in use.`);
else console.error('Server error:', err);
process.exit(1);
});
process.on('SIGINT', () => {
console.log('\nShutting down server...');
server.close(() => process.exit(0));
});