-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
59 lines (55 loc) · 1.73 KB
/
index.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
const express = require("express");
const { mf2 } = require("microformats-parser");
const pkg = require("./package.json");
const app = express();
const port = process.env.PORT || 9000;
function getDependencyVersion(dependencyName) {
const fs = require("fs");
const lockfile = require("@yarnpkg/lockfile");
const parsed = lockfile.parse(fs.readFileSync("./yarn.lock", "utf-8"));
if (parsed.type !== "success") return "unknown";
const dependency =
parsed.object[`${dependencyName}@${pkg.dependencies[dependencyName]}`];
if (dependency === undefined) return "unknown";
return dependency.version;
}
const mf2version = getDependencyVersion("microformats-parser");
function htmlToMf2(url, html, res) {
try {
const body = mf2(html, { baseUrl: url });
res
.header("content-type", "application/json; charset=UTF-8")
.send(JSON.stringify(body, null, 2));
} catch (err) {
res
.header("content-type", "application/json; charset=UTF-8")
.status(500)
.send(JSON.stringify({ error: err.message }, null, 2));
}
}
app.set("view engine", "ejs");
app.use(express.static("public"));
app.get("/", async (req, res) => {
if (req.query.url) {
const url = req.query.url;
await fetch(url, {
headers: {
accept: "text/html, text/mf2+html",
},
method: "GET",
}).then(async (response) => {
const html = await response.text();
htmlToMf2(url, html, res);
});
} else {
res.render("index.html.ejs", {
version: `${pkg.version} (lib: ${mf2version})`,
});
}
});
app.post("/", express.urlencoded({ extended: false }), (req, res) => {
htmlToMf2(req.body.url, req.body.html, res);
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});