-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
186 lines (162 loc) · 4.91 KB
/
server.js
File metadata and controls
186 lines (162 loc) · 4.91 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
import http from 'http';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PORT = Number(process.env.PORT || 8080);
const DIST_DIR = path.join(__dirname, 'dist');
const INDEX_FILE = path.join(DIST_DIR, 'index.html');
const MIME_TYPES = {
'.css': 'text/css',
'.gif': 'image/gif',
'.html': 'text/html',
'.ico': 'image/x-icon',
'.jpeg': 'image/jpeg',
'.jpg': 'image/jpeg',
'.js': 'application/javascript',
'.json': 'application/json',
'.map': 'application/json',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.txt': 'text/plain',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2': 'font/woff2'
};
function sendJson(res, statusCode, payload) {
const body = JSON.stringify(payload);
res.writeHead(statusCode, {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body)
});
res.end(body);
}
function readJsonBody(req) {
return new Promise((resolve, reject) => {
let data = '';
req.on('data', (chunk) => {
data += chunk;
if (data.length > 1024 * 1024) {
reject(new Error('Request body too large'));
req.destroy();
}
});
req.on('end', () => {
try {
resolve(data ? JSON.parse(data) : {});
} catch {
reject(new Error('Invalid JSON body'));
}
});
req.on('error', reject);
});
}
async function handleAnalyze(req, res) {
const endpoint = process.env.AZURE_OPENAI_ENDPOINT;
const apiKey = process.env.AZURE_OPENAI_API_KEY;
const deployment = process.env.AZURE_OPENAI_DEPLOYMENT;
const apiVersion = process.env.AZURE_OPENAI_API_VERSION || '2024-10-21';
if (!endpoint || !apiKey || !deployment) {
return sendJson(res, 500, {
error: 'Missing AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_API_KEY, or AZURE_OPENAI_DEPLOYMENT'
});
}
let body;
try {
body = await readJsonBody(req);
} catch (error) {
return sendJson(res, 400, { error: error.message });
}
const text = typeof body.text === 'string' ? body.text.trim() : '';
if (!text) {
return sendJson(res, 400, { error: 'Field "text" is required' });
}
const cleanEndpoint = endpoint.replace(/\/$/, '');
const url = `${cleanEndpoint}/openai/deployments/${encodeURIComponent(deployment)}/chat/completions?api-version=${encodeURIComponent(apiVersion)}`;
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'api-key': apiKey
},
body: JSON.stringify({
messages: [
{
role: 'system',
content: 'You are an empathetic counselling assistant. Return concise and practical guidance.'
},
{
role: 'user',
content: text
}
],
temperature: 0.3
})
});
const raw = await response.text();
const parsed = raw ? JSON.parse(raw) : {};
if (!response.ok) {
return sendJson(res, response.status, {
error: 'Azure OpenAI request failed',
details: parsed
});
}
const content = parsed?.choices?.[0]?.message?.content ?? '';
return sendJson(res, 200, {
result: content,
usage: parsed?.usage ?? null,
model: parsed?.model ?? deployment
});
} catch (error) {
return sendJson(res, 500, {
error: 'Unexpected analyze error',
details: error.message
});
}
}
function serveStatic(req, res) {
const parsedUrl = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
const pathname = decodeURIComponent(parsedUrl.pathname);
const normalizedPath = pathname === '/' ? '/index.html' : pathname;
const filePath = path.normalize(path.join(DIST_DIR, normalizedPath));
if (!filePath.startsWith(DIST_DIR)) {
res.writeHead(403);
res.end('Forbidden');
return;
}
fs.readFile(filePath, (fileError, content) => {
if (fileError) {
fs.readFile(INDEX_FILE, (indexError, indexContent) => {
if (indexError) {
res.writeHead(500);
res.end('Server misconfiguration: dist/index.html missing');
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(indexContent);
});
return;
}
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, { 'Content-Type': MIME_TYPES[ext] || 'application/octet-stream' });
res.end(content);
});
}
const server = http.createServer(async (req, res) => {
if (req.method === 'GET' && req.url && req.url.startsWith('/api/health')) {
return sendJson(res, 200, {
status: 'ok',
service: 'facilitatorai',
time: new Date().toISOString()
});
}
if (req.method === 'POST' && req.url === '/api/analyze') {
return handleAnalyze(req, res);
}
serveStatic(req, res);
});
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});