chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,41 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { cpSync, rmSync, existsSync, readdirSync, renameSync } from 'node:fs';
|
||||
import { resolve, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
function run(dir, script) {
|
||||
const npmCLI = process.env.npm_execpath;
|
||||
if (!npmCLI) throw new Error('Run the site build through npm so npm_execpath is available.');
|
||||
const result = spawnSync(process.execPath, [npmCLI, 'run', script], { cwd: resolve(root, dir), stdio: 'inherit' });
|
||||
if (result.error) throw new Error(`Could not run npm ${script}: ${result.error.message}`);
|
||||
if (result.status !== 0) process.exit(result.status || 1);
|
||||
}
|
||||
for (const dir of ['homepage', '.']) {
|
||||
if (!existsSync(resolve(root, dir, 'node_modules'))) throw new Error('Dependencies missing. Run npm run setup first.');
|
||||
}
|
||||
run('homepage', 'build');
|
||||
run('.', 'check:docs');
|
||||
run('.', 'build:docs');
|
||||
const output = resolve(root, 'homepage/out');
|
||||
// The upstream router forwards only `/` and `/docs/`, so the export keeps just the
|
||||
// two HTML entry points at the root. Chunks join the public assets under
|
||||
// /docs/_home/ (next.config.ts assetPrefix); RSC payloads and the not-found
|
||||
// route are never requested because the homepage uses plain links.
|
||||
const homeAssets = resolve(output, 'docs/_home');
|
||||
renameSync(resolve(output, '_next'), resolve(homeAssets, '_next'));
|
||||
for (const entry of readdirSync(output)) {
|
||||
if (!['index.html', '404.html', 'docs'].includes(entry)) rmSync(resolve(output, entry), { recursive: true, force: true });
|
||||
}
|
||||
cpSync(resolve(root, '.vitepress/dist'), resolve(output, 'docs'), { recursive: true });
|
||||
// The leaderboard is a homepage JSX page exported to /docs/models/. Keep a
|
||||
// sibling .html file so /docs/models resolves without a trailing slash.
|
||||
const modelsIndex = resolve(output, 'docs/models/index.html');
|
||||
if (existsSync(modelsIndex)) cpSync(modelsIndex, resolve(output, 'docs/models.html'));
|
||||
run('homepage', 'audit:content');
|
||||
const check = spawnSync(process.execPath, ['scripts/check-site.mjs', output], { cwd: root, stdio: 'inherit' });
|
||||
if (check.status !== 0) process.exit(check.status || 1);
|
||||
// Update the deployment directory only after both applications and their links pass.
|
||||
const destination = resolve(root, 'static-site');
|
||||
rmSync(destination, { recursive: true, force: true });
|
||||
cpSync(output, destination, { recursive: true });
|
||||
console.log('Unified site ready: static-site/ (homepage + /docs/).');
|
||||
@@ -0,0 +1,43 @@
|
||||
// 校验文档之间的相对链接。拆分章节时最容易留下指向已移动内容的死链,
|
||||
// 而 vitepress build 不会因为死链失败。
|
||||
import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs'
|
||||
import { join, relative, dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
|
||||
function walk(dir, out = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (['node_modules', 'homepage', 'shared', 'scripts', 'deploy', 'static-site', 'releases'].includes(name) || name.startsWith('.')) continue
|
||||
const path = join(dir, name)
|
||||
if (statSync(path).isDirectory()) walk(path, out)
|
||||
else if (name.endsWith('.md')) out.push(path)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const files = walk(root)
|
||||
const failures = []
|
||||
let checked = 0
|
||||
|
||||
for (const file of files) {
|
||||
const lines = readFileSync(file, 'utf-8').split('\n')
|
||||
lines.forEach((line, index) => {
|
||||
for (const match of line.matchAll(/\[[^\]]*\]\(([^)\s]+)\)/g)) {
|
||||
const target = match[1]
|
||||
if (/^(https?:|#|mailto:)/.test(target)) continue
|
||||
const [path] = target.split('#')
|
||||
if (!path || !path.endsWith('.md')) continue
|
||||
checked++
|
||||
if (!existsSync(resolve(dirname(file), path))) {
|
||||
failures.push({ file: relative(root, file), line: index + 1, target })
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
console.log(`检查 ${files.length} 篇文档的 ${checked} 个内部链接,失效 ${failures.length} 个`)
|
||||
for (const failure of failures) {
|
||||
console.log(` ${failure.file}:${failure.line} -> ${failure.target}`)
|
||||
}
|
||||
process.exit(failures.length === 0 ? 0 : 1)
|
||||
@@ -0,0 +1,77 @@
|
||||
// 用 mermaid 自带的解析器校验文档里所有 ```mermaid 代码块。
|
||||
// 站点构建不会检查图表语法——语法错的图只在浏览器里报错,
|
||||
// 所以这里在 CI/本地提前拦住。
|
||||
import { readFileSync, readdirSync, statSync } from 'node:fs'
|
||||
import { join, relative, dirname } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { JSDOM } from 'jsdom'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
|
||||
// mermaid 是浏览器库,parse() 需要 DOM 才能初始化。
|
||||
const dom = new JSDOM('<!DOCTYPE html><body></body>', { pretendToBeVisual: true })
|
||||
globalThis.window = dom.window
|
||||
globalThis.document = dom.window.document
|
||||
// Node 22 的 globalThis.navigator 只有 getter,只能用 defineProperty 覆盖。
|
||||
Object.defineProperty(globalThis, 'navigator', {
|
||||
value: dom.window.navigator,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
const { default: mermaid } = await import('mermaid')
|
||||
mermaid.initialize({ startOnLoad: false, securityLevel: 'loose' })
|
||||
|
||||
function walk(dir, out = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (['node_modules', 'homepage', 'shared', 'scripts', 'deploy', 'static-site', 'releases'].includes(name) || name.startsWith('.')) continue
|
||||
const path = join(dir, name)
|
||||
if (statSync(path).isDirectory()) walk(path, out)
|
||||
else if (name.endsWith('.md')) out.push(path)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 取出每个 mermaid 块及其起始行号,行号用于定位报错。 */
|
||||
function blocksOf(text) {
|
||||
const lines = text.split('\n')
|
||||
const blocks = []
|
||||
let start = -1
|
||||
let buffer = []
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i]
|
||||
if (start === -1 && /^\s*```mermaid\s*$/.test(line)) {
|
||||
start = i + 1
|
||||
buffer = []
|
||||
} else if (start !== -1 && /^\s*```\s*$/.test(line)) {
|
||||
blocks.push({ line: start + 1, code: buffer.join('\n') })
|
||||
start = -1
|
||||
} else if (start !== -1) {
|
||||
buffer.push(line)
|
||||
}
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
let total = 0
|
||||
const failures = []
|
||||
|
||||
for (const file of walk(root)) {
|
||||
for (const block of blocksOf(readFileSync(file, 'utf-8'))) {
|
||||
total++
|
||||
try {
|
||||
await mermaid.parse(block.code)
|
||||
} catch (error) {
|
||||
failures.push({
|
||||
file: relative(root, file),
|
||||
line: block.line,
|
||||
message: String(error?.message ?? error).split('\n').slice(0, 6).join('\n'),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`检查 ${total} 个 mermaid 图,失败 ${failures.length} 个`)
|
||||
for (const failure of failures) {
|
||||
console.log(`\n--- ${failure.file}:${failure.line}\n${failure.message}`)
|
||||
}
|
||||
process.exit(failures.length === 0 ? 0 : 1)
|
||||
@@ -0,0 +1,70 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile, readdir } from 'node:fs/promises';
|
||||
import { dirname, resolve, relative } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveSiteFile } from './site-files.mjs';
|
||||
const project = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const root = resolve(process.argv[2] || resolve(project, 'static-site'));
|
||||
async function walk(dir) {
|
||||
const result = [];
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
const path = resolve(dir, entry.name);
|
||||
if (entry.isDirectory()) result.push(...await walk(path));
|
||||
else if (entry.name.endsWith('.html')) result.push(path);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
for (const retired of ['/demo/', '/demo/1/', '/redesign/', '/redesign/1/', '/demo6/preview.html', '/brand/academy.svg', '/icon.svg', '/docs/favicon.svg', '/docs/README.html', '/docs/homepage/README.html', '/docs/homepage/BRAND-ASSETS.html', '/docs/static-site/', '/docs/releases/']) {
|
||||
assert.equal(await resolveSiteFile(root, retired), null, `Retired demo must not be published: ${retired}`);
|
||||
}
|
||||
const failures = [];
|
||||
for (const entry of await readdir(root)) {
|
||||
if (!['index.html', '404.html', 'docs'].includes(entry)) failures.push(`/${entry}: only index.html, 404.html and docs/ may sit at the site root`);
|
||||
}
|
||||
// Missing screenshots may use labelled placeholders; existing images must
|
||||
// reserve their intrinsic dimensions before loading to keep anchors stable.
|
||||
const pendingShots = new Set();
|
||||
const checked = new Map();
|
||||
const targetIds = new Map();
|
||||
const pages = await walk(root);
|
||||
for (const file of pages) {
|
||||
const html = await readFile(file, 'utf8');
|
||||
const route = '/' + relative(root, file).replaceAll('\\', '/');
|
||||
const base = new URL(route, 'https://academy.test');
|
||||
for (const match of html.matchAll(/<(?:a|link|img|script|source|video)\b[^>]*>/g)) {
|
||||
const tag = match[0];
|
||||
for (const [, raw] of tag.matchAll(/(?:href|src|poster)="([^"]+)"/g)) {
|
||||
const url = new URL(raw.replaceAll('&', '&'), base);
|
||||
if (url.origin !== base.origin) continue;
|
||||
// The upstream router forwards only these two prefixes to this service.
|
||||
if (url.pathname !== base.pathname && url.pathname !== '/' && !url.pathname.startsWith('/docs/')) failures.push(`${route}: ${url.pathname} is outside / and /docs/`);
|
||||
if (!checked.has(url.pathname)) checked.set(url.pathname, !!await resolveSiteFile(root, url.pathname));
|
||||
if (!checked.get(url.pathname)) {
|
||||
if (/class="wk-shot-img"/.test(tag) && url.pathname.startsWith('/docs/screenshots/')) pendingShots.add(url.pathname);
|
||||
else failures.push(`${route}: missing ${url.pathname}`);
|
||||
}
|
||||
if (tag.startsWith('<img') && /class="wk-shot-img"/.test(tag)) {
|
||||
if (!/\bwidth="[1-9]\d*"/.test(tag) || !/\bheight="[1-9]\d*"/.test(tag) || /display:\s*none/.test(tag)) {
|
||||
failures.push(`${route}: screenshot ${url.pathname} must reserve its intrinsic size before loading`);
|
||||
}
|
||||
}
|
||||
if (tag.startsWith('<a') && url.hash && checked.get(url.pathname)) {
|
||||
const target = (await resolveSiteFile(root, url.pathname))?.path;
|
||||
if (target?.endsWith('.html')) {
|
||||
if (!targetIds.has(target)) {
|
||||
const content = await readFile(target, 'utf8');
|
||||
targetIds.set(target, new Set([...content.matchAll(/\bid="([^"]+)"/g)].map(match => match[1].replaceAll('&', '&'))));
|
||||
}
|
||||
if (!targetIds.get(target).has(decodeURIComponent(url.hash.slice(1)))) failures.push(`${route}: missing anchor ${url.pathname}${url.hash}`);
|
||||
}
|
||||
}
|
||||
if (url.pathname === '/' && tag.startsWith('<a') && /target="_blank"/.test(tag)) failures.push(`${route}: homepage link opens a new tab`);
|
||||
}
|
||||
}
|
||||
if (/11\.141\.160\.83/.test(html)) failures.push(`${route}: stale private docs host`);
|
||||
if (route.startsWith('/docs/') && !route.endsWith('/404.html') && !/class="wk-brand"[^>]*href="\/"[^>]*target="_self"/.test(html)) failures.push(`${route}: documentation logo must navigate to the main site`);
|
||||
}
|
||||
for (const path of ['/docs/', '/docs/03-features/22-skills-sandbox.html', '/docs/03-features/23-memory.html', '/docs/07-releases/v0.8.3.html', '/docs/07-releases/v0.8.2.html', '/docs/07-releases/v0.8.0.html']) assert.ok(await resolveSiteFile(root, path), path);
|
||||
assert.equal(failures.length, 0, [...new Set(failures)].join('\n'));
|
||||
if (pendingShots.size) console.warn(`Screenshots still pending (placeholder shown): ${[...pendingShots].sort().join(', ')}`);
|
||||
console.log(`Unified site check passed: ${pages.length} pages, ${checked.size} local routes/assets, fragment targets, screenshot dimensions, same-tab homepage links and documentation logos.`);
|
||||
@@ -0,0 +1,13 @@
|
||||
import { mkdirSync, readFileSync } from 'node:fs';
|
||||
import { resolve, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const check = spawnSync(process.execPath, ['scripts/check-site.mjs'], { cwd: root, stdio: 'inherit' });
|
||||
if (check.status !== 0) process.exit(check.status || 1);
|
||||
mkdirSync(resolve(root, 'releases'), { recursive: true });
|
||||
const version = readFileSync(resolve(root, 'VERSION'), 'utf8').trim();
|
||||
const output = resolve(root, `releases/academy-site-v${version}.tar.gz`);
|
||||
const packed = spawnSync('tar', ['-czf', output, '-C', resolve(root, 'static-site'), '.'], { stdio: 'inherit', env: { ...process.env, COPYFILE_DISABLE: '1' } });
|
||||
if (packed.status !== 0) process.exit(packed.status || 1);
|
||||
console.log(`Deployable archive: ${output}`);
|
||||
@@ -0,0 +1,49 @@
|
||||
import { chromium } from 'playwright-core'
|
||||
const b = await chromium.launch({ executablePath: process.env.HOME + '/Library/Caches/ms-playwright/chromium-1161/chrome-mac/Chromium.app/Contents/MacOS/Chromium' })
|
||||
const q = await b.newPage()
|
||||
|
||||
const geom = (page) => page.evaluate(() => {
|
||||
const g = (s) => { const e = document.querySelector(s); if (!e) return null; const r = e.getBoundingClientRect(); return [Math.round(r.left), Math.round(r.right)] }
|
||||
return { logo: g('.VPNavBarTitle'), search: g('.VPNavBarSearch button, .VPNavBarSearch .DocSearch-Button'), menu: g('.VPNavBarMenu'), sidebarItem: g('.VPSidebarItem .link .text') }
|
||||
})
|
||||
|
||||
const scanLine = async (page, label) => {
|
||||
const buf = await page.screenshot({ clip: { x: 0, y: 58, width: 1680, height: 20 } })
|
||||
const url = 'data:image/png;base64,' + buf.toString('base64')
|
||||
const hits = await q.evaluate(async (u) => {
|
||||
const img = new Image(); img.src = u; await img.decode()
|
||||
const c = document.createElement('canvas'); c.width = img.width; c.height = img.height
|
||||
const ctx = c.getContext('2d'); ctx.drawImage(img, 0, 0)
|
||||
const res = []
|
||||
for (const x of [60, 200, 400, 800, 1200, 1560, 1660]) {
|
||||
for (let y = 0; y < img.height; y++) {
|
||||
const d = ctx.getImageData(x, y, 1, 1).data
|
||||
if (d[0] < 248) res.push(`x${x} y${y + 58} ${d[0]},${d[1]},${d[2]}`)
|
||||
}
|
||||
}
|
||||
return res
|
||||
}, url)
|
||||
console.log(' line@' + label, hits.length ? hits.join(' | ') : 'none')
|
||||
}
|
||||
|
||||
for (const w of [1440, 1680, 1920]) {
|
||||
for (const [name, path] of [['landing', '/'], ['doc ', '/03-features/07-agent']]) {
|
||||
const p = await b.newPage({ viewport: { width: w, height: 900 }, deviceScaleFactor: 1 })
|
||||
await p.goto('http://localhost:3011' + path, { waitUntil: 'networkidle' })
|
||||
await p.waitForTimeout(800)
|
||||
console.log(w, name, JSON.stringify(await geom(p)))
|
||||
await p.evaluate(() => window.scrollTo({ top: 1200, behavior: 'instant' }))
|
||||
await p.waitForTimeout(600)
|
||||
if (w === 1680) await scanLine(p, name.trim())
|
||||
await p.close()
|
||||
}
|
||||
}
|
||||
const s = await b.newPage({ viewport: { width: 1680, height: 900 }, deviceScaleFactor: 2 })
|
||||
for (const [name, path] of [['landing', '/'], ['doc', '/03-features/07-agent']]) {
|
||||
await s.goto('http://localhost:3011' + path, { waitUntil: 'networkidle' })
|
||||
await s.waitForTimeout(800)
|
||||
await s.evaluate(() => window.scrollTo({ top: 900, behavior: 'instant' }))
|
||||
await s.waitForTimeout(600)
|
||||
await s.screenshot({ path: `.shots/nav-${name}.png`, clip: { x: 0, y: 0, width: 1680, height: 120 } })
|
||||
}
|
||||
await b.close()
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { test } from 'node:test';
|
||||
import { readScreenshotSizes } from '../.vitepress/screenshot-sizes.mjs';
|
||||
|
||||
test('reserves each screenshot intrinsic ratio and picks up replacement dimensions', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'academy-shot-sizes-'));
|
||||
try {
|
||||
// IHDR bytes from a PNG header; the extractor deliberately does not decode pixels.
|
||||
const header = Buffer.from('89504e470d0a1a0a0000000d4948445200000f0000000840', 'hex');
|
||||
writeFileSync(join(dir, 'wide.png'), header);
|
||||
writeFileSync(join(dir, 'README.md'), 'Not an image');
|
||||
assert.deepEqual(readScreenshotSizes(dir), { '/screenshots/wide.png': { width: 3840, height: 2112 } });
|
||||
header.writeUInt32BE(900, 16);
|
||||
header.writeUInt32BE(1600, 20);
|
||||
writeFileSync(join(dir, 'wide.png'), header);
|
||||
assert.deepEqual(readScreenshotSizes(dir), { '/screenshots/wide.png': { width: 900, height: 1600 } });
|
||||
writeFileSync(join(dir, 'broken.png'), 'truncated');
|
||||
assert.throws(() => readScreenshotSizes(dir), /Invalid PNG screenshot/);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createServer } from 'node:http';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { resolve, dirname, extname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveSiteFile } from './site-files.mjs';
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '../static-site');
|
||||
const portIndex = process.argv.indexOf('--port');
|
||||
const port = Number(portIndex < 0 ? 3000 : process.argv[portIndex + 1]);
|
||||
const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8' };
|
||||
const server = createServer(async (request, response) => {
|
||||
try {
|
||||
if (!['GET', 'HEAD'].includes(request.method)) { response.writeHead(405, { Allow: 'GET, HEAD' }).end(); return; }
|
||||
const url = new URL(request.url, 'http://localhost');
|
||||
if (url.pathname === '/docs') { response.writeHead(308, { Location: '/docs/' + url.search }).end(); return; }
|
||||
let file = await resolveSiteFile(root, url.pathname);
|
||||
const status = file ? 200 : 404;
|
||||
if (!file) file = await resolveSiteFile(root, url.pathname.startsWith('/docs/') ? '/docs/404.html' : '/404.html');
|
||||
if (!file) { response.writeHead(404).end('Not found'); return; }
|
||||
response.writeHead(status, { 'Content-Type': types[extname(file.path)] || 'application/octet-stream', 'Content-Length': file.info.size, 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' });
|
||||
if (request.method === 'HEAD') response.end();
|
||||
else createReadStream(file.path).pipe(response);
|
||||
} catch { response.writeHead(500).end('Unable to serve this page'); }
|
||||
});
|
||||
server.listen(port, '127.0.0.1', () => console.log(`Academy unified preview: http://127.0.0.1:${port}/`));
|
||||
@@ -0,0 +1,14 @@
|
||||
import { stat } from 'node:fs/promises';
|
||||
import { resolve, sep } from 'node:path';
|
||||
export async function resolveSiteFile(root, pathname) {
|
||||
let decoded;
|
||||
try { decoded = decodeURIComponent(pathname); } catch { return null; }
|
||||
if (decoded.includes('\0') || decoded.includes('\\')) return null;
|
||||
const path = resolve(root, `.${decoded}`);
|
||||
if (path !== root && !path.startsWith(root + sep)) return null;
|
||||
for (const candidate of [path, `${path}.html`, resolve(path, 'index.html')]) {
|
||||
const info = await stat(candidate).catch(() => null);
|
||||
if (info?.isFile()) return { path: candidate, info };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { setTimeout } from 'node:timers/promises';
|
||||
|
||||
const image = process.argv[2] || 'academy-site:0.8.3';
|
||||
const name = `academy-site-test-${randomUUID()}`;
|
||||
function docker(...args) {
|
||||
const result = spawnSync('docker', args, { encoding: 'utf8' });
|
||||
if (result.error) throw result.error;
|
||||
assert.equal(result.status, 0, `docker ${args.join(' ')}\n${result.stderr}`);
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
const portName = `${name}-port`;
|
||||
const bashName = `${name}-bash`;
|
||||
const argsName = `${name}-args`;
|
||||
|
||||
async function waitReady(origin, label) {
|
||||
for (let attempt = 0; attempt < 30; attempt++) {
|
||||
try {
|
||||
if ((await fetch(origin, { signal: AbortSignal.timeout(2000) })).ok) return;
|
||||
} catch { /* Nginx may still be starting. */ }
|
||||
await setTimeout(200);
|
||||
}
|
||||
assert.fail(`${label} did not become ready`);
|
||||
}
|
||||
|
||||
try {
|
||||
docker('run', '-d', '--name', name, '-e', 'PORT=9999', '-p', '127.0.0.1::80', image);
|
||||
const origin = `http://${docker('port', name, '80/tcp')}`;
|
||||
docker('exec', name, 'nginx', '-t');
|
||||
docker('exec', name, 'sh', '-c', '! command -v node && test ! -d /build && test ! -e /usr/share/nginx/html/package.json');
|
||||
await waitReady(origin, 'Container');
|
||||
|
||||
// An unrelated PORT must not affect the default or overridden listener.
|
||||
// WEBSITE_NGINX_PORT moves the listen port without a rebuild; the default stays 80.
|
||||
docker('run', '-d', '--name', portName, '-e', 'WEBSITE_NGINX_PORT=8080', '-e', 'PORT=9999', '-p', '127.0.0.1::8080', image);
|
||||
const portOrigin = `http://${docker('port', portName, '8080/tcp')}`;
|
||||
await waitReady(portOrigin, 'Container with WEBSITE_NGINX_PORT=8080');
|
||||
assert.match(docker('exec', portName, 'cat', '/etc/nginx/conf.d/default.conf'), /listen 8080;/);
|
||||
assert.equal((await fetch(portOrigin + '/docs/')).status, 200);
|
||||
|
||||
// Deployment platforms may replace the image entrypoint with /bin/bash -c.
|
||||
// The wrapped command must still render the Nginx template before serving.
|
||||
docker('run', '-d', '--name', bashName, '--entrypoint', '/bin/bash',
|
||||
'-e', 'WEBSITE_NGINX_PORT=8088', '-e', 'uri=must-not-replace-nginx-uri',
|
||||
'-p', '127.0.0.1::8088', image, '-c', 'exec /docker-entrypoint.sh');
|
||||
const bashOrigin = `http://${docker('port', bashName, '8088/tcp')}`;
|
||||
await waitReady(bashOrigin, 'Container launched through Bash');
|
||||
docker('exec', bashName, 'nginx', '-t');
|
||||
assert.match(docker('exec', bashName, 'cat', '/etc/nginx/conf.d/default.conf'), /listen 8088;/);
|
||||
assert.match(docker('exec', bashName, 'cat', '/etc/nginx/conf.d/default.conf'), /try_files \$uri \$uri\.html/);
|
||||
assert.equal((await fetch(bashOrigin + '/docs/')).status, 200);
|
||||
assert.equal((await fetch(bashOrigin + '/docs/03-features/14-wiki')).status, 200);
|
||||
|
||||
// Like frontend, our entrypoint always configures and runs Nginx, even when
|
||||
// the platform passes a shell command as image arguments instead of replacing it.
|
||||
docker('run', '-d', '--name', argsName, '-e', 'WEBSITE_NGINX_PORT=8088',
|
||||
'-p', '127.0.0.1::8088', image, '/bin/bash', '-c', 'nginx; sleep infinity');
|
||||
const argsOrigin = `http://${docker('port', argsName, '8088/tcp')}`;
|
||||
await waitReady(argsOrigin, 'Container with platform command arguments');
|
||||
assert.equal((await fetch(argsOrigin + '/docs/')).status, 200);
|
||||
assert.match(docker('exec', argsName, 'cat', '/proc/1/comm'), /^nginx$/);
|
||||
|
||||
const redirect = await fetch(`${origin}/docs`, { redirect: 'manual' });
|
||||
assert.equal(redirect.status, 308);
|
||||
assert.equal(new URL(redirect.headers.get('location'), origin).origin, origin);
|
||||
assert.equal(new URL(redirect.headers.get('location'), origin).pathname, '/docs/');
|
||||
const assets = new Set(['/docs/_home/brand/academy-original.png', '/docs/_home/product/wiki-browser.png', '/docs/favicon.ico']);
|
||||
for (const path of ['/', '/docs/', '/docs/03-features/14-wiki', '/docs/03-features/14-wiki.html']) {
|
||||
const response = await fetch(origin + path);
|
||||
assert.equal(response.status, 200, path);
|
||||
assert.match(response.headers.get('content-type'), /text\/html/);
|
||||
assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
|
||||
assert.equal(response.headers.get('x-frame-options'), 'SAMEORIGIN');
|
||||
assert.equal(response.headers.get('referrer-policy'), 'strict-origin-when-cross-origin');
|
||||
const html = await response.text();
|
||||
assert.match(html, /Academy/i, path);
|
||||
for (const [, asset] of html.matchAll(/(?:src|href)="([^"?#]+\.(?:js|css))"/g)) {
|
||||
const url = new URL(asset, origin + path);
|
||||
if (url.origin === origin) assets.add(url.pathname);
|
||||
}
|
||||
}
|
||||
assert.ok([...assets].some(path => path.startsWith('/docs/_home/_next/')), 'Homepage scripts are missing');
|
||||
assert.ok([...assets].some(path => path.startsWith('/docs/assets/')), 'Documentation scripts are missing');
|
||||
for (const asset of assets) {
|
||||
const response = await fetch(origin + asset);
|
||||
assert.equal(response.status, 200, asset);
|
||||
assert.doesNotMatch(response.headers.get('content-type'), /text\/html/, asset);
|
||||
}
|
||||
const compressed = await fetch(origin + '/', { headers: { 'Accept-Encoding': 'gzip' } });
|
||||
assert.equal(compressed.headers.get('content-encoding'), 'gzip');
|
||||
for (const path of ['/not-found', '/docs/not-found']) {
|
||||
const response = await fetch(origin + path);
|
||||
assert.equal(response.status, 404, path);
|
||||
assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
|
||||
}
|
||||
console.log(`Docker site check passed: homepage, docs routes, ${assets.size} assets, redirects, 404s, compression, headers, runtime isolation, WEBSITE_NGINX_PORT override and Bash startup.`);
|
||||
} finally {
|
||||
spawnSync('docker', ['rm', '-f', name, portName, bashName, argsName], { stdio: 'ignore' });
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { chromium } from 'playwright-core';
|
||||
|
||||
const origin = process.env.SITE_TEST_URL || 'http://127.0.0.1:3000';
|
||||
const key = 'vitepress-theme-appearance';
|
||||
const browser = await chromium.launch({ channel: 'chrome', headless: true });
|
||||
const context = await browser.newContext({ colorScheme: 'light', viewport: { width: 1440, height: 1000 } });
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
context.on('page', p => p.on('pageerror', error => errors.push(error.message)));
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
async function expectTheme(p, dark) {
|
||||
await p.waitForFunction(expected => document.documentElement.classList.contains('dark') === expected, dark);
|
||||
}
|
||||
async function homepage(p = page) {
|
||||
await p.waitForSelector('#hero-title');
|
||||
assert.equal(new URL(p.url()).pathname, '/');
|
||||
}
|
||||
async function checkVisibleControl(p, selector) {
|
||||
await p.waitForFunction(selector => {
|
||||
const box = document.querySelector(selector)?.getBoundingClientRect();
|
||||
return box && box.width > 0 && box.x >= 0 && box.right <= innerWidth + 1;
|
||||
}, selector);
|
||||
const box = await p.locator(selector).boundingBox();
|
||||
assert.ok(box && box.width > 0 && box.x >= 0 && box.x + box.width <= p.viewportSize().width + 1, `${selector} must fit in the viewport`);
|
||||
}
|
||||
async function headerGeometry(p) {
|
||||
return p.locator('.wk-header').evaluate(header => ({
|
||||
links: [...header.querySelectorAll('#main-navigation a')].map(a => [a.textContent.trim(), a.getAttribute('href')]),
|
||||
controls: [...header.querySelectorAll('.wk-header-inner, .wk-brand, .wk-theme-toggle, .wk-header-github')].map(el => {
|
||||
const box = el.getBoundingClientRect();
|
||||
return [Math.round(box.x), Math.round(box.y), Math.round(box.width), Math.round(box.height)];
|
||||
}),
|
||||
}));
|
||||
}
|
||||
async function currentSidebarLinkVisible(p) {
|
||||
await p.waitForFunction(() => {
|
||||
const sidebar = document.querySelector('.VPSidebar');
|
||||
const active = sidebar?.querySelector('.VPSidebarItem.is-active > .item > a');
|
||||
if (!active) return false;
|
||||
const bounds = sidebar.getBoundingClientRect();
|
||||
const item = active.getBoundingClientRect();
|
||||
return item.height > 0 && item.top >= bounds.top && item.bottom <= bounds.bottom;
|
||||
});
|
||||
}
|
||||
try {
|
||||
assert.equal((await page.goto(origin + '/')).status(), 200);
|
||||
await expectTheme(page, false);
|
||||
const masthead = await headerGeometry(page);
|
||||
await page.getByRole('switch', { name: '切换到深色' }).click();
|
||||
await expectTheme(page, true);
|
||||
assert.equal(await page.evaluate(k => localStorage.getItem(k), key), 'dark');
|
||||
await page.reload();
|
||||
await expectTheme(page, true);
|
||||
await page.locator('#main-navigation').getByRole('link', { name: '文档', exact: true }).click();
|
||||
await page.waitForSelector('.VPDoc h1');
|
||||
await expectTheme(page, true);
|
||||
assert.equal(new URL(page.url()).pathname, '/docs/01-getting-started/03-quickstart.html');
|
||||
assert.match(await page.locator('.VPDoc h1').innerText(), /快速上手/);
|
||||
assert.equal(await page.getByRole('link', { name: '文档首页', exact: true }).count(), 0);
|
||||
assert.deepEqual((await headerGeometry(page)).controls, masthead.controls);
|
||||
assert.deepEqual((await headerGeometry(page)).links.map(link => link[0]), ['快速开始', '架构', '功能', 'API', '客户端', '开发', '版本', 'GitHub']);
|
||||
assert.equal(await page.locator('.wk-header').evaluate(el => el.getBoundingClientRect().height), 64);
|
||||
assert.equal(context.pages().length, 1);
|
||||
// Switching distant sections must reveal the selected sidebar item in both directions.
|
||||
for (const section of ['客户端', '开发', '快速开始', '功能', '架构']) {
|
||||
await page.locator('#main-navigation').getByRole('link', { name: section, exact: true }).click();
|
||||
await page.waitForFunction(section => document.querySelector('#main-navigation a[aria-current="page"]')?.textContent.trim() === section, section);
|
||||
await currentSidebarLinkVisible(page);
|
||||
assert.ok(await page.evaluate(() => window.scrollY < 2), 'Sidebar synchronization must not scroll the document');
|
||||
}
|
||||
// Manual sidebar scrolling must remain untouched until navigation occurs.
|
||||
await page.locator('.VPSidebar').evaluate(el => el.scrollTop = el.scrollHeight);
|
||||
await page.locator('.wk-theme-toggle').click();
|
||||
assert.ok(await page.locator('.VPSidebar').evaluate(el => el.scrollTop > 500));
|
||||
await page.locator('.wk-theme-toggle').click();
|
||||
await page.locator('#main-navigation').getByRole('link', { name: 'API', exact: true }).click();
|
||||
await page.waitForFunction(() => location.pathname.includes('/04-api/'));
|
||||
await page.waitForSelector('.VPDoc h1');
|
||||
await page.waitForFunction(() => document.querySelector('#main-navigation a[aria-current="page"]')?.textContent.trim() === 'API');
|
||||
const palette = await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--wk-paper').trim());
|
||||
assert.equal(palette, '#0b1220');
|
||||
await page.locator('.wk-header-search button').click();
|
||||
await page.locator('#localsearch-input').fill('长期记忆');
|
||||
await page.waitForSelector('.VPLocalSearchBox .result');
|
||||
await page.keyboard.press('Escape');
|
||||
await page.locator('.wk-theme-toggle').click();
|
||||
await expectTheme(page, false);
|
||||
await page.locator('.wk-brand').click();
|
||||
await homepage();
|
||||
await expectTheme(page, false);
|
||||
assert.equal(context.pages().length, 1);
|
||||
|
||||
// Navigation to the current release feature docs, returning through the explicit home link.
|
||||
await page.locator('#release').getByRole('link', { name: '原文引用定位', exact: true }).click();
|
||||
await page.waitForSelector('.VPDoc h1');
|
||||
assert.equal(new URL(page.url()).pathname, '/docs/03-features/18-chat-experience.html');
|
||||
assert.match(await page.locator('.VPDoc h1').innerText(), /会话与对话体验/);
|
||||
await page.locator('.wk-brand').click();
|
||||
await homepage();
|
||||
assert.equal(context.pages().length, 1);
|
||||
|
||||
// Preferences propagate between open homepage and docs tabs in both directions.
|
||||
const docs = await context.newPage();
|
||||
await docs.goto(origin + '/docs/');
|
||||
await docs.waitForSelector('.VPDoc h1');
|
||||
await docs.locator('.wk-theme-toggle').click();
|
||||
await expectTheme(docs, true);
|
||||
await expectTheme(page, true);
|
||||
await page.getByRole('switch', { name: '切换到浅色' }).click();
|
||||
await expectTheme(page, false);
|
||||
await expectTheme(docs, false);
|
||||
await docs.close();
|
||||
|
||||
// With no explicit selection, follow the operating-system preference.
|
||||
const automatic = await browser.newContext({ colorScheme: 'dark' });
|
||||
const autoPage = await automatic.newPage();
|
||||
await autoPage.goto(origin + '/');
|
||||
await expectTheme(autoPage, true);
|
||||
await autoPage.emulateMedia({ colorScheme: 'light' });
|
||||
await expectTheme(autoPage, false);
|
||||
await autoPage.goto(origin + '/docs/');
|
||||
await autoPage.waitForSelector('.VPDoc h1');
|
||||
await expectTheme(autoPage, false);
|
||||
await autoPage.emulateMedia({ colorScheme: 'dark' });
|
||||
await expectTheme(autoPage, true);
|
||||
await automatic.close();
|
||||
|
||||
// Switch and return links remain reachable on a narrow phone viewport.
|
||||
await page.setViewportSize({ width: 320, height: 800 });
|
||||
await page.goto(origin + '/');
|
||||
await checkVisibleControl(page, 'button[role="switch"]');
|
||||
await page.getByRole('switch', { name: '切换到深色' }).click();
|
||||
await expectTheme(page, true);
|
||||
await page.getByRole('button', { name: '打开导航' }).click();
|
||||
await page.locator('#main-navigation').getByRole('link', { name: '文档', exact: true }).click();
|
||||
await page.waitForSelector('.VPDoc h1');
|
||||
await expectTheme(page, true);
|
||||
await checkVisibleControl(page, '.wk-brand');
|
||||
await page.locator('.wk-theme-toggle').click();
|
||||
await page.getByRole('button', { name: '打开导航' }).click();
|
||||
await checkVisibleControl(page, '.wk-header-search button');
|
||||
await page.locator('.wk-header-search button').click();
|
||||
await page.locator('#localsearch-input').fill('长期记忆');
|
||||
await page.waitForSelector('.VPLocalSearchBox .result');
|
||||
await page.keyboard.press('Escape');
|
||||
await page.keyboard.press('Escape');
|
||||
await page.locator('.VPLocalNav button.menu').click();
|
||||
await checkVisibleControl(page, '.VPSidebar.open');
|
||||
await page.keyboard.press('Escape');
|
||||
// A deep link must reveal its entry after hydration, including the mobile drawer.
|
||||
await page.goto(origin + '/docs/05-clients/01-frontend.html');
|
||||
await page.locator('.VPLocalNav button.menu').click();
|
||||
await currentSidebarLinkVisible(page);
|
||||
await page.keyboard.press('Escape');
|
||||
await expectTheme(page, false);
|
||||
await page.locator('.wk-brand').click();
|
||||
await homepage();
|
||||
await expectTheme(page, false);
|
||||
assert.equal(context.pages().length, 1);
|
||||
|
||||
for (const path of ['/docs/03-features/22-skills-sandbox', '/docs/03-features/22-skills-sandbox.html', '/docs/03-features/23-memory.html']) {
|
||||
const response = await context.request.get(origin + path);
|
||||
assert.equal(response.status(), 200, path);
|
||||
assert.ok(!(await response.text()).includes('id="hero-title"'), 'A missing docs route must not fall back to the homepage');
|
||||
}
|
||||
assert.equal((await context.request.get(origin + '/docs/this-page-does-not-exist')).status(), 404);
|
||||
for (const width of [320, 801, 1024, 1920]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
for (const path of ['/', '/docs/01-getting-started/02-installation.html']) {
|
||||
await page.goto(origin + path);
|
||||
await page.waitForSelector('.wk-header');
|
||||
const dimensions = await page.locator('.wk-header').evaluate(el => ({ width: el.getBoundingClientRect().width, height: el.getBoundingClientRect().height, scrollWidth: el.scrollWidth }));
|
||||
assert.equal(dimensions.height, 64);
|
||||
assert.equal(dimensions.width, width);
|
||||
assert.equal(dimensions.scrollWidth, width);
|
||||
await checkVisibleControl(page, '.wk-brand');
|
||||
await page.waitForFunction(() => {
|
||||
const image = document.querySelector('.wk-brand img');
|
||||
return image?.complete && image.naturalWidth === 945 && image.naturalHeight === 650;
|
||||
});
|
||||
assert.equal(await page.locator('.wk-brand img').getAttribute('src'), '/docs/_home/brand/academy-original.png');
|
||||
await checkVisibleControl(page, '.wk-theme-toggle');
|
||||
}
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Integration checks passed: compact full-width mastheads, distinct product/docs navigation, quickstart entry, header search, theme toggle, reload, shared preferences, system theme, same-tab docs/home/logo navigation, mobile controls, and direct docs/404 routes.');
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
Reference in new issue
Block a user