import { createServer } from 'node:http'; import { readFile, stat } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; import path from 'node:path'; const root = fileURLToPath(new URL('../', import.meta.url)); const args = process.argv.slice(2); function option(name, fallback) { const index = args.indexOf(name); return index >= 0 ? args[index + 1] : fallback; } const host = option('--host', '127.0.0.1'); const port = Number(option('--port', '5173')); const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.webp': 'image/webp', '.ico': 'image/x-icon', '.mp3': 'audio/mpeg' }; createServer(async (request, response) => { try { if (!['GET', 'HEAD'].includes(request.method)) { response.writeHead(405).end(); return; } const pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname); if (pathname.split('/').some(part => part.startsWith('.'))) { response.writeHead(403).end(); return; } let filename = path.resolve(root, '.' + pathname); if (!filename.startsWith(root)) { response.writeHead(403).end(); return; } if ((await stat(filename)).isDirectory()) filename = path.join(filename, 'index.html'); const content = await readFile(filename); response.writeHead(200, { 'Content-Type': types[path.extname(filename)] ?? 'application/octet-stream', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' }); response.end(request.method === 'HEAD' ? undefined : content); } catch { response.writeHead(404).end('Not found'); } }).listen(port, host, () => console.log(`Workspace: http://${host}:${port}`));