/** * Static validation for the teaching hub. * * Catches the failures that would otherwise only show up as a dead spotlight * in class: a missing lesson, a typo'd check kind, a fixture or screenshot that * is not served, or a catalogue that drifted away from the lessons. * * Two sets share the schema: the 32-chapter guide (`teach/lessons`) and the * standalone PBR course (`teach/pbr/lessons`). Each set is validated on its own * and reported together. * * `node tools/web/teach/check-teach.mjs` → tests/golden/TEACH-HUB-001/check-report.json */ import fs from "node:fs"; import path from "node:path"; const REPO_ROOT = path.resolve(import.meta.dirname, "../../.."); const PUBLIC = path.join(REPO_ROOT, "web/app/public"); const REPORT_DIR = path.join(REPO_ROOT, "tests/golden/TEACH-HUB-001"); const CHECK_KINDS = new Set(["text", "count", "exists", "attr", "value", "scene", "event"]); const ACTION_KINDS = new Set([ "click", "dblclick", "fill", "selectOption", "importFile", "command", "join", "parent", "python", "save", "export", "wait", "workspace", "select", "asset", "openScene", "render", "renderDownload", "engineRender", ]); const SCENE_FIELDS = ["object", "active", "mode", "workspace", "dirty", "saved", "objectCount", "minObjects", "selected"]; const TARGET_KEYS = ["testid", "css", "role", "name", "nth"]; const EVENT_NAMES = new Set(["saved", "exported", "render"]); const SETS = [ { name: "main", dir: path.join(PUBLIC, "teach/lessons"), filePattern: /^ch\d{2}\.json$/, chapterPattern: /^ch\d{2}$/, stepPattern: /^ch\d{2}-s\d+$/, expectedCount: 32, catalogFile: path.join(PUBLIC, "teach/catalog.json"), }, { name: "pbr", dir: path.join(PUBLIC, "teach/pbr/lessons"), filePattern: /^pbr-\d{2}\.json$/, chapterPattern: /^pbr-\d{2}$/, stepPattern: /^pbr-\d{2}-s\d+$/, expectedCount: 4, catalogFile: path.join(PUBLIC, "teach/pbr/catalog.json"), }, ]; function servedFile(url) { if (typeof url !== "string" || !url.startsWith("/")) return null; return path.join(PUBLIC, url.slice(1)); } function validateSet(set, issues) { const issue = (chapter, message) => issues.push({ set: set.name, chapter, message }); const files = fs.existsSync(set.dir) ? fs.readdirSync(set.dir).filter((name) => set.filePattern.test(name)).sort() : []; if (files.length !== set.expectedCount) issue("set", `应有 ${set.expectedCount} 个课时文件,实际 ${files.length} 个`); const chapters = []; const numbers = []; for (const name of files) { const id = name.replace(/\.json$/, ""); const lesson = JSON.parse(fs.readFileSync(path.join(set.dir, name), "utf8")); const row = { id, steps: Array.isArray(lesson.steps) ? lesson.steps.length : 0, checks: 0, demos: 0 }; chapters.push(row); numbers.push(lesson.number); if (lesson.schemaVersion !== 1) issue(id, "schemaVersion 必须为 1"); if (lesson.id !== id) issue(id, `文件 id 与课时 id(${lesson.id})不一致`); if (!set.chapterPattern.test(id)) issue(id, "课时 id 不合法"); if (!/^part-[a-g]$/.test(String(lesson.part))) issue(id, `part 不合法:${lesson.part}`); if (!lesson.title || !lesson.summary) issue(id, "缺少 title 或 summary"); if (!Array.isArray(lesson.objectives) || lesson.objectives.length === 0) issue(id, "缺少 objectives"); if (!Number.isFinite(lesson.minutes) || lesson.minutes <= 0) issue(id, "minutes 必须是正数"); if (lesson.unit !== undefined && typeof lesson.unit !== "string") issue(id, "unit 必须是字符串"); if (lesson.setup?.fixture) { const file = servedFile(lesson.setup.fixture); if (!file || !fs.existsSync(file)) issue(id, `练习工程不存在:${lesson.setup.fixture}`); } if (lesson.setup?.entry !== undefined && !["web", "native"].includes(lesson.setup.entry)) { issue(id, `setup.entry 只能是 web 或 native,当前 ${lesson.setup.entry}`); } if (lesson.setup?.manual) { const file = servedFile(lesson.setup.manual); if (!file || !fs.existsSync(file)) issue(id, `manual 页面不存在:${lesson.setup.manual}`); } if (!Array.isArray(lesson.steps) || lesson.steps.length < 3) issue(id, "至少需要 3 个步骤"); const stepIds = new Set(); for (const step of lesson.steps ?? []) { const where = step.id || "(缺 id)"; if (!step.id || !set.stepPattern.test(step.id)) issue(id, `${where}: 步骤 id 格式应为 ${set.name === "main" ? "chNN-sN" : "pbr-NN-sN"}`); if (stepIds.has(step.id)) issue(id, `${step.id}: 步骤 id 重复`); stepIds.add(step.id); if (!step.title || !step.text) issue(id, `${where}: 缺少 title/text`); if (!Array.isArray(step.checks) || step.checks.length === 0) issue(id, `${where}: 缺少 checks`); if (step.target) checkTarget(id, `${where}.target`, step.target); if (step.referenceImage) { const file = servedFile(step.referenceImage); if (!file || !fs.existsSync(file)) issue(id, `${where}: 参考图不存在 ${step.referenceImage}`); } for (const check of step.checks ?? []) { row.checks += 1; if (!CHECK_KINDS.has(check.kind)) { issue(id, `${where}: 未知检查类型 ${check.kind}`); continue; } if (check.kind === "scene") { const present = SCENE_FIELDS.filter((field) => field in check); if (!present.length) issue(id, `${where}: scene 检查没有任何条件`); for (const field of Object.keys(check)) { if (field !== "kind" && field !== "label" && !SCENE_FIELDS.includes(field)) issue(id, `${where}: 未知 scene 字段 ${field}`); } } else if (check.kind === "event") { if (!EVENT_NAMES.has(check.event)) issue(id, `${where}: 未知事件 ${check.event}`); } else { checkTarget(id, `${where}.checks[${check.kind}]`, check.target); if (check.kind === "attr" && !check.attribute) issue(id, `${where}: attr 检查缺少 attribute`); if (check.kind === "count" && check.equals === undefined && check.atLeast === undefined) issue(id, `${where}: count 检查缺少 equals/atLeast`); } } for (const action of step.demo ?? []) { row.demos += 1; if (!ACTION_KINDS.has(action.kind)) issue(id, `${where}: 未知演示动作 ${action.kind}`); if (["click", "dblclick", "fill", "selectOption"].includes(action.kind)) checkTarget(id, `${where}.demo.${action.kind}`, action.target); if (["fill", "selectOption"].includes(action.kind) && typeof action.value !== "string") issue(id, `${where}: ${action.kind} 缺少 value`); if (["openScene", "importFile"].includes(action.kind)) { const file = servedFile(action.url); if (!file || !fs.existsSync(file)) issue(id, `${where}: ${action.kind} 资源不存在:${action.url}`); if (typeof action.fileName !== "string" || !action.fileName) issue(id, `${where}: ${action.kind} 缺少 fileName`); } } } } /* Numbers are contiguous from 1: a gap means a lesson was deleted or renamed * without updating its neighbours. */ const sorted = [...numbers].sort((a, b) => a - b); if (sorted.some((value, index) => value !== index + 1)) issue("set", `章节编号不连续:${sorted.join(",")}`); /* The catalogue is generated; assert it is in sync with the lessons. */ if (!fs.existsSync(set.catalogFile)) issue("catalog", "catalog.json 不存在,请运行 build-teach-catalog.mjs"); else { const catalog = JSON.parse(fs.readFileSync(set.catalogFile, "utf8")); if (catalog.count !== files.length) issue("catalog", `count=${catalog.count},课时文件 ${files.length} 个`); const listed = (catalog.chapters ?? []).map((chapter) => chapter.id).sort(); if (listed.join(",") !== files.map((file) => file.replace(/\.json$/, "")).sort().join(",")) { issue("catalog", "目录章节与课时文件不一致,请重新生成 catalog.json"); } for (const chapter of catalog.chapters ?? []) { const lesson = JSON.parse(fs.readFileSync(path.join(set.dir, `${chapter.id}.json`), "utf8")); if (chapter.title !== lesson.title) issue(chapter.id, "目录标题与课时不一致"); if (chapter.steps !== lesson.steps.length) issue(chapter.id, "目录步数与课时不一致"); if (chapter.manual !== (lesson.setup?.manual ?? chapter.manual)) issue(chapter.id, "目录手册链接与课时不一致"); } } return { name: set.name, chapters: chapters.length, steps: chapters.reduce((total, chapter) => total + chapter.steps, 0), checks: chapters.reduce((total, chapter) => total + chapter.checks, 0), demos: chapters.reduce((total, chapter) => total + chapter.demos, 0), }; } function checkTarget(chapter, where, target) { const issue = (id, message) => issues.push({ set: currentSet, chapter: id, message }); if (!target || typeof target !== "object") { issue(chapter, `${where}: 缺少 target`); return; } const keys = Object.keys(target); if (!keys.length) issue(chapter, `${where}: target 为空`); for (const key of keys) if (!TARGET_KEYS.includes(key)) issue(chapter, `${where}: 未知 target 字段 ${key}`); if (!target.testid && !target.css && !target.role && !target.name) issue(chapter, `${where}: target 没有定位条件`); if ((target.testid || target.css) && target.role) issue(chapter, `${where}: testid/css 与 role 同时出现,前者优先`); } const issues = []; /* `checkTarget` runs inside `validateSet`; keep the set name in reach for it. */ let currentSet = "main"; const totals = SETS.map((set) => { currentSet = set.name; return validateSet(set, issues); }); currentSet = "main"; fs.mkdirSync(REPORT_DIR, { recursive: true }); const main = totals[0]; const report = { schemaVersion: 1, tool: "check-teach", generatedAt: new Date().toISOString(), chapters: main.chapters, steps: totals.reduce((total, set) => total + set.steps, 0), checks: totals.reduce((total, set) => total + set.checks, 0), demos: totals.reduce((total, set) => total + set.demos, 0), sets: totals, issues, ok: issues.length === 0, status: "NOT_CLAIMED", }; fs.writeFileSync(path.join(REPORT_DIR, "check-report.json"), `${JSON.stringify(report, null, 2)}\n`); console.log(totals.map((set) => `${set.name}: ${set.chapters} lessons, ${set.steps} steps, ${set.checks} checks`).join(" · ")); console.log(`${issues.length} issue(s)`); for (const item of issues) console.log(` [${item.set}/${item.chapter}] ${item.message}`); process.exitCode = issues.length === 0 ? 0 : 1;