490 lines
19 KiB
JavaScript
490 lines
19 KiB
JavaScript
import assert from "node:assert/strict";
|
|
import test from "node:test";
|
|
import fs from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { createHash } from "node:crypto";
|
|
import { spawnSync } from "node:child_process";
|
|
import {
|
|
applyCompletionEvidence,
|
|
applyManualReview,
|
|
diagnoseTemplate,
|
|
isEvidenceSourcePath,
|
|
sourceTreeHash,
|
|
} from "../lib/template-doctor.mjs";
|
|
|
|
test("真实模板自动发现并读取完整声明,生成可追溯区域报告", () => {
|
|
const root = new URL("../../packages/", import.meta.url);
|
|
const dirs = fs
|
|
.readdirSync(root)
|
|
.filter(
|
|
(dir) => dir.startsWith("template-") && fs.existsSync(new URL(dir + "/template.json", root)),
|
|
);
|
|
assert.ok(dirs.length > 0);
|
|
for (const dir of dirs) {
|
|
const manifest = JSON.parse(fs.readFileSync(new URL(dir + "/template.json", root), "utf8"));
|
|
const source = fs.readFileSync(new URL(dir + "/taro/index.tsx", root), "utf8");
|
|
const report = diagnoseTemplate(manifest, source);
|
|
assert.equal(report.template, manifest.packageKey);
|
|
assert.ok(report.regions.length > 0);
|
|
assert.equal(report.completionStatus, "unverified");
|
|
for (const region of report.regions) {
|
|
for (const binding of region.bindings) {
|
|
const fields = [
|
|
...manifest.admin.sections.flatMap((s) => s.fields),
|
|
...(manifest.templateFields ?? []),
|
|
...(manifest.trustContentTypes ?? []).flatMap((t) =>
|
|
(t.configFields ?? []).map((f) => ({
|
|
...f,
|
|
previewTarget: f.previewTarget ?? "trust:" + t.type,
|
|
})),
|
|
),
|
|
...(manifest.trustContentTypes ?? []).flatMap((t) =>
|
|
["title", "summary", "content"]
|
|
.filter((name) => !t.hideStandardFields?.includes(name))
|
|
.map((name) => ({ binding: "trust." + name, previewTarget: "trust:" + t.type })),
|
|
),
|
|
];
|
|
assert.ok(
|
|
fields.some(
|
|
(f) =>
|
|
(f.previewTarget === region.target ||
|
|
(region.page === "detail" && f.binding.startsWith("offering."))) &&
|
|
(f.binding === binding || binding.startsWith(f.binding + ".")),
|
|
) ||
|
|
report.issues.some(
|
|
(i) =>
|
|
i.code === "REGION_FIELD_MISSING" &&
|
|
i.target === region.target &&
|
|
i.binding === binding,
|
|
),
|
|
`${manifest.packageKey}: ${region.target} ${binding}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
test("CLI 自动发现全部模板,问题退出 1,未知模板退出 2", () => {
|
|
const cli = new URL("../template-doctor.mjs", import.meta.url);
|
|
const all = spawnSync(process.execPath, [cli.pathname], { encoding: "utf8" });
|
|
const report = JSON.parse(all.stdout);
|
|
assert.equal(all.status, report.templates.some((t) => t.staticStatus === "fail") ? 1 : 0);
|
|
assert.ok(report.templates.length > 0);
|
|
const missing = spawnSync(
|
|
process.execPath,
|
|
[cli.pathname, "--template", "missing-template-fixture"],
|
|
{ encoding: "utf8" },
|
|
);
|
|
assert.equal(missing.status, 2);
|
|
});
|
|
|
|
test("证据哈希范围排除文档、CI 与部署脚本,保留模板交付相关源码", () => {
|
|
assert.equal(isEvidenceSourcePath("docs/ci.md"), false);
|
|
assert.equal(isEvidenceSourcePath("PROJECT_STATUS.md"), false);
|
|
assert.equal(isEvidenceSourcePath(".gitea/workflows/ci.yml"), false);
|
|
assert.equal(isEvidenceSourcePath("deploy/install-release.mjs"), false);
|
|
assert.equal(isEvidenceSourcePath("scripts/deploy/status.mjs"), false);
|
|
assert.equal(isEvidenceSourcePath(".codex-tasks/template-audit-execution/raw/a.json"), false);
|
|
assert.equal(isEvidenceSourcePath("docs/template-completion-rules.md"), true);
|
|
assert.equal(isEvidenceSourcePath("apps/api/src/main.ts"), true);
|
|
assert.equal(isEvidenceSourcePath("packages/template-linjing-editorial/template.json"), true);
|
|
});
|
|
|
|
test("文档改动不改变证据哈希,源码改动仍然改变", () => {
|
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "template-doctor-scope-"));
|
|
try {
|
|
fs.mkdirSync(path.join(root, "docs"), { recursive: true });
|
|
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 1;\n");
|
|
const baseline = sourceTreeHash(root);
|
|
|
|
fs.writeFileSync(path.join(root, "PROJECT_STATUS.md"), "状态更新\n");
|
|
fs.writeFileSync(path.join(root, "docs", "ci.md"), "文档更新\n");
|
|
assert.equal(sourceTreeHash(root), baseline);
|
|
|
|
fs.writeFileSync(path.join(root, "docs", "template-completion-rules.md"), "规则更新\n");
|
|
assert.notEqual(sourceTreeHash(root), baseline);
|
|
|
|
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 2;\n");
|
|
assert.notEqual(sourceTreeHash(root), baseline);
|
|
} finally {
|
|
fs.rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test("pre-commit 证据哈希按暂存区计算,不受部分暂存和未跟踪文件影响", () => {
|
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "template-doctor-staged-"));
|
|
const git = (...args) => {
|
|
const result = spawnSync("git", args, { cwd: root, encoding: "utf8" });
|
|
assert.equal(result.status, 0, result.stderr);
|
|
return result.stdout;
|
|
};
|
|
try {
|
|
git("init", "-q");
|
|
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 1;\n");
|
|
git("add", "app.ts");
|
|
const stagedBaseline = sourceTreeHash(root, { staged: true });
|
|
|
|
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 2;\n");
|
|
fs.writeFileSync(path.join(root, "untracked.ts"), "export const draft = true;\n");
|
|
const stagedWithUnstagedEdits = sourceTreeHash(root, { staged: true });
|
|
assert.equal(stagedWithUnstagedEdits, stagedBaseline);
|
|
assert.notEqual(sourceTreeHash(root), stagedBaseline);
|
|
|
|
git("-c", "user.name=test", "-c", "user.email=test@example.com", "commit", "-qm", "one");
|
|
git("checkout", "--", "app.ts");
|
|
assert.equal(sourceTreeHash(root), stagedBaseline);
|
|
assert.equal(sourceTreeHash(root, { staged: true }), stagedBaseline);
|
|
} finally {
|
|
fs.rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test("完成证据登记必须覆盖全部要求并校验产物哈希", () => {
|
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "template-doctor-evidence-"));
|
|
const artifactPath = path.join(root, "integration.log");
|
|
fs.writeFileSync(artifactPath, "passed\n");
|
|
const sha256 = createHash("sha256").update(fs.readFileSync(artifactPath)).digest("hex");
|
|
const report = {
|
|
template: "fixture",
|
|
staticStatus: "pass",
|
|
completionStatus: "unverified",
|
|
requiredEvidence: ["real-manifest-interaction", "visual-reference"],
|
|
};
|
|
const evidence = (items) => ({
|
|
schemaVersion: 1,
|
|
scope: "模板完成证据登记,保留命令、日志与产物哈希",
|
|
sourceTreeHash: sourceTreeHash(root),
|
|
templates: {
|
|
fixture: Object.fromEntries(
|
|
report.requiredEvidence.map((key) => [
|
|
key,
|
|
items.includes(key)
|
|
? {
|
|
status: "passed",
|
|
exitCode: 0,
|
|
commands: ["pnpm test"],
|
|
artifacts: [{ path: "integration.log", sha256 }],
|
|
}
|
|
: undefined,
|
|
]),
|
|
),
|
|
},
|
|
});
|
|
|
|
try {
|
|
const complete = applyCompletionEvidence(
|
|
[structuredClone(report)],
|
|
evidence(report.requiredEvidence),
|
|
root,
|
|
);
|
|
assert.equal(complete.completionStatus, "complete");
|
|
assert.equal(complete.reports[0].completionStatus, "complete");
|
|
|
|
const incomplete = applyCompletionEvidence(
|
|
[structuredClone(report)],
|
|
evidence(["real-manifest-interaction"]),
|
|
root,
|
|
);
|
|
assert.equal(incomplete.completionStatus, "incomplete");
|
|
assert.match(incomplete.reports[0].completionIssues.join("\n"), /visual-reference/);
|
|
|
|
const invalid = evidence(report.requiredEvidence);
|
|
invalid.templates.fixture["visual-reference"].artifacts[0].sha256 = "0".repeat(64);
|
|
const checksumMismatch = applyCompletionEvidence([structuredClone(report)], invalid, root);
|
|
assert.equal(checksumMismatch.completionStatus, "incomplete");
|
|
assert.match(checksumMismatch.reports[0].completionIssues.join("\n"), /checksum mismatch/);
|
|
|
|
const staleSource = evidence(report.requiredEvidence);
|
|
staleSource.sourceTreeHash = "0".repeat(64);
|
|
const sourceMismatch = applyCompletionEvidence([structuredClone(report)], staleSource, root);
|
|
assert.equal(sourceMismatch.completionStatus, "incomplete");
|
|
assert.match(sourceMismatch.reports[0].completionIssues.join("\n"), /source tree hash/);
|
|
|
|
const failedCommand = evidence(report.requiredEvidence);
|
|
failedCommand.templates.fixture["visual-reference"].exitCode = 1;
|
|
const failed = applyCompletionEvidence([structuredClone(report)], failedCommand, root);
|
|
assert.equal(failed.completionStatus, "incomplete");
|
|
|
|
const placeholderCommand = evidence(report.requiredEvidence);
|
|
placeholderCommand.templates.fixture["visual-reference"].commands = ["pnpm test --out <dir>"];
|
|
const placeholder = applyCompletionEvidence(
|
|
[structuredClone(report)],
|
|
placeholderCommand,
|
|
root,
|
|
);
|
|
assert.equal(placeholder.completionStatus, "incomplete");
|
|
} finally {
|
|
fs.rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test("人工审阅登记只能匹配真实 review,新问题仍会失败", () => {
|
|
const report = {
|
|
template: "fixture",
|
|
staticStatus: "pass",
|
|
completionStatus: "unverified",
|
|
issues: [],
|
|
};
|
|
const reviewed = {
|
|
file: "taro/index.tsx",
|
|
page: "home",
|
|
target: "identity",
|
|
binding: null,
|
|
line: 20,
|
|
message: "条件显示需验证全部分支与空数据入口。",
|
|
severity: "review",
|
|
reviewStatus: "source-reviewed",
|
|
decision: "已核对空数据分支。",
|
|
};
|
|
const clone = (issue) => structuredClone({ ...report, issues: issue ? [issue] : [] });
|
|
const issue = {
|
|
code: "CONDITIONAL_RENDER_REVIEW",
|
|
file: "taro/index.tsx",
|
|
page: "home",
|
|
target: "identity",
|
|
line: 20,
|
|
message: "条件显示需验证全部分支与空数据入口。",
|
|
severity: "review",
|
|
};
|
|
const empty = applyManualReview(
|
|
[clone()],
|
|
[],
|
|
"人工映射审查,保留原诊断,不是自动豁免或全条件组合证明",
|
|
);
|
|
assert.equal(empty[0].staticStatus, "pass");
|
|
assert.equal(
|
|
applyManualReview(
|
|
[clone(issue)],
|
|
[reviewed],
|
|
"人工映射审查,保留原诊断,不是自动豁免或全条件组合证明",
|
|
)[0].staticStatus,
|
|
"pass",
|
|
);
|
|
assert.equal(
|
|
applyManualReview(
|
|
[clone(issue)],
|
|
[],
|
|
"人工映射审查,保留原诊断,不是自动豁免或全条件组合证明",
|
|
)[0].staticStatus,
|
|
"fail",
|
|
);
|
|
assert.throws(() =>
|
|
applyManualReview(
|
|
[clone(issue)],
|
|
[{ ...reviewed, severity: "blocker" }],
|
|
"人工映射审查,保留原诊断,不是自动豁免或全条件组合证明",
|
|
),
|
|
);
|
|
assert.throws(() =>
|
|
applyManualReview(
|
|
[clone(issue)],
|
|
[{ ...reviewed, reviewStatus: "verified" }],
|
|
"人工映射审查,保留原诊断,不是自动豁免或全条件组合证明",
|
|
),
|
|
);
|
|
assert.throws(() => applyManualReview([clone(issue)], [reviewed], "unsupported scope"));
|
|
});
|
|
|
|
const manifest = () => ({
|
|
packageKey: "independent-template",
|
|
admin: {
|
|
sections: [
|
|
{
|
|
page: "home",
|
|
target: "brand",
|
|
previewTargets: [{ key: "identity", label: "人物介绍" }],
|
|
fields: [
|
|
{ binding: "brand.config.visualPresentation.home.badge", previewTarget: "identity" },
|
|
],
|
|
},
|
|
],
|
|
},
|
|
});
|
|
const renderer =
|
|
'function Home({workspace}) { const b = workspace.brand; const p = presentation(workspace, "home"); return <View data-editor-target="identity"><Text>{b.founder}</Text><Text>{p.badge}</Text></View>; }';
|
|
test("整卡仅有标签字段不能通过,报告具体缺失变量", () => {
|
|
const result = diagnoseTemplate(manifest(), renderer);
|
|
assert.equal(result.staticStatus, "fail");
|
|
assert.ok(
|
|
result.issues.some(
|
|
(i) => i.code === "REGION_FIELD_MISSING" && i.binding === "brand.config.founder",
|
|
),
|
|
);
|
|
});
|
|
test("完整字段通过静态检查但不能被宣称模板完成", () => {
|
|
const input = manifest();
|
|
input.admin.sections[0].fields.push({
|
|
binding: "brand.config.founder",
|
|
previewTarget: "identity",
|
|
});
|
|
const result = diagnoseTemplate(input, renderer);
|
|
assert.equal(result.staticStatus, "pass");
|
|
assert.equal(result.completionStatus, "unverified");
|
|
});
|
|
test("嵌套子区独立检查,父区字段不能遮蔽子区缺失", () => {
|
|
const input = manifest();
|
|
input.admin.sections[0].previewTargets.push({ key: "child", label: "姓名" });
|
|
input.admin.sections[0].fields.push({
|
|
binding: "brand.config.founder",
|
|
previewTarget: "identity",
|
|
});
|
|
const result = diagnoseTemplate(
|
|
input,
|
|
renderer.replace(
|
|
"<Text>{b.founder}</Text>",
|
|
'<Text data-editor-target="child">{b.founder}</Text>',
|
|
),
|
|
);
|
|
assert.ok(result.issues.some((i) => i.code === "REGION_FIELD_MISSING" && i.target === "child"));
|
|
});
|
|
test("组合根上的模板字段同样算误绑", () => {
|
|
const input = manifest();
|
|
input.admin.sections[0].previewTargets[0].composite = true;
|
|
input.templateFields = [
|
|
{ page: "home", binding: "brand.config.templateData.method", previewTarget: "identity" },
|
|
];
|
|
const result = diagnoseTemplate(input, renderer);
|
|
assert.ok(
|
|
result.issues.some((i) => i.code === "COMPOSITE_HAS_FIELDS" && i.binding.endsWith(".method")),
|
|
);
|
|
});
|
|
test("跨页目标不能作为合法字段入口", () => {
|
|
const input = manifest();
|
|
input.templateFields = [
|
|
{ page: "profile", binding: "brand.config.templateData.method", previewTarget: "identity" },
|
|
];
|
|
assert.ok(
|
|
diagnoseTemplate(input, renderer).issues.some((i) => i.code === "FIELD_TARGET_MISSING"),
|
|
);
|
|
});
|
|
test("信任子目标必须声明页面,品牌字段不可归给 trust 记录编辑器", () => {
|
|
const input = manifest();
|
|
input.trustContentTypes = [
|
|
{
|
|
type: "credential",
|
|
pages: ["home", "profile"],
|
|
previewTargets: [{ key: "stats" }],
|
|
configFields: [],
|
|
},
|
|
];
|
|
input.admin.sections[0].fields.push({ binding: "brand.description", previewTarget: "stats" });
|
|
const result = diagnoseTemplate(input, renderer);
|
|
assert.ok(result.issues.some((i) => i.code === "TARGET_PAGE_UNSPECIFIED"));
|
|
assert.ok(result.issues.some((i) => i.code === "TARGET_SOURCE_MISMATCH"));
|
|
});
|
|
test("动态路径保留 review,不能静默绿色", () => {
|
|
const result = diagnoseTemplate(manifest(), renderer.replace("b.founder", "b[key]"));
|
|
assert.ok(
|
|
result.issues.some((i) => i.code === "DYNAMIC_VALUE_REVIEW" && i.severity === "review"),
|
|
);
|
|
});
|
|
test("记录区域缺失 recordId 会报告", () => {
|
|
const input = manifest();
|
|
input.admin.sections[0].target = "offering";
|
|
input.admin.sections[0].fields = [{ binding: "offering.name", previewTarget: "identity" }];
|
|
assert.ok(diagnoseTemplate(input, renderer).issues.some((i) => i.code === "RECORD_ID_MISSING"));
|
|
});
|
|
test("section 为 inquiry 但字段全是品牌时按运行时推导品牌来源", () => {
|
|
const input = manifest();
|
|
input.admin.sections[0].target = "inquiry";
|
|
input.admin.sections[0].fields.push({
|
|
binding: "brand.config.founder",
|
|
previewTarget: "identity",
|
|
});
|
|
assert.equal(diagnoseTemplate(input, renderer).staticStatus, "pass");
|
|
});
|
|
test("同一区域混合记录和品牌字段不能豁免", () => {
|
|
const input = manifest();
|
|
input.admin.sections[0].fields.push({ binding: "offering.name", previewTarget: "identity" });
|
|
assert.ok(
|
|
diagnoseTemplate(input, renderer).issues.some((i) => i.code === "TARGET_SOURCE_MISMATCH"),
|
|
);
|
|
});
|
|
test("箭头组件不能被跳过而静默通过", () => {
|
|
assert.ok(
|
|
diagnoseTemplate(
|
|
manifest(),
|
|
'const Home = () => <View data-editor-target="identity">{brand.founder}</View>',
|
|
).issues.some((i) => i.code === "UNSUPPORTED_COMPONENT_REVIEW"),
|
|
);
|
|
});
|
|
test("条件只控制子区显示时不误判成父区展示字段", () => {
|
|
const input = manifest();
|
|
const source =
|
|
'function Home({workspace}) { const b=workspace.brand; return <View data-editor-target="identity">{b.avatarUrl && <Text>头像</Text>}</View>; }';
|
|
const result = diagnoseTemplate(input, source);
|
|
assert.ok(result.issues.some((i) => i.code === "CONDITIONAL_RENDER_REVIEW"));
|
|
assert.ok(!result.issues.some((i) => i.code === "REGION_FIELD_MISSING"));
|
|
});
|
|
test("JSON 合法但 TSX 损坏不能通过诊断", () => {
|
|
assert.ok(
|
|
diagnoseTemplate(manifest(), "function Home( { return <View>").issues.some(
|
|
(i) => i.code === "RENDERER_PARSE_ERROR",
|
|
),
|
|
);
|
|
});
|
|
|
|
test("循环业务卡片追踪实际字段,删除字段会失败", () => {
|
|
const input = manifest();
|
|
input.admin.sections[0].target = "offering";
|
|
input.admin.sections[0].fields = [{ binding: "offering.name", previewTarget: "identity" }];
|
|
const source =
|
|
'function Home({workspace}) { return <View>{workspace.offerings.map(offering).map(item => <View data-editor-target="identity" data-editor-record-id={item.id}>{item.name}{item.area}</View>)}</View>; }';
|
|
const result = diagnoseTemplate(input, source);
|
|
assert.ok(
|
|
result.issues.some(
|
|
(i) => i.code === "REGION_FIELD_MISSING" && i.binding === "offering.config.area",
|
|
),
|
|
);
|
|
input.admin.sections[0].fields.push({
|
|
binding: "offering.config.area",
|
|
previewTarget: "identity",
|
|
});
|
|
assert.ok(!diagnoseTemplate(input, source).issues.some((i) => i.code === "REGION_FIELD_MISSING"));
|
|
});
|
|
|
|
test("结构化信任列表追踪子字段,不跨循环混用别名", () => {
|
|
const input = manifest();
|
|
input.admin.sections[0].target = "trust";
|
|
input.admin.sections[0].fields = [{ binding: "trust.config.stats", previewTarget: "identity" }];
|
|
const source =
|
|
'function Home({workspace}) { const t=workspace.trustPresentation; return <View data-editor-target="identity" data-editor-record-id="fixture">{t.stats.map(item => <Text>{item.value}</Text>)}</View>; }';
|
|
const result = diagnoseTemplate(input, source);
|
|
assert.ok(result.regions[0].bindings.includes("trust.config.stats.value"));
|
|
assert.ok(!result.issues.some((i) => i.code === "REGION_FIELD_MISSING"));
|
|
});
|
|
|
|
test("动态索引保留待核查,但不把容器对象误当可编辑字段", () => {
|
|
const input = manifest();
|
|
const source =
|
|
'function Home({workspace}) { const b=workspace.brand; return <View data-editor-target="identity">{b.config[key]}</View>; }';
|
|
const result = diagnoseTemplate(input, source);
|
|
assert.ok(result.issues.some((i) => i.code === "DYNAMIC_VALUE_REVIEW"));
|
|
assert.ok(
|
|
!result.issues.some((i) => i.code === "REGION_FIELD_MISSING" && i.binding === "brand.config"),
|
|
);
|
|
});
|
|
|
|
test("列表声明存在仍须检查每个展示子字段", () => {
|
|
const input = manifest();
|
|
input.admin.sections[0].target = "trust";
|
|
input.admin.sections[0].fields = [
|
|
{
|
|
binding: "trust.config.stats",
|
|
previewTarget: "identity",
|
|
input: "list",
|
|
itemFields: [{ key: "value" }],
|
|
},
|
|
];
|
|
const source =
|
|
'function Home({workspace}) { const t=workspace.trustPresentation; return <View data-editor-target="identity" data-editor-record-id="fixture">{t.stats.map(item => <Text>{item.value}{item.sub}</Text>)}</View>; }';
|
|
assert.ok(
|
|
diagnoseTemplate(input, source).issues.some(
|
|
(i) => i.code === "LIST_FIELD_MISSING" && i.binding === "trust.config.stats.sub",
|
|
),
|
|
);
|
|
input.admin.sections[0].fields[0].itemFields.push({ key: "sub" });
|
|
assert.ok(!diagnoseTemplate(input, source).issues.some((i) => i.code === "LIST_FIELD_MISSING"));
|
|
});
|