// src/server.mjs import { createServer } from 'node:http'; import { readFile } from 'node:fs/promises'; // The web client's three files, by the path a browser asks for them. On the // platform, the deploy serves them from client/ ahead of these routes, and a // local run that names a port answers them the same way. A test, or a local // run that names none, has nothing in front of it, so this server answers them. const CLIENT_FILES = Object.freeze({ '/': ['index.html', 'text/html; charset=utf-8'], '/index.html': ['index.html', 'text/html; charset=utf-8'], '/app.js': ['app.js', 'text/javascript; charset=utf-8'], '/styles.css': ['styles.css', 'text/css; charset=utf-8'], }); // The longest turn the chat route takes, in characters. export const TURN_LENGTH_MAX = 4000; const readBody = async (request) => { // One decoder for the whole body: a character whose bytes arrive in two chunks is read whole. request.setEncoding('utf8'); let text = ''; for await (const chunk of request) text += chunk; return text; }; // The conversation a request posts as { messages }, or null where it is not // one the route takes: an array of { role, content } turns that alternate, // user then assistant, and start and end on a user turn, each content a // string with a character that is not white space and at most // TURN_LENGTH_MAX characters. export function conversationOf(posted) { const messages = posted?.messages; if (!Array.isArray(messages) || messages.length % 2 === 0) return null; const turns = []; for (const [index, turn] of messages.entries()) { const role = index % 2 === 0 ? 'user' : 'assistant'; if (turn === null || typeof turn !== 'object' || turn.role !== role || typeof turn.content !== 'string') return null; if (turn.content.trim() === '' || turn.content.length > TURN_LENGTH_MAX) return null; turns.push({ role, content: turn.content }); } return turns; } // A request's abort signal. The deployed runtime attaches its own signal to each // request, and it aborts at the request's window. A local run has none of its own, // and Node's request.signal can abort at a normal request end on some Node 24 // releases, so a local run's signal aborts when the response closes unfinished. function abortSignalOf(request, response) { const own = Object.hasOwn(request, 'signal') ? request.signal : undefined; if (own) return own; const controller = new AbortController(); response.once('close', () => { if (!response.writableFinished) controller.abort(); }); return controller.signal; } // The server over its two parts: userIdOf, which reads the signed-in user's // id from a request, or null; and reply, which answers a conversation's next // turn under the AI allowance, or names why the model gave no answer. export function createAppServer({ userIdOf, reply }) { return createServer(async (request, response) => { // End the response when the request is aborted (abortSignalOf, above). const signal = abortSignalOf(request, response); signal.addEventListener('abort', () => response.destroy(), { once: true }); const send = (status, body) => { if (response.destroyed) return; response.writeHead(status, { 'content-type': 'application/json' }); response.end(JSON.stringify(body)); }; try { // A target that does not parse as a URL names no route, so it is answered 404 below. let pathname = null; try { pathname = new URL(request.url, 'http://localhost').pathname; } catch {} // The service keeps no store, so its health is the process answering. if (request.method === 'GET' && pathname === '/health') return send(200, { ok: true }); if (request.method === 'GET' && Object.hasOwn(CLIENT_FILES, pathname)) { const [file, type] = CLIENT_FILES[pathname]; try { const body = await readFile(new URL(`../client/${file}`, import.meta.url)); if (!response.destroyed) response.writeHead(200, { 'content-type': type }).end(body); return; } catch (error) { if (error?.code === 'ENOENT') return send(404, { error: 'not_found' }); throw error; } } // The route under /api/ answers the signed-in user alone. if (pathname === '/api/ask') { const user = await userIdOf(request); if (user === null) return send(401, { error: 'sign_in_required' }); if (request.method === 'POST') { const conversation = conversationOf(JSON.parse(await readBody(request))); if (conversation === null) return send(400, { error: 'invalid_messages' }); // 503 names why the model gave no answer: allowance_unavailable, // account_paused, or upstream_quota (src/ai.mjs). const replied = await reply(conversation, signal); return 'answer' in replied ? send(200, { answer: replied.answer }) : send(503, { error: replied.unanswered }); } } send(404, { error: 'not_found' }); } catch (error) { const refused = error instanceof SyntaxError ? 'invalid_json' : null; if (refused === null && !signal.aborted) console.error(error); send(refused === null ? 500 : 400, { error: refused ?? 'internal' }); } }); }