feat: add navbar caching, live GitHub releases edge API, and 1:1 Reims-Go desktop UI with mobile fidelity

This commit is contained in:
Dnyo666 committed 2026-12-03 20:13:22 +08:00
1 parent 84e0fed5b4
commit 4b1f8d76b5
35 files changed
+9253 -1409

No files matched your search

+1 -4
View File
@@ -9,10 +9,7 @@ export default defineConfig({
site: SITE_URL, site: SITE_URL,
output: 'static', output: 'static',
trailingSlash: 'ignore', trailingSlash: 'ignore',
prefetch: { prefetch: false,
prefetchAll: true,
defaultStrategy: 'hover',
},
integrations: [ integrations: [
react(), react(),
mdx(), mdx(),
+2 -1
View File
@@ -10,7 +10,8 @@
"build": "astro check && astro build && pagefind --site dist", "build": "astro check && astro build && pagefind --site dist",
"build:fast": "astro build && pagefind --site dist", "build:fast": "astro build && pagefind --site dist",
"preview": "astro preview", "preview": "astro preview",
"check": "astro check" "check": "astro check",
"test": "node --test tests/*.test.mjs"
}, },
"dependencies": { "dependencies": {
"@astrojs/check": "^0.9.4", "@astrojs/check": "^0.9.4",
+52
View File
@@ -2,6 +2,58 @@
X-Content-Type-Options: nosniff X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN X-Frame-Options: SAMEORIGIN
Referrer-Policy: strict-origin-when-cross-origin Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
/
Cache-Control: public, max-age=60, stale-while-revalidate=600
/en
Cache-Control: public, max-age=60, stale-while-revalidate=600
/en/
Cache-Control: public, max-age=60, stale-while-revalidate=600
/docs/*
Cache-Control: public, max-age=60, stale-while-revalidate=600
/en/docs/*
Cache-Control: public, max-age=60, stale-while-revalidate=600
/plugins
Cache-Control: public, max-age=60, stale-while-revalidate=600
/plugins/
Cache-Control: public, max-age=60, stale-while-revalidate=600
/en/plugins
Cache-Control: public, max-age=60, stale-while-revalidate=600
/en/plugins/
Cache-Control: public, max-age=60, stale-while-revalidate=600
/compatibility
Cache-Control: public, max-age=60, stale-while-revalidate=600
/compatibility/
Cache-Control: public, max-age=60, stale-while-revalidate=600
/en/compatibility
Cache-Control: public, max-age=60, stale-while-revalidate=600
/en/compatibility/
Cache-Control: public, max-age=60, stale-while-revalidate=600
/changelog
Cache-Control: public, max-age=60, stale-while-revalidate=600
/changelog/
Cache-Control: public, max-age=60, stale-while-revalidate=600
/en/changelog
Cache-Control: public, max-age=60, stale-while-revalidate=600
/en/changelog/
Cache-Control: public, max-age=60, stale-while-revalidate=600
/_astro/* /_astro/*
Cache-Control: public, max-age=31536000, immutable Cache-Control: public, max-age=31536000, immutable
+96 -5
View File
@@ -1,7 +1,55 @@
{ {
"schema": 1, "schema": 1,
"updated_at": "2026-12-02T03:58:51.696Z", "updated_at": "2026-12-03T03:29:42.285Z",
"plugins": [ "plugins": [
{
"id": "reims.agent",
"version": "0.1.0",
"name": {
"zh-CN": "MCP服务",
"en-US": "MCP Service"
},
"description": {
"zh-CN": "通过宿主授权的控制通道向 MCP 客户端提供虚拟机交互工具",
"en-US": "Provides VM interaction tools to MCP clients through host-authorized channels"
},
"publisher": "Reims-Go",
"license": "Apache-2.0",
"channel": "stable",
"trust": "official",
"kind": "tool",
"tier": "L3",
"homepage": "https://github.com/reims-go/reims-agent",
"readme_url": "https://github.com/reims-go/reims-agent#readme",
"engines": {
"pluginApi": "^1.1.0"
},
"platforms": [
"windows-x64"
],
"permissions": [
"vm:read",
"vm:control",
"vm:screen",
"qmp:write"
],
"download_url": "https://github.com/reims-go/reims-agent/releases/download/v0.1.0/reims.agent-0.1.0.zip",
"sha256": "0c662804508b1b6b06e10f80f395b28814cc4e280907f833c5e629d3293dac79",
"size_bytes": 4510547,
"changelog": {
"zh-CN": "首个正式版本:提供受宿主按虚拟机授权的 MCP 服务,支持截图、批量桌面操作、光标去噪屏幕等待、DPAPI 自动解锁、SSH/SFTP 及隔离 CoW 测试运行。",
"en-US": "Initial stable release: official host-authorized MCP service for per-VM screenshots, batched desktop controls, cursor-tolerant screen waits, DPAPI unlock, SSH/SFTP, and isolated CoW test runs."
},
"tags": [
"mcp",
"agent",
"computer-use",
"ssh",
"automation",
"MCP"
],
"updated_at": "2026-12-03T03:29:41.346Z"
},
{ {
"id": "official.lang.zh-tw", "id": "official.lang.zh-tw",
"version": "1.0.0", "version": "1.0.0",
@@ -42,7 +90,7 @@
"traditional-chinese", "traditional-chinese",
"繁體中文" "繁體中文"
], ],
"updated_at": "2026-12-02T03:58:51.146Z" "updated_at": "2026-12-03T03:29:41.563Z"
}, },
{ {
"id": "community.lang.ko-kr", "id": "community.lang.ko-kr",
@@ -84,7 +132,7 @@
"korean", "korean",
"한국어" "한국어"
], ],
"updated_at": "2026-12-02T03:58:51.327Z" "updated_at": "2026-12-03T03:29:41.783Z"
}, },
{ {
"id": "abadx.lang.es-es", "id": "abadx.lang.es-es",
@@ -125,7 +173,7 @@
"spanish", "spanish",
"español" "español"
], ],
"updated_at": "2026-12-02T03:58:51.518Z" "updated_at": "2026-12-03T03:29:41.937Z"
}, },
{ {
"id": "community.lang.ar-sa", "id": "community.lang.ar-sa",
@@ -163,7 +211,50 @@
"arabic", "arabic",
"العربية" "العربية"
], ],
"updated_at": "2026-12-02T03:58:51.695Z" "updated_at": "2026-12-03T03:29:42.125Z"
},
{
"id": "yfl520.theme.wallpaper-studio",
"version": "1.1.0",
"name": {
"zh-CN": "动态壁纸工坊",
"en-US": "Wallpaper Studio"
},
"description": {
"zh-CN": "可交互的动态壁纸主题:导入本机图片、GIF 与 MP4/WebM 视频作为窗口背景,支持定时轮播、实时调节背景遮罩与卡片不透明度,虚拟机运行时自动暂停视频以节省资源",
"en-US": "Interactive wallpaper theme: use local images, GIFs, and MP4/WebM videos as the window background, with slideshow, live dimming and card opacity controls, and automatic video pause while a VM is running"
},
"publisher": "yfl520",
"license": "Apache-2.0",
"channel": "stable",
"trust": "community",
"kind": "theme",
"tier": "L1",
"homepage": "https://github.com/yfl520/reims-theme-wallpaper-studio",
"readme_url": "https://github.com/yfl520/reims-theme-wallpaper-studio#readme",
"engines": {
"pluginApi": "^1.0.0",
"uiApi": "^2.0.0"
},
"permissions": [
"ui:script"
],
"download_url": "https://github.com/yfl520/reims-theme-wallpaper-studio/releases/download/v1.1.0/yfl520.theme.wallpaper-studio-1.1.0.zip",
"sha256": "f2af730f8701964e3becbdf826cba112b9b38f76f146b02ca00cf0db82a0000d",
"size_bytes": 29496,
"changelog": {
"zh-CN": "首个上架版本:导入本机图片、GIF 与 MP4/WebM 视频壁纸,支持定时轮播、背景遮罩与卡片不透明度实时调节、虚拟机运行时自动暂停视频、清空壁纸库,内置昼夜双景与 6 套配色",
"en-US": "First marketplace release: import local images, GIFs, and MP4/WebM videos as wallpapers, with slideshow, live dimming and card opacity controls, automatic video pause while a VM is running, a clear library action, built-in day and night backdrops, and 6 accent schemes"
},
"tags": [
"theme",
"wallpaper",
"video",
"glass",
"动态壁纸",
"交互主题"
],
"updated_at": "2026-12-03T03:29:42.284Z"
} }
], ],
"withdrawn": [] "withdrawn": []
File diff suppressed because it is too large. Load diff
+13 -13
View File
@@ -1,19 +1,19 @@
{ {
"synced_at": "2026-12-02T00:00:00Z", "synced_at": "2026-12-03T06:51:34.121Z",
"stars": 1600, "stars": 1868,
"version": "v0.2.11", "version": "v0.2.12",
"published_at": "2026-12-01T00:00:00Z", "published_at": "2026-12-02T20:42:58Z",
"html_url": "https://github.com/Nwflower/Reims-Go/releases/latest", "html_url": "https://github.com/Nwflower/Reims-Go/releases/tag/v0.2.12",
"exe": { "exe": {
"name": "reims-go-v0.2.11-windows-amd64.exe", "name": "reims-go-v0.2.12-windows-amd64.exe",
"size": 19312640, "size": 21023744,
"url": "https://github.com/Nwflower/Reims-Go/releases/latest/download/reims-go-v0.2.11-windows-amd64.exe" "url": "https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/reims-go-v0.2.12-windows-amd64.exe"
}, },
"zip": { "zip": {
"name": "reims-go-v0.2.11-windows-amd64.zip", "name": "reims-go-v0.2.12-windows-amd64.zip",
"size": 18874368, "size": 8362065,
"url": "https://github.com/Nwflower/Reims-Go/releases/latest/download/reims-go-v0.2.11-windows-amd64.zip" "url": "https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/reims-go-v0.2.12-windows-amd64.zip"
}, },
"sha256_url": "https://github.com/Nwflower/Reims-Go/releases/latest/download/SHA256SUMS.txt", "sha256_url": "https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/SHA256SUMS.txt",
"sha256_sums": "" "sha256_sums": "9bb1cbc25085acd1b2b4aed4dd422775030d7829b865e15ee79a301e161ee206 reims-go-v0.2.12-windows-amd64.exe\nf59f22b535a4c87b49b2d536d5bcb7069f9f754790da3c1dc24178dd07dbd9cb reims-go-v0.2.12-windows-amd64.zip"
} }
+166 -23
View File
@@ -1,12 +1,99 @@
import { writeFileSync, mkdirSync } from 'node:fs'; import { mkdirSync, writeFileSync } from 'node:fs';
import { resolve } from 'node:path'; import { resolve } from 'node:path';
const DATA_DIR = resolve(process.cwd(), 'public/data'); const DATA_DIR = resolve(process.cwd(), 'public/data');
mkdirSync(DATA_DIR, { recursive: true }); mkdirSync(DATA_DIR, { recursive: true });
const SKIP_SECTIONS = /^(下载|download|downloads|已知限制|known limitations|许可证|license|构建与许可证)/i;
function normalizeTitle(raw) {
return String(raw || '')
.replace(/<[^>]+>/g, '')
.replace(/^#+\s*/, '')
.trim();
}
function parseSections(markdown) {
const lines = String(markdown || '').replace(/\r\n/g, '\n').split('\n');
const sections = [];
let current = null;
let skipping = false;
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line) continue;
const htmlHeading = line.match(/^<h[2-4][^>]*>(.*?)<\/h[2-4]>$/i);
const mdHeading = !htmlHeading ? line.match(/^#{2,4}\s+(.+)$/) : null;
if (htmlHeading || mdHeading) {
const title = normalizeTitle(htmlHeading ? htmlHeading[1] : mdHeading[1]);
if (!title || SKIP_SECTIONS.test(title)) {
skipping = true;
current = null;
} else {
skipping = false;
current = { title, items: [] };
sections.push(current);
}
continue;
}
if (skipping || /^\[中文\]\(#cn-/i.test(line) || line.startsWith('>')) continue;
const bullet = line.match(/^[-*]\s+(.+)$/);
if (bullet && bullet[1].trim()) {
if (!current) {
current = { title: '', items: [] };
sections.push(current);
}
current.items.push(bullet[1].trim());
}
}
return sections.filter((s) => s.items.length > 0);
}
function parseBilingualBody(body) {
const text = String(body || '').replace(/\r\n/g, '\n');
if (!text.trim()) return { 'zh-CN': [], 'en-US': [] };
const cn = text.match(/<h[2-4][^>]*\bid=["']cn-[^"']*["'][^>]*>/i);
const en = text.match(/<h[2-4][^>]*\bid=["']en-[^"']*["'][^>]*>/i);
if (cn && en && cn.index !== undefined && en.index !== undefined) {
const cnChunk = cn.index < en.index ? text.slice(cn.index, en.index) : text.slice(cn.index);
const enChunk = en.index > cn.index ? text.slice(en.index) : text.slice(en.index, cn.index);
const zhSections = parseSections(cnChunk);
const enSections = parseSections(enChunk);
return {
'zh-CN': zhSections.length ? zhSections : enSections,
'en-US': enSections.length ? enSections : zhSections,
};
}
const single = parseSections(text);
return { 'zh-CN': single, 'en-US': single };
}
function classifyChannel(tag, prerelease) {
const lower = tag.toLowerCase();
if (lower === 'dev' || lower.includes('-dev')) return 'dev';
if (prerelease || lower.includes('alpha') || lower.includes('beta') || lower.includes('rc')) return 'alpha';
return 'stable';
}
function isClientTag(tag) {
if (!tag || /^runtime-/i.test(tag)) return false;
return /^v\d+\.\d+/i.test(tag) || /^dev$/i.test(tag) || /^alpha/i.test(tag);
}
async function fetchJson(url) { async function fetchJson(url) {
const res = await fetch(url, { const res = await fetch(url, {
headers: { 'User-Agent': 'Reims-Go-Landing-Sync/1.0' }, headers: {
Accept: 'application/vnd.github+json',
'User-Agent': 'Reims-Go-Landing-Sync/2.0',
},
}); });
if (!res.ok) throw new Error(`${res.status} ${url}`); if (!res.ok) throw new Error(`${res.status} ${url}`);
return res.json(); return res.json();
@@ -14,7 +101,7 @@ async function fetchJson(url) {
async function fetchText(url) { async function fetchText(url) {
const res = await fetch(url, { const res = await fetch(url, {
headers: { 'User-Agent': 'Reims-Go-Landing-Sync/1.0' }, headers: { 'User-Agent': 'Reims-Go-Landing-Sync/2.0' },
}); });
if (!res.ok) throw new Error(`${res.status} ${url}`); if (!res.ok) throw new Error(`${res.status} ${url}`);
return res.text(); return res.text();
@@ -22,39 +109,95 @@ async function fetchText(url) {
async function syncReleases() { async function syncReleases() {
try { try {
const [repo, rel] = await Promise.all([ const [repo, rawReleases] = await Promise.all([
fetchJson('https://api.github.com/repos/Nwflower/Reims-Go'), fetchJson('https://api.github.com/repos/Nwflower/Reims-Go'),
fetchJson('https://api.github.com/repos/Nwflower/Reims-Go/releases/latest'), fetchJson('https://api.github.com/repos/Nwflower/Reims-Go/releases?per_page=25'),
]); ]);
const assets = Array.isArray(rel.assets) ? rel.assets : [];
const exeAsset = assets.find((a) => /windows-amd64\.exe$/i.test(a.name)); const list = Array.isArray(rawReleases) ? rawReleases : [];
const zipAsset = assets.find((a) => /windows-amd64\.zip$/i.test(a.name)); const entries = [];
const shaAsset = assets.find((a) => /^SHA256SUMS\.txt$/i.test(a.name)); let latestStableRaw = null;
for (const rel of list) {
if (!rel || rel.draft) continue;
const tag = String(rel.tag_name || '').trim();
if (!isClientTag(tag)) continue;
const assets = Array.isArray(rel.assets) ? rel.assets : [];
const exeAsset = assets.find((a) => /windows-amd64\.exe$/i.test(a.name));
const zipAsset = assets.find((a) => /windows-amd64\.zip$/i.test(a.name));
const shaAsset = assets.find((a) => /^SHA256SUMS\.txt$/i.test(a.name));
const prerelease = Boolean(rel.prerelease);
const channel = classifyChannel(tag, prerelease);
const published = rel.published_at || rel.created_at || '';
if (channel === 'stable' && !latestStableRaw) {
latestStableRaw = { rel, exeAsset, zipAsset, shaAsset };
}
entries.push({
tag,
name: String(rel.name || `Reims-Go ${tag}`).trim(),
published_at: published,
date: published ? published.slice(0, 10) : '',
html_url: rel.html_url || `https://github.com/Nwflower/Reims-Go/releases/tag/${encodeURIComponent(tag)}`,
prerelease,
channel,
exe: exeAsset ? { name: exeAsset.name, size: exeAsset.size, url: exeAsset.browser_download_url } : null,
zip: zipAsset ? { name: zipAsset.name, size: zipAsset.size, url: zipAsset.browser_download_url } : null,
sha256_url: shaAsset?.browser_download_url || null,
sections: parseBilingualBody(rel.body || ''),
});
}
entries.sort((a, b) => {
if (a.channel === 'stable' && b.channel !== 'stable') return -1;
if (a.channel !== 'stable' && b.channel === 'stable') return 1;
return (b.published_at || '').localeCompare(a.published_at || '');
});
const top = latestStableRaw?.rel;
const exeAsset = latestStableRaw?.exeAsset;
const zipAsset = latestStableRaw?.zipAsset;
const shaAsset = latestStableRaw?.shaAsset;
let sha256Text = ''; let sha256Text = '';
if (shaAsset?.browser_download_url) { const digestLines = [exeAsset, zipAsset]
.filter((a) => a?.name && a?.digest && /^sha256:[a-f0-9]{64}$/i.test(a.digest))
.map((a) => `${a.digest.replace(/^sha256:/i, '')} ${a.name}`);
if (digestLines.length > 0) {
sha256Text = digestLines.join('\n');
} else if (shaAsset?.browser_download_url) {
try { try {
sha256Text = await fetchText(shaAsset.browser_download_url); sha256Text = await fetchText(shaAsset.browser_download_url);
} catch { } catch {
sha256Text = ''; sha256Text = '';
} }
} }
const payload = {
synced_at: new Date().toISOString(), const nowIso = new Date().toISOString();
const latest = {
synced_at: nowIso,
stars: typeof repo.stargazers_count === 'number' ? repo.stargazers_count : 1600, stars: typeof repo.stargazers_count === 'number' ? repo.stargazers_count : 1600,
version: rel.tag_name || 'v0.2.11', version: top?.tag_name || entries[0]?.tag || 'v0.2.12',
published_at: rel.published_at || '2026-12-01T00:00:00Z', published_at: top?.published_at || nowIso,
html_url: rel.html_url || 'https://github.com/Nwflower/Reims-Go/releases/latest', html_url: top?.html_url || 'https://github.com/Nwflower/Reims-Go/releases/latest',
exe: exeAsset exe: exeAsset ? { name: exeAsset.name, size: exeAsset.size, url: exeAsset.browser_download_url } : null,
? { name: exeAsset.name, size: exeAsset.size, url: exeAsset.browser_download_url } zip: zipAsset ? { name: zipAsset.name, size: zipAsset.size, url: zipAsset.browser_download_url } : null,
: null,
zip: zipAsset
? { name: zipAsset.name, size: zipAsset.size, url: zipAsset.browser_download_url }
: null,
sha256_url: shaAsset?.browser_download_url || null, sha256_url: shaAsset?.browser_download_url || null,
sha256_sums: sha256Text, sha256_sums: sha256Text,
}; };
writeFileSync(resolve(DATA_DIR, 'releases.json'), JSON.stringify(payload, null, 2) + '\n', 'utf8');
console.log(`[sync] releases.json updated: ${payload.version} (${payload.stars} stars)`); const bundle = {
source: 'static-fallback',
synced_at: nowIso,
latest,
entries,
};
writeFileSync(resolve(DATA_DIR, 'releases.json'), JSON.stringify(latest, null, 2) + '\n', 'utf8');
writeFileSync(resolve(DATA_DIR, 'releases-bundle.json'), JSON.stringify(bundle, null, 2) + '\n', 'utf8');
console.log(`[sync] releases.json & releases-bundle.json updated: ${latest.version} (${latest.stars} stars, ${entries.length} releases)`);
} catch (err) { } catch (err) {
console.warn('[sync] skipped releases fetch, keeping local fallback:', err.message); console.warn('[sync] skipped releases fetch, keeping local fallback:', err.message);
} }
+97 -32
View File
@@ -1,68 +1,133 @@
import React, { useId } from 'react'; import React, { useId } from 'react';
/**
* Ported 1:1 from Reims-Go desktop client `VersionArt`:
* Frosted-glass macOS major version digits over soft colour folds (tile & 16:10 screen shapes).
*/
type Palette = [string, string, string, string]; type Palette = [string, string, string, string];
const PALETTES: Record<number, Palette> = { const PALETTES: Record<number, Palette> = {
26: ['#f6e8cf', '#ebc8b4', '#a597d8', '#5450b4'], 26: ['#f6e8cf', '#ebc8b4', '#a597d8', '#5450b4'], // sand -> rose -> lavender (Tahoe)
15: ['#ddf2e8', '#86ccb8', '#3f8ea3', '#22446e'], 15: ['#ddf2e8', '#86ccb8', '#3f8ea3', '#22446e'], // mint -> teal (Sequoia)
14: ['#ffe5d2', '#f5a48d', '#d6688f', '#6a3f8e'], 14: ['#ffe5d2', '#f5a48d', '#d6688f', '#6a3f8e'], // peach -> coral -> plum (Sonoma)
13: ['#fff1cc', '#f7b95e', '#df7140', '#83372b'], 13: ['#fff1cc', '#f7b95e', '#df7140', '#83372b'], // cream -> amber (Ventura)
12: ['#e4ecff', '#91b1f4', '#5b70df', '#2f3592'], 12: ['#e4ecff', '#91b1f4', '#5b70df', '#2f3592'], // ice -> blue (Monterey)
11: ['#e5f5ff', '#88c9ee', '#3f86d0', '#233f88'], // sky -> ocean (Big Sur)
}; };
const NEUTRAL: Palette = ['#eef0f4', '#c9ceda', '#8d95a9', '#4b5266']; const NEUTRAL: Palette = ['#eef0f4', '#c9ceda', '#8d95a9', '#4b5266'];
function paletteFor(major: number | null): Palette {
if (major === null) return NEUTRAL;
return PALETTES[major] || PALETTES[11];
}
function initial(name: string): string {
const ch = Array.from(name.trim().replace(/^macos[\s_-]*/i, ''))[0] ?? 'M';
return ch.toUpperCase();
}
const SHAPES = {
tile: { w: 64, h: 64, size: 38, weight: 700, blur: 2.4, rim: 2.0, shadow: 1.6, glass: 1.55, shade: 0.7 },
screen: { w: 160, h: 100, size: 76, weight: 600, blur: 3.6, rim: 1.1, shadow: 2.4, glass: 1, shade: 0.36 },
};
interface Props { interface Props {
major: number | null; major: number | null;
name?: string;
shape?: 'tile' | 'screen';
size?: number; size?: number;
className?: string; className?: string;
} }
export const VersionArt: React.FC<Props> = ({ major, size = 24, className }) => { export const VersionArt: React.FC<Props> = ({
const uid = useId().replace(/[^a-zA-Z0-9_-]/g, ''); major,
const p = major && PALETTES[major] ? PALETTES[major] : NEUTRAL; name = 'macOS',
const label = major !== null ? String(major) : 'M'; shape = 'tile',
size,
className,
}) => {
const id = useId().replace(/[^a-zA-Z0-9_-]/g, '');
const p = paletteFor(major);
const s = SHAPES[shape];
const label = major !== null ? String(major) : initial(name);
const fontSize = label.length > 2 ? s.size * 0.72 : label.length === 1 ? s.size * 1.08 : s.size;
const textProps = {
x: s.w / 2,
y: s.h / 2 + fontSize * 0.04,
textAnchor: 'middle' as const,
dominantBaseline: 'central' as const,
fontSize,
fontWeight: s.weight,
letterSpacing: label.length > 1 ? -fontSize * 0.04 : 0,
style: { fontFamily: 'var(--font-sans)', fontVariantNumeric: 'tabular-nums' as const },
};
const sx = s.w / 100;
const sy = s.h / 100;
return ( return (
<svg <svg
width={size} width={size}
height={size} height={shape === 'tile' ? size : undefined}
viewBox="0 0 64 64" viewBox={`0 0 ${s.w} ${s.h}`}
preserveAspectRatio="xMidYMid slice"
className={className} className={className}
aria-hidden="true" aria-hidden="true"
> >
<defs> <defs>
<linearGradient id={`${uid}-bg`} x1="0" y1="0" x2="1" y2="1"> <linearGradient id={`${id}bg`} x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stopColor={p[0]} /> <stop offset="0" stopColor={p[0]} />
<stop offset="0.38" stopColor={p[1]} /> <stop offset="0.38" stopColor={p[1]} />
<stop offset="0.72" stopColor={p[2]} /> <stop offset="0.72" stopColor={p[2]} />
<stop offset="1" stopColor={p[3]} /> <stop offset="1" stopColor={p[3]} />
</linearGradient> </linearGradient>
<linearGradient id={`${uid}-hi`} x1="0" y1="0" x2="0" y2="1"> <linearGradient id={`${id}hi`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor="#ffffff" stopOpacity="0.62" /> <stop offset="0" stopColor="#ffffff" stopOpacity="0.62" />
<stop offset="1" stopColor="#ffffff" stopOpacity="0" /> <stop offset="1" stopColor="#ffffff" stopOpacity="0" />
</linearGradient> </linearGradient>
<linearGradient id={`${uid}-rim`} x1="0" y1="0" x2="0.3" y2="1"> <linearGradient id={`${id}sh`} x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stopColor="#ffffff" stopOpacity="0.95" /> <stop offset="0" stopColor={p[3]} stopOpacity="0" />
<stop offset="1" stopColor="#ffffff" stopOpacity="0.55" /> <stop offset="1" stopColor={p[3]} stopOpacity="0.6" />
</linearGradient> </linearGradient>
<linearGradient id={`${id}gl`} x1="0" y1="0" x2="0.4" y2="1">
<stop offset="0" stopColor="#ffffff" stopOpacity={Math.min(1, 0.62 * s.glass)} />
<stop offset="0.55" stopColor="#ffffff" stopOpacity={Math.min(1, 0.22 * s.glass)} />
<stop offset="1" stopColor="#ffffff" stopOpacity={Math.min(1, 0.34 * s.glass)} />
</linearGradient>
<linearGradient id={`${id}rim`} x1="0" y1="0" x2="0.3" y2="1">
<stop offset="0" stopColor="#ffffff" stopOpacity="0.98" />
<stop offset="0.6" stopColor="#ffffff" stopOpacity="0.45" />
<stop offset="1" stopColor="#ffffff" stopOpacity="0.8" />
</linearGradient>
<filter id={`${id}blur`} x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation={s.blur} />
</filter>
<filter id={`${id}soft`} x="-30%" y="-30%" width="160%" height="160%">
<feGaussianBlur stdDeviation={s.shadow} />
</filter>
<clipPath id={`${id}clip`}>
<text {...textProps}>{label}</text>
</clipPath>
<g id={`${id}scene`}>
<rect width={s.w} height={s.h} fill={`url(#${id}bg)`} />
<g transform={`scale(${sx} ${sy})`}>
<path d="M-5 40 C16 14 40 60 70 32 S104 8 105 6 L105 -5 L-5 -5 Z" fill={`url(#${id}hi)`} />
<path d="M-5 58 C24 30 54 80 105 36 L105 50 C56 90 26 46 -5 72 Z" fill="#ffffff" fillOpacity="0.2" />
<path d="M-5 74 C22 50 52 94 80 64 S104 46 105 46 L105 105 L-5 105 Z" fill={`url(#${id}sh)`} />
<path d="M-5 58 C24 30 54 80 105 36" fill="none" stroke="#ffffff" strokeOpacity="0.55" strokeWidth="0.7" vectorEffect="non-scaling-stroke" />
</g>
</g>
</defs> </defs>
<rect width="64" height="64" rx="16" fill={`url(#${uid}-bg)`} />
<path d="M-4 26 C10 10 26 38 45 20 S66 5 68 4 L68 -4 L-4 -4 Z" fill={`url(#${uid}-hi)`} /> <use href={`#${id}scene`} />
<text <text {...textProps} y={textProps.y + fontSize * 0.05} fill={p[3]} fillOpacity={s.shade} filter={`url(#${id}soft)`}>
x="32" {label}
y="34" </text>
textAnchor="middle" <g clipPath={`url(#${id}clip)`}>
dominantBaseline="central" <use href={`#${id}scene`} filter={`url(#${id}blur)`} />
fontSize="34" <rect width={s.w} height={s.h} fill={`url(#${id}gl)`} />
fontWeight="700" </g>
letterSpacing="-1.4" <text {...textProps} fill="none" stroke={`url(#${id}rim)`} strokeWidth={s.rim}>
fill="#ffffff"
fillOpacity="0.88"
stroke={`url(#${uid}-rim)`}
strokeWidth="1.2"
style={{ fontFamily: 'var(--font-sans)', fontVariantNumeric: 'tabular-nums' }}
>
{label} {label}
</text> </text>
</svg> </svg>
+36
View File
@@ -0,0 +1,36 @@
import React from 'react';
import { t } from '../../i18n/translations';
import { localizedPath, type Locale } from '../../i18n/types';
import { useLatestRelease } from '../../lib/releases';
interface Props {
locale: Locale;
}
export const HeroReleaseMeta: React.FC<Props> = ({ locale }) => {
const strings = t(locale);
const { data: release, live } = useLatestRelease();
const changelogHref = localizedPath(locale, '/changelog');
return (
<p className="tnum mt-4 flex flex-wrap items-center justify-center gap-x-2 gap-y-1 text-xs text-slate">
<a
href={changelogHref}
title={
locale === 'zh-CN'
? `当前最新正式版 ${release.version}(来自 GitHub Releases,点击查看更新日志)`
: `Latest stable ${release.version} from GitHub Releases — view changelog`
}
className="inline-flex items-center gap-1.5 rounded-full border border-border bg-surface px-2.5 py-0.5 font-mono text-[11.5px] font-medium text-ink transition-colors hover:border-border-strong hover:text-accent"
>
<span
className={`size-1.5 rounded-full ${live ? 'bg-[#28cd41]' : 'bg-accent'}`}
aria-hidden="true"
/>
<span>{release.version}</span>
</a>
<span aria-hidden="true">·</span>
<span>{strings.hero.metaTail}</span>
</p>
);
};
File diff suppressed because it is too large. Load diff
+4 -7
View File
@@ -2,10 +2,10 @@
import BaseLayout from '../../layouts/BaseLayout.astro'; import BaseLayout from '../../layouts/BaseLayout.astro';
import { t } from '../../i18n/translations'; import { t } from '../../i18n/translations';
import { localizedPath, type Locale } from '../../i18n/types'; import { localizedPath, type Locale } from '../../i18n/types';
import { FALLBACK_RELEASE } from '../../lib/releases';
import { buildHomeJsonLd } from '../../lib/seo'; import { buildHomeJsonLd } from '../../lib/seo';
import { WordmarkBrush } from '../brand/WordmarkBrush'; import { WordmarkBrush } from '../brand/WordmarkBrush';
import { HeroHeadline } from './HeroHeadline'; import { HeroHeadline } from './HeroHeadline';
import { HeroReleaseMeta } from './HeroReleaseMeta';
import { HeroWindowPreview } from './HeroWindowPreview'; import { HeroWindowPreview } from './HeroWindowPreview';
import { GpuPipelineViz } from './GpuPipelineViz'; import { GpuPipelineViz } from './GpuPipelineViz';
import { InstallStepper } from './InstallStepper'; import { InstallStepper } from './InstallStepper';
@@ -20,7 +20,6 @@ interface Props {
const { locale } = Astro.props; const { locale } = Astro.props;
const strings = t(locale); const strings = t(locale);
const releaseVer = FALLBACK_RELEASE.version;
const homeJsonLd = buildHomeJsonLd(locale); const homeJsonLd = buildHomeJsonLd(locale);
--- ---
@@ -32,7 +31,7 @@ const homeJsonLd = buildHomeJsonLd(locale);
jsonLd={homeJsonLd} jsonLd={homeJsonLd}
> >
<!-- Hero Section: Minimalist 4-Beat Header + Full-Bleed Scroll Parallax 1:1 Client --> <!-- Hero Section: Minimalist 4-Beat Header + Full-Bleed Scroll Parallax 1:1 Client -->
<section class="bg-canvas pb-16 pt-12 sm:pb-20 sm:pt-18"> <section class="overflow-x-clip bg-canvas pb-16 pt-12 sm:pb-20 sm:pt-18">
<div class="mx-auto flex max-w-5xl flex-col items-center px-4 text-center sm:px-8"> <div class="mx-auto flex max-w-5xl flex-col items-center px-4 text-center sm:px-8">
<WordmarkBrush client:load locale={locale} width={204} /> <WordmarkBrush client:load locale={locale} width={204} />
@@ -63,10 +62,8 @@ const homeJsonLd = buildHomeJsonLd(locale);
</a> </a>
</div> </div>
<p class="tnum mt-4 text-xs text-slate"> <HeroReleaseMeta client:load locale={locale} />
{releaseVer} · {strings.hero.metaTail} <p class="mt-1.5 max-w-xl text-[11px] leading-relaxed text-slate">
</p>
<p class="mt-1.5 max-w-xl text-[11px] leading-relaxed text-slate/80">
{strings.hero.iconDisclaimer} {strings.hero.iconDisclaimer}
</p> </p>
</div> </div>
File diff suppressed because it is too large. Load diff
+304
View File
@@ -0,0 +1,304 @@
import React from 'react';
export type VmState = 'stopped' | 'starting' | 'running' | 'suspended';
export type SysPageId = '__images__' | '__plugins__' | '__kernel__' | '__settings__' | '__about__';
export type AppSelection = string; // VM id or SysPageId
export type LogTab = 'app' | 'serial' | 'qemu';
export interface SimVM {
id: string;
name: string;
displayName: string;
major: number;
state: VmState;
cpus: number;
memoryGb: number;
diskUsedGb: number;
diskTotalGb: number;
resolution: string;
graphics: 'reims-vgpu' | 'vmware-svga';
gpuName: string;
network: 'shared' | 'bridged';
lang: 'zh-CN' | 'en-US';
sshPort: number;
sshUser: string;
guestToolsAttached: boolean;
preventSleep: boolean;
hostDns: boolean;
captureShortcuts: boolean;
winToCmd: boolean;
uptimeSec: number;
suspendedAt?: string;
}
export interface SimLogLine {
id: number;
ts: string;
source: string;
level: 'info' | 'warn' | 'error';
line: string;
}
export interface SimPlugin {
id: string;
nameZh: string;
nameEn: string;
descZh: string;
descEn: string;
version: string;
trust: 'official' | 'builtin' | 'verified';
tier: 'L1' | 'L3' | 'L4';
tone: 'indigo' | 'purple' | 'sky' | 'emerald' | 'amber' | 'rose';
enabled: boolean;
installed: boolean;
locked?: boolean;
}
export interface SimDownloadTask {
version: string;
title: string;
percent: number;
speedMb: number;
paused: boolean;
}
export interface SimThemeVars {
chrome: string;
canvas: string;
rail: string;
sidebar: string;
sidebarBorder: string;
sidebarShadow: string;
surface1: string;
elevated: string;
surface2: string;
input: string;
hover: string;
active: string;
border: string;
borderStrong: string;
text: string;
text2: string;
text3: string;
textCode: string;
statusbar: string;
accent: string;
accentHover: string;
accentSoft: string;
accentSoftText: string;
okSoft: string;
okText: string;
warnSoft: string;
warnText: string;
danger: string;
dangerSoft: string;
dangerText: string;
segThumb: string;
shadowOverlay: string;
shadowBtn: string;
}
export function getSimThemeVars(dark: boolean): SimThemeVars {
if (dark) {
return {
chrome: 'linear-gradient(180deg, #212228 0%, #1c1d22 100%)',
canvas: '#1d1e23',
rail: '#17181c',
sidebar: 'linear-gradient(180deg, rgba(40,41,48,0.94) 0%, rgba(34,35,41,0.92) 100%)',
sidebarBorder: 'rgba(255,255,255,0.09)',
sidebarShadow: '0 6px 22px rgba(0,0,0,0.36), inset 0 1px 0 rgba(255,255,255,0.08)',
surface1: 'rgba(255,255,255,0.048)',
elevated: 'rgba(255,255,255,0.075)',
surface2: 'rgba(42,43,50,0.98)',
input: 'rgba(0,0,0,0.28)',
hover: 'rgba(255,255,255,0.075)',
active: 'rgba(255,255,255,0.12)',
border: 'rgba(255,255,255,0.085)',
borderStrong: 'rgba(255,255,255,0.16)',
text: '#f5f5f7',
text2: '#c2c2ca',
text3: '#92929c',
textCode: '#d4d6e0',
statusbar: '#18191e',
accent: '#0a84ff',
accentHover: '#2492ff',
accentSoft: 'rgba(10,132,255,0.20)',
accentSoftText: '#64b0ff',
okSoft: 'rgba(48,209,88,0.16)',
okText: '#30d158',
warnSoft: 'rgba(255,214,10,0.15)',
warnText: '#ffd60a',
danger: '#ff453a',
dangerSoft: 'rgba(255,69,58,0.15)',
dangerText: '#ff8b83',
segThumb: '#555760',
shadowOverlay: '0 18px 40px rgba(0,0,0,0.52), 0 0 0 1px rgba(255,255,255,0.09)',
shadowBtn: '0 1px 2px rgba(0,0,0,0.30), inset 0 1px 0 rgba(255,255,255,0.06)',
};
}
return {
chrome: 'linear-gradient(180deg, #eff4fb 0%, #e8f0fa 100%)',
canvas: '#ffffff',
rail: 'linear-gradient(180deg, #e7f0fa 0%, #dde8f7 100%)',
sidebar: 'linear-gradient(180deg, rgba(255,255,255,0.82) 0%, rgba(247,250,255,0.74) 100%)',
sidebarBorder: 'rgba(255,255,255,0.90)',
sidebarShadow: '0 4px 18px rgba(15,35,70,0.065), 0 0 0 1px rgba(15,23,42,0.06)',
surface1: '#f5f6f8',
elevated: '#ffffff',
surface2: 'rgba(255,255,255,0.98)',
input: '#ffffff',
hover: 'rgba(15,23,42,0.048)',
active: 'rgba(15,23,42,0.085)',
border: 'rgba(15,23,42,0.08)',
borderStrong: 'rgba(15,23,42,0.14)',
text: '#1d1d1f',
text2: '#424247',
text3: '#6e6e73',
textCode: '#2c2c30',
statusbar: '#eef3fa',
accent: '#007aff',
accentHover: '#006be6',
accentSoft: 'rgba(0,122,255,0.11)',
accentSoftText: '#0066d6',
okSoft: 'rgba(40,205,65,0.13)',
okText: '#147425',
warnSoft: 'rgba(255,159,10,0.14)',
warnText: '#945400',
danger: '#ff3b30',
dangerSoft: 'rgba(255,59,48,0.10)',
dangerText: '#d70015',
segThumb: '#ffffff',
shadowOverlay: '0 16px 36px rgba(15,23,42,0.16), 0 3px 10px rgba(15,23,42,0.06), 0 0 0 1px rgba(15,23,42,0.06)',
shadowBtn: '0 1px 2px rgba(15,23,42,0.06), inset 0 1px 0 rgba(255,255,255,0.7)',
};
}
/** Authentic Reims-Go StatusShape (running dot, stopped ring, suspended || bars, busy half-pie). */
export const StatusShape: React.FC<{
kind: 'running' | 'stopped' | 'suspended' | 'busy' | 'warn';
inverted?: boolean;
}> = ({ kind, inverted = false }) => {
if (kind === 'running') {
return (
<span
aria-hidden="true"
className="inline-block size-2 shrink-0 rounded-full"
style={{
backgroundColor: inverted ? '#ffffff' : '#28cd41',
boxShadow: inverted ? '0 0 0 2px rgba(255,255,255,0.28)' : undefined,
}}
/>
);
}
if (kind === 'suspended') {
const col = inverted ? '#ffffff' : '#ff9f0a';
return (
<span
aria-hidden="true"
className="inline-block h-2 w-[7px] shrink-0"
style={{
background: `linear-gradient(90deg, ${col} 0 2.5px, transparent 2.5px 4.5px, ${col} 4.5px 7px)`,
}}
/>
);
}
if (kind === 'busy') {
const col = inverted ? '#ffffff' : '#ff9f0a';
return (
<span
aria-hidden="true"
className="inline-block size-2 shrink-0 animate-pulse rounded-full motion-reduce:animate-none"
style={{
background: `conic-gradient(${col} 0 50%, transparent 50% 100%)`,
border: `1.5px solid ${col}`,
}}
/>
);
}
if (kind === 'warn') {
return (
<span
aria-hidden="true"
className="inline-block size-2 shrink-0 rounded-full"
style={{ backgroundColor: inverted ? '#ffd60a' : '#ff9f0a' }}
/>
);
}
return (
<span
aria-hidden="true"
className="inline-block size-2 shrink-0 rounded-full"
style={{
border: `1.5px solid ${inverted ? 'rgba(255,255,255,0.72)' : '#aeaeb2'}`,
}}
/>
);
};
/** Authentic macOS Tahoe spring Switch (38x22px, from app.css). */
export const TahoeSwitch: React.FC<{
checked: boolean;
onChange: (checked: boolean) => void;
label: string;
disabled?: boolean;
v: SimThemeVars;
}> = ({ checked, onChange, label, disabled = false, v }) => (
<button
type="button"
role="switch"
aria-label={label}
aria-checked={checked}
disabled={disabled}
onClick={() => !disabled && onChange(!checked)}
className="relative inline-block h-[22px] w-[38px] shrink-0 cursor-pointer rounded-full transition-colors duration-180 disabled:cursor-not-allowed disabled:opacity-45"
style={{ backgroundColor: checked ? v.accent : v.active }}
>
<span
className="pointer-events-none absolute top-[2px] left-[2px] block size-[18px] rounded-full bg-white shadow-[0_1px_3px_rgba(0,0,0,0.24)] transition-transform duration-180 ease-[cubic-bezier(0.32,0.72,0,1)]"
style={{ transform: checked ? 'translateX(16px)' : 'translateX(0px)' }}
/>
</button>
);
/** Authentic macOS Tahoe Segmented Control (from ui/settings.tsx + app.css). */
export function TahoeSegmented<T extends string>({
value,
options,
onChange,
v,
}: {
value: T;
options: Array<{ value: T; label: string }>;
onChange: (val: T) => void;
v: SimThemeVars;
}) {
return (
<div
role="radiogroup"
className="inline-flex items-center gap-0.5 rounded-[8px] p-[2px]"
style={{ background: v.active }}
>
{options.map((opt) => {
const active = opt.value === value;
return (
<button
key={opt.value}
type="button"
role="radio"
aria-checked={active}
onClick={() => onChange(opt.value)}
className="h-[26px] whitespace-nowrap rounded-[6px] px-3 text-[12.5px] transition-all duration-150"
style={{
backgroundColor: active ? v.segThumb : 'transparent',
color: active ? v.text : v.text2,
fontWeight: active ? 540 : 450,
boxShadow: active ? '0 1px 2px rgba(0,0,0,0.12), 0 0 0 0.5px rgba(0,0,0,0.06)' : 'none',
}}
>
{opt.label}
</button>
);
})}
</div>
);
}
@@ -0,0 +1,17 @@
import React from 'react';
import type { Locale } from '../../i18n/types';
import { useLatestRelease } from '../../lib/releases';
interface Props {
locale: Locale;
}
export const DocsVersionBadge: React.FC<Props> = ({ locale }) => {
const { data } = useLatestRelease();
const label = locale === 'zh-CN' ? `适用版本 ${data.version}` : `For ${data.version}`;
return (
<span className="tnum rounded-full border border-border bg-surface px-2.5 py-0.5 font-mono text-[11px]">
{label}
</span>
);
};
-155
View File
@@ -1,155 +0,0 @@
import { Menu, Moon, Search, Sun, X } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { t } from '../../i18n/translations';
import { localizedPath, switchLocalePath, type Locale } from '../../i18n/types';
import { formatStars, useLatestRelease } from '../../lib/releases';
import { SearchModal } from './SearchModal';
interface Props {
locale: Locale;
pathname: string;
activeSection: string;
}
export const HeaderControls: React.FC<Props> = ({ locale, pathname, activeSection }) => {
const strings = t(locale);
const { data: release } = useLatestRelease();
const [dark, setDark] = useState(false);
const [searchOpen, setSearchOpen] = useState(false);
const [mobileOpen, setMobileOpen] = useState(false);
useEffect(() => {
const syncTheme = () => setDark(document.documentElement.getAttribute('data-theme') === 'dark');
syncTheme();
const onKey = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') {
e.preventDefault();
setSearchOpen((v) => !v);
}
};
document.addEventListener('astro:after-swap', syncTheme);
window.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('astro:after-swap', syncTheme);
window.removeEventListener('keydown', onKey);
};
}, []);
const toggleTheme = () => {
const next = !dark;
setDark(next);
document.documentElement.setAttribute('data-theme', next ? 'dark' : 'light');
try {
localStorage.setItem('reims-landing-theme', next ? 'dark' : 'light');
} catch {
// Ignore storage failures.
}
};
const targetLocale: Locale = locale === 'zh-CN' ? 'en-US' : 'zh-CN';
const langHref = switchLocalePath(pathname, targetLocale);
const navItems = [
{ key: 'features', label: strings.nav.features, href: localizedPath(locale, '/') },
{ key: 'docs', label: strings.nav.docs, href: localizedPath(locale, '/docs/quick-start') },
{ key: 'plugins', label: strings.nav.plugins, href: localizedPath(locale, '/plugins') },
{ key: 'compatibility', label: strings.nav.compatibility, href: localizedPath(locale, '/compatibility') },
{ key: 'changelog', label: strings.nav.changelog, href: localizedPath(locale, '/changelog') },
];
return (
<>
<div className="flex shrink-0 items-center gap-1 sm:gap-1.5 lg:col-start-3 lg:justify-self-end">
<a
href={langHref}
data-astro-prefetch="load"
aria-label={strings.nav.langSwitchAria}
className="inline-flex h-8 min-w-8 shrink-0 items-center justify-center whitespace-nowrap rounded-full border border-border-strong px-2 text-[12px] font-medium text-slate transition-[color,background-color,transform] duration-150 hover:bg-surface hover:text-ink active:scale-95"
>
{strings.nav.langSwitchLabel}
</a>
<button
type="button"
onClick={() => setSearchOpen(true)}
aria-label={strings.nav.searchAria}
title="Ctrl+K"
className="grid size-8 shrink-0 place-items-center rounded-full border border-border-strong text-slate transition-[color,background-color,transform] duration-150 hover:bg-surface hover:text-ink active:scale-95 sm:border-transparent"
>
<Search className="size-[16px]" aria-hidden="true" />
</button>
<button
type="button"
onClick={toggleTheme}
aria-label={strings.nav.themeAria}
aria-pressed={dark}
className="grid size-8 shrink-0 place-items-center rounded-full border border-border-strong text-slate transition-[color,background-color,transform] duration-150 hover:bg-surface hover:text-ink active:scale-95 sm:border-transparent"
>
<Sun
className={`col-start-1 row-start-1 size-[17px] transition-[opacity,filter] duration-300 ${
dark ? 'opacity-100 blur-none' : 'opacity-0 blur-[3px]'
}`}
aria-hidden="true"
/>
<Moon
className={`col-start-1 row-start-1 size-[16px] transition-[opacity,filter] duration-300 ${
dark ? 'opacity-0 blur-[3px]' : 'opacity-100 blur-none'
}`}
aria-hidden="true"
/>
</button>
<a
href="https://github.com/Nwflower/Reims-Go"
target="_blank"
rel="noopener noreferrer"
aria-label={`GitHub Reims-Go · ${strings.nav.starPrefix} ${formatStars(release.stars)}`}
className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full border border-border-strong px-2.5 text-[13px] font-medium text-ink transition-colors duration-150 hover:bg-surface sm:px-3"
>
<svg viewBox="0 0 24 24" className="size-[15px] fill-current" aria-hidden="true">
<path d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.53 1.032 1.53 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0 1 12 6.844a9.59 9.59 0 0 1 2.504.337c1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.02 10.02 0 0 0 22 12.017C22 6.484 17.522 2 12 2Z" />
</svg>
<span className="tnum hidden items-center gap-1 sm:inline-flex">
<span className="text-slate">{strings.nav.starPrefix}</span>
<span>{formatStars(release.stars)}</span>
</span>
</a>
<button
type="button"
onClick={() => setMobileOpen((v) => !v)}
aria-label="Menu"
aria-expanded={mobileOpen}
className="grid size-8 shrink-0 place-items-center rounded-full border border-border-strong text-slate transition-colors hover:text-ink lg:hidden"
>
{mobileOpen ? <X className="size-4" /> : <Menu className="size-4" />}
</button>
</div>
{mobileOpen && (
<div className="fixed inset-x-0 top-14 z-40 border-b border-border bg-canvas/95 px-5 py-3 shadow-lg backdrop-blur-xl lg:hidden">
<ul className="flex flex-col gap-1">
{navItems.map((item) => (
<li key={item.key}>
<a
href={item.href}
onClick={() => setMobileOpen(false)}
className={`block rounded-xl px-3 py-2.5 text-sm transition-colors ${
activeSection === item.key
? 'bg-surface font-medium text-ink'
: 'text-slate hover:bg-surface hover:text-ink'
}`}
>
{item.label}
</a>
</li>
))}
</ul>
</div>
)}
<SearchModal open={searchOpen} onOpenChange={setSearchOpen} locale={locale} />
</>
);
};
+10 -49
View File
@@ -1,65 +1,26 @@
--- ---
import { t } from '../../i18n/translations'; import type { Locale } from '../../i18n/types';
import { localizedPath, type Locale } from '../../i18n/types'; import { SiteHeader, type NavSectionKey } from './SiteHeader';
import { HeaderControls } from './HeaderControls';
interface Props { interface Props {
locale: Locale; locale: Locale;
activeSection?: 'features' | 'docs' | 'plugins' | 'compatibility' | 'changelog'; activeSection?: NavSectionKey;
} }
const { locale, activeSection = 'features' } = Astro.props; const { locale, activeSection = 'features' } = Astro.props;
const strings = t(locale);
const pathname = Astro.url.pathname; const pathname = Astro.url.pathname;
const navLinks = [
{ key: 'features', label: strings.nav.features, href: localizedPath(locale, '/') },
{ key: 'docs', label: strings.nav.docs, href: localizedPath(locale, '/docs/quick-start') },
{ key: 'plugins', label: strings.nav.plugins, href: localizedPath(locale, '/plugins') },
{ key: 'compatibility', label: strings.nav.compatibility, href: localizedPath(locale, '/compatibility') },
{ key: 'changelog', label: strings.nav.changelog, href: localizedPath(locale, '/changelog') },
] as const;
--- ---
<header <header
transition:persist={`site-header-${locale}`}
transition:name="site-header" transition:name="site-header"
transition:animate="none" transition:animate="none"
class="fixed inset-x-0 top-0 z-50 border-b border-border bg-[var(--c-nav-glass)] backdrop-blur-xl backdrop-saturate-150" class="fixed inset-x-0 top-0 z-50 border-b border-border bg-[var(--c-nav-glass)] backdrop-blur-xl backdrop-saturate-150"
> >
<nav <SiteHeader
aria-label="Main" client:load
class="mx-auto flex h-14 w-full max-w-6xl items-center justify-between gap-2 px-4 sm:px-8 lg:grid lg:grid-cols-[1fr_auto_1fr]" locale={locale}
> initialPathname={pathname}
<a initialSection={activeSection}
href={localizedPath(locale, '/')} />
class="inline-flex shrink-0 items-center gap-2 whitespace-nowrap transition-opacity duration-150 hover:opacity-80 sm:gap-2.5 lg:col-start-1 lg:justify-self-start"
>
<img src="/logo.svg" alt="Reims-Go" class="size-7 shrink-0" width="28" height="28" />
<span class="text-[15px] font-semibold tracking-[-0.015em] text-ink">Reims-Go</span>
</a>
<ul class="hidden items-center gap-1 lg:col-start-2 lg:flex">
{navLinks.map((item) => {
const isActive = activeSection === item.key;
return (
<li>
<a
href={item.href}
aria-current={isActive ? 'page' : undefined}
class:list={[
'inline-flex items-center whitespace-nowrap rounded-full px-3.5 py-1.5 text-sm transition-colors duration-150',
isActive
? 'bg-surface font-medium text-ink'
: 'text-slate hover:bg-surface hover:text-ink',
]}
>
{item.label}
</a>
</li>
);
})}
</ul>
<HeaderControls client:load locale={locale} pathname={pathname} activeSection={activeSection} />
</nav>
</header> </header>
+4 -3
View File
@@ -26,7 +26,7 @@ const QUICK_PAGES: Record<Locale, Array<{ path: string; title: string; excerpt:
{ path: '/docs/troubleshooting', title: '故障排查与安全模式', excerpt: 'Vulkan 1.3 排障、VMware SVGA 回退与 --safe-mode 恢复' }, { path: '/docs/troubleshooting', title: '故障排查与安全模式', excerpt: 'Vulkan 1.3 排障、VMware SVGA 回退与 --safe-mode 恢复' },
{ path: '/plugins', title: '官方插件市场', excerpt: '实时同步 reims-go/plugins 索引,浏览语言包、主题与扩展' }, { path: '/plugins', title: '官方插件市场', excerpt: '实时同步 reims-go/plugins 索引,浏览语言包、主题与扩展' },
{ path: '/compatibility', title: '硬件兼容与环境清单', excerpt: 'NVIDIA RTX、AMD 显卡、核显与 BIOS 虚拟化支持说明' }, { path: '/compatibility', title: '硬件兼容与环境清单', excerpt: 'NVIDIA RTX、AMD 显卡、核显与 BIOS 虚拟化支持说明' },
{ path: '/changelog', title: '更新日志', excerpt: 'Reims-Go 客户端从 v0.1.0 到 v0.2.11 的完整版本记录' }, { path: '/changelog', title: '更新日志', excerpt: '实时同步 GitHub Releases,查看 Reims-Go 完整版本记录与校验下载' },
], ],
'en-US': [ 'en-US': [
{ path: '/docs/quick-start', title: 'Quick Start', excerpt: 'Host check, portable runtime, 3-click offline macOS install, and Guest Tools' }, { path: '/docs/quick-start', title: 'Quick Start', excerpt: 'Host check, portable runtime, 3-click offline macOS install, and Guest Tools' },
@@ -37,7 +37,7 @@ const QUICK_PAGES: Record<Locale, Array<{ path: string; title: string; excerpt:
{ path: '/docs/troubleshooting', title: 'Troubleshooting & Safe Mode', excerpt: 'Vulkan 1.3 diagnostics, VMware SVGA fallback, and --safe-mode recovery' }, { path: '/docs/troubleshooting', title: 'Troubleshooting & Safe Mode', excerpt: 'Vulkan 1.3 diagnostics, VMware SVGA fallback, and --safe-mode recovery' },
{ path: '/plugins', title: 'Official Plugin Marketplace', excerpt: 'Browse language packs, themes, and extensions from reims-go/plugins' }, { path: '/plugins', title: 'Official Plugin Marketplace', excerpt: 'Browse language packs, themes, and extensions from reims-go/plugins' },
{ path: '/compatibility', title: 'Hardware Compatibility', excerpt: 'NVIDIA RTX, AMD GPUs, integrated graphics, and WHPX requirements' }, { path: '/compatibility', title: 'Hardware Compatibility', excerpt: 'NVIDIA RTX, AMD GPUs, integrated graphics, and WHPX requirements' },
{ path: '/changelog', title: 'Changelog', excerpt: 'Release notes for Reims-Go client from v0.1.0 to v0.2.11' }, { path: '/changelog', title: 'Changelog', excerpt: 'Live GitHub Releases feed with full Reims-Go release notes and checksums' },
], ],
}; };
@@ -107,7 +107,7 @@ export const SearchModal: React.FC<Props> = ({ open, onOpenChange, locale }) =>
cancelled = true; cancelled = true;
window.clearTimeout(timer); window.clearTimeout(timer);
}; };
}, [open, query]); }, [open, query, pagefindReady]);
const displayItems: SearchResult[] = const displayItems: SearchResult[] =
query.trim() && results.length > 0 query.trim() && results.length > 0
@@ -133,6 +133,7 @@ export const SearchModal: React.FC<Props> = ({ open, onOpenChange, locale }) =>
ref={inputRef} ref={inputRef}
value={query} value={query}
onChange={(e) => setQuery(e.target.value)} onChange={(e) => setQuery(e.target.value)}
aria-label={strings.search.placeholder}
placeholder={strings.search.placeholder} placeholder={strings.search.placeholder}
className="w-full bg-transparent text-sm text-ink placeholder:text-slate focus:outline-none" className="w-full bg-transparent text-sm text-ink placeholder:text-slate focus:outline-none"
/> />
+365
View File
@@ -0,0 +1,365 @@
import { Menu, Moon, Search, Sun, X } from 'lucide-react';
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { t } from '../../i18n/translations';
import { localizedPath, switchLocalePath, type Locale } from '../../i18n/types';
import { formatStars, useLatestRelease } from '../../lib/releases';
import { SearchModal } from './SearchModal';
const useIsoLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;
export type NavSectionKey = 'features' | 'docs' | 'plugins' | 'compatibility' | 'changelog';
interface Props {
locale: Locale;
initialPathname: string;
initialSection: NavSectionKey;
}
function normalizePath(path: string): string {
const clean = path.split('#')[0].split('?')[0].replace(/\/+$/, '');
return clean === '' ? '/' : clean;
}
export function resolveSectionFromPath(pathname: string): NavSectionKey {
const norm = normalizePath(pathname);
const isEn = norm === '/en' || norm.startsWith('/en/');
const stripped = isEn ? (norm.slice(3) || '/') : norm;
if (stripped.startsWith('/docs')) return 'docs';
if (stripped.startsWith('/plugins')) return 'plugins';
if (stripped.startsWith('/compatibility')) return 'compatibility';
if (stripped.startsWith('/changelog')) return 'changelog';
return 'features';
}
declare global {
interface Window {
__reimsPrefetchUrl?: (href: string) => void;
}
}
export const SiteHeader: React.FC<Props> = ({ locale, initialPathname, initialSection }) => {
const strings = t(locale);
const { data: release } = useLatestRelease();
const [pathname, setPathname] = useState<string>(initialPathname);
const [activeSection, setActiveSection] = useState<NavSectionKey>(initialSection);
const [navPending, setNavPending] = useState(false);
const [dark, setDark] = useState(false);
const [searchOpen, setSearchOpen] = useState(false);
const [mobileOpen, setMobileOpen] = useState(false);
const listRef = useRef<HTMLUListElement>(null);
const itemRefs = useRef<Record<NavSectionKey, HTMLAnchorElement | null>>({
features: null,
docs: null,
plugins: null,
compatibility: null,
changelog: null,
});
const [pill, setPill] = useState<{ x: number; w: number; ready: boolean }>({ x: 0, w: 0, ready: false });
const pendingTimerRef = useRef<number | null>(null);
const navItems = useMemo(
() => [
{ key: 'features' as const, label: strings.nav.features, href: localizedPath(locale, '/') },
{ key: 'docs' as const, label: strings.nav.docs, href: localizedPath(locale, '/docs/quick-start') },
{ key: 'plugins' as const, label: strings.nav.plugins, href: localizedPath(locale, '/plugins') },
{ key: 'compatibility' as const, label: strings.nav.compatibility, href: localizedPath(locale, '/compatibility') },
{ key: 'changelog' as const, label: strings.nav.changelog, href: localizedPath(locale, '/changelog') },
],
[locale, strings],
);
const measurePill = useCallback((section: NavSectionKey) => {
const list = listRef.current;
const el = itemRefs.current[section];
if (!list || !el) return;
const listRect = list.getBoundingClientRect();
const elRect = el.getBoundingClientRect();
if (elRect.width <= 0) return;
setPill({
x: Math.round(elRect.left - listRect.left),
w: Math.round(elRect.width),
ready: true,
});
}, []);
useIsoLayoutEffect(() => {
measurePill(activeSection);
}, [activeSection, locale, measurePill]);
useEffect(() => {
const list = listRef.current;
if (!list || typeof ResizeObserver === 'undefined') return;
const ro = new ResizeObserver(() => measurePill(activeSection));
ro.observe(list);
return () => ro.disconnect();
}, [activeSection, measurePill]);
useEffect(() => {
const syncTheme = () => setDark(document.documentElement.getAttribute('data-theme') === 'dark');
const syncRouteFromLocation = () => {
const cur = window.location.pathname || initialPathname;
setPathname(cur);
setActiveSection(resolveSectionFromPath(cur));
setMobileOpen(false);
if (pendingTimerRef.current !== null) {
window.clearTimeout(pendingTimerRef.current);
pendingTimerRef.current = null;
}
setNavPending(false);
};
const onNavStart = (ev: Event) => {
const detail = (ev as CustomEvent<{ to?: string; cached?: boolean }>).detail;
if (detail?.to) {
setPathname(detail.to);
setActiveSection(resolveSectionFromPath(detail.to));
}
setMobileOpen(false);
if (pendingTimerRef.current !== null) {
window.clearTimeout(pendingTimerRef.current);
pendingTimerRef.current = null;
}
// Show subtle top progress line only if an uncached route takes >100ms
if (!detail?.cached) {
pendingTimerRef.current = window.setTimeout(() => setNavPending(true), 100);
}
};
const onNavEnd = () => {
if (pendingTimerRef.current !== null) {
window.clearTimeout(pendingTimerRef.current);
pendingTimerRef.current = null;
}
setNavPending(false);
syncRouteFromLocation();
syncTheme();
};
const onKey = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') {
e.preventDefault();
setSearchOpen((v) => !v);
} else if (e.key === 'Escape') {
setMobileOpen(false);
}
};
syncTheme();
syncRouteFromLocation();
window.addEventListener('reims:nav-start', onNavStart);
window.addEventListener('reims:nav-end', onNavEnd);
window.addEventListener('popstate', syncRouteFromLocation);
window.addEventListener('keydown', onKey);
return () => {
if (pendingTimerRef.current !== null) window.clearTimeout(pendingTimerRef.current);
window.removeEventListener('reims:nav-start', onNavStart);
window.removeEventListener('reims:nav-end', onNavEnd);
window.removeEventListener('popstate', syncRouteFromLocation);
window.removeEventListener('keydown', onKey);
};
}, [initialPathname]);
const toggleTheme = () => {
const next = !dark;
setDark(next);
document.documentElement.setAttribute('data-theme', next ? 'dark' : 'light');
try {
localStorage.setItem('reims-landing-theme', next ? 'dark' : 'light');
} catch {
// Ignore storage failures.
}
};
const handleOptimisticNav = (e: React.MouseEvent<HTMLAnchorElement>, section: NavSectionKey, href: string) => {
// Do not mutate current tab's active state when user opens link in a new tab/window
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0 || e.defaultPrevented) return;
setActiveSection(section);
setPathname(href);
setMobileOpen(false);
};
const warmHref = (href: string) => {
window.__reimsPrefetchUrl?.(href);
};
const targetLocale: Locale = locale === 'zh-CN' ? 'en-US' : 'zh-CN';
const langHref = switchLocalePath(pathname, targetLocale);
return (
<>
<nav
aria-label={locale === 'zh-CN' ? '主导航' : 'Main navigation'}
className="mx-auto flex h-14 w-full max-w-6xl items-center justify-between gap-2 px-4 sm:px-8 lg:grid lg:grid-cols-[1fr_auto_1fr]"
>
<a
href={localizedPath(locale, '/')}
onPointerEnter={() => warmHref(localizedPath(locale, '/'))}
onClick={(e) => handleOptimisticNav(e, 'features', localizedPath(locale, '/'))}
className="inline-flex shrink-0 items-center gap-2 whitespace-nowrap transition-opacity duration-150 hover:opacity-80 sm:gap-2.5 lg:col-start-1 lg:justify-self-start"
>
<img src="/logo.svg" alt="Reims-Go" className="size-7 shrink-0" width="28" height="28" />
<span className="text-[15px] font-semibold tracking-[-0.015em] text-ink">Reims-Go</span>
</a>
{/* Desktop Category Tabs with GPU-Accelerated Sliding Tahoe Pill */}
<ul
ref={listRef}
className="relative hidden items-center gap-1 lg:col-start-2 lg:flex"
>
{pill.ready && (
<span
aria-hidden="true"
className="pointer-events-none absolute top-0 bottom-0 left-0 rounded-full bg-surface shadow-[inset_0_0_0_1px_var(--c-border)] transition-[transform,width] duration-220 ease-[cubic-bezier(0.22,1,0.36,1)] will-change-transform motion-reduce:transition-none"
style={{
width: `${pill.w}px`,
transform: `translate3d(${pill.x}px, 0, 0)`,
}}
/>
)}
{navItems.map((item) => {
const isActive = activeSection === item.key;
return (
<li key={item.key} className="relative z-10">
<a
ref={(el) => {
itemRefs.current[item.key] = el;
}}
href={item.href}
aria-current={isActive ? 'page' : undefined}
onPointerEnter={() => warmHref(item.href)}
onFocus={() => warmHref(item.href)}
onClick={(e) => handleOptimisticNav(e, item.key, item.href)}
className={`inline-flex items-center whitespace-nowrap rounded-full px-2.5 py-1.5 text-sm transition-colors duration-150 xl:px-3.5 ${
isActive
? `${pill.ready ? '' : 'bg-surface '}font-medium text-ink`
: 'text-slate hover:text-ink'
}`}
>
{item.label}
</a>
</li>
);
})}
</ul>
<div className="flex shrink-0 items-center gap-1 sm:gap-1.5 lg:col-start-3 lg:justify-self-end">
<a
href={langHref}
onPointerEnter={() => warmHref(langHref)}
aria-label={strings.nav.langSwitchAria}
className="inline-flex h-8 min-w-8 shrink-0 items-center justify-center whitespace-nowrap rounded-full border border-border-strong px-2 text-[12px] font-medium text-slate transition-[color,background-color,transform] duration-150 hover:bg-surface hover:text-ink active:scale-95"
>
{strings.nav.langSwitchLabel}
</a>
<button
type="button"
onClick={() => setSearchOpen(true)}
aria-label={strings.nav.searchAria}
title="Ctrl+K"
className="grid size-8 shrink-0 place-items-center rounded-full border border-border-strong text-slate transition-[color,background-color,transform] duration-150 hover:bg-surface hover:text-ink active:scale-95 sm:border-transparent"
>
<Search className="size-[16px]" aria-hidden="true" />
</button>
<button
type="button"
onClick={toggleTheme}
aria-label={strings.nav.themeAria}
aria-pressed={dark}
className="grid size-8 shrink-0 place-items-center rounded-full border border-border-strong text-slate transition-[color,background-color,transform] duration-150 hover:bg-surface hover:text-ink active:scale-95 sm:border-transparent"
>
<Sun
className={`col-start-1 row-start-1 size-[17px] transition-[opacity,filter] duration-250 motion-reduce:transition-none ${
dark ? 'opacity-100 blur-none' : 'opacity-0 blur-[3px]'
}`}
aria-hidden="true"
/>
<Moon
className={`col-start-1 row-start-1 size-[16px] transition-[opacity,filter] duration-250 motion-reduce:transition-none ${
dark ? 'opacity-0 blur-[3px]' : 'opacity-100 blur-none'
}`}
aria-hidden="true"
/>
</button>
<a
href="https://github.com/Nwflower/Reims-Go"
target="_blank"
rel="noopener noreferrer"
aria-label={`GitHub Reims-Go · ${strings.nav.starPrefix} ${formatStars(release.stars)}`}
className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full border border-border-strong px-2.5 text-[13px] font-medium text-ink transition-colors duration-150 hover:bg-surface sm:px-3"
>
<svg viewBox="0 0 24 24" className="size-[15px] fill-current" aria-hidden="true">
<path d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.53 1.032 1.53 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0 1 12 6.844a9.59 9.59 0 0 1 2.504.337c1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.02 10.02 0 0 0 22 12.017C22 6.484 17.522 2 12 2Z" />
</svg>
<span className="tnum hidden items-center gap-1 sm:inline-flex">
<span className="text-slate">{strings.nav.starPrefix}</span>
<span>{formatStars(release.stars)}</span>
</span>
</a>
<button
type="button"
onClick={() => setMobileOpen((v) => !v)}
aria-label={locale === 'zh-CN' ? (mobileOpen ? '关闭导航菜单' : '打开导航菜单') : (mobileOpen ? 'Close menu' : 'Open menu')}
aria-expanded={mobileOpen}
className="grid size-8 shrink-0 place-items-center rounded-full border border-border-strong text-slate transition-colors hover:text-ink lg:hidden"
>
{mobileOpen ? <X className="size-4" aria-hidden="true" /> : <Menu className="size-4" aria-hidden="true" />}
</button>
</div>
</nav>
{/* Ultra-thin non-intrusive loading bar (visible only when an uncached route takes >100ms) */}
<div
aria-hidden="true"
className={`pointer-events-none absolute inset-x-0 bottom-0 h-[2px] overflow-hidden transition-opacity duration-150 ${
navPending ? 'opacity-100' : 'opacity-0'
}`}
>
<div className="reims-nav-progress-bar h-full w-1/3 rounded-full bg-accent" />
</div>
{/* Mobile Dropdown Drawer with Backdrop Outside-Click Dismissal */}
{mobileOpen && (
<>
<div
aria-hidden="true"
onClick={() => setMobileOpen(false)}
className="fixed inset-0 top-14 z-30 bg-black/15 lg:hidden"
/>
<div className="fixed inset-x-0 top-14 z-40 border-b border-border bg-canvas/95 px-5 py-3 shadow-lg backdrop-blur-xl lg:hidden">
<ul className="flex flex-col gap-1">
{navItems.map((item) => {
const isActive = activeSection === item.key;
return (
<li key={item.key}>
<a
href={item.href}
aria-current={isActive ? 'page' : undefined}
onPointerEnter={() => warmHref(item.href)}
onClick={(e) => handleOptimisticNav(e, item.key, item.href)}
className={`block rounded-xl px-3 py-2.5 text-sm transition-colors ${
isActive
? 'bg-surface font-medium text-ink'
: 'text-slate hover:bg-surface hover:text-ink'
}`}
>
{item.label}
</a>
</li>
);
})}
</ul>
</div>
</>
)}
<SearchModal open={searchOpen} onOpenChange={setSearchOpen} locale={locale} />
</>
);
};
+340
View File
@@ -0,0 +1,340 @@
import { Archive, ChevronDown, Download, ExternalLink, RefreshCw, ShieldCheck } from 'lucide-react';
import React, { useMemo, useState } from 'react';
import fallbackBundleRaw from '../../../public/data/releases-bundle.json';
import type { Locale } from '../../i18n/types';
import { formatBytes, useChangelogReleases, type ChangelogEntry, type ReleasesBundle } from '../../lib/releases';
const FALLBACK_ENTRIES: ChangelogEntry[] = Array.isArray((fallbackBundleRaw as ReleasesBundle).entries)
? (fallbackBundleRaw as ReleasesBundle).entries
: [];
interface Props {
locale: Locale;
}
/**
* Safe inline Markdown renderer for GitHub Release bullet lines:
* supports `inline code`, [label](https://...), and **bold** without innerHTML.
*/
function renderInlineMarkdown(text: string): React.ReactNode[] {
const tokens: React.ReactNode[] = [];
const pattern = /(`[^`]+`)|(\[([^\]]+)\]\((https?:\/\/[^\s)]+)\))|(\*\*([^*]+)\*\*)/g;
let lastIndex = 0;
let match: RegExpExecArray | null;
let keyIdx = 0;
while ((match = pattern.exec(text)) !== null) {
if (match.index > lastIndex) {
tokens.push(text.slice(lastIndex, match.index));
}
if (match[1]) {
tokens.push(
<code
key={`c-${keyIdx++}`}
className="break-words rounded-[5px] border border-border bg-surface px-1.5 py-0.5 font-mono text-[12px] text-ink"
>
{match[1].slice(1, -1)}
</code>,
);
} else if (match[2]) {
const label = match[3];
const href = match[4];
tokens.push(
<a
key={`a-${keyIdx++}`}
href={href}
target="_blank"
rel="noopener noreferrer"
className="font-medium text-accent underline decoration-accent/35 underline-offset-3 transition-colors hover:decoration-accent"
>
{label}
</a>,
);
} else if (match[5]) {
tokens.push(
<strong key={`b-${keyIdx++}`} className="font-semibold text-ink">
{match[6]}
</strong>,
);
}
lastIndex = pattern.lastIndex;
}
if (lastIndex < text.length) {
tokens.push(text.slice(lastIndex));
}
return tokens;
}
const COLLAPSE_SECTION_LIMIT = 2;
const ReleaseCard: React.FC<{
entry: ChangelogEntry;
isLatestStable: boolean;
locale: Locale;
}> = ({ entry, isLatestStable, locale }) => {
const isZh = locale === 'zh-CN';
const sections = entry.sections[locale]?.length ? entry.sections[locale] : entry.sections['zh-CN'];
const totalItems = sections.reduce((sum, s) => sum + s.items.length, 0);
const canCollapse = sections.length > COLLAPSE_SECTION_LIMIT && totalItems > 10;
const [expanded, setExpanded] = useState(false);
const visibleSections = canCollapse && !expanded ? sections.slice(0, COLLAPSE_SECTION_LIMIT) : sections;
const hiddenCount = canCollapse
? sections.slice(COLLAPSE_SECTION_LIMIT).reduce((sum, s) => sum + s.items.length, 0)
: 0;
return (
<article className="min-w-0 rounded-2xl border border-border bg-canvas p-5 transition-colors sm:p-7">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-2.5">
<a
href={entry.html_url}
target="_blank"
rel="noopener noreferrer"
className="font-mono text-xl font-semibold tracking-tight text-ink transition-colors hover:text-accent"
>
{entry.tag}
</a>
{isLatestStable && (
<span className="rounded-full bg-accent-soft px-2.5 py-0.5 text-xs font-medium text-accent">
{isZh ? '最新正式版' : 'Latest stable'}
</span>
)}
{entry.channel === 'dev' && (
<span className="rounded-full border border-amber-500/30 bg-amber-500/12 px-2.5 py-0.5 text-xs font-medium text-amber-700 dark:text-amber-300">
{isZh ? '开发版 Dev' : 'Dev rolling'}
</span>
)}
{entry.channel === 'alpha' && (
<span className="rounded-full border border-purple-500/30 bg-purple-500/12 px-2.5 py-0.5 text-xs font-medium text-purple-700 dark:text-purple-300">
Alpha
</span>
)}
</div>
<div className="flex items-center gap-3">
{entry.date && (
<time dateTime={entry.published_at || entry.date} className="tnum font-mono text-xs text-slate">
{entry.date}
</time>
)}
<a
href={entry.html_url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs font-medium text-slate transition-colors hover:text-ink"
>
<span>GitHub</span>
<ExternalLink className="size-3" aria-hidden="true" />
</a>
</div>
</div>
{/* Direct Release Asset Chips */}
{(entry.exe || entry.zip || entry.sha256_url) && (
<div className="mt-4 flex flex-wrap items-center gap-2">
{entry.exe && (
<a
href={entry.exe.url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex h-7 items-center gap-1.5 rounded-full border border-border-strong bg-surface px-3 text-xs font-medium text-ink transition-colors hover:border-accent/50 hover:text-accent"
>
<Download className="size-3 shrink-0" aria-hidden="true" />
<span>EXE</span>
{entry.exe.size > 0 && <span className="tnum text-[11px] text-slate">({formatBytes(entry.exe.size)})</span>}
</a>
)}
{entry.zip && (
<a
href={entry.zip.url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex h-7 items-center gap-1.5 rounded-full border border-border bg-surface px-3 text-xs font-medium text-slate transition-colors hover:border-border-strong hover:text-ink"
>
<Archive className="size-3 shrink-0" aria-hidden="true" />
<span>ZIP</span>
{entry.zip.size > 0 && <span className="tnum text-[11px] opacity-80">({formatBytes(entry.zip.size)})</span>}
</a>
)}
{entry.sha256_url && (
<a
href={entry.sha256_url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex h-7 items-center gap-1 rounded-full border border-border bg-canvas px-2.5 font-mono text-[11px] text-slate transition-colors hover:border-border-strong hover:text-ink"
>
<ShieldCheck className="size-3 shrink-0 text-[#188c2c] dark:text-[#30d158]" aria-hidden="true" />
<span>SHA256SUMS.txt</span>
</a>
)}
</div>
)}
{/* Categorized Release Notes */}
{visibleSections.length > 0 ? (
<div className="mt-5 flex flex-col gap-4">
{visibleSections.map((sec, sIdx) => (
<div key={`${entry.tag}-sec-${sIdx}`}>
{sec.title && (
<h3 className="mb-2 text-[13px] font-semibold text-ink">
{renderInlineMarkdown(sec.title)}
</h3>
)}
<ul className="flex list-disc flex-col gap-2 pl-4 text-sm leading-relaxed text-slate">
{sec.items.map((item, iIdx) => (
<li key={`${entry.tag}-${sIdx}-${iIdx}`} className="break-words">
{renderInlineMarkdown(item)}
</li>
))}
</ul>
</div>
))}
</div>
) : (
<p className="mt-4 text-sm text-slate">
{isZh ? '详见 GitHub Release 完整发布说明。' : 'See full release notes on GitHub.'}
</p>
)}
{canCollapse && (
<button
type="button"
aria-expanded={expanded}
onClick={() => setExpanded((v) => !v)}
className="mt-4 inline-flex items-center gap-1.5 rounded-full border border-border bg-surface px-3.5 py-1.5 text-xs font-medium text-ink transition-colors hover:border-border-strong"
>
<span>
{expanded
? isZh
? '收起详细变更'
: 'Show fewer changes'
: isZh
? `展开其余 ${hiddenCount} 条变更`
: `Show ${hiddenCount} more changes`}
</span>
<ChevronDown
className={`size-3.5 transition-transform duration-200 ${expanded ? 'rotate-180' : ''}`}
aria-hidden="true"
/>
</button>
)}
</article>
);
};
export const ChangelogFeed: React.FC<Props> = ({ locale }) => {
const isZh = locale === 'zh-CN';
const { entries, latest, live, loading, source, syncedAt, refresh } = useChangelogReleases(FALLBACK_ENTRIES);
const [channelFilter, setChannelFilter] = useState<'stable' | 'all'>('stable');
const stableCount = useMemo(() => entries.filter((e) => e.channel === 'stable').length, [entries]);
const visibleEntries = useMemo(
() => (channelFilter === 'stable' ? entries.filter((e) => e.channel === 'stable') : entries),
[entries, channelFilter],
);
const formattedSync = useMemo(() => {
if (!live || !syncedAt) return '';
try {
const d = new Date(syncedAt);
if (Number.isNaN(d.getTime())) return '';
return new Intl.DateTimeFormat(isZh ? 'zh-CN' : 'en-US', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).format(d);
} catch {
return '';
}
}, [live, syncedAt, isZh]);
const sourceLabel = useMemo(() => {
if (source === 'edge-api') return isZh ? '实时同步自 GitHub Releases(边缘缓存)' : 'Live from GitHub Releases (Edge cached)';
if (source === 'github-direct') return isZh ? '实时同步自 GitHub API' : 'Live from GitHub API';
if (loading) return isZh ? '已载入构建同步快照,正在拉取最新记录…' : 'Loaded synced snapshot; checking GitHub…';
return isZh ? '当前显示离线同步快照(点击右侧刷新重试)' : 'Showing synced snapshot (click refresh to retry)';
}, [source, loading, isZh]);
return (
<div className="flex flex-col gap-6">
{/* Live Sync Status & Channel Segmented Control */}
<div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-border bg-surface px-4 py-3">
<div className="flex flex-wrap items-center gap-2 text-xs text-slate">
<span
className={`size-2 shrink-0 rounded-full ${live ? 'bg-[#28cd41]' : 'bg-accent'}`}
aria-hidden="true"
/>
<span className="font-medium text-ink">{latest.version}</span>
<span>·</span>
<span>{sourceLabel}</span>
{formattedSync && <span className="tnum hidden sm:inline">({formattedSync})</span>}
</div>
<div className="flex items-center gap-2">
<div
role="group"
aria-label={isZh ? '版本通道筛选' : 'Release channel filter'}
className="inline-flex rounded-full border border-border bg-canvas p-0.5 text-xs"
>
<button
type="button"
aria-pressed={channelFilter === 'stable'}
onClick={() => setChannelFilter('stable')}
className={`rounded-full px-3 py-1 font-medium transition-colors ${
channelFilter === 'stable'
? 'bg-accent text-white'
: 'text-slate hover:text-ink'
}`}
>
{isZh ? `正式版 (${stableCount})` : `Stable (${stableCount})`}
</button>
<button
type="button"
aria-pressed={channelFilter === 'all'}
onClick={() => setChannelFilter('all')}
className={`rounded-full px-3 py-1 font-medium transition-colors ${
channelFilter === 'all'
? 'bg-accent text-white'
: 'text-slate hover:text-ink'
}`}
>
{isZh ? `含预览 (${entries.length})` : `All (${entries.length})`}
</button>
</div>
<button
type="button"
onClick={refresh}
disabled={loading}
title={isZh ? '立即从 GitHub 拉取最新版本' : 'Refresh releases from GitHub'}
aria-label={isZh ? '刷新版本列表' : 'Refresh releases'}
className="grid size-8 shrink-0 place-items-center rounded-full border border-border-strong bg-canvas text-slate transition-colors hover:bg-surface hover:text-ink disabled:opacity-50"
>
<RefreshCw className={`size-3.5 ${loading ? 'animate-spin' : ''}`} aria-hidden="true" />
</button>
</div>
</div>
{/* Release Cards */}
<div className="flex flex-col gap-5">
{visibleEntries.map((entry) => (
<ReleaseCard
key={entry.tag}
entry={entry}
isLatestStable={entry.channel === 'stable' && entry.tag === latest.version}
locale={locale}
/>
))}
</div>
</div>
);
};
+6 -166
View File
@@ -3,6 +3,7 @@ import BaseLayout from '../../layouts/BaseLayout.astro';
import { t } from '../../i18n/translations'; import { t } from '../../i18n/translations';
import type { Locale } from '../../i18n/types'; import type { Locale } from '../../i18n/types';
import { buildSubpageJsonLd } from '../../lib/seo'; import { buildSubpageJsonLd } from '../../lib/seo';
import { ChangelogFeed } from './ChangelogFeed';
interface Props { interface Props {
locale: Locale; locale: Locale;
@@ -10,148 +11,8 @@ interface Props {
const { locale } = Astro.props; const { locale } = Astro.props;
const isZh = locale === 'zh-CN'; const isZh = locale === 'zh-CN';
const releases = isZh
? [
{
version: 'v0.2.11',
date: '2026-12-01',
tag: '最新正式版',
highlights: [
'Intel 虚拟机支持运行中热挂起并保存内存与图形状态,下次启动恢复会话(需 Alpha 通道 vm-suspend 运行时)',
'Guest Tools v8 支持按虚拟机管理宿主机共享文件夹,并统一 WebDAV 与同步路径边界检查',
'「镜像」页取代「安装包」页,内置并行分片下载器并支持插件扩展下载器与镜像源',
'发布插件 UI 契约 uiApi 2.0 与桥接契约 bridgeApi 1.0;全屏切换保留客体 1.5× HiDPI 分辨率',
'支持按虚拟机重映射 Windows 修饰键(含 Win → Command)、OpenCore SMBIOS 轮换与 qcow2 extended_l2',
],
},
{
version: 'v0.2.10',
date: '2026-11-30',
highlights: [
'新增 reims-go plugin pack 打包命令,自动执行静态扫描、生成 SHA256SUMS 与 Ed25519 签名验证',
'插件市场默认读取 reims-go/plugins 组织仓库,主源不可用时自动回退至 jsDelivr 镜像',
'修复虚拟机中物理键盘输入偶发重复或错序,以及中文拼音首字母重复',
],
},
{
version: 'v0.2.9',
date: '2026-11-30',
highlights: [
'本地化 v2 支持区域回退、ICU 复数格式化与第三方语言包,新增 plugin locale init|check',
'「插件」页新增官方市场标签页,CLI 支持 plugin search / install / update',
'「关于」页支持在 stable、alpha 与 dev 更新通道间切换,并保留测试版回滚备份',
'FileVault 预启动界面支持鼠标和数字键盘输入;新增系统盘小文件 I/O 基准工具',
],
},
{
version: 'v0.2.8',
date: '2026-11-29',
highlights: [
'客户端和 reims-go doctor 检查 Vulkan 1.3、PCI ID 与扩展,提示风险显卡并提供 VMware SVGA 切换',
'内置 .tar.zst 解压,修复 Windows 10 22H2 缺少 zstd 解压器无法安装运行时的问题',
'新建虚拟机默认自动显卡选择,正确识别 AMD 核显与 Intel Core Ultra 集成 Arc',
],
},
{
version: 'v0.2.7',
date: '2026-11-29',
highlights: [
'新增「插件」页、reims-go plugin 命令与 --safe-mode 安全恢复启动',
'新增「虚拟机窗口安装引导」插件,贴靠虚拟机窗口完成一键安装',
'新增「关于」页与应用内断点续传更新(SHA256SUMS.txt 校验后原子替换重启)',
],
},
{
version: 'v0.2.6',
date: '2026-11-29',
highlights: [
'按虚拟机配置 P/E/LP-E 混合核 CPU 亲和性,运行中修改立即生效',
'停机创建、回滚与删除恢复点;SSH 一键打开终端、写入 ~/.ssh/config 与 VS Code 远程连接',
'支持拖拽文件到客户端直传共享文件夹;许可证切换为 Apache-2.0,同步提供 EXE 与 ZIP',
],
},
{
version: 'v0.2.3 — v0.2.1',
date: '2026-11-28',
highlights: [
'单一 reims-go.exe 合并 GUI 与 CLI 双模入口,CLI 启动虚拟机默认交接托盘托管',
'Guest Tools 双向图文剪贴板、共享文件夹、Windows 中文输入法与 Emoji 直输、防休眠开关',
'离线装机辅助盘 REIMSHELP 自动执行抹盘与安装;默认 NVMe 磁盘、CoW 派生副本与脱敏排障包',
],
},
]
: [
{
version: 'v0.2.11',
date: '2026-12-01',
tag: 'Latest stable',
highlights: [
'Suspend running Intel VMs with memory and graphics state and resume on next start (Alpha vm-suspend runtime)',
'Guest Tools v8 adds per-VM host shared folder management with unified path-boundary security checks',
'Images replaces Installers with built-in parallel chunk downloading and plugin-extensible sources',
'Published uiApi 2.0 and bridgeApi 1.0 plugin contracts; fullscreen preserves 1.5× HiDPI resolution',
'Per-VM Windows modifier remapping (Win → Command), OpenCore SMBIOS rotation, and qcow2 extended_l2',
],
},
{
version: 'v0.2.10',
date: '2026-11-30',
highlights: [
'Added reims-go plugin pack with static scanning, SHA256SUMS, and Ed25519 trusted keyring verification',
'Marketplace defaults to reims-go/plugins with automatic jsDelivr fallback',
'Fixed occasional duplicated or reordered physical keystrokes and Pinyin initial duplication',
],
},
{
version: 'v0.2.9',
date: '2026-11-30',
highlights: [
'Localization v2 with regional fallback, ICU plurals, third-party locale packs, and plugin locale init|check',
'Added dedicated Marketplace tab and CLI plugin search / install / update commands',
'Switch between stable, alpha, and dev update channels in About with automatic rollback backup',
'FileVault preboot mouse and numeric keypad input; system-disk small-file I/O benchmark tool',
],
},
{
version: 'v0.2.8',
date: '2026-11-29',
highlights: [
'Vulkan 1.3, PCI ID, and extension probing with risk warnings and VMware SVGA fallback',
'Built-in .tar.zst extraction for Windows 10 22H2 systems lacking zstd in system tar.exe',
'Automatic GPU selection for new VMs and improved AMD / Intel Core Ultra Arc iGPU detection',
],
},
{
version: 'v0.2.7',
date: '2026-11-29',
highlights: [
'Introduced Plugins page, reims-go plugin CLI, and --safe-mode startup recovery',
'Added docked VM Window Installation Guide plugin for one-click Recovery commands',
'Added About page and resumable in-app updates verified against SHA256SUMS.txt',
],
},
{
version: 'v0.2.6',
date: '2026-11-29',
highlights: [
'Per-VM hybrid CPU affinity (P/E/LP-E cores) applied live while VMs run',
'Restore points, SSH shortcuts (Terminal, ~/.ssh/config, VS Code Remote-SSH), and drag-and-drop file transfer',
'Switched client license to Apache-2.0 with standalone EXE and ZIP releases',
],
},
{
version: 'v0.2.3 — v0.2.1',
date: '2026-11-28',
highlights: [
'Merged GUI and CLI into a single reims-go.exe with seamless tray handoff',
'Bidirectional text/image clipboard, shared folders, Windows IME + emoji bridge, and prevent-sleep toggle',
'REIMSHELP offline auto-install helper, NVMe default disks, instant CoW clones, and redacted diagnostics',
],
},
];
const pageTitle = isZh ? '更新日志' : 'Changelog'; const pageTitle = isZh ? '更新日志' : 'Changelog';
const pageDesc = isZh ? 'Reims-Go 客户端各正式版本功能演进与修复记录' : 'Release history and improvements for Reims-Go'; const pageDesc = isZh ? 'Reims-Go 客户端各正式版本功能演进与修复记录(实时同步自 GitHub Releases)' : 'Live client release history and improvements for Reims-Go synced from GitHub Releases';
const changelogJsonLd = buildSubpageJsonLd({ const changelogJsonLd = buildSubpageJsonLd({
locale, locale,
path: '/changelog', path: '/changelog',
@@ -179,42 +40,21 @@ const changelogJsonLd = buildSubpageJsonLd({
{isZh ? '更新日志' : 'Changelog'} {isZh ? '更新日志' : 'Changelog'}
</h1> </h1>
<p class="mt-2 text-[15px] text-slate"> <p class="mt-2 text-[15px] text-slate">
{isZh ? '记录 Reims-Go 客户端面向用户与集成方的全部变更,最新版本在前' : 'Client releases listed newest first'} {isZh ? '实时获取自 GitHub Releases,记录 Reims-Go 客户端各版本功能演进与修复' : 'Synced live from GitHub Releases, newest client builds first'}
</p> </p>
</div> </div>
<a <a
href="https://github.com/Nwflower/Reims-Go/releases" href="https://github.com/Nwflower/Reims-Go/releases"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
class="inline-flex h-9 items-center rounded-full border border-border-strong bg-canvas px-4 text-xs font-medium text-ink hover:bg-surface" class="inline-flex h-9 items-center rounded-full border border-border-strong bg-canvas px-4 text-xs font-medium text-ink transition-colors hover:bg-surface"
> >
GitHub Releases ↗ GitHub Releases ↗
</a> </a>
</div> </div>
</section> </section>
<section class="mx-auto max-w-4xl px-5 py-12 sm:px-8"> <section class="mx-auto max-w-4xl px-5 py-10 sm:px-8 sm:py-12">
<div class="flex flex-col gap-6"> <ChangelogFeed client:load locale={locale} />
{releases.map((rel) => (
<article class="rounded-2xl border border-border bg-canvas p-6 sm:p-7">
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="flex items-center gap-2.5">
<h2 class="font-mono text-xl font-semibold text-ink">{rel.version}</h2>
{rel.tag && (
<span class="rounded-full bg-accent-soft px-2.5 py-0.5 text-xs font-medium text-accent">
{rel.tag}
</span>
)}
</div>
<time class="tnum font-mono text-xs text-slate">{rel.date}</time>
</div>
<ul class="mt-4 flex flex-col gap-2.5 pl-4 text-sm leading-relaxed text-slate list-disc">
{rel.highlights.map((h) => (
<li>{h}</li>
))}
</ul>
</article>
))}
</div>
</section> </section>
</BaseLayout> </BaseLayout>
+2 -2
View File
@@ -22,11 +22,11 @@ Verify your host machine meets the following requirements before starting:
## First launch and environment check ## First launch and environment check
1. Download `reims-go-v0.2.11-windows-amd64.exe` (or the `.zip` archive) from [GitHub Releases](https://github.com/Nwflower/Reims-Go/releases/latest). 1. Download the latest `reims-go-<version>-windows-amd64.exe` (or the `.zip` archive) from [GitHub Releases](https://github.com/Nwflower/Reims-Go/releases/latest).
2. Verify the binary against the release `SHA256SUMS.txt`: 2. Verify the binary against the release `SHA256SUMS.txt`:
```powershell ```powershell
Get-FileHash .\reims-go-v0.2.11-windows-amd64.exe -Algorithm SHA256 Get-FileHash .\reims-go-*-windows-amd64.exe -Algorithm SHA256
``` ```
3. Because the binary is currently unsigned, click **More info** and then **Run anyway** if Windows SmartScreen prompts on first launch. 3. Because the binary is currently unsigned, click **More info** and then **Run anyway** if Windows SmartScreen prompts on first launch.
+2 -2
View File
@@ -22,11 +22,11 @@ Reims-Go 是面向 64 位 Windows 10 与 Windows 11 的免编译 macOS 虚拟机
## 首次启动与环境预检 ## 首次启动与环境预检
1. 从 [GitHub Releases](https://github.com/Nwflower/Reims-Go/releases/latest) 下载 `reims-go-v0.2.11-windows-amd64.exe` 或对应的 `.zip` 压缩包。 1. 从 [GitHub Releases](https://github.com/Nwflower/Reims-Go/releases/latest) 下载最新版 `reims-go-<version>-windows-amd64.exe` 或对应的 `.zip` 压缩包。
2. 如需核对完整性,对照发布页附带的 `SHA256SUMS.txt` 执行校验: 2. 如需核对完整性,对照发布页附带的 `SHA256SUMS.txt` 执行校验:
```powershell ```powershell
Get-FileHash .\reims-go-v0.2.11-windows-amd64.exe -Algorithm SHA256 Get-FileHash .\reims-go-*-windows-amd64.exe -Algorithm SHA256
``` ```
3. 首次双击运行时,若 Windows SmartScreen 弹出未签名提示,点击「更多信息」再选择「仍要运行」。 3. 首次双击运行时,若 Windows SmartScreen 弹出未签名提示,点击「更多信息」再选择「仍要运行」。
+2 -2
View File
@@ -322,7 +322,7 @@ export const TRANSLATIONS: Record<Locale, SiteStrings> = {
prevLabel: '上一篇', prevLabel: '上一篇',
nextLabel: '下一篇', nextLabel: '下一篇',
homeLink: '返回官网首页', homeLink: '返回官网首页',
versionBadge: '适用版本 v0.2.11+', versionBadge: '最新正式版',
groups: [ groups: [
{ {
title: '入门指南', title: '入门指南',
@@ -717,7 +717,7 @@ export const TRANSLATIONS: Record<Locale, SiteStrings> = {
prevLabel: 'Previous', prevLabel: 'Previous',
nextLabel: 'Next', nextLabel: 'Next',
homeLink: 'Back to Home', homeLink: 'Back to Home',
versionBadge: 'For v0.2.11+', versionBadge: 'Latest stable',
groups: [ groups: [
{ {
title: 'Getting started', title: 'Getting started',
+7 -4
View File
@@ -11,7 +11,8 @@ export function localeFromPath(pathname: string): Locale {
} }
export function localizedPath(locale: Locale, path: string): string { export function localizedPath(locale: Locale, path: string): string {
const clean = path.startsWith('/') ? path : `/${path}`; // Collapse leading slashes so protocol-relative paths like //evil.com can never be emitted.
const clean = `/${path.replace(/^\/+/, '')}`;
if (locale === 'en-US') { if (locale === 'en-US') {
return clean === '/' ? '/en' : `/en${clean}`; return clean === '/' ? '/en' : `/en${clean}`;
} }
@@ -19,11 +20,13 @@ export function localizedPath(locale: Locale, path: string): string {
} }
export function switchLocalePath(pathname: string, target: Locale): string { export function switchLocalePath(pathname: string, target: Locale): string {
const stripped = pathname.replace(/^\/en(?=\/|$)/, '') || '/'; const normalized = `/${pathname.replace(/^\/+/, '')}`;
if (/^\/404(?:\.html|\/)?$/i.test(stripped)) { const stripped = normalized.replace(/^\/en(?=\/|$)/, '') || '/';
const safePath = `/${stripped.replace(/^\/+/, '')}`;
if (/^\/404(?:\.html|\/)?$/i.test(safePath)) {
return localizedPath(target, '/'); return localizedPath(target, '/');
} }
return localizedPath(target, stripped); return localizedPath(target, safePath);
} }
export interface SiteStrings { export interface SiteStrings {
+255 -5
View File
@@ -105,7 +105,15 @@ const markdownAltUrl = markdownAlternate ? canonicalUrl(markdownAlternate) : nul
<meta name="twitter:image" content={ogImageUrl} /> <meta name="twitter:image" content={ogImageUrl} />
<meta name="twitter:image:alt" content={ogImageAlt} /> <meta name="twitter:image:alt" content={ogImageAlt} />
{jsonLd && <script type="application/ld+json" set:html={JSON.stringify(jsonLd)} />} {jsonLd && (
<script
type="application/ld+json"
set:html={JSON.stringify(jsonLd)
.replace(/</g, '\\u003c')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')}
/>
)}
<ClientRouter /> <ClientRouter />
<script is:inline> <script is:inline>
@@ -127,11 +135,253 @@ const markdownAltUrl = markdownAlternate ? canonicalUrl(markdownAlternate) : nul
applyTheme(document); applyTheme(document);
if (!window.__reimsThemeSwapBound) { if (window.__reimsNavEngineBound) return;
window.__reimsThemeSwapBound = true; window.__reimsNavEngineBound = true;
document.addEventListener('astro:before-swap', (ev) => {
if (ev && ev.newDocument) applyTheme(ev.newDocument); const CACHE_TTL_MS = 5 * 60 * 1000;
const MAX_CACHE = 32;
const htmlCache = new Map();
const inflight = new Map();
let lastNavAt = 0;
let warmupTimer = null;
const stripQuery = (path) => (path || '/').split('?')[0];
const isEnPath = (path) => {
const base = stripQuery(path);
return base === '/en' || base.startsWith('/en/');
};
const normPath = (input) => {
try {
const u = new URL(input, window.location.origin);
if (u.origin !== window.location.origin) return null;
// Reject protocol-relative paths (e.g. //evil.com/...) so fetch can never resolve cross-origin
if (u.pathname.startsWith('//')) return null;
const clean = u.pathname.replace(/\/+$/, '');
return (clean === '' ? '/' : clean) + (u.search || '');
} catch (_) {
return null;
}
};
const sectionOrder = (path) => {
const base = stripQuery(path);
const stripped = isEnPath(base) ? (base.slice(3) || '/') : base;
if (stripped === '/') return 0;
if (stripped.startsWith('/docs')) return 1;
if (stripped.startsWith('/plugins')) return 2;
if (stripped.startsWith('/compatibility')) return 3;
if (stripped.startsWith('/changelog')) return 4;
return -1;
};
const putCache = (key, html) => {
if (!key || !html) return;
if (htmlCache.has(key)) htmlCache.delete(key);
htmlCache.set(key, { html, ts: Date.now() });
if (htmlCache.size > MAX_CACHE) {
const oldest = htmlCache.keys().next().value;
if (oldest) htmlCache.delete(oldest);
}
};
const getFreshCache = (key) => {
const hit = htmlCache.get(key);
if (!hit) return null;
if (Date.now() - hit.ts > CACHE_TTL_MS) {
htmlCache.delete(key);
return null;
}
return hit.html;
};
const raceWithAbort = (promise, signal) => {
if (!signal) return promise;
if (signal.aborted) return Promise.reject(new DOMException('Aborted', 'AbortError'));
return new Promise((resolve, reject) => {
const onAbort = () => reject(new DOMException('Aborted', 'AbortError'));
signal.addEventListener('abort', onAbort, { once: true });
promise.then(
(val) => {
signal.removeEventListener('abort', onAbort);
resolve(val);
},
(err) => {
signal.removeEventListener('abort', onAbort);
reject(err);
},
);
}); });
};
const fetchHtml = (key, signal) => {
const cached = getFreshCache(key);
if (cached) return Promise.resolve(cached);
const existing = inflight.get(key);
if (existing) return raceWithAbort(existing, signal);
const fullUrl = new URL(key, window.location.origin).href;
const p = fetch(fullUrl, {
credentials: 'same-origin',
headers: { Accept: 'text/html' },
})
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
// Guard against cross-origin redirects before parsing HTML
const finalOrigin = new URL(res.url, window.location.origin).origin;
if (finalOrigin !== window.location.origin) throw new Error('Cross-origin redirect');
const ct = res.headers.get('content-type') || '';
if (!ct.includes('text/html')) throw new Error('Non-HTML');
return res.text();
})
.then((html) => {
putCache(key, html);
return html;
})
.finally(() => {
if (inflight.get(key) === p) inflight.delete(key);
});
inflight.set(key, p);
return raceWithAbort(p, signal);
};
const prefetchUrl = (href) => {
const key = normPath(href);
if (!key) return;
if (getFreshCache(key) || inflight.has(key)) return;
// Skip non-HTML asset / API / raw markdown links
const base = stripQuery(key);
if (/\.(xml|txt|md|json|zip|exe|svg|png|pdf|webmanifest)$/i.test(base) || base.startsWith('/api/')) return;
fetchHtml(key).catch(() => {});
};
window.__reimsPrefetchUrl = prefetchUrl;
const warmTopLevelRoutes = () => {
warmupTimer = null;
const conn = navigator.connection;
if (conn && (conn.saveData || conn.effectiveType === 'slow-2g' || conn.effectiveType === '2g')) return;
const curPath = normPath(window.location.href) || '/';
const curBase = stripQuery(curPath);
const isEn = isEnPath(curBase);
const prefix = isEn ? '/en' : '';
const routes = [
prefix || '/',
`${prefix}/docs/quick-start`,
`${prefix}/plugins`,
`${prefix}/compatibility`,
`${prefix}/changelog`,
];
routes.forEach((r) => prefetchUrl(r));
const altBase = isEn ? (curBase.slice(3) || '/') : (curBase === '/' ? '/en' : `/en${curBase}`);
prefetchUrl(altBase);
};
const scheduleWarmup = () => {
if (warmupTimer !== null) return;
if (typeof window.requestIdleCallback === 'function') {
warmupTimer = window.requestIdleCallback(warmTopLevelRoutes, { timeout: 900 });
} else {
warmupTimer = window.setTimeout(warmTopLevelRoutes, 180);
}
};
const warmFromTarget = (target) => {
if (!target || typeof target.closest !== 'function') return;
const a = target.closest('a[href]');
if (!a || a.target === '_blank' || a.hasAttribute('download')) return;
const href = a.getAttribute('href');
if (!href || href.startsWith('#') || href.startsWith('mailto:') || href.startsWith('javascript:')) return;
prefetchUrl(a.href);
};
document.addEventListener('pointerenter', (e) => warmFromTarget(e.target), { capture: true, passive: true });
document.addEventListener('touchstart', (e) => warmFromTarget(e.target), { capture: true, passive: true });
document.addEventListener('focusin', (e) => warmFromTarget(e.target), { capture: true, passive: true });
document.addEventListener('astro:before-preparation', (ev) => {
const toKey = normPath(ev.to.href);
const fromKey = normPath(ev.from.href);
const now = Date.now();
const rapid = now - lastNavAt < 280;
lastNavAt = now;
const fromOrder = sectionOrder(fromKey);
const toOrder = sectionOrder(toKey);
const sameLocale = isEnPath(fromKey) === isEnPath(toKey);
let dir = 'fade';
if (sameLocale && fromOrder >= 0 && toOrder >= 0 && fromOrder !== toOrder) {
dir = toOrder > fromOrder ? 'forward' : 'backward';
}
document.documentElement.dataset.navDir = dir;
document.documentElement.dataset.rapidNav = rapid ? 'true' : 'false';
const isCached = Boolean(toKey && (getFreshCache(toKey) || inflight.has(toKey)));
window.dispatchEvent(
new CustomEvent('reims:nav-start', {
detail: { to: ev.to.pathname, from: ev.from.pathname, cached: isCached },
}),
);
// Always clean up loading state if Astro aborts this navigation (e.g. rapid click or #anchor)
if (ev.signal) {
ev.signal.addEventListener(
'abort',
() => {
window.dispatchEvent(new CustomEvent('reims:nav-end'));
},
{ once: true },
);
}
// Only intercept when we have a validated cache hit or active hover-prefetch;
// cold routes fall through cleanly to Astro's defaultLoader (preserving stylesheet preloads,
// redirects, and avoiding double fetches on 404).
if (!toKey || !isCached) return;
const originalLoader = ev.loader;
ev.loader = async () => {
try {
const html = getFreshCache(toKey) || (await fetchHtml(toKey, ev.signal));
if (ev.signal && ev.signal.aborted) return;
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
doc.querySelectorAll('noscript').forEach((el) => el.remove());
if (!doc.querySelector('meta[name="astro-view-transitions-enabled"]')) {
await originalLoader();
return;
}
ev.newDocument = doc;
} catch (_) {
if (ev.signal && ev.signal.aborted) return;
await originalLoader();
}
};
});
document.addEventListener('astro:before-swap', (ev) => {
if (ev && ev.newDocument) {
applyTheme(ev.newDocument);
ev.newDocument.documentElement.dataset.navDir = document.documentElement.dataset.navDir || 'fade';
ev.newDocument.documentElement.dataset.rapidNav = document.documentElement.dataset.rapidNav || 'false';
}
});
document.addEventListener('astro:after-swap', () => {
window.dispatchEvent(new CustomEvent('reims:nav-end'));
});
document.addEventListener('astro:page-load', () => {
scheduleWarmup();
});
if (document.readyState === 'complete') {
scheduleWarmup();
} else {
window.addEventListener('load', scheduleWarmup, { once: true });
} }
})(); })();
</script> </script>
+3 -4
View File
@@ -3,6 +3,7 @@ import BaseLayout from './BaseLayout.astro';
import { t } from '../i18n/translations'; import { t } from '../i18n/translations';
import { localizedPath, type Locale } from '../i18n/types'; import { localizedPath, type Locale } from '../i18n/types';
import { buildDocsJsonLd } from '../lib/seo'; import { buildDocsJsonLd } from '../lib/seo';
import { DocsVersionBadge } from '../components/layout/DocsVersionBadge';
interface Heading { interface Heading {
depth: number; depth: number;
@@ -44,7 +45,7 @@ const markdownAlternate = localizedPath(locale, `/docs/${currentSlug}.md`);
<!-- Mobile Collapsible Docs Navigation (<lg) --> <!-- Mobile Collapsible Docs Navigation (<lg) -->
<div class="border-b border-border bg-surface px-4 py-3 lg:hidden"> <div class="border-b border-border bg-surface px-4 py-3 lg:hidden">
<details class="group rounded-xl border border-border bg-canvas"> <details class="group rounded-xl border border-border bg-canvas">
<summary class="flex cursor-pointer list-none items-center justify-between px-3.5 py-2.5 text-sm font-medium text-ink"> <summary class="flex cursor-pointer list-none items-center justify-between px-3.5 py-2.5 text-sm font-medium text-ink [&::-webkit-details-marker]:hidden">
<span class="truncate">{strings.docs.badge} · {title}</span> <span class="truncate">{strings.docs.badge} · {title}</span>
<span class="ml-2 shrink-0 text-xs text-slate transition-transform group-open:rotate-180">▾</span> <span class="ml-2 shrink-0 text-xs text-slate transition-transform group-open:rotate-180">▾</span>
</summary> </summary>
@@ -115,9 +116,7 @@ const markdownAlternate = localizedPath(locale, `/docs/${currentSlug}.md`);
<div class="mx-auto max-w-[740px]"> <div class="mx-auto max-w-[740px]">
<div class="flex flex-wrap items-center justify-between gap-2 text-xs text-slate"> <div class="flex flex-wrap items-center justify-between gap-2 text-xs text-slate">
<span>{strings.docs.badge} / {sectionTitle} / {title}</span> <span>{strings.docs.badge} / {sectionTitle} / {title}</span>
<span class="rounded-full border border-border bg-surface px-2.5 py-0.5 font-mono text-[11px]"> <DocsVersionBadge client:load locale={locale} />
{strings.docs.versionBadge}
</span>
</div> </div>
<h1 class="mt-4 text-3xl font-semibold leading-tight text-ink sm:text-[32px]">{title}</h1> <h1 class="mt-4 text-3xl font-semibold leading-tight text-ink sm:text-[32px]">{title}</h1>
+1 -1
View File
@@ -17,7 +17,7 @@ export interface MarketEntry {
tier?: string; tier?: string;
homepage?: string; homepage?: string;
readme_url?: string; readme_url?: string;
engines?: Record<string, string>; engines?: Record<string, string | undefined>;
permissions?: string[]; permissions?: string[];
download_url: string; download_url: string;
sha256: string; sha256: string;
+249
View File
@@ -0,0 +1,249 @@
export interface ReleaseAsset {
name: string;
size: number;
url: string;
}
export interface ChangelogSection {
title: string;
items: string[];
}
export interface ChangelogEntry {
tag: string;
name: string;
published_at: string;
date: string;
html_url: string;
prerelease: boolean;
channel: 'stable' | 'alpha' | 'dev';
exe: ReleaseAsset | null;
zip: ReleaseAsset | null;
sha256_url: string | null;
sections: {
'zh-CN': ChangelogSection[];
'en-US': ChangelogSection[];
};
}
export interface RawGitHubAsset {
name?: string;
size?: number;
browser_download_url?: string;
digest?: string;
}
export interface RawGitHubRelease {
tag_name?: string;
name?: string;
draft?: boolean;
prerelease?: boolean;
published_at?: string;
created_at?: string;
html_url?: string;
body?: string;
assets?: RawGitHubAsset[];
}
const SKIP_SECTION_TITLES = new Set([
'下载',
'download',
'downloads',
'已知限制',
'known limitations',
'许可证',
'license',
'构建与许可证',
]);
function normalizeSectionTitle(raw: string): string {
return raw
.replace(/<[^>]+>/g, '')
.replace(/^#+\s*/, '')
.trim();
}
function shouldSkipSection(title: string): boolean {
const lower = title.toLowerCase();
if (SKIP_SECTION_TITLES.has(lower)) return true;
if (/^(已知限制|许可证|下载|known limitations|license|download)/i.test(lower)) return true;
return false;
}
function parseSectionBlocks(markdown: string): ChangelogSection[] {
const lines = markdown.replace(/\r\n/g, '\n').split('\n');
const sections: ChangelogSection[] = [];
let current: ChangelogSection | null = null;
let skipping = false;
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line) continue;
// Match markdown headings (### / ####) or inline HTML headings (<h3 ...>Title</h3>)
const htmlHeading = line.match(/^<h[2-4][^>]*>(.*?)<\/h[2-4]>$/i);
const mdHeading = !htmlHeading ? line.match(/^#{2,4}\s+(.+)$/) : null;
if (htmlHeading || mdHeading) {
const title = normalizeSectionTitle((htmlHeading ? htmlHeading[1] : mdHeading![1]) || '');
if (!title || shouldSkipSection(title)) {
skipping = true;
current = null;
} else {
skipping = false;
current = { title, items: [] };
sections.push(current);
}
continue;
}
if (skipping) continue;
// Skip navigation anchor links like "[中文](#cn-v0.2.12) | [English](#en-v0.2.12)"
if (/^\[中文\]\(#cn-/i.test(line)) continue;
// Skip blockquotes like Dev warning banners (handled via UI badge)
if (line.startsWith('>')) continue;
const bulletMatch = line.match(/^[-*]\s+(.+)$/);
if (bulletMatch) {
const itemText = bulletMatch[1].trim();
if (!itemText) continue;
if (!current) {
current = { title: '', items: [] };
sections.push(current);
}
current.items.push(itemText);
}
}
return sections.filter((s) => s.items.length > 0);
}
/**
* Splits a Reims-Go GitHub Release body into structured zh-CN and en-US changelog sections.
* Supports `<h3 id="cn-...">` / `<h3 id="en-...">` bilingual markers as well as single-language
* dev/alpha releases.
*/
export function parseBilingualReleaseBody(body: string): {
'zh-CN': ChangelogSection[];
'en-US': ChangelogSection[];
} {
const text = (body || '').replace(/\r\n/g, '\n');
if (!text.trim()) return { 'zh-CN': [], 'en-US': [] };
const cnMatch = text.match(/<h[2-4][^>]*\bid=["']cn-[^"']*["'][^>]*>/i);
const enMatch = text.match(/<h[2-4][^>]*\bid=["']en-[^"']*["'][^>]*>/i);
if (cnMatch && enMatch && cnMatch.index !== undefined && enMatch.index !== undefined) {
const cnStart = cnMatch.index;
const enStart = enMatch.index;
const cnChunk = cnStart < enStart ? text.slice(cnStart, enStart) : text.slice(cnStart);
const enChunk = enStart > cnStart ? text.slice(enStart) : text.slice(enStart, cnStart);
const zhSections = parseSectionBlocks(cnChunk);
const enSections = parseSectionBlocks(enChunk);
return {
'zh-CN': zhSections.length > 0 ? zhSections : enSections,
'en-US': enSections.length > 0 ? enSections : zhSections,
};
}
const fallback = parseSectionBlocks(text);
return { 'zh-CN': fallback, 'en-US': fallback };
}
export const CANONICAL_RELEASES_URL = 'https://github.com/Nwflower/Reims-Go/releases/latest';
export function sanitizeGitHubUrl(raw: string | null | undefined): string | null {
if (typeof raw !== 'string' || !raw.trim()) return null;
try {
const u = new URL(raw.trim());
if (u.protocol !== 'https:') return null;
const host = u.hostname.toLowerCase();
if (host === 'github.com' || host.endsWith('.githubusercontent.com')) {
return u.href;
}
return null;
} catch {
return null;
}
}
export function extractReleaseAssets(assets: RawGitHubAsset[] | undefined): {
exe: ReleaseAsset | null;
zip: ReleaseAsset | null;
sha256_url: string | null;
digestLines: string[];
} {
const list = Array.isArray(assets) ? assets : [];
const exeRaw = list.find((a) => typeof a.name === 'string' && /windows-amd64\.exe$/i.test(a.name));
const zipRaw = list.find((a) => typeof a.name === 'string' && /windows-amd64\.zip$/i.test(a.name));
const shaRaw = list.find((a) => typeof a.name === 'string' && /^SHA256SUMS\.txt$/i.test(a.name));
const exeUrl = sanitizeGitHubUrl(exeRaw?.browser_download_url);
const zipUrl = sanitizeGitHubUrl(zipRaw?.browser_download_url);
const shaUrl = sanitizeGitHubUrl(shaRaw?.browser_download_url);
const digestLines = [exeRaw, zipRaw]
.filter((a): a is RawGitHubAsset & { name: string; digest: string } =>
Boolean(a?.name && a?.digest && /^sha256:[a-f0-9]{64}$/i.test(a.digest)),
)
.map((a) => `${a.digest.replace(/^sha256:/i, '')} ${a.name}`);
return {
exe: exeRaw?.name && exeUrl ? { name: exeRaw.name, size: Number(exeRaw.size) || 0, url: exeUrl } : null,
zip: zipRaw?.name && zipUrl ? { name: zipRaw.name, size: Number(zipRaw.size) || 0, url: zipUrl } : null,
sha256_url: shaUrl,
digestLines,
};
}
export function classifyReleaseChannel(tag: string, prerelease: boolean): 'stable' | 'alpha' | 'dev' {
const lower = tag.toLowerCase();
if (lower === 'dev' || lower.includes('-dev')) return 'dev';
if (prerelease || lower.includes('alpha') || lower.includes('beta') || lower.includes('rc')) return 'alpha';
return 'stable';
}
export function isClientReleaseTag(tag: string): boolean {
if (!tag) return false;
if (/^runtime-/i.test(tag)) return false;
return /^v\d+\.\d+/i.test(tag) || /^dev$/i.test(tag) || /^alpha/i.test(tag);
}
export function normalizeGitHubReleases(rawList: RawGitHubRelease[]): ChangelogEntry[] {
const entries: ChangelogEntry[] = [];
for (const r of rawList) {
if (!r || r.draft) continue;
const tag = (r.tag_name || '').trim();
if (!isClientReleaseTag(tag)) continue;
const published = r.published_at || r.created_at || '';
const date = published ? published.slice(0, 10) : '';
const prerelease = Boolean(r.prerelease);
const channel = classifyReleaseChannel(tag, prerelease);
const { exe, zip, sha256_url } = extractReleaseAssets(r.assets);
const sections = parseBilingualReleaseBody(r.body || '');
entries.push({
tag,
name: (r.name || `Reims-Go ${tag}`).trim(),
published_at: published,
date,
html_url:
sanitizeGitHubUrl(r.html_url) ||
`https://github.com/Nwflower/Reims-Go/releases/tag/${encodeURIComponent(tag)}`,
prerelease,
channel,
exe,
zip,
sha256_url,
sections,
});
}
// Sort stable newest first by published_at, keeping dev/alpha properly ordered by date
return entries.sort((a, b) => {
if (a.channel === 'stable' && b.channel !== 'stable') return -1;
if (a.channel !== 'stable' && b.channel === 'stable') return 1;
return (b.published_at || '').localeCompare(a.published_at || '');
});
}
+301 -70
View File
@@ -1,11 +1,16 @@
import { useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import fallbackData from '../../public/data/releases.json'; import fallbackReleaseRaw from '../../public/data/releases.json';
import {
CANONICAL_RELEASES_URL,
extractReleaseAssets,
normalizeGitHubReleases,
sanitizeGitHubUrl,
type ChangelogEntry,
type RawGitHubRelease,
type ReleaseAsset,
} from './release-parser';
export interface ReleaseAsset { export type { ChangelogEntry, ChangelogSection, ReleaseAsset } from './release-parser';
name: string;
size: number;
url: string;
}
export interface ReleaseInfo { export interface ReleaseInfo {
synced_at: string; synced_at: string;
@@ -19,13 +24,26 @@ export interface ReleaseInfo {
sha256_sums: string; sha256_sums: string;
} }
export const FALLBACK_RELEASE: ReleaseInfo = fallbackData as ReleaseInfo; export interface ReleasesBundle {
source: 'edge-api' | 'github-direct' | 'static-fallback';
synced_at: string;
latest: ReleaseInfo;
entries: ChangelogEntry[];
}
const CACHE_KEY = 'reims-go-release-cache-v1'; export const FALLBACK_RELEASE: ReleaseInfo = fallbackReleaseRaw as ReleaseInfo;
const CACHE_TTL_MS = 10 * 60 * 1000; const INITIAL_EMPTY_BUNDLE: ReleasesBundle = {
source: 'static-fallback',
synced_at: FALLBACK_RELEASE.synced_at,
latest: FALLBACK_RELEASE,
entries: [],
};
const CACHE_KEY = 'reims-go-releases-bundle-v2';
const CACHE_TTL_MS = 5 * 60 * 1000;
export function formatStars(count: number): string { export function formatStars(count: number): string {
if (!Number.isFinite(count) || count <= 0) return '1.6k'; if (!Number.isFinite(count) || count <= 0) return '1.8k';
if (count >= 1000) { if (count >= 1000) {
return `${(count / 1000).toFixed(1)}k`; return `${(count / 1000).toFixed(1)}k`;
} }
@@ -49,74 +67,287 @@ export function extractShaForAsset(shaText: string, assetName?: string): string
return match ? match[1] : ''; return match ? match[1] : '';
} }
export function useLatestRelease(): { data: ReleaseInfo; live: boolean } { // ── Shared Singleton Reactive Store ────────────────────────────────────────────
const [data, setData] = useState<ReleaseInfo>(FALLBACK_RELEASE); // Deduplicates live GitHub/Edge fetches across Header, Hero, Download, Preview, and Changelog.
const [live, setLive] = useState(false); interface StoreSnapshot {
bundle: ReleasesBundle;
live: boolean;
loading: boolean;
}
useEffect(() => { const INITIAL_STORE_SNAPSHOT: StoreSnapshot = {
let active = true; bundle: INITIAL_EMPTY_BUNDLE,
live: false,
loading: false,
};
let storeState: StoreSnapshot = INITIAL_STORE_SNAPSHOT;
let lastFetchTs = 0;
let inflight: Promise<void> | null = null;
let inflightForced = false;
const listeners = new Set<() => void>();
function emit() {
for (const listener of listeners) listener();
}
function sanitizeAsset(asset: ReleaseAsset | null | undefined): ReleaseAsset | null {
if (!asset || typeof asset.name !== 'string') return null;
const safeUrl = sanitizeGitHubUrl(asset.url);
if (!safeUrl) return null;
return { name: asset.name, size: Number(asset.size) || 0, url: safeUrl };
}
function sanitizeEntry(entry: ChangelogEntry): ChangelogEntry {
return {
...entry,
html_url:
sanitizeGitHubUrl(entry.html_url) ||
`https://github.com/Nwflower/Reims-Go/releases/tag/${encodeURIComponent(entry.tag)}`,
exe: sanitizeAsset(entry.exe),
zip: sanitizeAsset(entry.zip),
sha256_url: sanitizeGitHubUrl(entry.sha256_url),
};
}
function sanitizeReleaseInfo(info: ReleaseInfo): ReleaseInfo {
return {
...info,
html_url: sanitizeGitHubUrl(info.html_url) || CANONICAL_RELEASES_URL,
exe: sanitizeAsset(info.exe),
zip: sanitizeAsset(info.zip),
sha256_url: sanitizeGitHubUrl(info.sha256_url),
};
}
function readCachedBundle(): ReleasesBundle | null {
if (typeof window === 'undefined') return null;
try {
const raw = sessionStorage.getItem(CACHE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as { ts?: number; bundle?: ReleasesBundle };
if (
parsed.ts &&
Date.now() - parsed.ts < CACHE_TTL_MS &&
parsed.bundle?.latest?.version &&
parsed.bundle.source !== 'static-fallback' &&
Array.isArray(parsed.bundle.entries)
) {
return {
...parsed.bundle,
latest: sanitizeReleaseInfo(parsed.bundle.latest),
entries: parsed.bundle.entries.map(sanitizeEntry),
};
}
} catch {
// Ignore storage failures in private browsing.
}
return null;
}
function writeCachedBundle(bundle: ReleasesBundle) {
if (typeof window === 'undefined' || bundle.source === 'static-fallback') return;
try {
sessionStorage.setItem(CACHE_KEY, JSON.stringify({ ts: Date.now(), bundle }));
} catch {
// Ignore quota errors.
}
}
async function fetchViaEdgeApi(): Promise<ReleasesBundle | null> {
const res = await fetch('/api/github/releases', {
headers: { Accept: 'application/json' },
});
if (!res.ok) return null;
const ct = res.headers.get('content-type') || '';
if (!ct.includes('application/json')) return null;
const data = (await res.json()) as ReleasesBundle;
if (!data?.latest?.version || !Array.isArray(data.entries)) return null;
const headerSource = res.headers.get('x-reims-source');
const resolvedSource: ReleasesBundle['source'] =
headerSource === 'static-fallback' || data.source === 'static-fallback' ? 'static-fallback' : data.source || 'edge-api';
const sameAsFallback = data.latest.version === FALLBACK_RELEASE.version;
return {
source: resolvedSource,
synced_at: data.synced_at || new Date().toISOString(),
latest: sanitizeReleaseInfo({
synced_at: data.latest.synced_at || data.synced_at || new Date().toISOString(),
stars: typeof data.latest.stars === 'number' ? data.latest.stars : FALLBACK_RELEASE.stars,
version: data.latest.version,
published_at: data.latest.published_at || (sameAsFallback ? FALLBACK_RELEASE.published_at : ''),
html_url: data.latest.html_url || CANONICAL_RELEASES_URL,
exe: data.latest.exe ?? (sameAsFallback ? FALLBACK_RELEASE.exe : null),
zip: data.latest.zip ?? (sameAsFallback ? FALLBACK_RELEASE.zip : null),
sha256_url: data.latest.sha256_url ?? (sameAsFallback ? FALLBACK_RELEASE.sha256_url : null),
sha256_sums: data.latest.sha256_sums || (sameAsFallback ? FALLBACK_RELEASE.sha256_sums : ''),
}),
entries: data.entries.length > 0 ? data.entries.map(sanitizeEntry) : storeState.bundle.entries,
};
}
async function fetchViaGitHubDirect(): Promise<ReleasesBundle | null> {
const headers = { Accept: 'application/vnd.github+json' };
const [repoRes, relRes] = await Promise.all([
fetch('https://api.github.com/repos/Nwflower/Reims-Go', { headers }).catch(() => null),
fetch('https://api.github.com/repos/Nwflower/Reims-Go/releases?per_page=25', { headers }).catch(() => null),
]);
const repo = repoRes?.ok ? ((await repoRes.json()) as { stargazers_count?: number }) : null;
const rawList = relRes?.ok ? ((await relRes.json()) as RawGitHubRelease[]) : null;
if (!repo && !Array.isArray(rawList)) return null;
const entries = Array.isArray(rawList) ? normalizeGitHubReleases(rawList) : storeState.bundle.entries;
const topEntry = entries.find((e) => e.channel === 'stable') || entries[0] || null;
const topRaw =
Array.isArray(rawList) && topEntry
? rawList.find((r) => (r.tag_name || '').trim() === topEntry.tag)
: undefined;
const topAssets = extractReleaseAssets(topRaw?.assets);
const nowIso = new Date().toISOString();
const sameAsFallback = !topEntry || topEntry.tag === FALLBACK_RELEASE.version;
const latest: ReleaseInfo = sanitizeReleaseInfo({
synced_at: nowIso,
stars: typeof repo?.stargazers_count === 'number' ? repo.stargazers_count : FALLBACK_RELEASE.stars,
version: topEntry?.tag || FALLBACK_RELEASE.version,
published_at: topEntry?.published_at || (sameAsFallback ? FALLBACK_RELEASE.published_at : nowIso),
html_url: topEntry?.html_url || FALLBACK_RELEASE.html_url,
exe: topEntry ? (topAssets.exe ?? (sameAsFallback ? FALLBACK_RELEASE.exe : null)) : FALLBACK_RELEASE.exe,
zip: topEntry ? (topAssets.zip ?? (sameAsFallback ? FALLBACK_RELEASE.zip : null)) : FALLBACK_RELEASE.zip,
sha256_url: topEntry
? (topAssets.sha256_url ?? (sameAsFallback ? FALLBACK_RELEASE.sha256_url : null))
: FALLBACK_RELEASE.sha256_url,
sha256_sums:
topAssets.digestLines.length > 0
? topAssets.digestLines.join('\n')
: sameAsFallback
? FALLBACK_RELEASE.sha256_sums
: '',
});
return {
source: 'github-direct',
synced_at: nowIso,
latest,
entries: entries.length > 0 ? entries : storeState.bundle.entries,
};
}
export async function refreshReleasesBundle(force = false): Promise<void> {
if (typeof window === 'undefined') return;
if (!force) {
if (storeState.live && Date.now() - lastFetchTs < CACHE_TTL_MS) return;
const cached = readCachedBundle();
if (cached) {
storeState = { bundle: cached, live: cached.source !== 'static-fallback', loading: false };
lastFetchTs = Date.now();
emit();
return;
}
}
if (inflight) {
if (!force || inflightForced) return inflight;
await inflight;
}
storeState = { ...storeState, loading: true };
emit();
inflightForced = force;
inflight = (async () => {
try { try {
const raw = sessionStorage.getItem(CACHE_KEY); let result: ReleasesBundle | null = null;
if (raw) { if (force) {
const parsed = JSON.parse(raw) as { ts: number; data: ReleaseInfo }; result = await fetchViaGitHubDirect().catch(() => null);
if (Date.now() - parsed.ts < CACHE_TTL_MS && parsed.data?.version) { if (!result) result = await fetchViaEdgeApi().catch(() => null);
setData(parsed.data); } else {
setLive(true); const edgeRes = await fetchViaEdgeApi().catch(() => null);
return; if (edgeRes && edgeRes.source !== 'static-fallback') {
result = edgeRes;
} else {
// Worker returned static-fallback or failed; try direct GitHub before settling on fallback
const directRes = await fetchViaGitHubDirect().catch(() => null);
result = directRes || edgeRes;
} }
} }
} catch {
// Ignore storage failures in private browsing.
}
const controller = new AbortController(); if (result) {
Promise.all([ const isLive = result.source !== 'static-fallback';
fetch('https://api.github.com/repos/Nwflower/Reims-Go', { signal: controller.signal }).then((r) => (r.ok ? r.json() : null)), storeState = { bundle: result, live: isLive, loading: false };
fetch('https://api.github.com/repos/Nwflower/Reims-Go/releases/latest', { signal: controller.signal }).then((r) => (r.ok ? r.json() : null)), if (isLive) {
]) lastFetchTs = Date.now();
.then(async ([repo, rel]) => { writeCachedBundle(result);
if (!active || (!repo && !rel)) return;
const assets: Array<{ name: string; size: number; browser_download_url: string; digest?: string }> = Array.isArray(rel?.assets) ? rel.assets : [];
const exeAsset = assets.find((a) => /windows-amd64\.exe$/i.test(a.name));
const zipAsset = assets.find((a) => /windows-amd64\.zip$/i.test(a.name));
const shaAsset = assets.find((a) => /^SHA256SUMS\.txt$/i.test(a.name));
const digestLines = [exeAsset, zipAsset]
.filter((a): a is NonNullable<typeof a> => Boolean(a?.digest && /^sha256:[a-f0-9]{64}$/i.test(a.digest)))
.map((a) => `${a.digest!.replace(/^sha256:/i, '')} ${a.name}`);
const shaText = digestLines.length > 0 ? digestLines.join('\n') : FALLBACK_RELEASE.sha256_sums;
const next: ReleaseInfo = {
synced_at: new Date().toISOString(),
stars: typeof repo?.stargazers_count === 'number' ? repo.stargazers_count : FALLBACK_RELEASE.stars,
version: rel?.tag_name || FALLBACK_RELEASE.version,
published_at: rel?.published_at || FALLBACK_RELEASE.published_at,
html_url: rel?.html_url || FALLBACK_RELEASE.html_url,
exe: exeAsset
? { name: exeAsset.name, size: exeAsset.size, url: exeAsset.browser_download_url }
: FALLBACK_RELEASE.exe,
zip: zipAsset
? { name: zipAsset.name, size: zipAsset.size, url: zipAsset.browser_download_url }
: FALLBACK_RELEASE.zip,
sha256_url: shaAsset?.browser_download_url || FALLBACK_RELEASE.sha256_url,
sha256_sums: shaText,
};
if (!active) return;
setData(next);
setLive(true);
try {
sessionStorage.setItem(CACHE_KEY, JSON.stringify({ ts: Date.now(), data: next }));
} catch {
// Ignore quota errors.
} }
}) } else {
.catch(() => { storeState = { ...storeState, loading: false };
// Keep static build-time fallback silently. }
}); } finally {
inflight = null;
inflightForced = false;
emit();
}
})();
return inflight;
}
function useReleasesStore(): StoreSnapshot & { refresh: () => void } {
// Always start from the deterministic build snapshot on the first render so SSR HTML
// and client hydration match identically even after client-side View Transitions when
// module-level `storeState` is already populated.
const [snap, setSnap] = useState<StoreSnapshot>(INITIAL_STORE_SNAPSHOT);
useEffect(() => {
const onUpdate = () => setSnap(storeState);
listeners.add(onUpdate);
onUpdate();
void refreshReleasesBundle(false);
return () => { return () => {
active = false; listeners.delete(onUpdate);
controller.abort();
}; };
}, []); }, []);
return { data, live }; const refresh = useCallback(() => {
void refreshReleasesBundle(true);
}, []);
return { ...snap, refresh };
}
export function useLatestRelease(): {
data: ReleaseInfo;
live: boolean;
source: ReleasesBundle['source'];
refresh: () => void;
} {
const { bundle, live, refresh } = useReleasesStore();
return {
data: bundle.latest,
live,
source: bundle.source,
refresh,
};
}
export function useChangelogReleases(fallbackEntries: ChangelogEntry[] = []): {
entries: ChangelogEntry[];
latest: ReleaseInfo;
live: boolean;
loading: boolean;
source: ReleasesBundle['source'];
syncedAt: string;
refresh: () => void;
} {
const { bundle, live, loading, refresh } = useReleasesStore();
return {
entries: bundle.entries.length > 0 ? bundle.entries : fallbackEntries,
latest: bundle.latest,
live,
loading,
source: bundle.source,
syncedAt: bundle.synced_at,
refresh,
};
} }
+81 -41
View File
@@ -219,14 +219,6 @@
} }
} }
@media (max-width: 639px) {
.docs-prose table {
display: block;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
}
.docs-prose th, .docs-prose th,
.docs-prose td { .docs-prose td {
padding: 0.65rem 0.85rem; padding: 0.65rem 0.85rem;
@@ -264,52 +256,100 @@
margin: 0; margin: 0;
} }
/* Smooth View Transitions for language switch & route navigation */ /* GPU-Only View Transitions (zero full-page blur rasterization; directional + rapid-switch optimized) */
@keyframes reims-page-out { @keyframes reims-nav-progress {
from { 0% { transform: translate3d(-100%, 0, 0); }
opacity: 1; 100% { transform: translate3d(380%, 0, 0); }
transform: translateY(0);
filter: blur(0px);
}
to {
opacity: 0;
transform: translateY(-4px);
filter: blur(2px);
}
} }
@keyframes reims-page-in { .reims-nav-progress-bar {
from { animation: reims-nav-progress 0.9s cubic-bezier(0.4, 0, 0.2, 1) infinite;
opacity: 0; will-change: transform;
transform: translateY(6px);
filter: blur(2px);
}
to {
opacity: 1;
transform: translateY(0);
filter: blur(0px);
}
} }
::view-transition-old(page-main) { @keyframes reims-page-out-fade {
animation: 150ms cubic-bezier(0.4, 0, 1, 1) both reims-page-out; from { opacity: 1; transform: translate3d(0, 0, 0); }
to { opacity: 0; transform: translate3d(0, -4px, 0); }
}
@keyframes reims-page-in-fade {
from { opacity: 0; transform: translate3d(0, 6px, 0); }
to { opacity: 1; transform: translate3d(0, 0, 0); }
} }
::view-transition-new(page-main) { @keyframes reims-page-out-fwd {
animation: 230ms cubic-bezier(0.22, 1, 0.36, 1) both reims-page-in; from { opacity: 1; transform: translate3d(0, 0, 0); }
to { opacity: 0; transform: translate3d(-10px, 0, 0); }
}
@keyframes reims-page-in-fwd {
from { opacity: 0; transform: translate3d(12px, 0, 0); }
to { opacity: 1; transform: translate3d(0, 0, 0); }
}
@keyframes reims-page-out-bwd {
from { opacity: 1; transform: translate3d(0, 0, 0); }
to { opacity: 0; transform: translate3d(10px, 0, 0); }
}
@keyframes reims-page-in-bwd {
from { opacity: 0; transform: translate3d(-12px, 0, 0); }
to { opacity: 1; transform: translate3d(0, 0, 0); }
}
@keyframes reims-rapid-out {
from { opacity: 1; }
to { opacity: 0; }
}
@keyframes reims-rapid-in {
from { opacity: 0; }
to { opacity: 1; }
}
::view-transition-group(site-header) {
z-index: 60;
animation: none;
} }
::view-transition-old(site-header), ::view-transition-old(site-header),
::view-transition-new(site-header) { ::view-transition-new(site-header) {
animation-duration: 160ms; animation: none;
animation-timing-function: ease-out; }
::view-transition-old(page-main) {
animation: 110ms cubic-bezier(0.4, 0, 1, 1) both reims-page-out-fade;
}
::view-transition-new(page-main) {
animation: 185ms cubic-bezier(0.22, 1, 0.36, 1) both reims-page-in-fade;
}
:root[data-nav-dir="forward"]::view-transition-old(page-main) {
animation: 110ms cubic-bezier(0.4, 0, 1, 1) both reims-page-out-fwd;
}
:root[data-nav-dir="forward"]::view-transition-new(page-main) {
animation: 185ms cubic-bezier(0.22, 1, 0.36, 1) both reims-page-in-fwd;
}
:root[data-nav-dir="backward"]::view-transition-old(page-main) {
animation: 110ms cubic-bezier(0.4, 0, 1, 1) both reims-page-out-bwd;
}
:root[data-nav-dir="backward"]::view-transition-new(page-main) {
animation: 185ms cubic-bezier(0.22, 1, 0.36, 1) both reims-page-in-bwd;
}
/* Rapid consecutive switches: instant crisp 75ms crossfade so fast tabbing never lags */
:root[data-rapid-nav="true"]::view-transition-old(page-main) {
animation: 65ms ease-out both reims-rapid-out;
}
:root[data-rapid-nav="true"]::view-transition-new(page-main) {
animation: 95ms ease-out both reims-rapid-in;
} }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
::view-transition-old(page-main), .reims-nav-progress-bar {
::view-transition-new(page-main), animation: none !important;
::view-transition-old(site-header), }
::view-transition-new(site-header) { ::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation: none !important; animation: none !important;
} }
} }
+212
View File
@@ -0,0 +1,212 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { join, resolve } from 'node:path';
const ROOT = resolve(import.meta.dirname, '..');
const DIST = join(ROOT, 'dist');
function readText(relPath) {
return readFileSync(join(ROOT, relPath), 'utf8');
}
function parseJsonc(raw) {
// Strip single-line // comments (outside strings) and /* */ block comments
const stripped = raw.replace(/\/\*[\s\S]*?\*\/|(?<=^|[^:\\])\/\/.*$/gm, '');
return JSON.parse(stripped);
}
function extractCssKeyframeBlocks(css, prefix) {
const blocks = [];
const re = new RegExp(`@keyframes\\s+(${prefix}[a-z0-9_-]*)\\s*\\{`, 'gi');
let match;
while ((match = re.exec(css)) !== null) {
let depth = 1;
let i = match.index + match[0].length;
while (i < css.length && depth > 0) {
if (css[i] === '{') depth += 1;
else if (css[i] === '}') depth -= 1;
i += 1;
}
blocks.push({ name: match[1], body: css.slice(match.index, i) });
}
return blocks;
}
describe('Configuration Invariants — wrangler.jsonc & public/_headers', () => {
it('wrangler.jsonc configures worker entrypoint, observability, ASSETS binding, /api/* routing, and custom domain', () => {
const config = parseJsonc(readText('wrangler.jsonc'));
assert.equal(config.main, 'worker/index.js');
assert.equal(config.observability?.enabled, true);
assert.equal(config.observability?.traces?.enabled, true);
assert.equal(config.assets?.binding, 'ASSETS');
assert.equal(config.assets?.directory, './dist');
assert.ok(Array.isArray(config.assets?.run_worker_first), 'assets.run_worker_first must be an array');
assert.ok(config.assets.run_worker_first.includes('/api/*'), 'run_worker_first must include "/api/*"');
assert.ok(Array.isArray(config.routes), 'routes must be an array');
assert.ok(
config.routes.some((r) => r?.pattern === 'reims.dev'),
'routes must include pattern "reims.dev"',
);
});
it('public/_headers defines security headers, HTML Cache-Control, and immutable /_astro/* caching', () => {
const headers = readText('public/_headers');
// Global security headers under /*
assert.match(headers, /^\/\*\r?\n[\s\S]*?X-Content-Type-Options:\s*nosniff/m);
assert.match(headers, /^\/\*\r?\n[\s\S]*?X-Frame-Options:\s*SAMEORIGIN/m);
assert.match(headers, /^\/\*\r?\n[\s\S]*?Referrer-Policy:\s*strict-origin-when-cross-origin/m);
// HTML routes have Cache-Control with stale-while-revalidate
for (const route of ['/', '/en', '/docs/*', '/en/docs/*', '/changelog', '/en/changelog', '/plugins', '/compatibility']) {
const escaped = route.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const routeRe = new RegExp(`^${escaped}\\r?\\n\\s+Cache-Control:.*stale-while-revalidate=`, 'm');
assert.match(headers, routeRe, `Route ${route} must have Cache-Control with stale-while-revalidate`);
}
// Immutable hashed Astro assets
assert.match(
headers,
/^\/_astro\/\*\r?\n\s+Cache-Control:\s*public,\s*max-age=31536000,\s*immutable/m,
'/_astro/* must have immutable 1-year Cache-Control',
);
});
});
describe('Built Site Regression Checks — dist/', () => {
it('all required built HTML, SEO, data, and Pagefind artifacts exist and are non-empty', () => {
const requiredFiles = [
'dist/index.html',
'dist/en/index.html',
'dist/changelog/index.html',
'dist/en/changelog/index.html',
'dist/docs/quick-start/index.html',
'dist/en/docs/quick-start/index.html',
'dist/plugins/index.html',
'dist/compatibility/index.html',
'dist/404.html',
'dist/sitemap.xml',
'dist/robots.txt',
'dist/llms.txt',
'dist/llms-full.txt',
'dist/data/releases.json',
'dist/data/releases-bundle.json',
'dist/pagefind/pagefind.js',
];
for (const rel of requiredFiles) {
const full = join(ROOT, rel);
assert.equal(existsSync(full), true, `Missing required built artifact: ${rel}`);
assert.ok(statSync(full).size > 0, `Built artifact must be non-empty: ${rel}`);
}
});
it('dist/_astro/*.css View Transition keyframes have zero blur() filters and include prefers-reduced-motion', () => {
const astroDir = join(DIST, '_astro');
const cssFiles = readdirSync(astroDir).filter((f) => f.endsWith('.css'));
assert.ok(cssFiles.length > 0, 'Expected at least one CSS bundle in dist/_astro');
const combinedCss = cssFiles.map((f) => readFileSync(join(astroDir, f), 'utf8')).join('\n');
const pageKeyframes = extractCssKeyframeBlocks(combinedCss, 'reims-page-');
const rapidKeyframes = extractCssKeyframeBlocks(combinedCss, 'reims-rapid-');
assert.ok(pageKeyframes.length > 0, 'Expected reims-page-* View Transition keyframes');
assert.ok(rapidKeyframes.length > 0, 'Expected reims-rapid-* View Transition keyframes');
for (const kf of [...pageKeyframes, ...rapidKeyframes]) {
assert.equal(
/blur\s*\(/i.test(kf.body),
false,
`Keyframe ${kf.name} must not use blur() filter: ${kf.body}`,
);
}
assert.match(
combinedCss,
/prefers-reduced-motion\s*:\s*reduce/i,
'Built CSS must include prefers-reduced-motion: reduce handling',
);
});
it('dist/data/releases.json and dist/data/releases-bundle.json conform to strict schema invariants', () => {
const releases = JSON.parse(readText('dist/data/releases.json'));
const bundle = JSON.parse(readText('dist/data/releases-bundle.json'));
// Validate releases.json
assert.ok(Date.parse(releases.synced_at) > 0, 'releases.synced_at must be valid ISO date');
assert.equal(typeof releases.stars, 'number');
assert.ok(releases.stars > 0, 'releases.stars must be positive');
assert.match(releases.version, /^v\d+\.\d+\.\d+/i, 'releases.version must be valid semver tag');
assert.ok(Date.parse(releases.published_at) > 0, 'releases.published_at must be valid ISO date');
assert.match(releases.html_url, /^https:\/\//);
for (const assetKey of ['exe', 'zip']) {
const asset = releases[assetKey];
assert.ok(asset && typeof asset === 'object', `releases.${assetKey} must exist`);
assert.ok(asset.name.length > 0);
assert.ok(typeof asset.size === 'number' && asset.size > 0);
assert.match(asset.url, /^https:\/\//);
}
assert.match(releases.sha256_url, /^https:\/\//);
assert.match(releases.sha256_sums, /[a-f0-9]{64}\s+/i);
// Validate releases-bundle.json
assert.ok(['static-fallback', 'edge-api', 'github-direct'].includes(bundle.source));
assert.ok(Date.parse(bundle.synced_at) > 0);
assert.equal(bundle.latest?.version, releases.version, 'bundle.latest.version should match releases.json');
assert.ok(Array.isArray(bundle.entries) && bundle.entries.length > 0, 'bundle.entries must be non-empty');
for (const entry of bundle.entries) {
assert.ok(typeof entry.tag === 'string' && entry.tag.length > 0);
assert.equal(/^runtime-/i.test(entry.tag), false, `runtime tag leaked into bundle: ${entry.tag}`);
assert.ok(typeof entry.name === 'string' && entry.name.length > 0);
assert.match(entry.date, /^\d{4}-\d{2}-\d{2}$/, `Invalid entry.date for ${entry.tag}`);
assert.match(entry.html_url, /^https:\/\//, `Invalid entry.html_url for ${entry.tag}`);
assert.equal(typeof entry.prerelease, 'boolean');
assert.ok(['stable', 'alpha', 'dev'].includes(entry.channel), `Invalid channel for ${entry.tag}`);
if (entry.exe) assert.match(entry.exe.url, /^https:\/\//);
if (entry.zip) assert.match(entry.zip.url, /^https:\/\//);
if (entry.sha256_url) assert.match(entry.sha256_url, /^https:\/\//);
assert.ok(Array.isArray(entry.sections?.['zh-CN']), `Missing zh-CN sections for ${entry.tag}`);
assert.ok(Array.isArray(entry.sections?.['en-US']), `Missing en-US sections for ${entry.tag}`);
for (const locale of ['zh-CN', 'en-US']) {
for (const sec of entry.sections[locale]) {
assert.equal(typeof sec.title, 'string');
assert.ok(Array.isArray(sec.items) && sec.items.length > 0);
}
}
}
});
it('quick-start docs (zh & en) do not contain hardcoded stale reims-go-v0.2.11-windows-amd64.exe', () => {
for (const rel of ['dist/docs/quick-start/index.html', 'dist/en/docs/quick-start/index.html']) {
const html = readText(rel);
assert.equal(
html.includes('reims-go-v0.2.11-windows-amd64.exe'),
false,
`${rel} must not contain stale v0.2.11 binary filename`,
);
}
});
it('dist/index.html contains nav engine guard, persisted site-header, and Hero live release meta', () => {
const html = readText('dist/index.html');
const releases = JSON.parse(readText('dist/data/releases.json'));
assert.ok(html.includes('__reimsNavEngineBound'), 'index.html must include __reimsNavEngineBound');
assert.ok(html.includes('site-header'), 'index.html must include site-header');
assert.ok(
html.includes('data-astro-transition-persist'),
'index.html must include Astro transition:persist marker (data-astro-transition-persist)',
);
assert.ok(html.includes('HeroReleaseMeta'), 'index.html must hydrate HeroReleaseMeta island');
assert.ok(
html.includes(releases.version),
`index.html must render current release version (${releases.version})`,
);
});
});
+363
View File
@@ -0,0 +1,363 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { registerHooks } from 'node:module';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import {
parseBilingualReleaseBody,
extractReleaseAssets,
classifyReleaseChannel,
isClientReleaseTag,
normalizeGitHubReleases,
sanitizeGitHubUrl,
} from '../src/lib/release-parser.ts';
import { localizedPath, switchLocalePath } from '../src/i18n/types.ts';
import worker from '../worker/index.js';
// Register lightweight hooks so Node 22 can import src/lib/releases.ts directly
// (resolving extensionless ./release-parser -> .ts and JSON imports without import attributes).
registerHooks({
resolve(specifier, context, nextResolve) {
if (specifier === './release-parser') {
return nextResolve('./release-parser.ts', context);
}
return nextResolve(specifier, context);
},
load(url, context, nextLoad) {
if (url.endsWith('.json')) {
const source = readFileSync(fileURLToPath(url), 'utf8');
return { format: 'json', shortCircuit: true, source };
}
return nextLoad(url, context);
},
});
const { formatStars, formatBytes, extractShaForAsset, FALLBACK_RELEASE } = await import('../src/lib/releases.ts');
const HASH_A = '1'.repeat(64);
const HASH_B = 'f'.repeat(64);
describe('src/lib/release-parser.ts — Unit Tests', () => {
it('parses bilingual cn-first and en-first release bodies and strips HTML tags in headings', () => {
const cnFirst = [
'[中文](#cn-v0.2.12) | [English](#en-v0.2.12)',
'<h3 id="cn-v0.2.12"><strong>重点</strong> <em>更新</em></h3>',
'- 支持拖放文件',
'* 剪贴板同步修复',
'### 已知限制',
'- 忽略限制项',
'### 下载',
'- 忽略下载项',
'### 构建与许可证',
'- 忽略许可证项',
'<h3 id="en-v0.2.12"><span>Key</span> Updates</h3>',
'> Ignore blockquote line',
'- Drag-and-drop file support',
'* Clipboard sync fix',
'### Known Limitations (Windows)',
'- Ignore English limitations',
'### Downloads',
'- Ignore English downloads',
'### License',
'- Ignore English license',
].join('\r\n');
const parsed = parseBilingualReleaseBody(cnFirst);
assert.deepEqual(parsed['zh-CN'], [
{ title: '重点 更新', items: ['支持拖放文件', '剪贴板同步修复'] },
]);
assert.deepEqual(parsed['en-US'], [
{ title: 'Key Updates', items: ['Drag-and-drop file support', 'Clipboard sync fix'] },
]);
const enFirst = [
'<h2 id="en-v0.2.12">Added</h2>',
'- English item',
'<h2 id="cn-v0.2.12">新增</h2>',
'- 中文项',
].join('\n');
const parsedReversed = parseBilingualReleaseBody(enFirst);
assert.deepEqual(parsedReversed['en-US'], [{ title: 'Added', items: ['English item'] }]);
assert.deepEqual(parsedReversed['zh-CN'], [{ title: '新增', items: ['中文项'] }]);
});
it('falls back single-language body and empty-half bilingual body cleanly', () => {
const single = '### Improvements\n- Faster VM startup\n- Lower memory footprint';
const resSingle = parseBilingualReleaseBody(single);
assert.deepEqual(resSingle['zh-CN'], [
{ title: 'Improvements', items: ['Faster VM startup', 'Lower memory footprint'] },
]);
assert.deepEqual(resSingle['en-US'], resSingle['zh-CN']);
// Bilingual markers present, but English half only contains a skipped section -> falls back to zh-CN
const oneEmptyHalf = [
'<h3 id="cn-v1">修复</h3>',
'- 修复启动闪烁',
'<h3 id="en-v1">Download</h3>',
'- Skipped only',
].join('\n');
const resHalf = parseBilingualReleaseBody(oneEmptyHalf);
assert.deepEqual(resHalf['zh-CN'], [{ title: '修复', items: ['修复启动闪烁'] }]);
assert.deepEqual(resHalf['en-US'], [{ title: '修复', items: ['修复启动闪烁'] }]);
});
it('handles empty, whitespace, unheaded bullets, and headings with zero bullets', () => {
assert.deepEqual(parseBilingualReleaseBody(''), { 'zh-CN': [], 'en-US': [] });
assert.deepEqual(parseBilingualReleaseBody(' \r\n '), { 'zh-CN': [], 'en-US': [] });
const mixed = [
'- Orphan bullet before heading',
'### Empty Heading',
'#### Real Section',
'- Real item',
].join('\n');
const parsed = parseBilingualReleaseBody(mixed);
assert.deepEqual(parsed['zh-CN'], [
{ title: '', items: ['Orphan bullet before heading'] },
{ title: 'Real Section', items: ['Real item'] },
]);
});
it('filters client release tags and excludes runtime-* tags', () => {
assert.equal(isClientReleaseTag('v0.2.12'), true);
assert.equal(isClientReleaseTag('v1.0.0-alpha.2'), true);
assert.equal(isClientReleaseTag('V2.10'), true);
assert.equal(isClientReleaseTag('dev'), true);
assert.equal(isClientReleaseTag('DEV'), true);
assert.equal(isClientReleaseTag('alpha'), true);
assert.equal(isClientReleaseTag('alpha-20261203'), true);
assert.equal(isClientReleaseTag(''), false);
assert.equal(isClientReleaseTag('runtime-2df30ff'), false);
assert.equal(isClientReleaseTag('RUNTIME-v1.0'), false);
assert.equal(isClientReleaseTag('docs-v1.0'), false);
assert.equal(isClientReleaseTag('v1'), false);
assert.equal(isClientReleaseTag('latest'), false);
});
it('classifies stable, alpha, and dev channels accurately', () => {
assert.equal(classifyReleaseChannel('v0.2.12', false), 'stable');
assert.equal(classifyReleaseChannel('dev', false), 'dev');
assert.equal(classifyReleaseChannel('dev', true), 'dev');
assert.equal(classifyReleaseChannel('v0.3.0-dev.1', true), 'dev');
assert.equal(classifyReleaseChannel('v0.3.0-alpha.1', false), 'alpha');
assert.equal(classifyReleaseChannel('v0.3.0-beta.2', false), 'alpha');
assert.equal(classifyReleaseChannel('v0.3.0-rc.1', false), 'alpha');
assert.equal(classifyReleaseChannel('v0.2.12', true), 'alpha');
});
it('extracts exe, zip, SHA256SUMS.txt assets, validates GitHub HTTPS URLs, and extracts valid sha256 digests', () => {
const assets = [
{
name: 'reims-go-v0.2.12-windows-amd64.exe',
size: 21023744,
browser_download_url: 'https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/reims.exe',
digest: `sha256:${HASH_A}`,
},
{
name: 'reims-go-v0.2.12-WINDOWS-AMD64.ZIP',
size: 8362065,
browser_download_url: 'https://objects.githubusercontent.com/reims.zip',
digest: `SHA256:${HASH_B}`,
},
{
name: 'SHA256SUMS.txt',
size: 180,
browser_download_url: 'https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/SHA256SUMS.txt',
},
];
const out = extractReleaseAssets(assets);
assert.deepEqual(out.exe, {
name: 'reims-go-v0.2.12-windows-amd64.exe',
size: 21023744,
url: 'https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/reims.exe',
});
assert.deepEqual(out.zip, {
name: 'reims-go-v0.2.12-WINDOWS-AMD64.ZIP',
size: 8362065,
url: 'https://objects.githubusercontent.com/reims.zip',
});
assert.equal(out.sha256_url, 'https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/SHA256SUMS.txt');
assert.deepEqual(out.digestLines, [
`${HASH_A} reims-go-v0.2.12-windows-amd64.exe`,
`${HASH_B} reims-go-v0.2.12-WINDOWS-AMD64.ZIP`,
]);
// Reject untrusted schemes & non-GitHub hosts
assert.equal(sanitizeGitHubUrl('javascript:alert(1)'), null);
assert.equal(sanitizeGitHubUrl('data:text/html,<script>alert(1)</script>'), null);
assert.equal(sanitizeGitHubUrl('http://github.com/Nwflower/Reims-Go'), null);
assert.equal(sanitizeGitHubUrl('https://evil.com/reims.exe'), null);
assert.equal(sanitizeGitHubUrl('https://github.com.evil.com/reims.exe'), null);
// Undefined / malformed assets
const empty = extractReleaseAssets(undefined);
assert.deepEqual(empty, { exe: null, zip: null, sha256_url: null, digestLines: [] });
const missingUrlsAndBadDigest = extractReleaseAssets([
{ name: 'reims-windows-amd64.exe', size: 123, digest: 'md5:1234' },
{ name: 'reims-windows-amd64.zip', size: 456, browser_download_url: 'https://evil.com/a.zip' },
]);
assert.deepEqual(missingUrlsAndBadDigest, { exe: null, zip: null, sha256_url: null, digestLines: [] });
});
it('prevents protocol-relative open redirects in localizedPath and switchLocalePath', () => {
assert.equal(localizedPath('zh-CN', '//evil.com/phish'), '/evil.com/phish');
assert.equal(localizedPath('en-US', '//evil.com/phish'), '/en/evil.com/phish');
assert.equal(switchLocalePath('/en//evil.com/phish', 'zh-CN'), '/evil.com/phish');
assert.equal(switchLocalePath('//evil.com/phish', 'en-US'), '/en/evil.com/phish');
assert.equal(switchLocalePath('/en/docs/quick-start', 'zh-CN'), '/docs/quick-start');
assert.equal(switchLocalePath('/docs/quick-start', 'en-US'), '/en/docs/quick-start');
});
it('normalizes and sorts releases (stable newest first, then prereleases newest first)', () => {
const raw = [
{ tag_name: 'runtime-abc123', published_at: '2026-12-03T10:00:00Z' },
{ tag_name: 'v0.9.9', draft: true, published_at: '2026-12-03T11:00:00Z' },
{ tag_name: 'dev', prerelease: true, published_at: '2026-12-03T09:00:00Z', body: '- Dev item' },
{ tag_name: 'v0.2.10', published_at: '2026-11-01T00:00:00Z', body: '- Older stable' },
{ tag_name: 'v0.3.0-alpha.2', prerelease: true, published_at: '2026-12-03T08:00:00Z', body: '- Alpha' },
{ tag_name: 'v0.2.12', published_at: '2026-12-02T20:00:00Z', body: '- Latest stable' },
];
const entries = normalizeGitHubReleases(raw);
assert.deepEqual(
entries.map((e) => e.tag),
['v0.2.12', 'v0.2.10', 'dev', 'v0.3.0-alpha.2'],
);
assert.equal(entries[0].date, '2026-12-02');
assert.equal(entries[0].name, 'Reims-Go v0.2.12');
assert.equal(entries[0].html_url, 'https://github.com/Nwflower/Reims-Go/releases/tag/v0.2.12');
});
it('maintains 100% output parity with worker/index.js on identical GitHub fixtures', async () => {
const fixtures = [
{
tag_name: 'runtime-999999',
draft: false,
prerelease: false,
published_at: '2026-12-03T00:00:00Z',
body: '### Runtime\n- Ignored',
assets: [],
},
{
tag_name: 'v0.2.12',
name: 'Reims-Go v0.2.12',
draft: false,
prerelease: false,
published_at: '2026-12-02T20:42:58Z',
html_url: 'https://github.com/Nwflower/Reims-Go/releases/tag/v0.2.12',
body: [
'[中文](#cn-v0.2.12) | [English](#en-v0.2.12)',
'<h3 id="cn-v0.2.12">重点更新</h3>',
'- 拖放支持',
'### 已知限制',
'- 跳过',
'<h3 id="en-v0.2.12">Highlights</h3>',
'- Drag and drop support',
'### Download',
'- Skip',
].join('\n'),
assets: [
{
name: 'reims-go-v0.2.12-windows-amd64.exe',
size: 21023744,
browser_download_url: 'https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/reims.exe',
digest: `sha256:${HASH_A}`,
},
{
name: 'SHA256SUMS.txt',
size: 128,
browser_download_url: 'https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/SHA256SUMS.txt',
},
],
},
{
tag_name: 'v0.3.0-dev.1',
name: 'Dev Preview',
draft: false,
prerelease: true,
published_at: '2026-12-03T06:00:00Z',
body: '> Warning\n### Fixes\n- Single language fix',
assets: [],
},
];
const parserEntries = normalizeGitHubReleases(fixtures);
const origFetch = globalThis.fetch;
const origCaches = globalThis.caches;
try {
globalThis.caches = {
default: {
async match() {
return undefined;
},
async put() {},
},
};
globalThis.fetch = async (url) =>
new Response(JSON.stringify(String(url).includes('/releases') ? fixtures : { stargazers_count: 1868 }), {
status: 200,
});
const res = await worker.fetch(
new Request('https://reims.dev/api/github/releases'),
{},
{ waitUntil() {} },
);
const workerPayload = await res.json();
assert.deepEqual(workerPayload.entries, parserEntries);
} finally {
globalThis.fetch = origFetch;
globalThis.caches = origCaches;
}
});
});
describe('src/lib/releases.ts — Utility Helpers', () => {
it('formatStars formats star counts and invalid values cleanly', () => {
assert.equal(formatStars(1868), '1.9k');
assert.equal(formatStars(1000), '1.0k');
assert.equal(formatStars(999), '999');
assert.equal(formatStars(1), '1');
assert.equal(formatStars(0), '1.8k');
assert.equal(formatStars(-42), '1.8k');
assert.equal(formatStars(Number.NaN), '1.8k');
assert.equal(formatStars(Number.POSITIVE_INFINITY), '1.8k');
});
it('formatBytes formats bytes, KB, MB and handles empty/non-positive inputs', () => {
assert.equal(formatBytes(undefined), '');
assert.equal(formatBytes(0), '');
assert.equal(formatBytes(-100), '');
assert.equal(formatBytes(512), '512 B');
assert.equal(formatBytes(1024), '1.0 KB');
assert.equal(formatBytes(1536), '1.5 KB');
assert.equal(formatBytes(1024 * 1024), '1.0 MB');
assert.equal(formatBytes(21023744), '20.0 MB');
});
it('extractShaForAsset extracts 64-hex SHA-256 digests case-insensitively', () => {
const shaText = [
`${HASH_A} reims-go-v0.2.12-windows-amd64.exe`,
`${HASH_B} reims-go-v0.2.12-windows-amd64.zip`,
`not-a-hash broken-file.bin`,
].join('\r\n');
assert.equal(extractShaForAsset(shaText, 'reims-go-v0.2.12-windows-amd64.exe'), HASH_A);
assert.equal(extractShaForAsset(shaText, 'REIMS-GO-V0.2.12-WINDOWS-AMD64.ZIP'), HASH_B);
assert.equal(extractShaForAsset(shaText, 'broken-file.bin'), '');
assert.equal(extractShaForAsset(shaText, 'nonexistent.exe'), '');
assert.equal(extractShaForAsset('', 'reims-go-v0.2.12-windows-amd64.exe'), '');
assert.equal(extractShaForAsset(shaText, undefined), '');
// Also verifies real FALLBACK_RELEASE sha256_sums parses cleanly
if (FALLBACK_RELEASE.exe?.name && FALLBACK_RELEASE.sha256_sums) {
const realHash = extractShaForAsset(FALLBACK_RELEASE.sha256_sums, FALLBACK_RELEASE.exe.name);
assert.match(realHash, /^[a-f0-9]{64}$/i);
}
});
});
+664
View File
@@ -0,0 +1,664 @@
import { describe, it, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import worker from '../worker/index.js';
const VALID_EXE_HASH = 'a'.repeat(64);
const VALID_ZIP_HASH = 'b'.repeat(64);
function createMockCache() {
const store = new Map();
return {
store,
putCalls: [],
matchCalls: [],
async match(req) {
const key = typeof req === 'string' ? req : req.url;
this.matchCalls.push(key);
const hit = store.get(key);
return hit ? hit.clone() : undefined;
},
async put(req, res) {
const key = typeof req === 'string' ? req : req.url;
this.putCalls.push(key);
store.set(key, res.clone());
},
};
}
function createMockCtx() {
const promises = [];
return {
promises,
waitUntil(p) {
promises.push(Promise.resolve(p));
},
async flush() {
await Promise.all(promises);
},
};
}
function sampleGitHubRepo(overrides = {}) {
return {
stargazers_count: 1924,
...overrides,
};
}
function sampleGitHubReleases() {
return [
{
tag_name: 'runtime-2df30ff',
name: 'Runtime 2df30ff',
draft: false,
prerelease: false,
published_at: '2026-12-03T01:00:00Z',
html_url: 'https://github.com/Nwflower/Reims-Go/releases/tag/runtime-2df30ff',
body: '### Runtime\n- Should be filtered out',
assets: [],
},
{
tag_name: 'v0.2.13-draft',
name: 'Draft release',
draft: true,
prerelease: false,
published_at: '2026-12-03T02:00:00Z',
html_url: 'https://github.com/Nwflower/Reims-Go/releases/tag/v0.2.13-draft',
body: '### Draft\n- Should not appear',
assets: [],
},
{
tag_name: 'docs-v1',
name: 'Docs Tag',
draft: false,
prerelease: false,
published_at: '2026-12-03T01:30:00Z',
body: '- Ignored non-client tag',
assets: [],
},
{
tag_name: 'dev',
name: 'Reims-Go Dev',
draft: false,
prerelease: true,
published_at: '2026-12-03T05:00:00Z',
html_url: 'https://github.com/Nwflower/Reims-Go/releases/tag/dev',
body: '> Dev warning banner\n### Changes\n- Nightly dev build fix',
assets: [],
},
{
tag_name: 'v0.3.0-alpha.1',
name: 'Reims-Go v0.3.0 Alpha 1',
draft: false,
prerelease: true,
published_at: '2026-12-03T04:00:00Z',
html_url: 'https://github.com/Nwflower/Reims-Go/releases/tag/v0.3.0-alpha.1',
body: '### Highlights\n- Experimental GPU scheduler',
assets: [],
},
{
tag_name: 'v0.2.12',
name: 'Reims-Go v0.2.12',
draft: false,
prerelease: false,
published_at: '2026-12-02T20:42:58Z',
html_url: 'https://github.com/Nwflower/Reims-Go/releases/tag/v0.2.12',
body: [
'[中文](#cn-v0.2.12) | [English](#en-v0.2.12)',
'',
'<h3 id="cn-v0.2.12"><strong>重点更新</strong></h3>',
'- 支持文件拖拽与剪贴板修复',
'* 支持 Npcap 无线桥接',
'',
'### 已知限制',
'- 这段应该被跳过',
'',
'### 下载',
'- 下载链接应被跳过',
'',
'### 许可证',
'- GPL-3.0 应被跳过',
'',
'<h3 id="en-v0.2.12">Highlights</h3>',
'> Note blockquote should be ignored',
'- Drag-and-drop file transfer and clipboard fix',
'* Npcap Wi-Fi bridging support',
'',
'### Known Limitations',
'- Should be skipped in English',
'',
'### Download',
'- Skipped download section',
'',
'### License',
'- Skipped license section',
].join('\n'),
assets: [
{
name: 'reims-go-v0.2.12-windows-amd64.exe',
size: 21023744,
browser_download_url:
'https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/reims-go-v0.2.12-windows-amd64.exe',
digest: `sha256:${VALID_EXE_HASH}`,
},
{
name: 'reims-go-v0.2.12-windows-amd64.zip',
size: 8362065,
browser_download_url:
'https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/reims-go-v0.2.12-windows-amd64.zip',
digest: `sha256:${VALID_ZIP_HASH}`,
},
{
name: 'SHA256SUMS.txt',
size: 204,
browser_download_url:
'https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/SHA256SUMS.txt',
},
{
name: 'extra-bad-digest.bin',
size: 100,
browser_download_url: 'https://example.com/extra.bin',
digest: 'sha256:short',
},
],
},
{
tag_name: 'v0.2.11',
name: 'Reims-Go v0.2.11',
draft: false,
prerelease: false,
published_at: '2026-11-20T10:00:00Z',
html_url: 'https://github.com/Nwflower/Reims-Go/releases/tag/v0.2.11',
body: '### Bug Fixes\n- Fixed display fallback',
assets: [],
},
];
}
describe('worker/index.js — Edge API & Caching', () => {
let origFetch;
let origCaches;
let origConsoleWarn;
let mockCache;
let loggedMessages;
beforeEach(() => {
origFetch = globalThis.fetch;
origCaches = globalThis.caches;
origConsoleWarn = console.warn;
mockCache = createMockCache();
loggedMessages = [];
globalThis.caches = { default: mockCache };
console.warn = (...args) => loggedMessages.push(args.join(' '));
});
afterEach(() => {
globalThis.fetch = origFetch;
globalThis.caches = origCaches;
console.warn = origConsoleWarn;
});
it('handles GET /api/github/releases cache MISS, fetches GitHub, sets security headers, and populates cache via waitUntil', async () => {
const fetchedUrls = [];
const fetchedHeaders = [];
globalThis.fetch = async (url, init) => {
fetchedUrls.push(String(url));
fetchedHeaders.push(init?.headers || {});
if (String(url).includes('/releases')) {
return new Response(JSON.stringify(sampleGitHubReleases()), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}
return new Response(JSON.stringify(sampleGitHubRepo()), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
};
const ctx = createMockCtx();
const req = new Request('https://reims.dev/api/github/releases', { method: 'GET' });
const res = await worker.fetch(req, { GITHUB_TOKEN: 'ghp_test_token' }, ctx);
await ctx.flush();
assert.equal(res.status, 200);
assert.equal(res.headers.get('X-Reims-Cache'), 'MISS');
assert.equal(res.headers.get('X-Reims-Source'), 'edge-api');
assert.equal(res.headers.get('X-Content-Type-Options'), 'nosniff');
assert.equal(res.headers.get('X-Frame-Options'), 'DENY');
assert.equal(res.headers.get('Content-Security-Policy'), "default-src 'none'");
assert.equal(res.headers.get('Cache-Control'), 'public, max-age=120, s-maxage=3600');
assert.ok(Number(res.headers.get('X-Reims-Fetched-At')) > 0);
assert.match(res.headers.get('Content-Type') || '', /application\/json/i);
assert.equal(fetchedUrls.length, 2);
assert.ok(fetchedUrls.includes('https://api.github.com/repos/Nwflower/Reims-Go'));
assert.ok(fetchedUrls.includes('https://api.github.com/repos/Nwflower/Reims-Go/releases?per_page=25'));
for (const h of fetchedHeaders) {
assert.equal(h.Authorization, 'Bearer ghp_test_token');
assert.equal(h.Accept, 'application/vnd.github+json');
assert.match(h['User-Agent'], /Reims-Go-Landing-Worker/);
}
const body = await res.json();
assert.equal(body.source, 'edge-api');
assert.ok(Date.parse(body.synced_at) > 0);
assert.equal(body.latest.stars, 1924);
assert.equal(body.latest.version, 'v0.2.12');
assert.equal(body.latest.exe?.name, 'reims-go-v0.2.12-windows-amd64.exe');
assert.equal(body.latest.zip?.name, 'reims-go-v0.2.12-windows-amd64.zip');
assert.equal(
body.latest.sha256_url,
'https://github.com/Nwflower/Reims-Go/releases/download/v0.2.12/SHA256SUMS.txt',
);
assert.equal(
body.latest.sha256_sums,
`${VALID_EXE_HASH} reims-go-v0.2.12-windows-amd64.exe\n${VALID_ZIP_HASH} reims-go-v0.2.12-windows-amd64.zip`,
);
// Written to caches.default via ctx.waitUntil
assert.equal(ctx.promises.length, 1);
assert.deepEqual(mockCache.putCalls, ['https://reims.dev/api/github/releases']);
});
it('omits Authorization header when env.GITHUB_TOKEN is not set', async () => {
const capturedHeaders = [];
globalThis.fetch = async (url, init) => {
capturedHeaders.push(init?.headers || {});
return new Response(JSON.stringify(String(url).includes('/releases') ? [] : { stargazers_count: 100 }), {
status: 200,
});
};
const ctx = createMockCtx();
const res = await worker.fetch(new Request('https://reims.dev/api/github/releases'), {}, ctx);
await ctx.flush();
assert.equal(res.status, 200);
assert.equal(capturedHeaders.length, 2);
for (const h of capturedHeaders) {
assert.equal('Authorization' in h, false);
}
});
it('returns X-Reims-Cache: HIT on subsequent request without calling fetch', async () => {
let fetchCount = 0;
globalThis.fetch = async (url) => {
fetchCount += 1;
return new Response(
JSON.stringify(String(url).includes('/releases') ? sampleGitHubReleases() : sampleGitHubRepo()),
{ status: 200 },
);
};
const ctx1 = createMockCtx();
const res1 = await worker.fetch(new Request('https://reims.dev/api/github/releases'), {}, ctx1);
await ctx1.flush();
assert.equal(res1.headers.get('X-Reims-Cache'), 'MISS');
assert.equal(fetchCount, 2);
const body1 = await res1.json();
const ctx2 = createMockCtx();
const res2 = await worker.fetch(new Request('https://reims.dev/api/github/releases'), {}, ctx2);
await ctx2.flush();
assert.equal(res2.status, 200);
assert.equal(res2.headers.get('X-Reims-Cache'), 'HIT');
assert.equal(fetchCount, 2, 'fetch must not be called on cache HIT');
const body2 = await res2.json();
assert.deepEqual(body2, body1);
});
it('normalizes query strings to the canonical /api/github/releases cache key', async () => {
let fetchCount = 0;
globalThis.fetch = async (url) => {
fetchCount += 1;
return new Response(
JSON.stringify(String(url).includes('/releases') ? sampleGitHubReleases() : sampleGitHubRepo()),
{ status: 200 },
);
};
const ctx1 = createMockCtx();
const res1 = await worker.fetch(
new Request('https://reims.dev/api/github/releases?locale=en&cachebust=123'),
{},
ctx1,
);
await ctx1.flush();
assert.equal(res1.headers.get('X-Reims-Cache'), 'MISS');
assert.deepEqual(mockCache.putCalls, ['https://reims.dev/api/github/releases']);
const ctx2 = createMockCtx();
const res2 = await worker.fetch(
new Request('https://reims.dev/api/github/releases?different=query'),
{},
ctx2,
);
assert.equal(res2.headers.get('X-Reims-Cache'), 'HIT');
assert.equal(fetchCount, 2);
const ctx3 = createMockCtx();
const res3 = await worker.fetch(new Request('https://reims.dev/api/github/releases'), {}, ctx3);
assert.equal(res3.headers.get('X-Reims-Cache'), 'HIT');
assert.equal(fetchCount, 2);
});
it('falls back to env.ASSETS /data/releases-bundle.json on GitHub 403 rate limit', async () => {
globalThis.fetch = async () => new Response('API rate limit exceeded', { status: 403 });
const assetRequests = [];
const fallbackPayload = { source: 'static-fallback', latest: { version: 'v0.2.12' }, entries: [] };
const env = {
ASSETS: {
async fetch(req) {
assetRequests.push(req.url);
return new Response(JSON.stringify(fallbackPayload), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
},
},
};
const ctx = createMockCtx();
const res = await worker.fetch(new Request('https://reims.dev/api/github/releases'), env, ctx);
await ctx.flush();
assert.equal(res.status, 200);
assert.equal(res.headers.get('X-Reims-Source'), 'static-fallback');
assert.equal(res.headers.get('X-Reims-Cache'), 'FALLBACK');
assert.equal(res.headers.get('X-Content-Type-Options'), 'nosniff');
assert.equal(res.headers.get('Cache-Control'), 'public, max-age=60, s-maxage=60');
assert.deepEqual(assetRequests, ['https://reims.dev/data/releases-bundle.json']);
assert.deepEqual(await res.json(), fallbackPayload);
// Negative-cached for 60s to shield GitHub API during outages / rate limits
assert.deepEqual(mockCache.putCalls, ['https://reims.dev/api/github/releases']);
assert.ok(loggedMessages.some((m) => m.includes('github_releases_fallback') && m.includes('403')));
});
it('serves stale edge cache immediately and triggers background SWR refresh via waitUntil', async () => {
const stalePayload = { source: 'edge-api', latest: { version: 'v0.2.11' }, entries: [] };
mockCache.store.set(
'https://reims.dev/api/github/releases',
new Response(JSON.stringify(stalePayload), {
status: 200,
headers: {
'Content-Type': 'application/json',
'X-Reims-Source': 'edge-api',
'X-Reims-Fetched-At': String(Date.now() - 400_000),
},
}),
);
let bgFetched = 0;
globalThis.fetch = async (url) => {
bgFetched += 1;
return new Response(
JSON.stringify(String(url).includes('/releases') ? sampleGitHubReleases() : sampleGitHubRepo()),
{ status: 200 },
);
};
const ctx = createMockCtx();
const res = await worker.fetch(new Request('https://reims.dev/api/github/releases'), {}, ctx);
assert.equal(res.status, 200);
assert.equal(res.headers.get('X-Reims-Cache'), 'STALE');
assert.equal((await res.json()).latest.version, 'v0.2.11');
await ctx.flush();
assert.equal(bgFetched, 2, 'SWR must trigger background GitHub refresh');
const refreshed = await worker.fetch(new Request('https://reims.dev/api/github/releases'), {}, createMockCtx());
assert.equal(refreshed.headers.get('X-Reims-Cache'), 'HIT');
assert.equal((await refreshed.json()).latest.version, 'v0.2.12');
});
it('falls back to env.ASSETS on GitHub 500 error and network throw', async () => {
const fallbackBody = JSON.stringify({ source: 'static-fallback', latest: { version: 'v0.2.12' }, entries: [] });
const env = {
ASSETS: {
async fetch() {
return new Response(fallbackBody, { status: 200 });
},
},
};
// Case 1: HTTP 500
globalThis.fetch = async () => new Response('Internal Server Error', { status: 500 });
const res500 = await worker.fetch(new Request('https://reims.dev/api/github/releases'), env, createMockCtx());
assert.equal(res500.status, 200);
assert.equal(res500.headers.get('X-Reims-Source'), 'static-fallback');
// Case 2: Network rejection (clear negative cache between sub-cases)
mockCache.store.clear();
globalThis.fetch = async () => {
throw new TypeError('Network unreachable');
};
const resNet = await worker.fetch(new Request('https://reims.dev/api/github/releases'), env, createMockCtx());
assert.equal(resNet.status, 200);
assert.equal(resNet.headers.get('X-Reims-Source'), 'static-fallback');
assert.ok(loggedMessages.some((m) => m.includes('Network unreachable')));
});
it('returns HTTP 502 JSON error with no-store when GitHub fails and env.ASSETS fails, throws, or is missing', async () => {
globalThis.fetch = async () => new Response('Forbidden', { status: 403 });
// Missing env.ASSETS
const resNoAssets = await worker.fetch(new Request('https://reims.dev/api/github/releases'), {}, createMockCtx());
assert.equal(resNoAssets.status, 502);
assert.equal(resNoAssets.headers.get('Cache-Control'), 'no-store');
assert.equal(resNoAssets.headers.get('X-Content-Type-Options'), 'nosniff');
assert.match(resNoAssets.headers.get('Content-Type') || '', /application\/json/i);
assert.deepEqual(await resNoAssets.json(), { error: 'Unable to fetch GitHub releases' });
// env.ASSETS returns 404
const envFailingAssets = {
ASSETS: {
async fetch() {
return new Response('Not Found', { status: 404 });
},
},
};
const resAssets404 = await worker.fetch(
new Request('https://reims.dev/api/github/releases'),
envFailingAssets,
createMockCtx(),
);
assert.equal(resAssets404.status, 502);
assert.deepEqual(await resAssets404.json(), { error: 'Unable to fetch GitHub releases' });
// env.ASSETS throws an exception
const envThrowingAssets = {
ASSETS: {
async fetch() {
throw new Error('ASSETS binding unavailable');
},
},
};
const resAssetsThrow = await worker.fetch(
new Request('https://reims.dev/api/github/releases'),
envThrowingAssets,
createMockCtx(),
);
assert.equal(resAssetsThrow.status, 502);
assert.deepEqual(await resAssetsThrow.json(), { error: 'Unable to fetch GitHub releases' });
});
it('handles HEAD on /api/github/releases, returns 405 for POST, and passes non-API paths to env.ASSETS', async () => {
let fetchCount = 0;
globalThis.fetch = async (url) => {
fetchCount += 1;
return new Response(
JSON.stringify(String(url).includes('/releases') ? sampleGitHubReleases() : sampleGitHubRepo()),
{ status: 200 },
);
};
const passthroughLog = [];
const env = {
ASSETS: {
async fetch(req) {
passthroughLog.push(`${req.method} ${new URL(req.url).pathname}`);
return new Response(`asset:${new URL(req.url).pathname}`, { status: 200 });
},
},
};
// Non-API GETs pass through to ASSETS without touching GitHub
for (const req of [
new Request('https://reims.dev/', { method: 'GET' }),
new Request('https://reims.dev/changelog', { method: 'GET' }),
new Request('https://reims.dev/_astro/foo.js', { method: 'GET' }),
]) {
const res = await worker.fetch(req, env, createMockCtx());
assert.equal(res.status, 200);
}
assert.equal(fetchCount, 0);
assert.deepEqual(passthroughLog, ['GET /', 'GET /changelog', 'GET /_astro/foo.js']);
// POST on /api/github/releases -> 405 Method Not Allowed JSON
const postRes = await worker.fetch(
new Request('https://reims.dev/api/github/releases', { method: 'POST' }),
env,
createMockCtx(),
);
assert.equal(postRes.status, 405);
assert.equal(postRes.headers.get('Allow'), 'GET, HEAD');
assert.equal(postRes.headers.get('Cache-Control'), 'no-store');
assert.deepEqual(await postRes.json(), { error: 'Method Not Allowed' });
// HEAD on /api/github/releases -> 200 with empty body
const headCtx = createMockCtx();
const headRes = await worker.fetch(
new Request('https://reims.dev/api/github/releases', { method: 'HEAD' }),
env,
headCtx,
);
await headCtx.flush();
assert.equal(headRes.status, 200);
assert.equal(await headRes.text(), '');
// Non-API path when ASSETS binding is absent -> 404
const res404 = await worker.fetch(new Request('https://reims.dev/missing'), {}, createMockCtx());
assert.equal(res404.status, 404);
});
it('filters draft/runtime tags, classifies channels, sorts stable first, and parses bilingual sections accurately', async () => {
globalThis.fetch = async (url) => {
if (String(url).includes('/releases')) {
return new Response(JSON.stringify(sampleGitHubReleases()), { status: 200 });
}
return new Response(JSON.stringify(sampleGitHubRepo()), { status: 200 });
};
const ctx = createMockCtx();
const res = await worker.fetch(new Request('https://reims.dev/api/github/releases'), {}, ctx);
await ctx.flush();
const payload = await res.json();
// Expect only client non-draft releases: v0.2.12, v0.2.11 (stable sorted newest first), then dev, v0.3.0-alpha.1 (prereleases sorted newest first)
assert.deepEqual(
payload.entries.map((e) => ({ tag: e.tag, channel: e.channel })),
[
{ tag: 'v0.2.12', channel: 'stable' },
{ tag: 'v0.2.11', channel: 'stable' },
{ tag: 'dev', channel: 'dev' },
{ tag: 'v0.3.0-alpha.1', channel: 'alpha' },
],
);
const v0212 = payload.entries[0];
assert.equal(v0212.date, '2026-12-02');
assert.deepEqual(v0212.sections['zh-CN'], [
{
title: '重点更新',
items: ['支持文件拖拽与剪贴板修复', '支持 Npcap 无线桥接'],
},
]);
assert.deepEqual(v0212.sections['en-US'], [
{
title: 'Highlights',
items: ['Drag-and-drop file transfer and clipboard fix', 'Npcap Wi-Fi bridging support'],
},
]);
// Single-language dev body mirrors into both zh-CN and en-US and skips blockquote
const devEntry = payload.entries.find((e) => e.tag === 'dev');
assert.deepEqual(devEntry.sections['zh-CN'], [{ title: 'Changes', items: ['Nightly dev build fix'] }]);
assert.deepEqual(devEntry.sections['en-US'], [{ title: 'Changes', items: ['Nightly dev build fix'] }]);
});
it('handles en-first bilingual ordering and missing stargazers/stable fallbacks cleanly', async () => {
const enFirstRelease = [
{
tag_name: 'v0.4.0-rc.1',
name: '',
draft: false,
prerelease: true,
created_at: '2026-12-03T12:00:00Z',
body: [
'<h3 id="en-v0.4.0-rc.1">Features</h3>',
'- English first feature',
'<h3 id="cn-v0.4.0-rc.1">新特性</h3>',
'- 中文后置特性',
].join('\n'),
assets: [],
},
];
globalThis.fetch = async (url) => {
if (String(url).includes('/releases')) {
return new Response(JSON.stringify(enFirstRelease), { status: 200 });
}
return new Response(JSON.stringify({}), { status: 200 });
};
const res = await worker.fetch(new Request('https://reims.dev/api/github/releases'), {}, createMockCtx());
const payload = await res.json();
assert.equal(payload.latest.stars, 1868);
assert.equal(payload.latest.version, 'v0.4.0-rc.1');
assert.equal(payload.entries[0].name, 'Reims-Go v0.4.0-rc.1');
assert.equal(payload.entries[0].channel, 'alpha');
assert.deepEqual(payload.entries[0].sections['en-US'], [{ title: 'Features', items: ['English first feature'] }]);
assert.deepEqual(payload.entries[0].sections['zh-CN'], [{ title: '新特性', items: ['中文后置特性'] }]);
});
it('preserves live releases when repo metadata fails, sorts out-of-order releases before choosing latest, and strips untrusted asset URLs', async () => {
const outOfOrder = [
{
tag_name: 'v0.2.10',
published_at: '2026-11-01T00:00:00Z',
html_url: 'javascript:alert(1)',
assets: [
{
name: 'reims-go-v0.2.10-windows-amd64.exe',
size: 1000,
browser_download_url: 'https://evil.com/malware.exe',
},
],
},
{
tag_name: 'v0.2.12',
published_at: '2026-12-02T20:00:00Z',
html_url: 'https://github.com/Nwflower/Reims-Go/releases/tag/v0.2.12',
assets: [],
},
];
globalThis.fetch = async (url) => {
if (String(url).includes('/releases')) {
return new Response(JSON.stringify(outOfOrder), { status: 200 });
}
return new Response('rate limited repo', { status: 403 });
};
const res = await worker.fetch(new Request('https://reims.dev/api/github/releases'), {}, createMockCtx());
assert.equal(res.status, 200);
const payload = await res.json();
assert.equal(payload.latest.version, 'v0.2.12');
assert.equal(payload.latest.stars, 1868);
const older = payload.entries.find((e) => e.tag === 'v0.2.10');
assert.equal(older.html_url, 'https://github.com/Nwflower/Reims-Go/releases/tag/v0.2.10');
assert.equal(older.exe, null);
});
});
+377
View File
@@ -0,0 +1,377 @@
const GITHUB_REPO_API = 'https://api.github.com/repos/Nwflower/Reims-Go';
const GITHUB_RELEASES_API = 'https://api.github.com/repos/Nwflower/Reims-Go/releases?per_page=25';
const EDGE_FRESH_MS = 300 * 1000; // 5 min fresh window before background SWR refresh
const EDGE_STORE_SECONDS = 3600; // 1 hour max cache lifetime in caches.default
const FALLBACK_CACHE_SECONDS = 60; // Negative-cache static fallback to avoid upstream storms
const UPSTREAM_TIMEOUT_MS = 4000;
const CANONICAL_RELEASES_URL = 'https://github.com/Nwflower/Reims-Go/releases/latest';
const API_SECURITY_HEADERS = {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Content-Security-Policy': "default-src 'none'",
};
const SKIP_SECTIONS = /^(下载|download|downloads|已知限制|known limitations|许可证|license|构建与许可证)/i;
// Isolate-level in-flight coalescing to prevent cache stampedes
let liveInflight = null;
function sanitizeGitHubUrl(raw) {
if (typeof raw !== 'string' || !raw.trim()) return null;
try {
const u = new URL(raw.trim());
if (u.protocol !== 'https:') return null;
const host = u.hostname.toLowerCase();
if (host === 'github.com' || host.endsWith('.githubusercontent.com')) {
return u.href;
}
return null;
} catch {
return null;
}
}
function normalizeTitle(raw) {
return String(raw || '')
.replace(/<[^>]+>/g, '')
.replace(/^#+\s*/, '')
.trim();
}
function parseSections(markdown) {
const lines = String(markdown || '').replace(/\r\n/g, '\n').split('\n');
const sections = [];
let current = null;
let skipping = false;
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line) continue;
const htmlHeading = line.match(/^<h[2-4][^>]*>(.*?)<\/h[2-4]>$/i);
const mdHeading = !htmlHeading ? line.match(/^#{2,4}\s+(.+)$/) : null;
if (htmlHeading || mdHeading) {
const title = normalizeTitle(htmlHeading ? htmlHeading[1] : mdHeading[1]);
if (!title || SKIP_SECTIONS.test(title)) {
skipping = true;
current = null;
} else {
skipping = false;
current = { title, items: [] };
sections.push(current);
}
continue;
}
if (skipping || /^\[中文\]\(#cn-/i.test(line) || line.startsWith('>')) continue;
const bullet = line.match(/^[-*]\s+(.+)$/);
if (bullet && bullet[1].trim()) {
if (!current) {
current = { title: '', items: [] };
sections.push(current);
}
current.items.push(bullet[1].trim());
}
}
return sections.filter((s) => s.items.length > 0);
}
function parseBilingualBody(body) {
const text = String(body || '').replace(/\r\n/g, '\n');
if (!text.trim()) return { 'zh-CN': [], 'en-US': [] };
const cn = text.match(/<h[2-4][^>]*\bid=["']cn-[^"']*["'][^>]*>/i);
const en = text.match(/<h[2-4][^>]*\bid=["']en-[^"']*["'][^>]*>/i);
if (cn && en && cn.index !== undefined && en.index !== undefined) {
const cnChunk = cn.index < en.index ? text.slice(cn.index, en.index) : text.slice(cn.index);
const enChunk = en.index > cn.index ? text.slice(en.index) : text.slice(en.index, cn.index);
const zhSections = parseSections(cnChunk);
const enSections = parseSections(enChunk);
return {
'zh-CN': zhSections.length ? zhSections : enSections,
'en-US': enSections.length ? enSections : zhSections,
};
}
const single = parseSections(text);
return { 'zh-CN': single, 'en-US': single };
}
function extractAssets(assets) {
const list = Array.isArray(assets) ? assets : [];
const exe = list.find((a) => typeof a?.name === 'string' && /windows-amd64\.exe$/i.test(a.name));
const zip = list.find((a) => typeof a?.name === 'string' && /windows-amd64\.zip$/i.test(a.name));
const sha = list.find((a) => typeof a?.name === 'string' && /^SHA256SUMS\.txt$/i.test(a.name));
const exeUrl = sanitizeGitHubUrl(exe?.browser_download_url);
const zipUrl = sanitizeGitHubUrl(zip?.browser_download_url);
const shaUrl = sanitizeGitHubUrl(sha?.browser_download_url);
const digestLines = [exe, zip]
.filter((a) => a?.name && a?.digest && /^sha256:[a-f0-9]{64}$/i.test(a.digest))
.map((a) => `${a.digest.replace(/^sha256:/i, '')} ${a.name}`);
return {
exe: exeUrl ? { name: exe.name, size: Number(exe.size) || 0, url: exeUrl } : null,
zip: zipUrl ? { name: zip.name, size: Number(zip.size) || 0, url: zipUrl } : null,
sha256_url: shaUrl,
sha256_sums: digestLines.join('\n'),
};
}
function classifyChannel(tag, prerelease) {
const lower = tag.toLowerCase();
if (lower === 'dev' || lower.includes('-dev')) return 'dev';
if (prerelease || lower.includes('alpha') || lower.includes('beta') || lower.includes('rc')) return 'alpha';
return 'stable';
}
function isClientTag(tag) {
if (!tag || /^runtime-/i.test(tag)) return false;
return /^v\d+\.\d+/i.test(tag) || /^dev$/i.test(tag) || /^alpha/i.test(tag);
}
async function fetchGitHubJson(url, token) {
const headers = {
Accept: 'application/vnd.github+json',
'User-Agent': 'Reims-Go-Landing-Worker/2.0 (+https://reims.dev)',
};
if (token) headers.Authorization = `Bearer ${token}`;
const init = { headers };
if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
init.signal = AbortSignal.timeout(UPSTREAM_TIMEOUT_MS);
}
const res = await fetch(url, init);
if (!res.ok) {
throw new Error(`GitHub HTTP ${res.status} for ${url}`);
}
return res.json();
}
async function buildLivePayload(env) {
const token = env?.GITHUB_TOKEN || '';
const [repoRes, releasesRes] = await Promise.allSettled([
fetchGitHubJson(GITHUB_REPO_API, token),
fetchGitHubJson(GITHUB_RELEASES_API, token),
]);
if (releasesRes.status !== 'fulfilled') {
throw releasesRes.reason instanceof Error ? releasesRes.reason : new Error(String(releasesRes.reason));
}
const repo = repoRes.status === 'fulfilled' ? repoRes.value : null;
const rawReleases = releasesRes.value;
const releasesArr = Array.isArray(rawReleases) ? rawReleases : [];
const mapped = [];
for (const r of releasesArr) {
if (!r || r.draft) continue;
const tag = String(r.tag_name || '').trim();
if (!isClientTag(tag)) continue;
const prerelease = Boolean(r.prerelease);
const channel = classifyChannel(tag, prerelease);
const published = r.published_at || r.created_at || '';
const assets = extractAssets(r.assets);
const safeHtmlUrl =
sanitizeGitHubUrl(r.html_url) ||
`https://github.com/Nwflower/Reims-Go/releases/tag/${encodeURIComponent(tag)}`;
mapped.push({
entry: {
tag,
name: String(r.name || `Reims-Go ${tag}`).trim(),
published_at: published,
date: published ? published.slice(0, 10) : '',
html_url: safeHtmlUrl,
prerelease,
channel,
exe: assets.exe,
zip: assets.zip,
sha256_url: assets.sha256_url,
sections: parseBilingualBody(r.body || ''),
},
sha256_sums: assets.sha256_sums,
});
}
mapped.sort((a, b) => {
if (a.entry.channel === 'stable' && b.entry.channel !== 'stable') return -1;
if (a.entry.channel !== 'stable' && b.entry.channel === 'stable') return 1;
return (b.entry.published_at || '').localeCompare(a.entry.published_at || '');
});
const entries = mapped.map((m) => m.entry);
const topStable = mapped.find((m) => m.entry.channel === 'stable') || mapped[0] || null;
const nowIso = new Date().toISOString();
const latest = {
synced_at: nowIso,
stars: typeof repo?.stargazers_count === 'number' ? repo.stargazers_count : 1868,
version: topStable?.entry.tag || 'v0.2.12',
published_at: topStable?.entry.published_at || nowIso,
html_url: topStable?.entry.html_url || CANONICAL_RELEASES_URL,
exe: topStable?.entry.exe || null,
zip: topStable?.entry.zip || null,
sha256_url: topStable?.entry.sha256_url || null,
sha256_sums: topStable?.sha256_sums || '',
};
return {
source: 'edge-api',
synced_at: nowIso,
latest,
entries,
};
}
function buildEdgeJsonResponse(payload) {
return new Response(JSON.stringify(payload), {
status: 200,
headers: {
...API_SECURITY_HEADERS,
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': `public, max-age=120, s-maxage=${EDGE_STORE_SECONDS}`,
'X-Reims-Cache': 'MISS',
'X-Reims-Source': 'edge-api',
'X-Reims-Fetched-At': String(Date.now()),
},
});
}
async function fetchAndCacheLive(cache, cacheKey, env) {
if (!liveInflight) {
liveInflight = buildLivePayload(env)
.then((payload) => {
const res = buildEdgeJsonResponse(payload);
return cache
.put(cacheKey, res.clone())
.catch(() => {})
.then(() => res);
})
.finally(() => {
liveInflight = null;
});
}
return liveInflight;
}
async function handleReleasesApi(request, env, ctx) {
const url = new URL(request.url);
const cacheKey = new Request(`${url.origin}/api/github/releases`, { method: 'GET' });
const cache = caches.default;
const isHead = request.method === 'HEAD';
const cached = await cache.match(cacheKey);
if (cached) {
const fetchedAt = Number(cached.headers.get('X-Reims-Fetched-At') || '0');
const isEdgeEntry = cached.headers.get('X-Reims-Source') === 'edge-api';
const isStale = isEdgeEntry && fetchedAt > 0 && Date.now() - fetchedAt > EDGE_FRESH_MS;
if (isStale) {
ctx.waitUntil(fetchAndCacheLive(cache, cacheKey, env).catch(() => {}));
}
const headers = new Headers(cached.headers);
headers.set('X-Reims-Cache', isStale ? 'STALE' : 'HIT');
return new Response(isHead ? null : cached.body, {
status: cached.status,
statusText: cached.statusText,
headers,
});
}
try {
const liveRes = await (liveInflight || buildLivePayload(env).then((payload) => buildEdgeJsonResponse(payload)));
// Cache live response via ctx.waitUntil so client gets an immediate response
const clonedForCache = liveRes.clone();
ctx.waitUntil(cache.put(cacheKey, clonedForCache).catch(() => {}));
if (isHead) {
return new Response(null, { status: liveRes.status, headers: liveRes.headers });
}
return liveRes;
} catch (err) {
console.warn(
JSON.stringify({
level: 'warn',
event: 'github_releases_fallback',
error: err instanceof Error ? err.message : String(err),
}),
);
if (env?.ASSETS) {
try {
const fallbackRes = await env.ASSETS.fetch(new Request(`${url.origin}/data/releases-bundle.json`));
if (fallbackRes.ok) {
const fallbackHeaders = {
...API_SECURITY_HEADERS,
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': `public, max-age=${FALLBACK_CACHE_SECONDS}, s-maxage=${FALLBACK_CACHE_SECONDS}`,
'X-Reims-Cache': 'FALLBACK',
'X-Reims-Source': 'static-fallback',
'X-Reims-Fetched-At': String(Date.now()),
};
const out = new Response(fallbackRes.body, {
status: 200,
headers: fallbackHeaders,
});
// Negative-cache fallback for 60s to shield GitHub API during outages / rate limits
ctx.waitUntil(cache.put(cacheKey, out.clone()).catch(() => {}));
if (isHead) {
return new Response(null, { status: 200, headers: fallbackHeaders });
}
return out;
}
} catch (assetErr) {
console.warn(
JSON.stringify({
level: 'warn',
event: 'github_releases_assets_fallback_failed',
error: assetErr instanceof Error ? assetErr.message : String(assetErr),
}),
);
}
}
return new Response(isHead ? null : JSON.stringify({ error: 'Unable to fetch GitHub releases' }), {
status: 502,
headers: {
...API_SECURITY_HEADERS,
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
},
});
}
}
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
if (url.pathname === '/api/github/releases') {
if (request.method === 'GET' || request.method === 'HEAD') {
return handleReleasesApi(request, env, ctx);
}
return new Response(JSON.stringify({ error: 'Method Not Allowed' }), {
status: 405,
headers: {
...API_SECURITY_HEADERS,
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
Allow: 'GET, HEAD',
},
});
}
if (env?.ASSETS) {
return env.ASSETS.fetch(request);
}
return new Response('Not Found', { status: 404 });
},
};
+5 -2
View File
@@ -1,7 +1,8 @@
{ {
"$schema": "node_modules/wrangler/config-schema.json", "$schema": "node_modules/wrangler/config-schema.json",
"name": "reims-go-landing", "name": "reims-go-landing",
"compatibility_date": "2026-12-02", "main": "worker/index.js",
"compatibility_date": "2026-12-03",
"observability": { "observability": {
"enabled": true, "enabled": true,
"traces": { "traces": {
@@ -10,7 +11,9 @@
}, },
"assets": { "assets": {
"directory": "./dist", "directory": "./dist",
"not_found_handling": "404-page" "binding": "ASSETS",
"not_found_handling": "404-page",
"run_worker_first": ["/api/*"]
}, },
"routes": [ "routes": [
{ {