-
Notifications
You must be signed in to change notification settings - Fork 2
/
run-in-browser
executable file
·87 lines (74 loc) · 2.2 KB
/
run-in-browser
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
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import http from "node:http";
import { bundleWeb } from "./build/scripts/build/bundle-web.js";
// get first and only command line argument
let src = process.argv[2];
// transform ts file name in the source tree to js file in /build
let srcjs = src.replace(/\.ts$/, ".js");
let entrypoint = path.resolve("build/", srcjs);
entrypoint = fs.existsSync(entrypoint) ? entrypoint : src;
let targetDir = path.dirname(path.join("build/web/", srcjs));
let absPath = await bundleWeb(entrypoint, targetDir);
let fileName = path.basename(absPath);
let filePath = path.join(targetDir, fileName);
console.log(`running in the browser: ${filePath}`);
const indexHtml = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="icon" href="data:," />
<title>${fileName}</title>
<script>
// pass command line arguments
window.process = { argv: ${JSON.stringify(process.argv)} };
</script>
<script type="module" src="./${fileName}">
</script>
</head>
<body>
<div>Check out the console (F12)</div>
</body>
</html>
`;
const port = 8000;
const defaultHeaders = {
"content-type": "text/html",
"Cross-Origin-Embedder-Policy": "require-corp",
"Cross-Origin-Opener-Policy": "same-origin",
};
const server = http.createServer(async (req, res) => {
let file = "." + req.url;
if (file === "./") file = "./index.html";
// console.log('serving', file);
let content;
if (file === "./index.html") content = indexHtml;
else {
try {
content = await fs.promises.readFile(
path.resolve(targetDir, file),
"utf8"
);
} catch (err) {
res.writeHead(404, defaultHeaders);
res.write("<html><body>404</body><html>");
res.end();
return;
}
}
const extension = path.basename(file).split(".").pop();
const contentType = {
html: "text/html",
js: "application/javascript",
map: "application/json",
}[extension];
const headers = { ...defaultHeaders, "content-type": contentType };
res.writeHead(200, headers);
res.write(content);
res.end();
});
server.listen(port, () => {
console.log(`Server is running on: http://localhost:${port}`);
});