-
Notifications
You must be signed in to change notification settings - Fork 62
/
serve.js
93 lines (82 loc) · 2.48 KB
/
serve.js
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
88
89
90
91
92
93
const { readdirSync, statSync } = require("fs");
const { join } = require("path");
const express = require("express");
const ts = require("typescript");
const genKaitaiFsFiles = require("./genKaitaiFsFiles");
const port = 8000;
const watchPattern = /(\.html$)|(^js\/)|(^css\/)$/;
const ignorePattern = /node_modules/;
const tsFormatHost = {
getCanonicalFileName: path => path,
getCurrentDirectory: ts.sys.getCurrentDirectory,
getNewLine: () => ts.sys.newLine
};
const app = express();
function reportDiagnostic(diagnostic) {
console.error(
`Error ${diagnostic.code}:`,
ts.flattenDiagnosticMessageText(
diagnostic.messageText,
tsFormatHost.getNewLine()
)
);
}
function reportWatchStatusChanged(diagnostic) {
console.info(ts.formatDiagnostic(diagnostic, tsFormatHost).trimRight());
}
function startWatcher() {
console.log("Starting typescript compiler...");
const configPath = ts.findConfigFile(
"./",
ts.sys.fileExists,
"tsconfig.json"
);
if (!configPath) {
throw new Error("Could not find a valid 'tsconfig.json'.");
}
const createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram;
const host = ts.createWatchCompilerHost(
configPath,
{},
ts.sys,
createProgram,
reportDiagnostic,
reportWatchStatusChanged
);
return ts.createWatchProgram(host);
}
function findLatestChange(dir = ".", latestChange = 0) {
const fns = readdirSync(dir, "utf-8");
for (const fn of fns) {
const path = join(dir, fn);
const stats = statSync(path);
if (stats.isDirectory() && !ignorePattern.test(path)) {
latestChange = findLatestChange(path, latestChange);
} else if (stats.isFile() && watchPattern.test(path)) {
if (stats.mtimeMs > latestChange) {
latestChange = stats.mtimeMs;
}
}
}
return latestChange;
}
app.get("/onchange", (req, res, next) => {
const initialChange = findLatestChange();
const checkChange = () => {
if (findLatestChange() > initialChange) {
res.send({ changed: true });
return;
}
setTimeout(checkChange, 500);
};
checkChange();
});
app.use(express.static("."));
function main() {
genKaitaiFsFiles('');
if (process.argv.includes("--compile")) {
startWatcher();
}
app.listen(port, () => console.log(`Listening on ${port}.`));
}
main();