#!/usr/bin/env node
// Simple static server for local development — serves dist/ and wasm/ on port 8080
import http from "http";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT ?? 8080;

const MIME = {
  ".js": "application/javascript",
  ".wasm": "application/wasm",
  ".ts": "text/plain",
  ".d.ts": "text/plain",
};

http
  .createServer((req, res) => {
    const filePath = path.join(__dirname, decodeURIComponent(req.url.split("?")[0]));
    const ext = path.extname(filePath);

    fs.readFile(filePath, (err, data) => {
      if (err) {
        res.writeHead(404);
        res.end("Not found");
        return;
      }
      res.writeHead(200, {
        "Content-Type": MIME[ext] ?? "application/octet-stream",
        "Cache-Control": "no-cache",
        "Cross-Origin-Resource-Policy": "cross-origin",
      });
      res.end(data);
    });
  })
  .listen(PORT, () => {
    console.log(`[buttplug] serving on http://localhost:${PORT}`);
  });
