Repository navigation
Expand file tree
/
Copy pathprerender.js
More file actions
205 lines (184 loc) · 8.04 KB
/
Copy pathprerender.js
File metadata and controls
205 lines (184 loc) · 8.04 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
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
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import { localePath } from './src/utils/localePath.js'
import { aiAuthorshipLabel, usesAiWriting } from './src/utils/aiAuthorship.js'
import { buildDailyAiContext } from './scripts/build-daily-ai-context.js'
import { buildLegacySite } from './scripts/build-legacy.js'
import { buildLlms } from './scripts/build-llms.js'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const enMeta = JSON.parse(fs.readFileSync(path.join(__dirname, 'src/locales/en/meta.json'), 'utf8'))
const zhMeta = JSON.parse(fs.readFileSync(path.join(__dirname, 'src/locales/zh-CN/meta.json'), 'utf8'))
const staticRoutes = [
{ path: '/', key: 'home' },
{ path: '/about', key: 'about' },
{ path: '/projects', key: 'projects' },
{ path: '/gallery', key: 'gallery' },
{ path: '/api-docs', key: 'api-docs' },
{ path: '/now', key: 'now' },
{ path: '/space', key: 'space' },
{ path: '/shelf', key: 'shelf' },
{ path: '/stats', key: 'stats' },
{ path: '/spotting', key: 'spotting' },
{ path: '/changelog', key: 'changelog' },
{ path: '/homelab', key: 'homelab' },
{ path: '/tokens', key: 'tokens' },
{ path: '/ip', key: 'ip' },
{ path: '/time', key: 'time' },
{ path: '/terminal', key: 'terminal' },
{ path: '/stack', key: 'stack' },
{ path: '/feed', key: 'feed' },
{ path: '/blog', key: 'blog' },
{ path: '/contact', key: 'contact' },
{ path: '/pgp', key: 'pgp' },
{ path: '/privacy', key: 'privacy' },
{ path: '/ai', key: 'ai' },
{ path: '/daily', key: 'daily' },
{ path: '/interests', key: 'interests' },
]
function escapeXml(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
}
function escapeAttribute(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<')
}
function withMeta(html, { path: routePath, title, description, locale }) {
const fullTitle = title ? `${title} | leodeng.dev` : 'leodeng.dev'
const safeTitle = escapeAttribute(fullTitle)
const safeDescription = escapeAttribute(description)
const basePath = locale === 'zh' ? routePath.replace(/^\/zh(?=\/|$)/, '') || '/' : routePath
const enUrl = `https://leodeng.dev${localePath(basePath, 'en')}`
const zhUrl = `https://leodeng.dev${localePath(basePath, 'zh')}`
const currentUrl = locale === 'zh' ? zhUrl : enUrl
let out = html.replace(/<html lang="[^"]*"/, `<html lang="${locale === 'zh' ? 'zh-CN' : 'en'}"`)
out = out.replace(/<title>.*?<\/title>/, `<title>${safeTitle}</title>`)
out = out.replace(/(<meta name="description" content=").*?(")/, `$1${safeDescription}$2`)
out = out.replace(/(<meta property="og:title"\s+content=").*?(")/, `$1${safeTitle}$2`)
out = out.replace(/(<meta property="og:description" content=").*?(")/, `$1${safeDescription}$2`)
out = out.replace(/(<meta property="og:url"\s+content=").*?(")/, `$1${currentUrl}$2`)
out = out.replace(/(<meta property="og:locale"\s+content=").*?(")/, `$1${locale === 'zh' ? 'zh_CN' : 'en_US'}$2`)
out = out.replace(/(<meta name="twitter:title"\s+content=").*?(")/, `$1${safeTitle}$2`)
out = out.replace(/(<meta name="twitter:description" content=").*?(")/, `$1${safeDescription}$2`)
out = out.replace(/(<link rel="canonical" href=").*?(")/, `$1${currentUrl}$2`)
out = out.replace(/(<link rel="alternate" hreflang="en" href=").*?(")/, `$1${enUrl}$2`)
out = out.replace(/(<link rel="alternate" hreflang="zh-CN" href=").*?(")/, `$1${zhUrl}$2`)
out = out.replace(/(<link rel="alternate" hreflang="x-default" href=").*?(")/, `$1${enUrl}$2`)
return out
}
function localizeRoute(route, locale) {
const meta = locale === 'zh' ? zhMeta : enMeta
const entry = route.key ? meta[route.key] : null
return {
...route,
locale,
path: localePath(route.path, locale),
title: entry?.title ?? route.title ?? null,
description: entry?.description ?? route.description ?? meta.defaultDescription,
}
}
async function prerender() {
const { render, getAllPosts, getPost, getPostMarkdown, collections } = await import('./dist-ssr/entry-server.js')
const templatePath = path.join(__dirname, 'dist/index.html')
const template = fs.readFileSync(templatePath, 'utf-8')
const postRoutes = getAllPosts().map(p => ({
path: `/blog/${p.slug}`,
title: p.title,
description: p.description,
}))
const collectionRoutes = collections.map(c => ({
path: `/gallery/${c.slug}`,
title: c.title,
description: c.description,
}))
const baseRoutes = [...staticRoutes, ...postRoutes, ...collectionRoutes]
const routes = baseRoutes.flatMap((route) => [
localizeRoute(route, 'en'),
localizeRoute(route, 'zh'),
])
for (const route of routes) {
const appHtml = await render(route.path)
const page = withMeta(
template.replace('<div id="app"></div>', `<div id="app">${appHtml}</div>`),
route
)
const outPath = route.path === '/'
? templatePath
: path.join(__dirname, 'dist', `${route.path.slice(1)}.html`)
fs.mkdirSync(path.dirname(outPath), { recursive: true })
fs.writeFileSync(outPath, page)
console.log(`✓ Pre-rendered ${route.path}`)
}
const sitemapRoutes = baseRoutes.map((route) => ({
en: `https://leodeng.dev${localePath(route.path, 'en')}`,
zh: `https://leodeng.dev${localePath(route.path, 'zh')}`,
}))
const sitemap = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">',
...sitemapRoutes.flatMap(({ en, zh }) => [en, zh].map((url) => [
' <url>',
` <loc>${url}</loc>`,
` <xhtml:link rel="alternate" hreflang="en" href="${en}" />`,
` <xhtml:link rel="alternate" hreflang="zh-CN" href="${zh}" />`,
` <xhtml:link rel="alternate" hreflang="x-default" href="${en}" />`,
' </url>',
].join('\n'))),
'</urlset>',
'',
].join('\n')
fs.writeFileSync(path.join(__dirname, 'dist/sitemap.xml'), sitemap)
console.log('✓ Generated sitemap.xml')
const rssItems = postRoutes.map(r => {
const post = getPost(r.path.replace('/blog/', ''))
const link = `https://leodeng.dev${r.path}`
const label = aiAuthorshipLabel(post.aiAuthorship)
const note = post.aiAuthorship === 'human'
? 'No AI was involved, including grammar checks.'
: usesAiWriting(post.aiAuthorship) ? post.aiReason?.trim() : ''
const disclosure = label
? `<aside><p><a href="https://leodeng.dev/ai">${label}</a></p>${note ? `<p>${escapeXml(note)}</p>` : ''}</aside>`
: ''
return [
' <item>',
` <title>${escapeXml(r.title)}</title>`,
` <link>${link}</link>`,
` <guid>${link}</guid>`,
` <pubDate>${new Date(post.date).toUTCString()}</pubDate>`,
r.description ? ` <description>${escapeXml(r.description)}</description>` : '',
` <content:encoded><![CDATA[${disclosure}${post.html}]]></content:encoded>`,
' </item>',
].filter(Boolean).join('\n')
})
const rss = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">',
' <channel>',
' <title>leodeng.dev</title>',
' <link>https://leodeng.dev/blog</link>',
' <description>Leo Deng\'s blog: self-hosting, IoT, and building things.</description>',
' <language>en</language>',
...rssItems,
' </channel>',
'</rss>',
'',
].join('\n')
fs.writeFileSync(path.join(__dirname, 'dist/rss.xml'), rss)
console.log('✓ Generated rss.xml')
await buildLlms(__dirname, {
pages: staticRoutes.map(route => ({
path: route.path,
title: enMeta[route.key]?.title || (route.path === '/' ? 'Home' : route.key),
description: enMeta[route.key]?.description,
})),
posts: getAllPosts(),
collections,
getPostMarkdown,
})
fs.writeFileSync(path.join(__dirname, 'dist/_site-routes.json'), JSON.stringify(routes))
await buildDailyAiContext(__dirname, getAllPosts(), getPost)
await buildLegacySite({ routes, collections })
}
prerender().catch(err => {
console.error('Pre-render failed:', err)
process.exit(1)
})