29 lines
2.1 KiB
JavaScript
29 lines
2.1 KiB
JavaScript
import { createServer } from 'node:http';
|
|
import { readFile, stat } from 'node:fs/promises';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { extname, resolve, sep } from 'node:path';
|
|
const root = fileURLToPath(new URL('../', import.meta.url));
|
|
const production = process.argv.includes('--dist');
|
|
const port = Number(process.env.PORT ?? 4176);
|
|
const types = {'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.json':'application/json'};
|
|
const server = createServer(async (request,response) => {
|
|
try {
|
|
const path = decodeURIComponent(new URL(request.url,'http://localhost').pathname);
|
|
if (request.method!=='GET' && request.method!=='HEAD') { response.writeHead(405);response.end();return; }
|
|
if (path.startsWith('/v1/') || ['/health','/ready','/version'].includes(path)) {
|
|
response.writeHead(503,{'content-type':'application/json','cache-control':'no-store'});
|
|
response.end(JSON.stringify({error:'preview_has_no_backend'}));return;
|
|
}
|
|
const sourcePath = !production && path.startsWith('/src/');
|
|
const base = production ? resolve(root,'dist') : sourcePath ? resolve(root,'src') : resolve(root,'public');
|
|
let file = resolve(base, sourcePath ? path.slice('/src/'.length) : `.${path}`);
|
|
if (path==='/' || path==='/account' || path==='/account/') file=resolve(base,'index.html');
|
|
if (!file.startsWith(base+sep)) { response.writeHead(403);response.end();return; }
|
|
const info=await stat(file);
|
|
if (!info.isFile()) throw new Error('not_file');
|
|
response.writeHead(200,{'content-type':types[extname(file)]??'application/octet-stream','cache-control':'no-store','x-content-type-options':'nosniff'});
|
|
response.end(request.method==='HEAD'?undefined:await readFile(file));
|
|
} catch { response.writeHead(404,{'content-type':'text/plain'});response.end('Not found'); }
|
|
});
|
|
server.listen(port,'127.0.0.1',()=>console.log(`VNOX Web: http://127.0.0.1:${port}`));
|
|
for (const signal of ['SIGINT','SIGTERM']) process.on(signal,()=>server.close(()=>process.exit(0)));
|