41 lines
1.5 KiB
JavaScript
41 lines
1.5 KiB
JavaScript
import { createReadStream, existsSync, statSync } from "node:fs";
|
|
import { createServer } from "node:http";
|
|
import { extname, join, normalize, resolve } from "node:path";
|
|
|
|
const root = resolve(process.cwd(), process.argv[2] ?? "dist");
|
|
const port = Number(process.env.PORT ?? 4173);
|
|
const mimeTypes = new Map([
|
|
[".css", "text/css; charset=utf-8"],
|
|
[".html", "text/html; charset=utf-8"],
|
|
[".js", "text/javascript; charset=utf-8"],
|
|
[".json", "application/json; charset=utf-8"],
|
|
[".png", "image/png"],
|
|
[".svg", "image/svg+xml"],
|
|
[".webp", "image/webp"],
|
|
]);
|
|
|
|
const server = createServer((request, response) => {
|
|
const rawPath = decodeURIComponent((request.url ?? "/").split("?")[0]);
|
|
const relativePath = normalize(rawPath).replace(/^([/\\])+/, "");
|
|
let filePath = resolve(join(root, relativePath || "index.html"));
|
|
|
|
if (!filePath.startsWith(root)) {
|
|
response.writeHead(403).end("Forbidden");
|
|
return;
|
|
}
|
|
|
|
if (!existsSync(filePath) || statSync(filePath).isDirectory()) {
|
|
filePath = join(root, "index.html");
|
|
}
|
|
|
|
response.setHeader("Content-Type", mimeTypes.get(extname(filePath)) ?? "application/octet-stream");
|
|
response.setHeader("X-Content-Type-Options", "nosniff");
|
|
response.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
|
|
response.setHeader("Cross-Origin-Opener-Policy", "same-origin");
|
|
createReadStream(filePath).pipe(response);
|
|
});
|
|
|
|
server.listen(port, "127.0.0.1", () => {
|
|
console.log(`GLM Hub disponible en http://127.0.0.1:${port}`);
|
|
});
|