-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
78 lines (74 loc) · 2.34 KB
/
server.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
const express = require("express");
const Number = require("./number");
const pandoc = require("./pandoc");
const { execSync } = require("child_process");
const path = require("path");
const fs = require("fs");
const yaml = require("js-yaml");
const iterator = require("./iterator");
const livereload = require("livereload");
const liveReloadServer = livereload.createServer({ extraExts: ["md"] });
liveReloadServer.watch(path.join(__dirname, ".."));
const connectLivereload = require("connect-livereload");
const statics = { images: {} };
const app = express()
.enable("strict routing")
.use(connectLivereload())
.get("/", function (_req, res, _next) {
var docs = [];
iterator(function (srcname, name, variant) {
docs.push(
`<li><a href="${srcname}/?variant=${variant}">${name}</a></li>`,
);
});
res.send(`<h1>Documents</h1><ul>${docs.join("")}</ul>`);
})
.get("/:doc", function (req, res, _next) {
var url = new URL("s://" + req.originalUrl);
url.pathname += "/";
res.redirect(url.href.substring(4));
})
.get("/:doc/", function (req, res, next) {
try {
var branch = execSync("git branch --show-current", {
cwd: __dirname,
}).toString();
if (branch) req.query["-T"] = branch;
} catch (e) {}
try {
var number = new Number(
`${__dirname}/../${req.params.doc}`,
req.query.variant,
);
var metaname = `${__dirname}/../${req.params.doc}/${
req.query.variant || "meta"
}.yaml`;
delete req.query.variant;
var meta = yaml.load(fs.readFileSync(metaname));
res.type("html");
var proc = pandoc({
"--metadata-file": metaname,
"-H": "scripts/folding.html",
...meta.pandocOptions,
...req.query,
});
proc.stdout.pipe(res);
number.build(proc.stdin).catch((err) => {
console.error();
console.error(err.join("\n"));
});
} catch (err) {
next();
}
})
.use("/:doc/styles", express.static(`${__dirname}/../styles`))
.use("/:doc/images", function (req, res, next) {
(statics.images[req.params.doc] ||= express.static(
`${__dirname}/../${req.params.doc}/images`,
))(req, res, next);
});
if (module.parent) module.exports = app;
else
app.listen(8080, function () {
console.log("Server running on http://localhost:8080");
});