Extract the console runner into web/teaching/console-runner.js (classic script, file:// safe) and mount it on carrier-toolkit.html: per-part 运行本件, per-group 运行本组, 运行全部 and 运行装配, all fed by lessons.mjs ids at build time. Fix runButton() emitting a duplicate class attribute that dropped run-group/run-assembly. Server banner now prints the carrier page URL; new check:carrier-live gate drives the dry lesson end-to-end. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
228 lines
12 KiB
JavaScript
228 lines
12 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* Browser gate for the beginner page web/teaching/carrier-toolkit.html.
|
||
*
|
||
* Default (offline): opens the generated page over file:// — it must stay
|
||
* readable with no server — and asserts: 20 part cards, every system section,
|
||
* copyable commands and links, the runner UI degrading to disabled buttons with
|
||
* an offline banner, no unexpected pageerror/console/request failures, and zero
|
||
* horizontal overflow at 1440×900 and 390×844.
|
||
*
|
||
* --live: starts the teaching server on an ephemeral port, opens the page with
|
||
* its token and runs the environment lesson (dry, seconds) through the in-page
|
||
* runner, asserting the same verdict/results/evidence the console gate expects.
|
||
*
|
||
* Prerequisite: playwright resolvable from web/node_modules.
|
||
* Exit: 0 pass / 1 page problem / 2 prerequisite missing.
|
||
*
|
||
* Usage: node web/tools/teaching-console/check-carrier-page.mjs [--live]
|
||
*/
|
||
import path from "node:path";
|
||
import { spawn } from "node:child_process";
|
||
import { pathToFileURL } from "node:url";
|
||
import { createRequire } from "node:module";
|
||
import { fileURLToPath } from "node:url";
|
||
|
||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||
const REPO = path.resolve(HERE, "../../..");
|
||
const require = createRequire(path.join(REPO, "web/package.json"));
|
||
const PAGE = path.join(REPO, "web/teaching/carrier-toolkit.html");
|
||
const SERVER = path.join(REPO, "web/teaching/server.mjs");
|
||
const LIVE = process.argv.includes("--live");
|
||
|
||
const failures = [];
|
||
const note = (message) => { failures.push(message); console.error(`FAIL ${message}`); };
|
||
|
||
let chromium;
|
||
try {
|
||
({ chromium } = require("playwright"));
|
||
} catch {
|
||
console.error("前置缺失:web/node_modules 下没有 playwright");
|
||
process.exit(2);
|
||
}
|
||
|
||
const VIEWPORTS = [{ width: 1440, height: 900 }, { width: 390, height: 844 }];
|
||
|
||
/** Failure paths we design for: the offline health probe, plus live guard/abort requests. */
|
||
function ignoreExpected(list, { offline }) {
|
||
return list.filter((entry) => {
|
||
if (offline) return !(/\/api\/console\/|ERR_FILE_NOT_FOUND|ERR_CONNECTION_REFUSED|Failed to load resource/.test(entry));
|
||
return !(/status of 401|status of 404|\/api\/console\/events\?.*ERR_ABORTED/.test(entry));
|
||
});
|
||
}
|
||
|
||
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"] });
|
||
|
||
async function openPage(url) {
|
||
const page = await browser.newPage({ viewport: VIEWPORTS[0] });
|
||
const pageErrors = [];
|
||
const consoleErrors = [];
|
||
const failedRequests = [];
|
||
page.on("pageerror", (error) => pageErrors.push(String(error.message ?? error)));
|
||
page.on("console", (message) => { if (message.type() === "error") consoleErrors.push(message.text()); });
|
||
page.on("requestfailed", (request) => failedRequests.push(`${request.url()} ${request.failure()?.errorText ?? ""}`));
|
||
const response = await page.goto(url, { waitUntil: "load" });
|
||
return { page, response, pageErrors, consoleErrors, failedRequests };
|
||
}
|
||
|
||
async function checkOffline() {
|
||
const { page, response, pageErrors, consoleErrors, failedRequests } = await openPage(pathToFileURL(PAGE).href);
|
||
if (!response) note("file:// 打开页面失败(无 response)");
|
||
|
||
const dom = await page.evaluate(() => {
|
||
const text = document.body.innerText;
|
||
const partIds = [...document.querySelectorAll("article.part[id]")].map((node) => node.id);
|
||
const hrefs = [...document.querySelectorAll("a[href]")].map((node) => node.getAttribute("href"));
|
||
const commands = [...document.querySelectorAll("code")].map((node) => node.textContent).join("\n");
|
||
const runParts = [...document.querySelectorAll("button.run-part")];
|
||
return {
|
||
partIds,
|
||
groups: document.querySelectorAll("section.group").length,
|
||
stepRows: document.querySelectorAll("ol.steps li").length,
|
||
hrefs,
|
||
hasConsole: hrefs.some((href) => /console\.html/.test(href)),
|
||
hasCase: hrefs.some((href) => /cases\/carrier\.html/.test(href)),
|
||
hasIndex: hrefs.some((href) => /(^|\/)index\.html$/.test(href)),
|
||
command: /create-part\.mjs P\d{2}/.test(commands) && /create-assembly\.mjs/.test(commands)
|
||
&& /create-all\.mjs/.test(commands),
|
||
leakage: ["[object Object]", "undefined", "NaN", "${"].filter((token) => text.includes(token)),
|
||
runParts: runParts.length,
|
||
runPartsDisabled: runParts.every((button) => button.disabled),
|
||
runAllDisabled: document.getElementById("run")?.disabled ?? null,
|
||
banner: !document.getElementById("offline-banner").hidden,
|
||
runnerState: document.body.dataset.runnerState,
|
||
};
|
||
});
|
||
|
||
const expectedIds = Array.from({ length: 20 }, (_, index) => `P${String(index + 1).padStart(2, "0")}`);
|
||
const missing = expectedIds.filter((id) => !dom.partIds.includes(id));
|
||
if (dom.partIds.length !== 20) note(`零件卡片 ${dom.partIds.length} 张,应为 20 张`);
|
||
if (missing.length) note(`缺少零件卡片:${missing.join(", ")}`);
|
||
// 12 system sections + assembly/tools/troubleshooting.
|
||
if (dom.groups < 15) note(`分组区仅 ${dom.groups} 个,应至少 15 个(12 系统 + 装配/工具/排错)`);
|
||
if (dom.stepRows < 200) note(`界面步骤条目仅 ${dom.stepRows} 条,应至少 200 条(记录 210 步)`);
|
||
if (!dom.hasConsole) note("没有跳转教学控制台的链接");
|
||
if (!dom.hasCase) note("没有跳转旧版案例(cases/carrier.html)的链接");
|
||
if (!dom.hasIndex) note("没有返回 index.html 的链接");
|
||
if (!dom.command) note("缺少可复制的 create-part / create-all / create-assembly 命令");
|
||
for (const token of dom.leakage) note(`模板泄漏标记:${token}`);
|
||
// The runner must degrade, not fail, without a server.
|
||
if (dom.runParts !== 20) note(`运行本件按钮 ${dom.runParts} 个,应为 20 个`);
|
||
if (!dom.runPartsDisabled) note("file:// 下仍有可点的运行本件按钮");
|
||
if (dom.runAllDisabled !== true) note("file:// 下「运行全部」按钮未禁用");
|
||
if (!dom.banner) note("file:// 下未显示离线提示");
|
||
if (dom.runnerState !== "offline") note(`file:// 下 runnerState=${dom.runnerState},应为 offline`);
|
||
for (const error of pageErrors) note(`pageerror: ${error}`);
|
||
for (const error of ignoreExpected(consoleErrors, { offline: true })) note(`console: ${error}`);
|
||
for (const error of ignoreExpected(failedRequests, { offline: true })) note(`request: ${error}`);
|
||
|
||
for (const viewport of VIEWPORTS) {
|
||
await page.setViewportSize(viewport);
|
||
await page.waitForTimeout(120);
|
||
const overflow = await page.evaluate(() => Math.max(0, document.documentElement.scrollWidth - window.innerWidth));
|
||
if (overflow > 0) note(`${viewport.width}px: 横向溢出 ${overflow}px`);
|
||
console.log(`${viewport.width}x${viewport.height}: overflow=${overflow}`);
|
||
}
|
||
await page.close();
|
||
console.log(`offline: 20 卡片 / ${dom.groups} 分区 / ${dom.stepRows} 步 / 运行按钮禁用 / runnerState=${dom.runnerState}`);
|
||
}
|
||
|
||
function startServer() {
|
||
const token = "carrier-gate-" + Date.now().toString(36);
|
||
const child = spawn(process.execPath, [SERVER], {
|
||
cwd: REPO,
|
||
env: { ...process.env, TEACHING_PORT: "0", TEACHING_TOKEN: token },
|
||
stdio: ["ignore", "pipe", "pipe"],
|
||
});
|
||
const ready = new Promise((resolve, reject) => {
|
||
let buffer = "";
|
||
const timer = setTimeout(() => reject(new Error("server did not report an origin within 15s")), 15000);
|
||
child.stdout.on("data", (chunk) => {
|
||
buffer += chunk.toString("utf8");
|
||
for (const line of buffer.split("\n")) {
|
||
try {
|
||
const parsed = JSON.parse(line);
|
||
if (parsed.origin) {
|
||
clearTimeout(timer);
|
||
resolve({ origin: parsed.origin, token });
|
||
return;
|
||
}
|
||
} catch {
|
||
/* partial line */
|
||
}
|
||
}
|
||
});
|
||
child.on("exit", (code) => reject(new Error(`server exited early (${code})`)));
|
||
});
|
||
return { child, ready };
|
||
}
|
||
|
||
async function checkLive() {
|
||
const server = startServer();
|
||
try {
|
||
const { origin, token } = await server.ready;
|
||
console.log(`live: ${origin}`);
|
||
const { page, pageErrors, consoleErrors, failedRequests } = await openPage(`${origin}/carrier-toolkit.html?token=${token}`);
|
||
await page.waitForFunction(() => document.body.dataset.runnerState === "ready", null, { timeout: 120000 });
|
||
await page.waitForFunction(() => document.querySelectorAll("#preflight-chips .chip.bad").length === 0
|
||
&& document.querySelectorAll("#preflight-chips .chip").length >= 5, null, { timeout: 120000 });
|
||
const ready = await page.evaluate(() => ({
|
||
runParts: document.querySelectorAll("button.run-part").length,
|
||
runPartsEnabled: [...document.querySelectorAll("button.run-part")].every((button) => !button.disabled),
|
||
groups: document.querySelectorAll("button.run-group").length,
|
||
assembly: Boolean(document.querySelector("button.run-assembly")),
|
||
status: document.getElementById("status").textContent,
|
||
}));
|
||
if (ready.runParts !== 20) note(`live: 运行本件按钮 ${ready.runParts} 个`);
|
||
if (!ready.runPartsEnabled) note("live: 前置已满足但运行本件按钮仍禁用");
|
||
if (ready.groups < 12) note(`live: 分组运行按钮 ${ready.groups} 个,应至少 12 个`);
|
||
if (!ready.assembly) note("live: 缺少装配运行按钮");
|
||
|
||
// The environment lesson is the dry run: seconds, not minutes. Never click a
|
||
// part card here — those rebuild a full model headed.
|
||
await page.click('button[data-lesson-id="lesson-carrier-environment"]');
|
||
await page.waitForFunction(() => document.getElementById("terminal").textContent.includes("前置全部满足"), null, { timeout: 180000 });
|
||
await page.waitForFunction(() => /通过|失败|运行失败|超时|已取消/.test(document.getElementById("verdict").textContent), null, { timeout: 240000 });
|
||
const outcome = await page.evaluate(() => ({
|
||
verdict: document.getElementById("verdict").textContent,
|
||
rows: document.querySelectorAll("#results tbody tr").length,
|
||
evidence: document.querySelectorAll('#evidence a[href*="/api/console/artifacts/"]').length,
|
||
runnerState: document.body.dataset.runnerState,
|
||
buttonsReenabled: [...document.querySelectorAll("button[data-run]")].every((button) => !button.disabled),
|
||
}));
|
||
if (!/通过/.test(outcome.verdict)) note(`live: 判定为「${outcome.verdict}」`);
|
||
if (outcome.rows < 1) note("live: 结果表没有行");
|
||
if (outcome.evidence < 1) note("live: 没有报告 JSON 证据链接");
|
||
if (outcome.runnerState !== "ready") note(`live: 结束后 runnerState=${outcome.runnerState}`);
|
||
if (!outcome.buttonsReenabled) note("live: 结束后运行按钮未恢复");
|
||
console.log(`live: verdict=${outcome.verdict} rows=${outcome.rows} evidence=${outcome.evidence}`);
|
||
|
||
for (const viewport of VIEWPORTS) {
|
||
await page.setViewportSize(viewport);
|
||
await page.waitForTimeout(200);
|
||
const overflow = await page.evaluate(() => Math.max(0, document.documentElement.scrollWidth - window.innerWidth));
|
||
if (overflow > 0) note(`live ${viewport.width}px: 横向溢出 ${overflow}px`);
|
||
}
|
||
for (const error of pageErrors) note(`live pageerror: ${error}`);
|
||
for (const error of ignoreExpected(consoleErrors, { offline: false })) note(`live console: ${error}`);
|
||
for (const error of ignoreExpected(failedRequests, { offline: false })) note(`live request: ${error}`);
|
||
await page.close();
|
||
} finally {
|
||
server.child.kill("SIGTERM");
|
||
await new Promise((resolve) => server.child.once("exit", resolve));
|
||
}
|
||
}
|
||
|
||
try {
|
||
if (LIVE) await checkLive();
|
||
else await checkOffline();
|
||
} finally {
|
||
await browser.close();
|
||
}
|
||
|
||
if (failures.length) {
|
||
console.error(`\ncarrier-toolkit.html 门禁失败:${failures.length} 项`);
|
||
process.exit(1);
|
||
}
|
||
console.log(`\ncarrier-toolkit.html 门禁通过${LIVE ? "(live)" : ""}`);
|