Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
77 lines (69 loc) · 2.12 KB
/
Copy pathserver.ts
File metadata and controls
77 lines (69 loc) · 2.12 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { resolve, sep } from "node:path";
import {
publicAliases,
rootAssetNames,
} from "./scripts/artifacts.mjs";
const repoRoot = resolve(import.meta.dir);
const rootAssets = new Set(["index.html", ...rootAssetNames]);
const allowedDirectories = ["dist", "icons", "polyfills", "src", "tests"];
const extendedAssets = new Set([
"fig-editor.js",
"fig-editor.css",
"fig-lab.js",
"fig-lab.css",
"fig-input-rotate.js",
"fig-input-rotate.css",
"fig-input-slider.js",
"fig-input-slider.css",
]);
const packagePrefix = "@rogieking/figui3/";
const requestedPort = Number.parseInt(process.env.FIGUI_PORT ?? "3000", 10);
const port = Number.isFinite(requestedPort) ? requestedPort : 3000;
function resolvePublicAsset(pathname: string) {
const name = pathname.replace(/^\/+/, "");
if (extendedAssets.has(name)) {
return resolve(
repoRoot,
"node_modules",
"@rogieking",
"figui3-extended",
"dist",
name,
);
}
if (name.startsWith(packagePrefix)) {
return resolve(repoRoot, "dist", name.slice(packagePrefix.length));
}
const allowed =
rootAssets.has(name) ||
allowedDirectories.some(
(directory) => name === directory || name.startsWith(`${directory}/`),
);
if (!allowed) return null;
const filePath = resolve(repoRoot, name);
return filePath.startsWith(`${repoRoot}${sep}`) ? filePath : null;
}
const server = Bun.serve({
port,
async fetch(req) {
const url = new URL(req.url);
let path = url.pathname;
// Default to index.html
if (path === "/") {
path = "/index.html";
}
const name = path.replace(/^\/+/, "");
const sourceAlias = publicAliases[name];
if (sourceAlias) {
return Response.redirect(new URL(`/${sourceAlias}`, url), 302);
}
const filePath = resolvePublicAsset(path);
if (!filePath) return new Response("Not Found", { status: 404 });
const file = Bun.file(filePath);
if (await file.exists()) {
return new Response(file);
}
return new Response("Not Found", { status: 404 });
},
});
console.log(`🎨 FigUI Dev Server running at http://localhost:${server.port}`);