Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (64 loc) · 2.1 KB
/
Copy pathindex.js
File metadata and controls
69 lines (64 loc) · 2.1 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
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 readExperimental(params) {
const experimental = {};
for (const flag of ["lang", "textContent", "metaformats"]) {
if (params[flag] === "true") experimental[flag] = true;
}
return Object.keys(experimental).length > 0 ? { experimental } : {};
}
function htmlToMf2(url, html, experimental, res) {
try {
const body = mf2(html, { baseUrl: url, ...experimental });
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;
const experimental = readExperimental(req.query);
await fetch(url, {
headers: {
accept: "text/html, text/mf2+html",
},
method: "GET",
}).then(async (response) => {
const html = await response.text();
htmlToMf2(url, html, experimental, res);
});
} else {
res.render("index.html.ejs", {
site_version: pkg.version,
mf2_version: 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}`);
});