import { createServer } from 'node:http'
import { readFile } from 'node:fs/promises'
import { extname, join, normalize } from 'node:path'
import { fileURLToPath } from 'node:url'

const root = fileURLToPath(new URL('.', import.meta.url))
const types = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8' }
createServer(async (request, response) => {
  const raw = request.url === '/' ? 'index.html' : request.url.split('?')[0].replace(/^[/\\]+/, '')
  const file = normalize(join(root, raw))
  if (!file.startsWith(normalize(root))) { response.writeHead(403); response.end('Forbidden'); return }
  try { const content = await readFile(file); response.writeHead(200, { 'Content-Type': types[extname(file)] || 'application/octet-stream' }); response.end(content) }
  catch {
    const content = await readFile(join(root, 'index.html'))
    response.writeHead(200, { 'Content-Type': types['.html'] })
    response.end(content)
  }
}).listen(4173, () => console.log('\nPAXO preview is ready: http://localhost:4173\nKeep this window open while reviewing the website.'))
