-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
render.ts
284 lines (261 loc) · 8.13 KB
/
render.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import { isBooleanAttr } from '@vue/shared'
import escape from 'escape-html'
import fs from 'fs-extra'
import path from 'path'
import { pathToFileURL } from 'url'
import { normalizePath, transformWithEsbuild, type Rollup } from 'vite'
import type { SiteConfig } from '../config'
import {
EXTERNAL_URL_RE,
createTitle,
mergeHead,
notFoundPageData,
resolveSiteDataByRoute,
sanitizeFileName,
slash,
type HeadConfig,
type PageData,
type SSGContext
} from '../shared'
import { version } from '../../../package.json'
export async function renderPage(
render: (path: string) => Promise<SSGContext>,
config: SiteConfig,
page: string, // foo.md
result: Rollup.RollupOutput | null,
appChunk: Rollup.OutputChunk | null,
cssChunk: Rollup.OutputAsset | null,
assets: string[],
pageToHashMap: Record<string, string>,
metadataScript: { html: string; inHead: boolean },
additionalHeadTags: HeadConfig[]
) {
const routePath = `/${page.replace(/\.md$/, '')}`
const siteData = resolveSiteDataByRoute(config.site, routePath)
// render page
const context = await render(routePath)
const { content, teleports } = (await config.postRender?.(context)) ?? context
const pageName = sanitizeFileName(page.replace(/\//g, '_'))
// server build doesn't need hash
const pageServerJsFileName = pageName + '.js'
// for any initial page load, we only need the lean version of the page js
// since the static content is already on the page!
const pageHash = pageToHashMap[pageName.toLowerCase()]
const pageClientJsFileName = `${config.assetsDir}/${pageName}.${pageHash}.lean.js`
let pageData: PageData
let hasCustom404 = true
try {
// resolve page data so we can render head tags
const { __pageData } = await import(
pathToFileURL(
path.join(config.tempDir, pageServerJsFileName)
).toString() +
'?t=' +
Date.now()
)
pageData = __pageData
} catch (e) {
if (page === '404.md') {
hasCustom404 = false
pageData = notFoundPageData
} else {
throw e
}
}
const title: string = createTitle(siteData, pageData)
const description: string = pageData.description || siteData.description
const stylesheetLink = cssChunk
? `<link rel="preload stylesheet" href="${siteData.base}${cssChunk.fileName}" as="style">`
: ''
let preloadLinks =
config.mpa || (!hasCustom404 && page === '404.md')
? []
: result && appChunk
? [
...new Set([
// resolve imports for index.js + page.md.js and inject script tags
// for them as well so we fetch everything as early as possible
// without having to wait for entry chunks to parse
...resolvePageImports(config, page, result, appChunk),
pageClientJsFileName
])
]
: []
let prefetchLinks: string[] = []
const { shouldPreload } = config
if (shouldPreload) {
prefetchLinks = preloadLinks.filter((link) => !shouldPreload(link, page))
preloadLinks = preloadLinks.filter((link) => shouldPreload(link, page))
}
const toHeadTags = (files: string[], rel: string): HeadConfig[] =>
files.map((file) => [
'link',
{
rel,
// don't add base to external urls
href: (EXTERNAL_URL_RE.test(file) ? '' : siteData.base) + file
}
])
const preloadHeadTags = toHeadTags(preloadLinks, 'modulepreload')
const prefetchHeadTags = toHeadTags(prefetchLinks, 'prefetch')
const headBeforeTransform = [
...additionalHeadTags,
...preloadHeadTags,
...prefetchHeadTags,
...mergeHead(
siteData.head,
filterOutHeadDescription(pageData.frontmatter.head)
)
]
const head = mergeHead(
headBeforeTransform,
(await config.transformHead?.({
page,
siteConfig: config,
siteData,
pageData,
title,
description,
head: headBeforeTransform,
content,
assets
})) || []
)
let inlinedScript = ''
if (config.mpa && result) {
const matchingChunk = result.output.find(
(chunk) =>
chunk.type === 'chunk' &&
chunk.facadeModuleId === slash(path.join(config.srcDir, page))
) as Rollup.OutputChunk
if (matchingChunk) {
if (!matchingChunk.code.includes('import')) {
inlinedScript = `<script type="module">${matchingChunk.code}</script>`
fs.removeSync(path.resolve(config.outDir, matchingChunk.fileName))
} else {
inlinedScript = `<script type="module" src="${siteData.base}${matchingChunk.fileName}"></script>`
}
}
}
const dir = pageData.frontmatter.dir || siteData.dir || 'ltr'
const html = `<!DOCTYPE html>
<html lang="${siteData.lang}" dir="${dir}">
<head>
<meta charset="utf-8">
${
isMetaViewportOverridden(head)
? ''
: '<meta name="viewport" content="width=device-width,initial-scale=1">'
}
<title>${title}</title>
${
isDescriptionOverridden(head)
? ''
: `<meta name="description" content="${description}">`
}
<meta name="generator" content="VitePress v${version}">
${stylesheetLink}
${metadataScript.inHead ? metadataScript.html : ''}
${
appChunk
? `<script type="module" src="${siteData.base}${appChunk.fileName}"></script>`
: ''
}
${await renderHead(head)}
</head>
<body>${teleports?.body || ''}
<div id="app">${page === '404.md' ? '' : content}</div>
${metadataScript.inHead ? '' : metadataScript.html}
${inlinedScript}
</body>
</html>`
const htmlFileName = path.join(config.outDir, page.replace(/\.md$/, '.html'))
await fs.ensureDir(path.dirname(htmlFileName))
const transformedHtml = await config.transformHtml?.(html, htmlFileName, {
page,
siteConfig: config,
siteData,
pageData,
title,
description,
head,
content,
assets
})
await fs.writeFile(htmlFileName, transformedHtml || html)
}
function resolvePageImports(
config: SiteConfig,
page: string,
result: Rollup.RollupOutput,
appChunk: Rollup.OutputChunk
) {
page = config.rewrites.inv[page] || page
// find the page's js chunk and inject script tags for its imports so that
// they start fetching as early as possible
let srcPath = path.resolve(config.srcDir, page)
try {
if (!config.vite?.resolve?.preserveSymlinks) {
srcPath = fs.realpathSync(srcPath)
}
} catch (e) {
// if the page is a virtual page generated by a dynamic route this would
// fail, which is expected
}
srcPath = normalizePath(srcPath)
const pageChunk = result.output.find(
(chunk) => chunk.type === 'chunk' && chunk.facadeModuleId === srcPath
) as Rollup.OutputChunk
return [
...appChunk.imports,
...appChunk.dynamicImports,
...pageChunk.imports,
...pageChunk.dynamicImports
]
}
async function renderHead(head: HeadConfig[]): Promise<string> {
const tags = await Promise.all(
head.map(async ([tag, attrs = {}, innerHTML = '']) => {
const openTag = `<${tag}${renderAttrs(attrs)}>`
if (tag !== 'link' && tag !== 'meta') {
if (
tag === 'script' &&
(attrs.type === undefined || attrs.type.includes('javascript'))
) {
innerHTML = (
await transformWithEsbuild(innerHTML, 'inline-script.js', {
minify: true
})
).code.trim()
}
return `${openTag}${innerHTML}</${tag}>`
} else {
return openTag
}
})
)
return tags.join('\n ')
}
function renderAttrs(attrs: Record<string, string>): string {
return Object.keys(attrs)
.map((key) => {
if (isBooleanAttr(key)) return ` ${key}`
return ` ${key}="${escape(attrs[key] as string)}"`
})
.join('')
}
function filterOutHeadDescription(head: HeadConfig[] = []) {
return head.filter(([type, attrs]) => {
return !(type === 'meta' && attrs?.name === 'description')
})
}
function isDescriptionOverridden(head: HeadConfig[] = []) {
return head.some(([type, attrs]) => {
return type === 'meta' && attrs?.name === 'description'
})
}
function isMetaViewportOverridden(head: HeadConfig[] = []) {
return head.some(([type, attrs]) => {
return type === 'meta' && attrs?.name === 'viewport'
})
}