#!/usr/bin/env node // Minimal static server for the browser host (serves host/, config/, build/ only). // node host/serve.mjs [port] (default: $PORT or 8080) import http from 'node:http'; import { readFile } from 'node:fs/promises'; import { join, extname, normalize } from 'node:path'; import { fileURLToPath } from 'node:url'; const ROOT = join(fileURLToPath(import.meta.url), '..', '..'); const MIME = { '.html': 'text/html', '.mjs': 'text/javascript', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm' }; const ALLOWED = ['host/', 'config/', 'build/']; export function serve(port = 0) { const srv = http.createServer(async (req, res) => { try { let p = decodeURIComponent(new URL(req.url, 'http://x').pathname); if (p === '/') p = '/host/web/index.html'; const rel = normalize(p).replace(/^\/+/, ''); if (rel.includes('..') || !ALLOWED.some((a) => rel.startsWith(a)) || rel.startsWith('host/node_modules')) { res.writeHead(404).end('not found'); return; } const body = await readFile(join(ROOT, rel)); res.writeHead(200, { 'content-type': MIME[extname(rel)] ?? 'application/octet-stream', 'cache-control': 'no-store' }).end(body); } catch { res.writeHead(404).end('not found'); } }); return new Promise((resolve) => srv.listen(port, '127.0.0.1', () => resolve(srv))); } if (process.argv[1] === fileURLToPath(import.meta.url)) { const srv = await serve(Number(process.argv[2] ?? process.env.PORT ?? 8080)); console.log(`moon-plasma host: http://127.0.0.1:${srv.address().port}/`); }