-
Notifications
You must be signed in to change notification settings - Fork 38
/
RedirectIntegration.ts
81 lines (77 loc) · 2.31 KB
/
RedirectIntegration.ts
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
import type { AstroIntegration } from "astro";
import fs from "fs/promises";
import matter from "gray-matter";
import { extname, join, relative } from "path";
import { fileURLToPath } from "url";
import { glob } from "glob";
import { VFile } from "vfile";
const source = [".md", ".markdown", ".mdx"];
export default function redirect(): AstroIntegration {
return {
name: "redirect",
hooks: {
"astro:config:setup": async ({ updateConfig, config }) => {
const pages = join(fileURLToPath(config.srcDir), "pages");
const paths = await glob("**/*", { cwd: pages, nodir: true, absolute: true });
const files = (
await Promise.all(
paths.map(async (path) => {
if (!source.includes(extname(path))) return null;
return readFile(path);
})
)).filter((file) => file !== null);
const redirects = files.flatMap((file) => {
const { redirect_to, redirect_from } = file.data;
const here =
"/" +
relative(pages, file.path).replace(
/(?:index)?\.(?:md|mdx|markdown|astro)$/,
""
);
if (typeof redirect_to === "string") {
return { from: here, to: redirect_to };
}
if (typeof redirect_from === "string") {
return { from: redirect_from, to: here };
}
if (
Array.isArray(redirect_from) &&
redirect_from.every((x) => typeof x === "string")
) {
return redirect_from.map((from) => ({ from, to: here }));
}
return [];
});
updateConfig({
redirects: Object.fromEntries(
redirects.map(({ from, to }) => [from, to])
),
});
},
},
};
}
async function readFile(path: string) {
const value = await fs.readFile(path, "utf-8");
const { data } = matter(value);
return new VFile({ path, value, data });
}
function html(to: string) {
return `\
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="refresh" content="0; url=${to}" />
<link rel="canonical" href="${to}" />
</head>
<body>
<h1>Redirecting...</h1>
<p>
If you are not redirected automatically, follow this
<a href="${to}">link</a>.
</p>
</body>
</html>
`;
}