-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathexternalLinks.ts
More file actions
77 lines (64 loc) · 2.02 KB
/
externalLinks.ts
File metadata and controls
77 lines (64 loc) · 2.02 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
70
71
72
73
74
75
76
77
import type { MiddlewareHandler } from "astro";
import type { Element } from "hast";
import { convertElement } from "hast-util-is-element";
import rehypeExternalLinks, {
type Options as RehypeExternalLinksOptions,
} from "rehype-external-links";
import rehypeParse from "rehype-parse";
import rehypeStringify from "rehype-stringify";
import { unified } from "unified";
import type { Compatible } from "vfile";
type Anchor = Element & { tagName: "a"; properties: { href: string } };
function isAnchor(e: Element): e is Anchor {
return e.tagName === "a" && typeof e.properties.href === "string";
}
class Processor {
hostname?: string;
private readonly processor;
constructor(options: RehypeExternalLinksOptions) {
const check = convertElement(options.test);
const hostnameIsIdentical = (e: Element) => {
if (isAnchor(e))
try {
return new URL(e.properties.href).hostname === this.hostname;
} catch {}
return false;
};
this.processor = unified()
.use(rehypeParse)
.use(rehypeExternalLinks, {
...options,
// all anchor elements are tested, and
// external links which passed are processed.
test: (e, i, p) => !hostnameIsIdentical(e) && check(e, i, p),
})
.use(rehypeStringify);
}
process(file?: Compatible) {
return this.processor.process(file);
}
}
const processor = new Processor({
target: "_blank",
rel: ["noopener", "noreferrer"],
content: { type: "text", value: "" },
contentProperties: { className: ["external-link"] },
});
const mimeHtmlPattern = /^\s*text\/html(?:[\s;].*|$)/;
export const onRequest: MiddlewareHandler = async (
{ site: { hostname } = {} },
next
) => {
processor.hostname = hostname;
const response = await next();
if (response.headers.get("content-type")?.match(mimeHtmlPattern)) {
return new Response(
(await processor.process(await response.text())).value,
{
status: response.status,
headers: response.headers,
}
);
}
return response;
};