feat: add standalone themed error pages

This commit is contained in:
2026-11-02 11:36:11 +08:00
parent bcc32d9626
commit 5291b2ab72
15 changed files with 348 additions and 13 deletions
+22
View File
@@ -0,0 +1,22 @@
import { createHash } from 'node:crypto'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { errorCodes, errorMessages, apiErrorCodes } from '../src/error-pages.ts'
import { initializeErrorPage } from '../src/error-page.js'
const escape = (value: string) => value.replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]!)
const runtime = `(${initializeErrorPage.toString()})(${JSON.stringify(errorMessages)});\n`
const script = `/assets/error-pages-${createHash('sha256').update(runtime).digest('hex').slice(0, 12)}.js`
const template = await readFile('error.html', 'utf8')
const messages = errorMessages['zh-CN']
const languages = Object.entries(errorMessages).map(([locale, value]) => `<option value="${locale}" lang="${locale}">${escape(value.common.languageName)}</option>`).join('')
const themes = Object.entries(messages.common.themes).map(([value, label]) => `<option value="${value}">${escape(label)}</option>`).join('')
await mkdir('dist/errors', { recursive: true })
await writeFile('dist' + script, runtime)
for (const status of errorCodes) {
const state = messages.errors.codes[status as keyof typeof messages.errors.codes]
const values: Record<string, string> = { status, script, title: state.title, description: state.description, pageTitle: `${status} · ${state.title} · ${messages.common.brand}`, siteName: messages.common.siteName, language: messages.common.language, theme: messages.common.theme, home: messages.errors.home, retry: messages.errors.retry }
const html = template.replace(/\{\{(\w+)\}\}/g, (_, key) => key === 'languages' ? languages : key === 'themes' ? themes : escape(values[key]!))
await writeFile(`dist/errors/${status}.html`, html)
await writeFile(`dist/errors/api-${status}.json`, JSON.stringify({ code: apiErrorCodes[status] }) + '\n')
}
console.log(`Built ${errorCodes.length} independent error pages and JSON gateway responses.`)
+19
View File
@@ -0,0 +1,19 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import { errorCodes, errorMessages, apiErrorCodes } from '../src/error-pages.ts'
assert.deepEqual(Object.keys(errorMessages['zh-CN'].errors.codes), Object.keys(errorMessages['en-US'].errors.codes))
for (const status of errorCodes) {
const html = await readFile(`dist/errors/${status}.html`, 'utf8')
assert.ok(html.includes(`data-error-status="${status}"`))
assert.ok(html.includes(errorMessages['zh-CN'].errors.codes[status as keyof typeof errorMessages['zh-CN']['errors']['codes']].title))
assert.ok(!html.includes('{{') && !html.includes('/src/'))
assert.ok(html.includes('href="/"') && html.includes('noindex, nofollow'))
for (const [, asset] of html.matchAll(/(?:src|href)="(\/assets\/[^"]+)"/g)) await readFile('dist' + asset)
const runtimePath = html.match(/defer src="([^"]+)"/)![1]!
const runtime = await readFile('dist' + runtimePath, 'utf8')
assert.ok(runtime.includes('mirrorouc.locale') && runtime.includes('mirrorouc.theme'))
assert.ok(!/fetch\(|XMLHttpRequest|\/api\//.test(runtime), 'Error page must work without the backend')
assert.deepEqual(JSON.parse(await readFile(`dist/errors/api-${status}.json`, 'utf8')), { code: apiErrorCodes[status] })
}
console.log(`Error pages passed: ${errorCodes.length} statuses, language parity, local assets and backend-independent rendering.`)
+4 -2
View File
@@ -12,6 +12,8 @@ import { createI18n } from 'vue-i18n'
import { adminZh, adminEn } from '../src/locales/admin-messages.ts'
import directoryZh from '../src/locales/zh-CN/directory.ts'
import directoryEn from '../src/locales/en-US/directory.ts'
import errorsZh from '../src/locales/zh-CN/errors.ts'
import errorsEn from '../src/locales/en-US/errors.ts'
function flatten(value: Record<string, unknown>, prefix = ''): Record<string, string> {
return Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => {
@@ -20,8 +22,8 @@ function flatten(value: Record<string, unknown>, prefix = ''): Record<string, st
}))
}
const zh = flatten({ common: commonZh, mirrors: mirrorsZh, announcements: announcementsZh, monitor: monitorZh, admin: adminZh, directory: directoryZh })
const en = flatten({ common: commonEn, mirrors: mirrorsEn, announcements: announcementsEn, monitor: monitorEn, admin: adminEn, directory: directoryEn })
const zh = flatten({ common: commonZh, mirrors: mirrorsZh, announcements: announcementsZh, monitor: monitorZh, admin: adminZh, directory: directoryZh, errors: errorsZh })
const en = flatten({ common: commonEn, mirrors: mirrorsEn, announcements: announcementsEn, monitor: monitorEn, admin: adminEn, directory: directoryEn, errors: errorsEn })
const errors: string[] = []
const formats = {
'zh-CN': { datetimeFormats: datetimeZh, numberFormats: numbersZh },