-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·54 lines (45 loc) · 1.6 KB
/
server.js
File metadata and controls
executable file
·54 lines (45 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env bun
// Bun static file server. No backend logic. All dynamic behaviour lives in
// the browser's Service Worker (sw.js). This server only ships files.
import { file } from "bun";
import { extname, join, normalize } from "node:path";
const PORT = Number(process.env.PORT ?? 3000);
const ROOT = import.meta.dir;
const MIME = {
".html": "text/html; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".mjs": "application/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".png": "image/png",
".jpg": "image/jpeg",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".json": "application/json; charset=utf-8",
".txt": "text/plain; charset=utf-8",
};
function resolvePath(urlPath) {
let p = decodeURIComponent(urlPath.split("?")[0]);
if (p === "/" || p === "") p = "/index.html";
p = normalize(p).replace(/^([./\\]+)/, "/");
return join(ROOT, p);
}
Bun.serve({
port: PORT,
development: true,
async fetch(req) {
const url = new URL(req.url);
const fsPath = resolvePath(url.pathname);
if (!fsPath.startsWith(ROOT)) return new Response("forbidden", { status: 403 });
const f = file(fsPath);
if (!(await f.exists())) return new Response("not found", { status: 404 });
const headers = new Headers();
const ext = extname(fsPath).toLowerCase();
if (MIME[ext]) headers.set("Content-Type", MIME[ext]);
headers.set("Cache-Control", "no-cache");
if (url.pathname === "/sw.js") {
headers.set("Service-Worker-Allowed", "/");
}
return new Response(f, { headers });
},
});
console.log(`webloom :: http://localhost:${PORT}`);