-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathtransform.ts
50 lines (46 loc) · 1.28 KB
/
transform.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
/* SPDX-FileCopyrightText: 2020-present Kriasoft */
/* SPDX-License-Identifier: MIT */
type Page = {
title?: string;
description?: string;
data?: Record<string, unknown>;
};
/**
* Injects HTML page metadata (title, description, etc.) as well as
* the serialized application store.
*/
export function transform(res: Response, page: Page): Response {
return (
new HTMLRewriter()
// <title>...</title>
.on("title:first-of-type", {
element(el) {
if (page.title) {
el.setInnerContent(page.title);
}
},
})
// <meta name="description" content="..." />
.on('meta[name="description"]:first-of-type', {
element(el) {
if (page.description) {
el.setAttribute("content", page.description);
}
},
})
// <script id="data" type="application/json"></script>
// https://developer.mozilla.org/docs/Web/HTML/Element/script#embedding_data_in_html
.on("script#data", {
element(el) {
if (page.data) {
const json = JSON.stringify(page.data).replace(
/<\/script/g,
"</\\u0073cript"
);
el.setInnerContent(json, { html: true });
}
},
})
.transform(res)
);
}