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
+2
View File
@@ -57,4 +57,6 @@ go -C backend build -o ../.local/mirrorouc .
镜像目录与下载由已有的 Web 服务器提供,路径为 `/mirrors/<源名>/`。自定义目录页的 Fancyindex 模板随前端构建生成在 `dist/fancy-index/` 中。 镜像目录与下载由已有的 Web 服务器提供,路径为 `/mirrors/<源名>/`。自定义目录页的 Fancyindex 模板随前端构建生成在 `dist/fancy-index/` 中。
构建还会生成 `dist/errors/` 下的独立错误页。后端自动使用这些页面;使用 Nginx 时,可将其错误页指向对应文件,并保留 API 错误的 JSON 响应。
需要本机监控采集或受限配置写入时,可按需对接 `backend/tools/` 中的工具。更多启动参数可通过 `./mirrorouc -help` 查看。 需要本机监控采集或受限配置写入时,可按需对接 `backend/tools/` 中的工具。更多启动参数可通过 `./mirrorouc -help` 查看。
+42
View File
@@ -0,0 +1,42 @@
package main
import (
"errors"
"net/http"
"os"
"path/filepath"
"strconv"
)
// The generated page needs no API calls and preserves the actual failure status.
func (a *App) errorPage(w http.ResponseWriter, r *http.Request, status int) {
raw, err := os.ReadFile(filepath.Join(a.cfg.Static, "errors", strconv.Itoa(status)+".html"))
if err != nil {
http.Error(w, http.StatusText(status), status)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
if r.Method != http.MethodHead {
w.Write(raw)
}
}
func (a *App) servePageFile(w http.ResponseWriter, r *http.Request, path string) {
info, err := os.Stat(path)
if errors.Is(err, os.ErrNotExist) {
a.errorPage(w, r, http.StatusNotFound)
return
}
if errors.Is(err, os.ErrPermission) || (err == nil && info.IsDir()) {
a.errorPage(w, r, http.StatusForbidden)
return
}
if err != nil {
a.logger.Printf("file unavailable: %v", err)
a.errorPage(w, r, http.StatusInternalServerError)
return
}
http.ServeFile(w, r, path)
}
+68
View File
@@ -0,0 +1,68 @@
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestStyledBrowserErrorsRetainStatusAndAPIJSON(t *testing.T) {
c := fixture(t)
dir := filepath.Join(c.app.cfg.Static, "errors")
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
for _, code := range []int{403, 404, 405, 500, 502, 503, 504} {
html := fmt.Sprintf("<!doctype html><title>MirrorITS %d</title><h1>%d</h1>", code, code)
if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("%d.html", code)), []byte(html), 0600); err != nil {
t.Fatal(err)
}
for _, method := range []string{"GET", "HEAD"} {
w := httptest.NewRecorder()
c.app.errorPage(w, httptest.NewRequest(method, "/missing?code=200", nil), code)
if w.Code != code || !strings.HasPrefix(w.Header().Get("Content-Type"), "text/html") || w.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("error response lost status or headers: %+v", w)
}
if method == "HEAD" && w.Body.Len() != 0 {
t.Fatal("HEAD error includes a body")
}
if method == "GET" && w.Body.String() != html {
t.Fatal("error response did not use the static page")
}
}
}
for _, path := range []string{"/missing-page", "/assets/missing.js", "/uploads/missing.png", "/uploads/mirrorouc.db"} {
w := c.call("GET", path, nil, false)
status(t, w, 404)
if !strings.Contains(w.Body.String(), "MirrorITS 404") {
t.Fatalf("default browser error remains at %s", path)
}
}
w := c.call("POST", "/missing-page", nil, false)
status(t, w, 405)
if w.Header().Get("Allow") != "GET, HEAD" {
t.Fatal("Allow header was lost")
}
for _, path := range []string{"/api/missing", "/api/v1/help/missing"} {
w = c.call("GET", path, nil, false)
status(t, w, 404)
if !strings.HasPrefix(w.Header().Get("Content-Type"), "application/json") || !strings.Contains(w.Body.String(), `"NOT_FOUND"`) {
t.Fatal("API error changed to an HTML page")
}
}
// Healthy assets still support byte ranges through the ordinary file server.
assets := filepath.Join(c.app.cfg.Static, "assets")
os.MkdirAll(assets, 0700)
os.WriteFile(filepath.Join(assets, "sample.txt"), []byte("0123456789"), 0600)
r := httptest.NewRequest("GET", "/assets/sample.txt", nil)
r.Header.Set("Range", "bytes=2-5")
response := httptest.NewRecorder()
c.app.handler().ServeHTTP(response, r)
if response.Code != http.StatusPartialContent || response.Body.String() != "2345" {
t.Fatal("error pages changed healthy file range handling")
}
}
+16 -7
View File
@@ -131,15 +131,15 @@ func (a *App) handler() http.Handler {
mux.HandleFunc("GET /uploads/{name}", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("GET /uploads/{name}", func(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name") name := r.PathValue("name")
if !validName(name) || (!strings.HasSuffix(name, ".png") && !strings.HasSuffix(name, ".jpg")) { if !validName(name) || (!strings.HasSuffix(name, ".png") && !strings.HasSuffix(name, ".jpg")) {
http.NotFound(w, r) a.errorPage(w, r, http.StatusNotFound)
return return
} }
http.ServeFile(w, r, filepath.Join(a.cfg.Data, "uploads", name)) a.servePageFile(w, r, filepath.Join(a.cfg.Data, "uploads", name))
}) })
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "HEAD" { if r.Method != "GET" && r.Method != "HEAD" {
w.Header().Set("Allow", "GET, HEAD") w.Header().Set("Allow", "GET, HEAD")
fail(w, 405, "METHOD_NOT_ALLOWED") a.errorPage(w, r, http.StatusMethodNotAllowed)
return return
} }
path := r.URL.Path path := r.URL.Path
@@ -148,20 +148,29 @@ func (a *App) handler() http.Handler {
return return
} }
if path == "/" || path == "/status" || path == "/status/" || path == "/announcements" || path == "/announcements/" || path == "/admin" || strings.HasPrefix(path, "/admin/") { if path == "/" || path == "/status" || path == "/status/" || path == "/announcements" || path == "/announcements/" || path == "/admin" || strings.HasPrefix(path, "/admin/") {
http.ServeFile(w, r, filepath.Join(a.cfg.Static, "index.html")) a.servePageFile(w, r, filepath.Join(a.cfg.Static, "index.html"))
return return
} }
if strings.HasPrefix(path, "/assets/") { if strings.HasPrefix(path, "/assets/") {
http.FileServer(http.Dir(a.cfg.Static)).ServeHTTP(w, r) local := strings.TrimPrefix(path, "/")
if !filepath.IsLocal(local) || strings.ContainsAny(local, "\\\x00") {
a.errorPage(w, r, http.StatusNotFound)
return
}
a.servePageFile(w, r, filepath.Join(a.cfg.Static, local))
return return
} }
http.NotFound(w, r) a.errorPage(w, r, http.StatusNotFound)
}) })
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() { defer func() {
if v := recover(); v != nil { if v := recover(); v != nil {
a.logger.Printf("panic: %v", v) a.logger.Printf("panic: %v", v)
fail(w, 500, "INTERNAL_ERROR") if strings.HasPrefix(r.URL.Path, "/api/") || r.URL.Path == "/healthz" {
fail(w, 500, "INTERNAL_ERROR")
} else {
a.errorPage(w, r, http.StatusInternalServerError)
}
} }
}() }()
w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Content-Type-Options", "nosniff")
+63
View File
@@ -0,0 +1,63 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#ffffff" />
<meta name="robots" content="noindex, nofollow" />
<link rel="icon" type="image/png" href="/assets/ouc-seal.png" />
<title>{{pageTitle}}</title>
<script src="/assets/directory-theme.js"></script>
<script defer src="{{script}}"></script>
<style>
:root { color-scheme: light; --paper: #fff; --ink: #24292f; --muted: #343a40; --blue: #0969da; --line: #d0d7de; --accent-ink: #fff; }
:root[data-theme='dark'] { color-scheme: dark; --paper: #0d1117; --ink: #c9d1d9; --muted: #8b949e; --blue: #58a6ff; --line: #30363d; --accent-ink: #0d1117; }
@media (prefers-color-scheme: dark) { :root:not([data-theme]) { color-scheme: dark; --paper: #0d1117; --ink: #c9d1d9; --muted: #8b949e; --blue: #58a6ff; --line: #30363d; --accent-ink: #0d1117; } }
* { box-sizing: border-box; scrollbar-width: thin; scrollbar-color: var(--blue) transparent; }
@supports selector(::-webkit-scrollbar) { * { scrollbar-width: auto; scrollbar-color: auto; } ::-webkit-scrollbar { width: 6px; height: 6px; } ::-webkit-scrollbar-track, ::-webkit-scrollbar-corner { background: transparent; } ::-webkit-scrollbar-thumb { border-radius: 0; background: var(--blue); } ::-webkit-scrollbar-button { display: none; } }
[hidden] { display: none !important; }
body { display: flex; flex-direction: column; min-height: 100svh; margin: 0; background: var(--paper); color: var(--ink); font-family: system-ui, -apple-system, 'Segoe UI', 'Microsoft YaHei', sans-serif; line-height: 1.7; }
a { color: inherit; text-decoration: none; }
button, select { font: inherit; color: inherit; }
:focus-visible { outline: 2px solid var(--blue); outline-offset: 4px; }
.error-header { display: flex; align-items: center; justify-content: space-between; gap: 20px; min-height: 112px; padding: 24px clamp(24px, 5vw, 120px); }
.error-brand { display: block; min-width: 0; width: 260px; }
.error-brand img { display: block; width: 100%; height: auto; }
.error-logo-dark { display: none !important; }
:root[data-theme='dark'] .error-logo-light { display: none; }
:root[data-theme='dark'] .error-logo-dark { display: block !important; }
@media (prefers-color-scheme: dark) { :root:not([data-theme]) .error-logo-light { display: none; } :root:not([data-theme]) .error-logo-dark { display: block !important; } }
.error-tools { display: flex; gap: 14px; flex-shrink: 0; }
.error-tools select { max-width: 120px; min-height: 44px; padding: 6px 4px; border: 0; border-radius: 0; background: var(--paper); font-size: 13px; cursor: pointer; }
.error-main { display: grid; flex: 1; grid-template-columns: auto minmax(0, 1fr); align-content: center; align-items: center; gap: 64px; width: min(940px, calc(100% - 64px)); margin: 0 auto; padding: 48px 0 120px; }
.error-status { margin: 0; color: var(--blue); font: 500 clamp(104px, 16vw, 176px)/1 ui-monospace, Consolas, monospace; letter-spacing: -.075em; }
.error-copy { min-width: 0; }
h1 { margin: 0 0 16px; font-size: 32px; font-weight: 600; line-height: 1.35; overflow-wrap: anywhere; }
.error-description { max-width: 470px; margin: 0; color: var(--muted); font-size: 16px; overflow-wrap: anywhere; }
.error-actions { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 30px; }
.error-actions a, .error-actions button { display: inline-flex; align-items: center; justify-content: center; min-height: 44px; padding: 9px 18px; border: 1px solid var(--line); border-radius: 3px; background: transparent; font-size: 14px; cursor: pointer; }
.error-actions a { border-color: var(--blue); background: var(--blue); color: var(--accent-ink); }
.error-actions :hover { filter: brightness(.9); }
@media (max-width: 640px) {
.error-header { min-height: 88px; gap: 12px; padding: 18px 16px; }
.error-brand { width: 180px; }
.error-tools { gap: 4px; }
.error-tools select { max-width: 96px; font-size: 12px; }
.error-main { grid-template-columns: minmax(0, 1fr); gap: 24px; width: calc(100% - 40px); padding: 36px 0 88px; }
.error-status { font-size: 112px; }
h1 { font-size: 28px; }
}
@media (max-width: 360px) { .error-header { padding-inline: 12px; } .error-brand { width: 148px; } .error-tools select { max-width: 82px; } }
</style>
</head>
<body data-error-status="{{status}}">
<header class="error-header">
<a class="error-brand" href="/" aria-label="{{siteName}}"><img class="error-logo-light" src="/assets/mirrorOUC_dark.png" alt="" width="2000" height="433" /><img class="error-logo-dark" src="/assets/mirrorOUC.png" alt="" width="2000" height="433" /></a>
<div id="error-tools" class="error-tools" hidden><select id="error-language" aria-label="{{language}}">{{languages}}</select><select id="error-theme" aria-label="{{theme}}">{{themes}}</select></div>
</header>
<main class="error-main">
<p class="error-status">{{status}}</p>
<div class="error-copy"><h1 id="error-title">{{title}}</h1><p id="error-description" class="error-description">{{description}}</p><div class="error-actions"><a id="error-home" href="/">{{home}}</a><button id="error-retry" type="button" hidden>{{retry}}</button></div></div>
</main>
</body>
</html>
+3 -2
View File
@@ -8,13 +8,14 @@
}, },
"scripts": { "scripts": {
"dev": "vite --host 127.0.0.1", "dev": "vite --host 127.0.0.1",
"build": "vue-tsc -b && vite build && node scripts/build-directory.ts", "build": "vue-tsc -b && vite build && node scripts/build-directory.ts && node scripts/build-errors.ts",
"preview": "vite preview --host 127.0.0.1", "preview": "vite preview --host 127.0.0.1",
"check:i18n": "node scripts/check-locales.ts", "check:i18n": "node scripts/check-locales.ts",
"check:monitoring": "node scripts/check-monitoring.ts", "check:monitoring": "node scripts/check-monitoring.ts",
"check:help": "node scripts/check-help.ts", "check:help": "node scripts/check-help.ts",
"check:debian": "node scripts/check-debian-sources.ts", "check:debian": "node scripts/check-debian-sources.ts",
"check:directory": "node scripts/check-directory.ts" "check:directory": "node scripts/check-directory.ts",
"check:errors": "node scripts/check-errors.ts"
}, },
"dependencies": { "dependencies": {
"dompurify": "^3.4.17", "dompurify": "^3.4.17",
+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 { adminZh, adminEn } from '../src/locales/admin-messages.ts'
import directoryZh from '../src/locales/zh-CN/directory.ts' import directoryZh from '../src/locales/zh-CN/directory.ts'
import directoryEn from '../src/locales/en-US/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> { function flatten(value: Record<string, unknown>, prefix = ''): Record<string, string> {
return Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => { 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 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 }) const en = flatten({ common: commonEn, mirrors: mirrorsEn, announcements: announcementsEn, monitor: monitorEn, admin: adminEn, directory: directoryEn, errors: errorsEn })
const errors: string[] = [] const errors: string[] = []
const formats = { const formats = {
'zh-CN': { datetimeFormats: datetimeZh, numberFormats: numbersZh }, 'zh-CN': { datetimeFormats: datetimeZh, numberFormats: numbersZh },
+48
View File
@@ -0,0 +1,48 @@
// Bundled as a small independent script: an unavailable API must not break its error page.
export function initializeErrorPage(messages) {
const read = key => { try { return localStorage.getItem(key) } catch { return null } }
const save = (key, value) => { try { localStorage.setItem(key, value) } catch { /* Optional preference. */ } }
const locales = Object.keys(messages)
const savedLocale = read('mirrorouc.locale')
const preferred = navigator.languages.map(value => locales.find(locale => locale.toLowerCase() === value.toLowerCase()) || locales.find(locale => locale.split('-')[0] === value.split('-')[0])).find(Boolean)
let locale = locales.includes(savedLocale) ? savedLocale : preferred || 'zh-CN'
const storedTheme = read('mirrorouc.theme')
let theme = ['light', 'dark'].includes(storedTheme) ? storedTheme : 'system'
const system = matchMedia('(prefers-color-scheme: dark)')
const language = document.getElementById('error-language')
const themes = document.getElementById('error-theme')
const code = document.body.dataset.errorStatus
function applyTheme() {
const dark = theme === 'dark' || (theme === 'system' && system.matches)
document.documentElement.dataset.theme = dark ? 'dark' : 'light'
document.querySelector('meta[name="theme-color"]').content = dark ? '#0d1117' : '#ffffff'
themes.value = theme
}
function applyLocale() {
const value = messages[locale]
const state = value.errors.codes[code]
document.documentElement.lang = locale
document.title = `${code} · ${state.title} · ${value.common.brand}`
document.getElementById('error-title').textContent = state.title
document.getElementById('error-description').textContent = state.description
document.getElementById('error-home').textContent = value.errors.home
document.getElementById('error-retry').textContent = value.errors.retry
document.querySelector('.error-brand').setAttribute('aria-label', value.common.siteName)
language.setAttribute('aria-label', value.common.language)
themes.setAttribute('aria-label', value.common.theme)
for (const option of themes.options) option.textContent = value.common.themes[option.value]
language.value = locale
}
language.addEventListener('change', () => {
if (!locales.includes(language.value)) return
locale = language.value; save('mirrorouc.locale', locale); applyLocale()
})
themes.addEventListener('change', () => {
theme = themes.value; save('mirrorouc.theme', theme); applyTheme()
})
system.addEventListener('change', applyTheme)
document.getElementById('error-retry').addEventListener('click', () => location.reload())
applyTheme(); applyLocale()
document.getElementById('error-tools').hidden = false
document.getElementById('error-retry').hidden = false
}
+16
View File
@@ -0,0 +1,16 @@
import commonZh from './locales/zh-CN/common.ts'
import commonEn from './locales/en-US/common.ts'
import errorsZh from './locales/zh-CN/errors.ts'
import errorsEn from './locales/en-US/errors.ts'
export const errorMessages = {
'zh-CN': { common: commonZh, errors: errorsZh },
'en-US': { common: commonEn, errors: errorsEn },
}
export const errorCodes = Object.keys(errorsZh.codes)
export const apiErrorCodes: Record<string, string> = {
'400': 'INVALID_INPUT', '401': 'UNAUTHORIZED', '403': 'FORBIDDEN', '404': 'NOT_FOUND',
'405': 'METHOD_NOT_ALLOWED', '408': 'REQUEST_TIMEOUT', '410': 'NOT_FOUND',
'413': 'PAYLOAD_TOO_LARGE', '414': 'INVALID_INPUT', '429': 'RATE_LIMITED',
'500': 'INTERNAL_ERROR', '502': 'UPSTREAM_UNAVAILABLE', '503': 'UPSTREAM_UNAVAILABLE', '504': 'UPSTREAM_UNAVAILABLE',
}
+1
View File
@@ -24,6 +24,7 @@ const pairs = {
target: ['对象', 'Target'], action: ['动作', 'Action'], result: ['结果', 'Result'], time: ['时间', 'Time'], actor: ['操作人', 'User'], notice: ['提示', 'Notice'], conflictHint: ['数据已被其他操作修改,请重新加载后再编辑。', 'Another operation changed this data. Reload before editing.'], target: ['对象', 'Target'], action: ['动作', 'Action'], result: ['结果', 'Result'], time: ['时间', 'Time'], actor: ['操作人', 'User'], notice: ['提示', 'Notice'], conflictHint: ['数据已被其他操作修改,请重新加载后再编辑。', 'Another operation changed this data. Reload before editing.'],
} as const } as const
const errors = { const errors = {
UPSTREAM_UNAVAILABLE: ['站点服务暂不可用,请稍后重试。', 'The site service is unavailable. Try again shortly.'], REQUEST_TIMEOUT: ['请求超时,请稍后重试。', 'The request timed out. Try again shortly.'], PAYLOAD_TOO_LARGE: ['提交内容过大,请缩小后重试。', 'The submitted content is too large. Reduce its size and try again.'],
NETWORK_ERROR: ['网络连接失败。', 'Network connection failed.'], INVALID_RESPONSE: ['服务器响应无效。', 'Invalid server response.'], INTERNAL_ERROR: ['服务器处理失败,请稍后重试。', 'Server error. Try again shortly.'], INVALID_INPUT: ['请检查填写的内容和数值范围。', 'Check the form values and allowed ranges.'], UNAUTHORIZED: ['请重新登录。', 'Please sign in again.'], FORBIDDEN: ['没有执行此操作的权限。', 'You do not have permission for this action.'], CSRF_INVALID: ['登录状态已变化,请重新登录。', 'Your session has changed. Sign in again.'], INVALID_CREDENTIALS: ['用户名或密码不正确。', 'Incorrect username or password.'], RATE_LIMITED: ['登录尝试过于频繁,请稍后重试。', 'Too many sign-in attempts. Try again shortly.'], CONFLICT: ['内容已发生变化,请刷新后重新编辑。', 'The content has changed. Reload and edit again.'], NOT_FOUND: ['未找到对应记录。', 'The entry was not found.'], CONFIG_UNAVAILABLE: ['无法读取 Worker 配置。', 'Worker configuration is unavailable.'], NO_CHANGES: ['配置没有变化。', 'There are no configuration changes.'], CONFIG_APPLY_FAILED: ['配置应用失败,已尝试恢复原文件。请检查 Worker 状态。', 'Configuration failed. Original files were restored where possible. Check the worker status.'], CONFIG_ROLLBACK_FAILED: ['配置恢复未完成,需要检查服务器配置与 Worker 状态。', 'Configuration restore did not complete. Check the server files and worker.'], CONFIG_STATE_UNCERTAIN: ['文件可能已生效,但版本记录未完成,请检查配置。', 'Files may have been applied, but the version record failed. Check the configuration.'], COMMAND_UNCERTAIN: ['命令结果未确认,请检查节点状态后再操作。', 'Command delivery is unconfirmed. Check the worker before retrying.'], MANAGER_UNAVAILABLE: ['同步管理器暂时不可用。', 'The sync manager is unavailable.'], LOGS_UNAVAILABLE: ['日志暂时不可用。', 'Logs are unavailable.'], UPLOAD_INVALID: ['请选择不超过 4 MB 的 PNG 或 JPEG 图片。', 'Choose a PNG or JPEG image of at most 4 MB.'], INVALID_PASSWORD: ['密码需要 12 至 256 个字符。', 'The password must contain 12 to 256 characters.'], TUNASYNC_UNAVAILABLE: ['同步节点暂时不可用。', 'The sync worker is unavailable.'], LOG_UNAVAILABLE: ['日志暂时不可用。', 'Logs are unavailable.'], INVALID_IMAGE: ['图片无效,请使用不超过 4 MB 的 PNG 或 JPEG。', 'Use a valid PNG or JPEG image of at most 4 MB.'], PASSWORD_TOO_SHORT: ['密码至少需要 12 个字符。', 'Use at least 12 characters for the password.'], NETWORK_ERROR: ['网络连接失败。', 'Network connection failed.'], INVALID_RESPONSE: ['服务器响应无效。', 'Invalid server response.'], INTERNAL_ERROR: ['服务器处理失败,请稍后重试。', 'Server error. Try again shortly.'], INVALID_INPUT: ['请检查填写的内容和数值范围。', 'Check the form values and allowed ranges.'], UNAUTHORIZED: ['请重新登录。', 'Please sign in again.'], FORBIDDEN: ['没有执行此操作的权限。', 'You do not have permission for this action.'], CSRF_INVALID: ['登录状态已变化,请重新登录。', 'Your session has changed. Sign in again.'], INVALID_CREDENTIALS: ['用户名或密码不正确。', 'Incorrect username or password.'], RATE_LIMITED: ['登录尝试过于频繁,请稍后重试。', 'Too many sign-in attempts. Try again shortly.'], CONFLICT: ['内容已发生变化,请刷新后重新编辑。', 'The content has changed. Reload and edit again.'], NOT_FOUND: ['未找到对应记录。', 'The entry was not found.'], CONFIG_UNAVAILABLE: ['无法读取 Worker 配置。', 'Worker configuration is unavailable.'], NO_CHANGES: ['配置没有变化。', 'There are no configuration changes.'], CONFIG_APPLY_FAILED: ['配置应用失败,已尝试恢复原文件。请检查 Worker 状态。', 'Configuration failed. Original files were restored where possible. Check the worker status.'], CONFIG_ROLLBACK_FAILED: ['配置恢复未完成,需要检查服务器配置与 Worker 状态。', 'Configuration restore did not complete. Check the server files and worker.'], CONFIG_STATE_UNCERTAIN: ['文件可能已生效,但版本记录未完成,请检查配置。', 'Files may have been applied, but the version record failed. Check the configuration.'], COMMAND_UNCERTAIN: ['命令结果未确认,请检查节点状态后再操作。', 'Command delivery is unconfirmed. Check the worker before retrying.'], MANAGER_UNAVAILABLE: ['同步管理器暂时不可用。', 'The sync manager is unavailable.'], LOGS_UNAVAILABLE: ['日志暂时不可用。', 'Logs are unavailable.'], UPLOAD_INVALID: ['请选择不超过 4 MB 的 PNG 或 JPEG 图片。', 'Choose a PNG or JPEG image of at most 4 MB.'], INVALID_PASSWORD: ['密码需要 12 至 256 个字符。', 'The password must contain 12 to 256 characters.'], TUNASYNC_UNAVAILABLE: ['同步节点暂时不可用。', 'The sync worker is unavailable.'], LOG_UNAVAILABLE: ['日志暂时不可用。', 'Logs are unavailable.'], INVALID_IMAGE: ['图片无效,请使用不超过 4 MB 的 PNG 或 JPEG。', 'Use a valid PNG or JPEG image of at most 4 MB.'], PASSWORD_TOO_SHORT: ['密码至少需要 12 个字符。', 'Use at least 12 characters for the password.'],
} as const } as const
const events = { const events = {
+20
View File
@@ -0,0 +1,20 @@
export default {
home: 'Back to mirrors',
retry: 'Reload',
codes: {
'400': { title: 'Bad request', description: 'The server could not understand this request. Check the address and try again.' },
'401': { title: 'Sign-in required', description: 'Please sign in to access this page.' },
'403': { title: 'Access denied', description: 'Access to this page or file is not allowed.' },
'404': { title: 'Page not found', description: 'This page or file does not exist. Check the address or return to the mirror list.' },
'405': { title: 'Method not allowed', description: 'This address does not support the request method used.' },
'408': { title: 'Request timed out', description: 'The request did not finish in time. Please try again shortly.' },
'410': { title: 'Content removed', description: 'This page or file is no longer available.' },
'413': { title: 'Request too large', description: 'The submitted content exceeds the server limit. Reduce its size and try again.' },
'414': { title: 'Address too long', description: 'The request address exceeds the server limit. Check it and try again.' },
'429': { title: 'Too many requests', description: 'Please wait a moment before trying again.' },
'500': { title: 'Server error', description: 'The server could not complete this request. Please try again shortly.' },
'502': { title: 'Gateway connection failed', description: 'The site service could not be reached. Please try again shortly.' },
'503': { title: 'Service unavailable', description: 'The site is under maintenance or temporarily busy. Please try again shortly.' },
'504': { title: 'Service timed out', description: 'The site service did not respond in time. Please try again shortly.' },
},
}
+4 -2
View File
@@ -10,12 +10,14 @@ import monitorEn from './en-US/monitor'
import { adminZh, adminEn } from './admin-messages' import { adminZh, adminEn } from './admin-messages'
import directoryZh from './zh-CN/directory' import directoryZh from './zh-CN/directory'
import directoryEn from './en-US/directory' import directoryEn from './en-US/directory'
import errorsZh from './zh-CN/errors'
import errorsEn from './en-US/errors'
import { datetimeFormats as datetimeZh, numberFormats as numbersZh } from './zh-CN/formats' import { datetimeFormats as datetimeZh, numberFormats as numbersZh } from './zh-CN/formats'
import { datetimeFormats as datetimeEn, numberFormats as numbersEn } from './en-US/formats' import { datetimeFormats as datetimeEn, numberFormats as numbersEn } from './en-US/formats'
export const messages = { export const messages = {
'zh-CN': { common: commonZh, mirrors: mirrorsZh, announcements: announcementsZh, monitor: monitorZh, admin: adminZh, directory: directoryZh }, 'zh-CN': { common: commonZh, mirrors: mirrorsZh, announcements: announcementsZh, monitor: monitorZh, admin: adminZh, directory: directoryZh, errors: errorsZh },
'en-US': { common: commonEn, mirrors: mirrorsEn, announcements: announcementsEn, monitor: monitorEn, admin: adminEn, directory: directoryEn }, 'en-US': { common: commonEn, mirrors: mirrorsEn, announcements: announcementsEn, monitor: monitorEn, admin: adminEn, directory: directoryEn, errors: errorsEn },
} }
export type Locale = keyof typeof messages export type Locale = keyof typeof messages
export const supportedLocales = Object.keys(messages) as Locale[] export const supportedLocales = Object.keys(messages) as Locale[]
+20
View File
@@ -0,0 +1,20 @@
export default {
home: '返回镜像列表',
retry: '重新加载',
codes: {
'400': { title: '请求无效', description: '服务器无法识别这个请求,请检查地址后重试。' },
'401': { title: '需要登录', description: '访问这个页面需要先登录。' },
'403': { title: '无法访问', description: '当前页面或文件不允许访问。' },
'404': { title: '页面未找到', description: '请求的页面或文件不存在,请检查地址,或返回镜像列表。' },
'405': { title: '请求方式不支持', description: '这个地址不支持当前的请求方式。' },
'408': { title: '请求超时', description: '请求未能及时完成,请稍后重试。' },
'410': { title: '内容已移除', description: '这个页面或文件已不再提供。' },
'413': { title: '请求内容过大', description: '提交的内容超过服务器允许的大小,请缩小后重试。' },
'414': { title: '请求地址过长', description: '请求地址超过服务器允许的长度,请检查后重试。' },
'429': { title: '请求过于频繁', description: '请稍等片刻后再试。' },
'500': { title: '服务发生错误', description: '服务器暂时无法完成这个请求,请稍后重试。' },
'502': { title: '网关连接失败', description: '暂时无法连接到站点服务,请稍后重试。' },
'503': { title: '服务暂不可用', description: '站点正在维护或暂时繁忙,请稍后重试。' },
'504': { title: '服务响应超时', description: '站点服务未能及时响应,请稍后重试。' },
},
}