Remove Python from report validation and rendering
This commit is contained in:
1 parent
c1a5cc20e9
commit
fb7948307c
19 files changed
+743
-90
No files matched your search
@@ -11,6 +11,7 @@
|
|||||||
"ky": "^2.0.2",
|
"ky": "^2.0.2",
|
||||||
"marked": "15.0.12",
|
"marked": "15.0.12",
|
||||||
"pinyin-pro": "^3.29.3",
|
"pinyin-pro": "^3.29.3",
|
||||||
|
"pngjs": "7.0.0",
|
||||||
"yauzl": "^3.4.0",
|
"yauzl": "^3.4.0",
|
||||||
"zod": "^4.4.3",
|
"zod": "^4.4.3",
|
||||||
},
|
},
|
||||||
@@ -18,6 +19,7 @@
|
|||||||
"@modelcontextprotocol/client": "^2.0.0",
|
"@modelcontextprotocol/client": "^2.0.0",
|
||||||
"@types/archiver": "^8.0.0",
|
"@types/archiver": "^8.0.0",
|
||||||
"@types/bun": "^1.3.14",
|
"@types/bun": "^1.3.14",
|
||||||
|
"@types/pngjs": "6.0.5",
|
||||||
"@types/yauzl": "^3.4.0",
|
"@types/yauzl": "^3.4.0",
|
||||||
"bun-types": "^1.3.14",
|
"bun-types": "^1.3.14",
|
||||||
"oxlint": "1.86.0",
|
"oxlint": "1.86.0",
|
||||||
@@ -81,6 +83,8 @@
|
|||||||
|
|
||||||
"@types/node": ["@types/node@25.9.1", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="],
|
"@types/node": ["@types/node@25.9.1", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="],
|
||||||
|
|
||||||
|
"@types/pngjs": ["@types/pngjs@6.0.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ=="],
|
||||||
|
|
||||||
"@types/readdir-glob": ["@types/readdir-glob@1.1.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg=="],
|
"@types/readdir-glob": ["@types/readdir-glob@1.1.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg=="],
|
||||||
|
|
||||||
"@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="],
|
"@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="],
|
||||||
@@ -253,6 +257,8 @@
|
|||||||
|
|
||||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||||
|
|
||||||
|
"pngjs": ["pngjs@7.0.0", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="],
|
||||||
|
|
||||||
"process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
|
"process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
|
||||||
|
|
||||||
"process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
|
"process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
|
||||||
|
|||||||
@@ -45,6 +45,7 @@
|
|||||||
"ky": "^2.0.2",
|
"ky": "^2.0.2",
|
||||||
"marked": "15.0.12",
|
"marked": "15.0.12",
|
||||||
"pinyin-pro": "^3.29.3",
|
"pinyin-pro": "^3.29.3",
|
||||||
|
"pngjs": "7.0.0",
|
||||||
"yauzl": "^3.4.0",
|
"yauzl": "^3.4.0",
|
||||||
"zod": "^4.4.3"
|
"zod": "^4.4.3"
|
||||||
},
|
},
|
||||||
@@ -52,6 +53,7 @@
|
|||||||
"@modelcontextprotocol/client": "^2.0.0",
|
"@modelcontextprotocol/client": "^2.0.0",
|
||||||
"@types/archiver": "^8.0.0",
|
"@types/archiver": "^8.0.0",
|
||||||
"@types/bun": "^1.3.14",
|
"@types/bun": "^1.3.14",
|
||||||
|
"@types/pngjs": "6.0.5",
|
||||||
"@types/yauzl": "^3.4.0",
|
"@types/yauzl": "^3.4.0",
|
||||||
"bun-types": "^1.3.14",
|
"bun-types": "^1.3.14",
|
||||||
"oxlint": "1.86.0",
|
"oxlint": "1.86.0",
|
||||||
|
|||||||
@@ -7,7 +7,8 @@
|
|||||||
| `monthly.md` | 模板本体。**可变的皮**:章节标题、表格结构允许增删改名——填充逻辑从标题反推数据需求(`src/domains/seal/reports/describe.ts`),改这里通常不用改代码 |
|
| `monthly.md` | 模板本体。**可变的皮**:章节标题、表格结构允许增删改名——填充逻辑从标题反推数据需求(`src/domains/seal/reports/describe.ts`),改这里通常不用改代码 |
|
||||||
| `assets/` | 报告配图(图 1 数据图、图 2/3 占位图),相对引用,渲染时随 md 一起解析 |
|
| `assets/` | 报告配图(图 1 数据图、图 2/3 占位图),相对引用,渲染时随 md 一起解析 |
|
||||||
| `examples/` | 填充真实数据的成品示例(结构参考 + 测试夹具) |
|
| `examples/` | 填充真实数据的成品示例(结构参考 + 测试夹具) |
|
||||||
| `validate.py` / `render.py` | 结构校验 + HTML/PNG/PDF 渲染引擎,随 CLI 内嵌,由 `report validate` / `report render` 调用;也保留独立 Python 入口 |
|
| `report.css` | HTML、长图和 A4 PDF 共用的版式,随 CLI 内嵌 |
|
||||||
|
| `validate.py` / `render.py` | 历史独立工具,保留作迁移对照;CLI 已使用 `src/domains/seal/reports/` 下的 TypeScript 校验和渲染模块,不再内嵌或调用这两个脚本 |
|
||||||
|
|
||||||
模板纪律见模板仓库 README:不引入 frontmatter/占位符标记(结构即契约)、正文不含 HTML 注释、表格只换数据行。
|
模板纪律见模板仓库 README:不引入 frontmatter/占位符标记(结构即契约)、正文不含 HTML 注释、表格只换数据行。
|
||||||
|
|
||||||
@@ -23,6 +24,6 @@ seal-use report render reports/报告.md --out build/报告
|
|||||||
|
|
||||||
校验、渲染仅操作本地文件,不需要 `--corp`、登录或网络取数。校验失败返回结构化问题、退出码 1,并阻止导出。渲染成功返回产物路径、格式和字节数;HTML 内嵌本地配图及公式资源,可随产物移动。默认产出 HTML、完整长图 PNG、A4 分页 PDF;`--format html|png|pdf` 可选格式,PNG/PDF 同时保留 HTML。
|
校验、渲染仅操作本地文件,不需要 `--corp`、登录或网络取数。校验失败返回结构化问题、退出码 1,并阻止导出。渲染成功返回产物路径、格式和字节数;HTML 内嵌本地配图及公式资源,可随产物移动。默认产出 HTML、完整长图 PNG、A4 分页 PDF;`--format html|png|pdf` 可选格式,PNG/PDF 同时保留 HTML。
|
||||||
|
|
||||||
运行环境:校验和渲染需要 Python 3;PNG/PDF 需要 Chrome/Chromium,PNG 还需要该 Python 环境中的 Pillow。可通过 `--python`、`--chrome` 指定可执行文件。自动发现优先使用 PATH 或 Playwright 缓存中已有的 `chrome-headless-shell`,再查普通 Chrome/Chromium;不自动安装浏览器。CLI 自带 Markdown 解析器,不再运行 `npx`。含公式的报告首次渲染需联网下载 KaTeX 0.16.11 到 `~/.cache/seal-use/report-render/`,之后复用缓存;可用 `SEAL_REPORT_CACHE_DIR` 指定缓存目录。
|
运行环境:生成月报、校验和 HTML 导出使用 CLI 自带运行时;PNG/PDF 另需 Chrome/Chromium,可用 `--chrome` 指定。长 PNG 拼接由随二进制打包的 JavaScript 库完成,无需 Python、Pillow、Node 或 npm。`--python` 已移除,传入时返回用法错误(退出码 2)。自动发现优先使用 PATH 或 Playwright 缓存中已有的 `chrome-headless-shell`,再查普通 Chrome/Chromium;不自动安装浏览器。CLI 自带 Markdown 解析器,不运行 `npx`。含公式的报告首次渲染需联网下载 KaTeX 0.16.11 到 `~/.cache/seal-use/report-render/`,之后复用缓存;可用 `SEAL_REPORT_CACHE_DIR` 指定缓存目录。
|
||||||
|
|
||||||
配图仍是模板示例/占位图,当前不会按当月数据自动重绘;对外使用前需替换。结构与数值校验通过也不代表示例值或人工裁决已经完备,应同时检查月报返回的 `notes`。
|
配图仍是模板示例/占位图,当前不会按当月数据自动重绘;对外使用前需替换。结构与数值校验通过也不代表示例值或人工裁决已经完备,应同时检查月报返回的 `notes`。
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
:root { --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --bg:#fff; --head:#f6f8fa; }
|
||||||
|
* { box-sizing: border-box; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
||||||
|
body { margin:0 auto; max-width:900px; padding:48px 56px; background:var(--bg); color:var(--fg);
|
||||||
|
font:16px/1.75 -apple-system,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;
|
||||||
|
-webkit-font-smoothing:antialiased; }
|
||||||
|
h1 { font-size:28px; line-height:1.35; margin:0 0 20px; padding-bottom:14px; border-bottom:2px solid var(--line); }
|
||||||
|
h2 { font-size:22px; margin:40px 0 14px; padding-bottom:8px; border-bottom:1px solid var(--line); }
|
||||||
|
h3 { font-size:18px; margin:28px 0 12px; }
|
||||||
|
h4 { font-size:16px; margin:22px 0 10px; color:var(--muted); }
|
||||||
|
p, li { margin:10px 0; }
|
||||||
|
blockquote { margin:16px 0; padding:10px 18px; border-left:4px solid #4c8bf5; background:var(--head);
|
||||||
|
color:#33404d; border-radius:0 6px 6px 0; }
|
||||||
|
blockquote p { margin:6px 0; }
|
||||||
|
code { background:rgba(129,139,152,.14); padding:.15em .4em; border-radius:4px;
|
||||||
|
font:.9em ui-monospace,SFMono-Regular,Menlo,monospace; }
|
||||||
|
pre { background:#0d1117; color:#e6edf3; padding:16px 18px; border-radius:8px; overflow:auto; }
|
||||||
|
pre code { background:none; padding:0; color:inherit; font-size:13px; line-height:1.6; }
|
||||||
|
table { border-collapse:collapse; width:100%; margin:16px 0; font-size:14px; }
|
||||||
|
th, td { border:1px solid var(--line); padding:8px 10px; text-align:left; vertical-align:top; }
|
||||||
|
th { background:var(--head); font-weight:600; }
|
||||||
|
tr:nth-child(even) td { background:#fbfcfd; }
|
||||||
|
img { max-width:100%; border:1px solid var(--line); border-radius:6px; display:block; margin:14px 0; }
|
||||||
|
em { color:var(--muted); font-size:14px; }
|
||||||
|
hr { border:0; border-top:1px solid var(--line); margin:32px 0; }
|
||||||
|
a { color:#0969da; }
|
||||||
|
.katex-display { margin:18px 0; }
|
||||||
|
@page { size: A4; margin: 14mm 12mm; }
|
||||||
|
@media print {
|
||||||
|
body { max-width:none; padding:0; font-size:12pt; }
|
||||||
|
h2, h3 { page-break-after:avoid; break-after:avoid; }
|
||||||
|
tr, img, blockquote { page-break-inside:avoid; break-inside:avoid; }
|
||||||
|
thead { display:table-header-group; }
|
||||||
|
}
|
||||||
@@ -142,7 +142,7 @@ seal-use report render reports/报告.md --out build/报告
|
|||||||
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
|
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
|
||||||
- 默认模板、配图和校验/渲染引擎由仓库 Git 管理并随二进制内嵌,不依赖当前目录或原模板仓库。`--out` 保存 Markdown 与配图;不传则继续返回 `content`。`--output-file` 保存的是 JSON。
|
- 默认模板、配图和校验/渲染引擎由仓库 Git 管理并随二进制内嵌,不依赖当前目录或原模板仓库。`--out` 保存 Markdown 与配图;不传则继续返回 `content`。`--output-file` 保存的是 JSON。
|
||||||
- 结果里的 `next` 给出 CLI 校验与导出命令。`report validate` / `report render` 不需企业登录;校验失败返回 issues 和退出码 1,阻止导出。`render` 默认产出 HTML / 全长 PNG / A4 PDF,`--format html|png|pdf` 可选格式。已有文件须显式 `--overwrite` 才允许替换。
|
- 结果里的 `next` 给出 CLI 校验与导出命令。`report validate` / `report render` 不需企业登录;校验失败返回 issues 和退出码 1,阻止导出。`render` 默认产出 HTML / 全长 PNG / A4 PDF,`--format html|png|pdf` 可选格式。已有文件须显式 `--overwrite` 才允许替换。
|
||||||
- 本地运行环境:Python 3;PNG/PDF 另需 Chrome/Chromium,PNG 需 Pillow(可用 `--python` / `--chrome` 指定环境)。Markdown 解析已打包,不需 npm/npx;含公式时首次渲染联网缓存 KaTeX。模板配图仍是示例/占位图,对外使用前检查 `notes` 并替换配图。
|
- 本地运行环境:生成月报、校验与 HTML 导出只需 CLI;PNG/PDF 另需 Chrome/Chromium(可用 `--chrome` 指定)。无需 Python、Pillow、Node 或 npm;`--python` 已移除,传入返回用法错误。Markdown 解析和长图拼接已打包;含公式时首次渲染联网缓存 KaTeX。模板配图仍是示例/占位图,对外使用前检查 `notes` 并替换配图。
|
||||||
- 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
|
- 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
|
||||||
|
|
||||||
### 人工裁决回填(算出人工审核准确率)
|
### 人工裁决回填(算出人工审核准确率)
|
||||||
|
|||||||
@@ -13,9 +13,9 @@ import type { ParsedArgs } from "../types.js";
|
|||||||
export async function handleLocalReportCommand(action: "validate" | "render", args: ParsedArgs) {
|
export async function handleLocalReportCommand(action: "validate" | "render", args: ParsedArgs) {
|
||||||
const file = args.command[2] ?? stringOption(args.options.file);
|
const file = args.command[2] ?? stringOption(args.options.file);
|
||||||
if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : ""}`);
|
if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : ""}`);
|
||||||
const python = stringOption(args.options.python);
|
if ("python" in args.options) throw usageError("报告工具已移除 Python 依赖,请去掉 --python 参数。");
|
||||||
if (action === "validate") {
|
if (action === "validate") {
|
||||||
const result = await validateReportFile(file, { python });
|
const result = await validateReportFile(file);
|
||||||
printJson(result, outputOptions(args.options));
|
printJson(result, outputOptions(args.options));
|
||||||
if (!result.valid) throw new CliError("报告校验未通过,请按 issues 修正后重试。", 1);
|
if (!result.valid) throw new CliError("报告校验未通过,请按 issues 修正后重试。", 1);
|
||||||
return;
|
return;
|
||||||
@@ -23,7 +23,7 @@ export async function handleLocalReportCommand(action: "validate" | "render", ar
|
|||||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||||
if (!out) throw usageError("Usage: seal-use report render <报告文件.md> --out <产物路径词干>");
|
if (!out) throw usageError("Usage: seal-use report render <报告文件.md> --out <产物路径词干>");
|
||||||
const result = await renderReportFile(file, {
|
const result = await renderReportFile(file, {
|
||||||
out, python, format: stringOption(args.options.format), width: numberOption(args.options.width),
|
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
|
||||||
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
|
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
|
||||||
});
|
});
|
||||||
printJson(result, outputOptions(args.options));
|
printJson(result, outputOptions(args.options));
|
||||||
|
|||||||
+3
-4
@@ -631,8 +631,8 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
{
|
{
|
||||||
name: "validate",
|
name: "validate",
|
||||||
summary: "Check a local report's structure, images, totals, and formulas",
|
summary: "Check a local report's structure, images, totals, and formulas",
|
||||||
usage: ["seal-use report validate <报告.md> [--python <executable>]"],
|
usage: ["seal-use report validate <报告.md>"],
|
||||||
options: [{ flag: "--python <executable>", description: "Python 3 executable; defaults to python3 on PATH" }],
|
options: [],
|
||||||
description: "Local only: no --corp, credentials, or Seal requests. Returns JSON issues; exit 1 if validation fails."
|
description: "Local only: no --corp, credentials, or Seal requests. Returns JSON issues; exit 1 if validation fails."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -643,11 +643,10 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
{ flag: "--out <stem>", description: "Output filename stem; extensions are appended" },
|
{ flag: "--out <stem>", description: "Output filename stem; extensions are appended" },
|
||||||
{ flag: "--format <format>", description: "all (default), html, png, or pdf; PNG/PDF also produce HTML" },
|
{ flag: "--format <format>", description: "all (default), html, png, or pdf; PNG/PDF also produce HTML" },
|
||||||
{ flag: "--width <px>", description: "PNG viewport width, default 1200 (320–5000)" },
|
{ flag: "--width <px>", description: "PNG viewport width, default 1200 (320–5000)" },
|
||||||
{ flag: "--python <executable>", description: "Python 3 executable; defaults to python3 on PATH" },
|
|
||||||
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
|
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
|
||||||
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files after successful rendering" }
|
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files after successful rendering" }
|
||||||
],
|
],
|
||||||
description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Requires Python 3; PNG/PDF also need Chrome/Chromium, PNG needs Pillow. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency."
|
description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Validation and HTML use the bundled runtime; PNG/PDF need Chrome/Chromium. No Python or Pillow required. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "review set",
|
name: "review set",
|
||||||
|
|||||||
+3
-2
@@ -61,7 +61,7 @@ export const VALUE_FLAGS = new Set([
|
|||||||
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
|
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
|
||||||
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
|
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
|
||||||
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
|
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
|
||||||
"prod", "prod-corp", "prodCorp", "purpose", "python", "q", "query",
|
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
|
||||||
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum",
|
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum",
|
||||||
"reviewed-by", "reviewedBy",
|
"reviewed-by", "reviewedBy",
|
||||||
"report-id",
|
"report-id",
|
||||||
@@ -115,7 +115,7 @@ export const KNOWN_FLAGS = new Set([
|
|||||||
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
|
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
|
||||||
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
|
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
|
||||||
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
|
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
|
||||||
"prod", "prod-corp", "prodCorp", "publish", "purpose", "python", "q",
|
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
|
||||||
"query", "quiet", "r", "recode", "record-id", "record-ids",
|
"query", "quiet", "r", "recode", "record-id", "record-ids",
|
||||||
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo",
|
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo",
|
||||||
"report-id",
|
"report-id",
|
||||||
@@ -169,6 +169,7 @@ export function parseArgs(argv: string[]): ParsedArgs {
|
|||||||
const eqIdx = raw.indexOf("=");
|
const eqIdx = raw.indexOf("=");
|
||||||
const key = raw.slice(0, eqIdx);
|
const key = raw.slice(0, eqIdx);
|
||||||
const val = raw.slice(eqIdx + 1);
|
const val = raw.slice(eqIdx + 1);
|
||||||
|
if (key === "python") throw usageError("--python 已移除:报告工具不再依赖 Python。");
|
||||||
options[key] = val;
|
options[key] = val;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+1
-1
@@ -13,7 +13,7 @@ declare module "*.yml" {
|
|||||||
export default content;
|
export default content;
|
||||||
}
|
}
|
||||||
|
|
||||||
declare module "*.py" {
|
declare module "*.css" {
|
||||||
const content: string;
|
const content: string;
|
||||||
export default content;
|
export default content;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { spawn } from "node:child_process"
|
||||||
|
import { accessSync, constants, existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||||
|
import { homedir } from "node:os"
|
||||||
|
import { dirname, join } from "node:path"
|
||||||
|
import { pathToFileURL } from "node:url"
|
||||||
|
import { CliError, validationError } from "../../../core/errors.js"
|
||||||
|
import { pngDimensions, stitchPngBands, type PngBand } from "./png.js"
|
||||||
|
|
||||||
|
export const PNG_BAND_HEIGHT = 14_000
|
||||||
|
|
||||||
|
function executable(path: string | null | undefined): path is string {
|
||||||
|
if (!path) return false
|
||||||
|
try { accessSync(path, constants.X_OK); return statSync(path).isFile() } catch { return false }
|
||||||
|
}
|
||||||
|
|
||||||
|
function cachedHeadlessShells(): string[] {
|
||||||
|
const roots = [join(homedir(), "Library", "Caches", "ms-playwright"), join(homedir(), ".cache", "ms-playwright")]
|
||||||
|
if (process.env.LOCALAPPDATA) roots.push(join(process.env.LOCALAPPDATA, "ms-playwright"))
|
||||||
|
const candidates: string[] = []
|
||||||
|
for (const root of roots) {
|
||||||
|
if (!existsSync(root)) continue
|
||||||
|
for (const version of readdirSync(root, { withFileTypes: true })) {
|
||||||
|
if (!version.isDirectory() || !version.name.startsWith("chromium_headless_shell-")) continue
|
||||||
|
const versionRoot = join(root, version.name)
|
||||||
|
for (const platform of readdirSync(versionRoot, { withFileTypes: true })) {
|
||||||
|
if (!platform.isDirectory() || !platform.name.startsWith("chrome-headless-shell-")) continue
|
||||||
|
for (const name of ["chrome-headless-shell", "chrome-headless-shell.exe"]) {
|
||||||
|
const path = join(versionRoot, platform.name, name)
|
||||||
|
if (executable(path)) candidates.push(path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return candidates.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dedicated headless shells avoid desktop Chrome startup/shutdown problems on headless hosts. */
|
||||||
|
export function findReportChrome(explicit?: string): string {
|
||||||
|
if (explicit) {
|
||||||
|
const path = Bun.which(explicit) ?? explicit
|
||||||
|
if (executable(path)) return path
|
||||||
|
throw validationError("未找到 Chrome/Chromium:请安装浏览器,或通过 --chrome <可执行文件> 指定")
|
||||||
|
}
|
||||||
|
const candidates = [
|
||||||
|
Bun.which("chrome-headless-shell"), ...cachedHeadlessShells(),
|
||||||
|
...["google-chrome", "chromium", "chromium-browser", "chrome", "msedge"].map((name) => Bun.which(name)),
|
||||||
|
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||||
|
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
||||||
|
join(process.env.PROGRAMFILES || "C:/Program Files", "Google", "Chrome", "Application", "chrome.exe"),
|
||||||
|
join(process.env["PROGRAMFILES(X86)"] || "C:/Program Files (x86)", "Microsoft", "Edge", "Application", "msedge.exe")
|
||||||
|
]
|
||||||
|
const path = candidates.find(executable)
|
||||||
|
if (!path) throw validationError("未找到 Chrome/Chromium:请安装浏览器,或通过 --chrome <可执行文件> 指定")
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
function chrome(binary: string, profile: string, args: string[]): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const child = spawn(binary, [
|
||||||
|
"--headless", "--disable-gpu", "--hide-scrollbars", `--user-data-dir=${profile}`,
|
||||||
|
"--no-first-run", "--no-default-browser-check", "--force-device-scale-factor=1",
|
||||||
|
"--run-all-compositor-stages-before-draw", ...args
|
||||||
|
], { stdio: ["ignore", "pipe", "pipe"] })
|
||||||
|
let title = "", tail = "", diagnostic = "", settled = false
|
||||||
|
const finish = (error?: Error) => {
|
||||||
|
if (settled) return
|
||||||
|
settled = true
|
||||||
|
clearTimeout(timeout)
|
||||||
|
if (error) reject(error); else resolve(title)
|
||||||
|
}
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
child.kill("SIGKILL")
|
||||||
|
finish(new CliError("浏览器渲染超时。可通过 --chrome 指定可用的 Chrome/Chromium 或 chrome-headless-shell。", 1))
|
||||||
|
}, 60_000)
|
||||||
|
// dump-dom contains embedded images and can be very large. Retain only the measured title,
|
||||||
|
// including cross-chunk matches, rather than imposing a new buffer limit on report size.
|
||||||
|
child.stdout?.on("data", (chunk: Buffer) => {
|
||||||
|
if (!args.includes("--dump-dom")) return
|
||||||
|
const text = tail + chunk.toString()
|
||||||
|
for (const match of text.matchAll(/<title>PAGEH:(\d+)<\/title>/g)) title = `PAGEH:${match[1]}`
|
||||||
|
tail = text.slice(-256)
|
||||||
|
})
|
||||||
|
child.stderr?.on("data", (chunk: Buffer) => { diagnostic = (diagnostic + chunk.toString()).slice(-65_536) })
|
||||||
|
child.once("error", (error) => finish(new CliError(`报告浏览器执行失败:${error.message}`, 1)))
|
||||||
|
child.once("close", (code, signal) => finish(code === 0 ? undefined : new CliError(`报告浏览器执行失败:${diagnostic.trim() || `退出 ${code ?? signal}`}`, 1)))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 注入测量脚本,用 dump-dom 取文档真实高度,等待图片和公式字体加载。 */
|
||||||
|
async function measureHeight(html: string, width: number, binary: string, profile: string): Promise<number> {
|
||||||
|
const probe = join(dirname(html), "_measure.html")
|
||||||
|
const script = '<script>async function measureReport(){await document.fonts.ready;document.title="PAGEH:"+Math.ceil(document.documentElement.scrollHeight)}window.addEventListener("load",measureReport);setTimeout(measureReport,3000)</script>'
|
||||||
|
writeFileSync(probe, readFileSync(html, "utf8").replace("</body>", script + "</body>"))
|
||||||
|
const output = await chrome(binary, profile, [`--window-size=${width},1000`, "--virtual-time-budget=30000", "--dump-dom", pathToFileURL(probe).href])
|
||||||
|
const hits = [...output.matchAll(/PAGEH:(\d+)/g)]
|
||||||
|
const height = Number(hits.at(-1)?.[1])
|
||||||
|
if (!Number.isSafeInteger(height) || height <= 0) throw new CliError("量取页面高度失败,未生成 PNG。", 1)
|
||||||
|
return height
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 位移样式放在所有样式之后,避免长图分带重复开头或丢失结尾。 */
|
||||||
|
export function offsetReportBand(html: string, offset: number): string {
|
||||||
|
return html.replace("</head>", `<style>body{margin-top:-${offset}px}</style></head>`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renderPng(html: string, output: string, width: number, binary: string, profile: string) {
|
||||||
|
const height = await measureHeight(html, width, binary, profile)
|
||||||
|
const screenshot = async (source: string, destination: string, bandHeight: number) => {
|
||||||
|
await chrome(binary, profile, [`--screenshot=${destination}`, `--window-size=${width},${bandHeight}`, "--virtual-time-budget=30000", pathToFileURL(source).href])
|
||||||
|
const dimensions = pngDimensions(destination)
|
||||||
|
if (dimensions.width !== width || dimensions.height !== bandHeight) throw new CliError("浏览器截图尺寸与请求不一致,未发布 PNG。", 1)
|
||||||
|
}
|
||||||
|
if (height <= PNG_BAND_HEIGHT) {
|
||||||
|
await screenshot(html, output, height)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const bands: PngBand[] = []
|
||||||
|
const content = readFileSync(html, "utf8")
|
||||||
|
for (let offset = 0; offset < height; offset += PNG_BAND_HEIGHT) {
|
||||||
|
const bandHeight = Math.min(PNG_BAND_HEIGHT, height - offset)
|
||||||
|
const source = join(dirname(html), `_band${bands.length}.html`)
|
||||||
|
const file = join(dirname(html), `_band${bands.length}.png`)
|
||||||
|
writeFileSync(source, offsetReportBand(content, offset))
|
||||||
|
await screenshot(source, file, bandHeight)
|
||||||
|
bands.push({ file, height: bandHeight })
|
||||||
|
}
|
||||||
|
stitchPngBands(bands, width, height, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PNG 为完整长图;PDF 使用 Chrome 的 A4 打印管线,保留表头重复和行不跨页样式。 */
|
||||||
|
export async function renderBrowserArtifacts(html: string, formats: string[], width: number, binary: string, profile: string) {
|
||||||
|
const stem = html.slice(0, -".html".length)
|
||||||
|
if (formats.includes("png")) await renderPng(html, `${stem}.png`, width, binary, profile)
|
||||||
|
if (formats.includes("pdf")) {
|
||||||
|
await chrome(binary, profile, [`--print-to-pdf=${stem}.pdf`, "--no-pdf-header-footer", "--virtual-time-budget=30000", pathToFileURL(html).href])
|
||||||
|
if (!existsSync(`${stem}.pdf`) || statSync(`${stem}.pdf`).size === 0) throw new CliError("浏览器未生成 PDF 文件。", 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
|
|||||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
|
import { PNG } from "pngjs";
|
||||||
import { runCli } from "../../../cli/runner.js";
|
import { runCli } from "../../../cli/runner.js";
|
||||||
import { buildMonthlyReport } from "./monthly.js";
|
import { buildMonthlyReport } from "./monthly.js";
|
||||||
import { renderReportFile, saveReportMarkdown, validateReportFile } from "./files.js";
|
import { renderReportFile, saveReportMarkdown, validateReportFile } from "./files.js";
|
||||||
@@ -108,7 +109,7 @@ describe("local report CLI", () => {
|
|||||||
expect(JSON.parse(bad.stdout)).toMatchObject({ valid: false, issues: expect.arrayContaining([expect.objectContaining({ code: "IMG001" })]) });
|
expect(JSON.parse(bad.stdout)).toMatchObject({ valid: false, issues: expect.arrayContaining([expect.objectContaining({ code: "IMG001" })]) });
|
||||||
});
|
});
|
||||||
|
|
||||||
test("renders self-contained HTML without Chrome, npm, or Seal credentials", async () => {
|
test("renders self-contained HTML without Python, Chrome, npm, or Seal credentials", async () => {
|
||||||
const dir = workspace();
|
const dir = workspace();
|
||||||
writeFileSync(join(dir, "image.svg"), '<svg xmlns="http://www.w3.org/2000/svg"><text>hello</text></svg>');
|
writeFileSync(join(dir, "image.svg"), '<svg xmlns="http://www.w3.org/2000/svg"><text>hello</text></svg>');
|
||||||
const file = localReport(dir, validReport + "\n\n");
|
const file = localReport(dir, validReport + "\n\n");
|
||||||
@@ -137,7 +138,9 @@ describe("local report CLI", () => {
|
|||||||
const file = localReport(dir);
|
const file = localReport(dir);
|
||||||
const cases: Array<[string[], number]> = [
|
const cases: Array<[string[], number]> = [
|
||||||
[["report", "validate", join(dir, "absent.md")], 13],
|
[["report", "validate", join(dir, "absent.md")], 13],
|
||||||
[["report", "validate", file, "--python", join(dir, "absent-python")], 13],
|
[["report", "validate", file, "--python", join(dir, "absent-python")], 2],
|
||||||
|
[["report", "render", file, "--out", join(dir, "out"), "--python=python3"], 2],
|
||||||
|
[["report", "monthly", "--month", "2026-08", "--python=python3"], 2],
|
||||||
[["report", "render", file], 2],
|
[["report", "render", file], 2],
|
||||||
[["report", "render", file, "--out", join(dir, "out"), "--format", "docx"], 2],
|
[["report", "render", file, "--out", join(dir, "out"), "--format", "docx"], 2],
|
||||||
[["report", "render", file, "--out", join(dir, "out"), "--width", "10"], 2]
|
[["report", "render", file, "--out", join(dir, "out"), "--width", "10"], 2]
|
||||||
@@ -155,4 +158,31 @@ describe("local report CLI", () => {
|
|||||||
expect(readFileSync(out + ".html", "utf8")).toBe("existing html");
|
expect(readFileSync(out + ".html", "utf8")).toBe("existing html");
|
||||||
expect(readFileSync(out + ".pdf", "utf8")).toBe("existing pdf");
|
expect(readFileSync(out + ".pdf", "utf8")).toBe("existing pdf");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("browser failure after HTML generation preserves outputs and keeps child logs out of stdout", async () => {
|
||||||
|
const dir = workspace();
|
||||||
|
const file = localReport(dir), out = join(dir, "result");
|
||||||
|
const chrome = join(dir, "fake chrome");
|
||||||
|
writeFileSync(chrome, "#!/bin/sh\nprintf 'browser fixture failed\\n' >&2\nexit 1\n", { mode: 0o755 });
|
||||||
|
writeFileSync(out + ".html", "existing html");
|
||||||
|
writeFileSync(out + ".pdf", "existing pdf");
|
||||||
|
const result = await runCli(["report", "render", file, "--out", out, "--format", "pdf", "--chrome", chrome, "--overwrite"]);
|
||||||
|
expect(result.exitCode).toBe(1);
|
||||||
|
expect(result.stdout).toBe("");
|
||||||
|
expect(result.stderr).toContain("browser fixture failed");
|
||||||
|
expect(readFileSync(out + ".html", "utf8")).toBe("existing html");
|
||||||
|
expect(readFileSync(out + ".pdf", "utf8")).toBe("existing pdf");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("large browser DOM output and split measurement tags do not impose an export buffer limit", async () => {
|
||||||
|
const dir = workspace(), file = localReport(dir), out = join(dir, "large");
|
||||||
|
const screenshot = new PNG({ width: 320, height: 2000 });
|
||||||
|
screenshot.data.fill(255);
|
||||||
|
const fixture = join(dir, "fixture.png"), chrome = join(dir, "fake chrome");
|
||||||
|
writeFileSync(fixture, PNG.sync.write(screenshot));
|
||||||
|
writeFileSync(chrome, `#!${process.execPath}\nimport {copyFileSync} from "node:fs";\nconst args=process.argv.slice(2);\nif(args.includes("--dump-dom")){process.stdout.write(Buffer.alloc(17*1024*1024,120));process.stdout.write("<tit");process.stdout.write("le>PAGEH:2000</title>")}\nelse{const target=args.find(arg=>arg.startsWith("--screenshot="));if(!target)process.exit(1);copyFileSync(${JSON.stringify(fixture)},target.slice("--screenshot=".length))}\n`, { mode: 0o755 });
|
||||||
|
const result = await renderReportFile(file, { out, format: "png", width: 320, chrome });
|
||||||
|
expect(result.artifacts.map((artifact) => artifact.format)).toEqual(["html", "png"]);
|
||||||
|
expect(existsSync(out + ".png")).toBe(true);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,21 +1,14 @@
|
|||||||
import { constants, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
import { constants, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||||
import { execFile } from "node:child_process";
|
import { tmpdir } from "node:os"
|
||||||
import { tmpdir } from "node:os";
|
import { basename, dirname, extname, join, resolve } from "node:path"
|
||||||
import { basename, dirname, extname, join, resolve } from "node:path";
|
import { CliError, usageError, validationError } from "../../../core/errors.js"
|
||||||
import { promisify } from "node:util";
|
import { BUILTIN_TEMPLATE_PATH, REPORT_ASSETS } from "./resources.js"
|
||||||
import { marked } from "marked";
|
import { validateReportDocument, type ReportValidation } from "./validate.js"
|
||||||
import { z } from "zod";
|
import { buildReportHtml } from "./html.js"
|
||||||
import { CliError, usageError, validationError } from "../../../core/errors.js";
|
import { findReportChrome, renderBrowserArtifacts } from "./browser.js"
|
||||||
import { BUILTIN_TEMPLATE_PATH, REPORT_ASSETS, REPORT_SCRIPTS } from "./resources.js";
|
|
||||||
|
|
||||||
const execute = promisify(execFile);
|
export type { ReportValidation } from "./validate.js"
|
||||||
const validationSchema = z.object({
|
export type ReportRenderOptions = {
|
||||||
file: z.string(), valid: z.boolean(), tables: z.number(), figures: z.number(),
|
|
||||||
issues: z.array(z.object({ level: z.enum(["ERROR", "WARN"]), code: z.string(), message: z.string() }))
|
|
||||||
});
|
|
||||||
export type ReportValidation = z.infer<typeof validationSchema>;
|
|
||||||
type LocalToolOptions = { python?: string };
|
|
||||||
export type ReportRenderOptions = LocalToolOptions & {
|
|
||||||
out: string;
|
out: string;
|
||||||
format?: string;
|
format?: string;
|
||||||
width?: number;
|
width?: number;
|
||||||
@@ -63,45 +56,12 @@ export function saveReportMarkdown(content: string, templatePath: string, output
|
|||||||
return { file, assets: [...files.keys()].filter((path) => path !== file) };
|
return { file, assets: [...files.keys()].filter((path) => path !== file) };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function withTools<T>(options: LocalToolOptions, operation: (dir: string, python: string) => Promise<T>): Promise<T> {
|
/** Local validation deliberately needs no tenant selection, token, HTTP client or external interpreter. */
|
||||||
const python = Bun.which(options.python ?? "python3");
|
export async function validateReportFile(file: string): Promise<ReportValidation> {
|
||||||
if (!python) throw validationError("报告工具需要 Python 3。请安装 Python 3,或通过 --python <可执行文件> 指定。");
|
return validateReportDocument(inputFile(file))
|
||||||
const dir = mkdtempSync(join(tmpdir(), "seal-report-tools-"));
|
|
||||||
try {
|
|
||||||
for (const [name, content] of Object.entries(REPORT_SCRIPTS)) writeFileSync(join(dir, name), content);
|
|
||||||
return await operation(dir, python);
|
|
||||||
} finally {
|
|
||||||
rmSync(dir, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runTool(python: string, args: string[], allowInvalid = false): Promise<unknown> {
|
/** Render through bundled TypeScript modules and the existing browser, returning clean JSON. */
|
||||||
let stdout: string;
|
|
||||||
try {
|
|
||||||
stdout = (await execute(python, args, { encoding: "utf8", timeout: 600_000, maxBuffer: 16 * 1024 * 1024 })).stdout;
|
|
||||||
} catch (error) {
|
|
||||||
const failure = error as { code?: number; stdout?: string; stderr?: string; message?: string };
|
|
||||||
if (allowInvalid && failure.code === 1 && failure.stdout?.trim()) stdout = failure.stdout;
|
|
||||||
else {
|
|
||||||
const message = failure.stderr?.trim() || failure.message || String(error);
|
|
||||||
if (/^(?:未找到 Chrome\/Chromium|PNG 导出需要 Pillow)/.test(message)) throw validationError(message);
|
|
||||||
throw new CliError(`报告工具执行失败:${message}`, 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return JSON.parse(stdout);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function validateWithTools(file: string, dir: string, python: string): Promise<ReportValidation> {
|
|
||||||
return z.array(validationSchema).length(1).parse(await runTool(python, [join(dir, "validate.py"), "--json", file], true))[0]!;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Local validation deliberately needs no tenant selection, token, or HTTP client. */
|
|
||||||
export async function validateReportFile(file: string, options: LocalToolOptions = {}): Promise<ReportValidation> {
|
|
||||||
const path = inputFile(file);
|
|
||||||
return withTools(options, (dir, python) => validateWithTools(path, dir, python));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Preserve the existing Python layout engine while bundling Markdown parsing and returning clean JSON. */
|
|
||||||
export async function renderReportFile(file: string, options: ReportRenderOptions) {
|
export async function renderReportFile(file: string, options: ReportRenderOptions) {
|
||||||
const path = inputFile(file);
|
const path = inputFile(file);
|
||||||
const format = options.format ?? "all";
|
const format = options.format ?? "all";
|
||||||
@@ -113,24 +73,33 @@ export async function renderReportFile(file: string, options: ReportRenderOption
|
|||||||
const destinations = formats.map((extension) => `${stem}.${extension}`);
|
const destinations = formats.map((extension) => `${stem}.${extension}`);
|
||||||
if (destinations.includes(path)) throw validationError("渲染输出不能覆盖报告源文件。");
|
if (destinations.includes(path)) throw validationError("渲染输出不能覆盖报告源文件。");
|
||||||
for (const destination of destinations) checkOutput(destination, options.overwrite);
|
for (const destination of destinations) checkOutput(destination, options.overwrite);
|
||||||
return withTools(options, async (dir, python) => {
|
const validation = await validateReportFile(path)
|
||||||
const validation = await validateWithTools(path, dir, python);
|
if (!validation.valid) return { file: path, validation, artifacts: [] }
|
||||||
if (!validation.valid) return { file: path, validation, artifacts: [] };
|
const binary = formats.length > 1 ? findReportChrome(options.chrome) : undefined
|
||||||
// The same pinned marked major as the original renderer, embedded in the CLI instead of downloaded by npx.
|
const stage = mkdtempSync(join(tmpdir(), "seal-report-render-"))
|
||||||
const bodyFile = join(dir, "body.html");
|
try {
|
||||||
writeFileSync(bodyFile, marked.parse(readFileSync(path, "utf8"), { async: false }));
|
const html = join(stage, "report.html")
|
||||||
const args = [join(dir, "render.py"), path, "--out", join(dir, "report"), "--body-file", bodyFile,
|
writeFileSync(html, await buildReportHtml(path))
|
||||||
"--format", format, "--width", String(width), "--json"];
|
if (binary) {
|
||||||
if (options.chrome) args.push("--chrome", options.chrome);
|
const profile = join(stage, "browser-profile")
|
||||||
const rendered = z.object({ artifacts: z.array(z.object({ path: z.string(), format: z.string(), bytes: z.number().positive() })) })
|
mkdirSync(profile, { mode: 0o700 })
|
||||||
.parse(await runTool(python, args));
|
await renderBrowserArtifacts(html, formats, width, binary, profile)
|
||||||
|
}
|
||||||
|
const rendered = formats.map((format) => {
|
||||||
|
const file = join(stage, `report.${format}`)
|
||||||
|
const bytes = statSync(file).size
|
||||||
|
if (!bytes) throw new CliError(`报告渲染产物为空:${format}`, 1)
|
||||||
|
return { file, format, bytes }
|
||||||
|
})
|
||||||
// Publish only after the full requested set succeeds; failed rendering leaves existing outputs intact.
|
// Publish only after the full requested set succeeds; failed rendering leaves existing outputs intact.
|
||||||
mkdirSync(dirname(stem), { recursive: true });
|
mkdirSync(dirname(stem), { recursive: true })
|
||||||
const artifacts = rendered.artifacts.map((artifact) => {
|
const artifacts = rendered.map((artifact) => {
|
||||||
const destination = `${stem}.${artifact.format}`;
|
const destination = `${stem}.${artifact.format}`
|
||||||
copyFileSync(artifact.path, destination, options.overwrite ? 0 : constants.COPYFILE_EXCL);
|
copyFileSync(artifact.file, destination, options.overwrite ? 0 : constants.COPYFILE_EXCL)
|
||||||
return { ...artifact, path: destination };
|
return { path: destination, format: artifact.format, bytes: artifact.bytes }
|
||||||
});
|
})
|
||||||
return { file: path, validation, artifacts };
|
return { file: path, validation, artifacts }
|
||||||
});
|
} finally {
|
||||||
|
rmSync(stage, { recursive: true, force: true })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { afterEach, describe, expect, test } from "bun:test"
|
||||||
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
||||||
|
import { tmpdir } from "node:os"
|
||||||
|
import { dirname, join } from "node:path"
|
||||||
|
import { buildReportHtml } from "./html.js"
|
||||||
|
|
||||||
|
const dirs: string[] = []
|
||||||
|
const originalFetch = globalThis.fetch
|
||||||
|
const originalCache = process.env.SEAL_REPORT_CACHE_DIR
|
||||||
|
afterEach(() => {
|
||||||
|
globalThis.fetch = originalFetch
|
||||||
|
if (originalCache === undefined) delete process.env.SEAL_REPORT_CACHE_DIR; else process.env.SEAL_REPORT_CACHE_DIR = originalCache
|
||||||
|
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
|
||||||
|
})
|
||||||
|
function source(content: string) {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), "seal-html-test-"))
|
||||||
|
dirs.push(dir)
|
||||||
|
process.env.SEAL_REPORT_CACHE_DIR = join(dir, "cache")
|
||||||
|
const file = join(dir, "报告.md")
|
||||||
|
writeFileSync(file, content)
|
||||||
|
return file
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("native report HTML", () => {
|
||||||
|
test("preserves code escaping and leaves code examples and escaped dollars out of math rendering", async () => {
|
||||||
|
globalThis.fetch = Object.assign(async () => { throw new Error("must not fetch") }, { preconnect: originalFetch.preconnect })
|
||||||
|
const html = await buildReportHtml(source('# Title\n\n```text\n<img src="missing.png">\n$example$\n```\n\n\\$5\n'))
|
||||||
|
expect(html).toContain("<img")
|
||||||
|
expect(html).toContain("$example$")
|
||||||
|
expect(html).not.toContain("renderMathInElement")
|
||||||
|
})
|
||||||
|
test("embeds math resources and fonts, and reuses the existing cache layout offline", async () => {
|
||||||
|
const calls: string[] = []
|
||||||
|
globalThis.fetch = Object.assign(async (input: string | URL | Request) => {
|
||||||
|
const url = String(input)
|
||||||
|
calls.push(url)
|
||||||
|
return new Response(url.endsWith("katex.min.css") ? ".katex{src:url(fonts/Mock.woff2)}" : "fixture")
|
||||||
|
}, { preconnect: originalFetch.preconnect })
|
||||||
|
const file = source("# Math\n\n$a_b < c$\n\n$$\\frac{100}{100} = 100\\%$$\n")
|
||||||
|
const html = await buildReportHtml(file)
|
||||||
|
expect(html).toContain("a_b < c")
|
||||||
|
expect(html).not.toContain("<em>")
|
||||||
|
expect(html).toContain("\\displaystyle \\frac{100}{100} = 100\\%")
|
||||||
|
expect(html).not.toContain("100\\\\%")
|
||||||
|
expect(html).toContain("data:font/woff2;base64,")
|
||||||
|
expect(html).toContain("renderMathInElement")
|
||||||
|
expect(html).not.toContain("cdn.jsdelivr")
|
||||||
|
expect(calls).toHaveLength(4)
|
||||||
|
globalThis.fetch = Object.assign(async () => { throw new Error("offline cache miss") }, { preconnect: originalFetch.preconnect })
|
||||||
|
expect(await buildReportHtml(file)).toBe(html)
|
||||||
|
})
|
||||||
|
test("failed formula downloads produce domain errors instead of an incomplete HTML", async () => {
|
||||||
|
globalThis.fetch = Object.assign(async () => new Response("not found", { status: 404 }), { preconnect: originalFetch.preconnect })
|
||||||
|
await expect(buildReportHtml(source("# Math\n\n$x$"))).rejects.toMatchObject({ exitCode: 1 })
|
||||||
|
})
|
||||||
|
test("percent-encoded literal entity names are decoded only once", async () => {
|
||||||
|
const file = source("# Image\n\n")
|
||||||
|
writeFileSync(join(dirname(file), "&.svg"), '<svg xmlns="http://www.w3.org/2000/svg"></svg>')
|
||||||
|
expect(await buildReportHtml(file)).toContain("data:image/svg+xml;base64,")
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { randomUUID } from "node:crypto"
|
||||||
|
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||||
|
import { homedir } from "node:os"
|
||||||
|
import { basename, dirname, extname, join, resolve } from "node:path"
|
||||||
|
import { Marked, type TokenizerExtension, type Tokens } from "marked"
|
||||||
|
import { CliError } from "../../../core/errors.js"
|
||||||
|
import { REPORT_CSS } from "./resources.js"
|
||||||
|
|
||||||
|
const katexBase = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/"
|
||||||
|
const mimeTypes: Record<string, string> = {
|
||||||
|
".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp",
|
||||||
|
".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf"
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(text: string) {
|
||||||
|
return text.replace(/[&<>"']/g, (character) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[character]!)
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeHtml(text: string) {
|
||||||
|
return text.replace(/&(?:amp|lt|gt|quot|apos|#\d+|#x[\da-f]+);/gi, (entity) => {
|
||||||
|
if (entity.startsWith("&#")) {
|
||||||
|
const number = entity.toLowerCase().startsWith("&#x") ? parseInt(entity.slice(3, -1), 16) : Number(entity.slice(2, -1))
|
||||||
|
return number > 0 && number <= 0x10ffff ? String.fromCodePoint(number) : "�"
|
||||||
|
}
|
||||||
|
return ({ "&": "&", "<": "<", ">": ">", """: '"', "'": "'" })[entity.toLowerCase()] ?? entity
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** CDN 资源缓存命中不联网;原子写入避免并发导出或中途失败留下半个文件。 */
|
||||||
|
async function localAsset(name: string, resource = name): Promise<Buffer> {
|
||||||
|
const root = process.env.SEAL_REPORT_CACHE_DIR || join(homedir(), ".cache", "seal-use", "report-render", "katex-0.16.11")
|
||||||
|
const path = join(root, name)
|
||||||
|
if (existsSync(path) && statSync(path).size > 0) return readFileSync(path)
|
||||||
|
const response = await fetch(katexBase + resource, { signal: AbortSignal.timeout(30_000) })
|
||||||
|
if (!response.ok) throw new CliError(`公式资源下载失败:${name}(HTTP ${response.status})`, 1)
|
||||||
|
const content = Buffer.from(await response.arrayBuffer())
|
||||||
|
if (!content.length) throw new CliError(`公式资源下载为空:${name}`, 1)
|
||||||
|
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
|
||||||
|
const temporary = `${path}.${randomUUID()}.tmp`
|
||||||
|
try {
|
||||||
|
writeFileSync(temporary, content, { mode: 0o600 })
|
||||||
|
renameSync(temporary, path)
|
||||||
|
} finally {
|
||||||
|
rmSync(temporary, { force: true })
|
||||||
|
}
|
||||||
|
return content
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 字体也内嵌,避免 HTML 引用临时目录或缺少 KaTeX 字体。 */
|
||||||
|
async function mathAssets(): Promise<{ styles: string; scripts: string }> {
|
||||||
|
let css = (await localAsset("katex.min.css")).toString("utf8")
|
||||||
|
const names = [...new Set([...css.matchAll(/url\((fonts\/[^)]+)\)/g)].map((match) => match[1]!))]
|
||||||
|
const fonts = new Map<string, Buffer>()
|
||||||
|
// Limit font downloads to the same eight concurrent requests as the previous renderer.
|
||||||
|
for (let start = 0; start < names.length; start += 8) {
|
||||||
|
await Promise.all(names.slice(start, start + 8).map(async (name) => { fonts.set(name, await localAsset(name)) }))
|
||||||
|
}
|
||||||
|
css = css.replace(/url\((fonts\/[^)]+)\)/g, (_, name: string) => `url(data:${mimeTypes[extname(name)] ?? "application/octet-stream"};base64,${fonts.get(name)!.toString("base64")})`)
|
||||||
|
const scripts = await Promise.all(["katex.min.js", "auto-render.min.js"].map(async (name) => {
|
||||||
|
const resource = name === "auto-render.min.js" ? "contrib/" + name : name
|
||||||
|
return `<script>${(await localAsset(name, resource)).toString("utf8")}</script>`
|
||||||
|
}))
|
||||||
|
return { styles: `<style>${css}</style>\n`, scripts: scripts.join("\n") }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 渲染完整 HTML;标题取自正文 H1,并剥掉可能夹在里面的 HTML 注释。 */
|
||||||
|
export async function buildReportHtml(file: string): Promise<string> {
|
||||||
|
const text = readFileSync(file, "utf8").replace(/\r\n?/g, "\n")
|
||||||
|
let hasMath = false
|
||||||
|
const math: TokenizerExtension = {
|
||||||
|
name: "reportMath", level: "inline", start: (source) => source.indexOf("$"),
|
||||||
|
tokenizer(source) {
|
||||||
|
const display = source.match(/^\$\$([\s\S]+?)\$\$/)
|
||||||
|
const inline = display ?? source.match(/^\$([^$\n]+?)\$(?!\$)/)
|
||||||
|
if (!inline) return undefined
|
||||||
|
hasMath = true
|
||||||
|
return { type: "reportMath", raw: inline[0], text: inline[1]!, display: Boolean(display) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Tokenize math before Markdown emphasis; escape only the math text, never unescape the full HTML.
|
||||||
|
const markdown = new Marked({ extensions: [{ ...math, renderer(token: Tokens.Generic) {
|
||||||
|
const expression = String(token.text).replace(/(?<!\\)%/g, "\\%")
|
||||||
|
return escapeHtml(`\\(${token.display ? "\\displaystyle " : ""}${expression} \\)`)
|
||||||
|
} }] })
|
||||||
|
let body = markdown.parse(text, { async: false })
|
||||||
|
// 本地图片内嵌;marked 已做一次百分号编码,先解码再读取,产物移动后仍可显示。
|
||||||
|
body = body.replace(/<img src="([^"]+)"/g, (match, source: string) => {
|
||||||
|
if (/^(?:https?:|file:|data:)/.test(source)) return match
|
||||||
|
const path = resolve(dirname(file), decodeURIComponent(decodeHtml(source)))
|
||||||
|
const data = readFileSync(path).toString("base64")
|
||||||
|
return match.replace(source, `data:${mimeTypes[extname(path).toLowerCase()] ?? "application/octet-stream"};base64,${data}`)
|
||||||
|
})
|
||||||
|
const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.replace(/<!--[\s\S]*?-->/g, "").trim() || basename(file, extname(file))
|
||||||
|
const assets = hasMath ? await mathAssets() : { styles: "", scripts: "" }
|
||||||
|
const init = hasMath ? '<script>document.addEventListener("DOMContentLoaded",function(){renderMathInElement(document.body,{delimiters:[{left:"\\\\(",right:"\\\\)",display:false}],throwOnError:false});});</script>' : ""
|
||||||
|
return `<!doctype html>\n<html lang="zh-CN">\n<head>\n<meta charset="utf-8">\n<title>${escapeHtml(title)}</title>\n${assets.styles}<style>${REPORT_CSS}</style>\n</head>\n<body>\n${assets.scripts}\n${body}\n${init}\n</body>\n</html>\n`
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { afterEach, describe, expect, test } from "bun:test"
|
||||||
|
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||||
|
import { tmpdir } from "node:os"
|
||||||
|
import { join } from "node:path"
|
||||||
|
import { PNG } from "pngjs"
|
||||||
|
import { offsetReportBand } from "./browser.js"
|
||||||
|
import { pngDimensions, stitchPngBands } from "./png.js"
|
||||||
|
|
||||||
|
const dirs: string[] = []
|
||||||
|
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
|
||||||
|
function workspace() { const dir = mkdtempSync(join(tmpdir(), "seal-png-test-")); dirs.push(dir); return dir }
|
||||||
|
function image(dir: string, name: string, width: number, height: number, red: number) {
|
||||||
|
const png = new PNG({ width, height })
|
||||||
|
for (let i = 0; i < png.data.length; i += 4) { png.data[i] = red; png.data[i + 3] = 255 }
|
||||||
|
const file = join(dir, name)
|
||||||
|
writeFileSync(file, PNG.sync.write(png))
|
||||||
|
return file
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("native report PNG", () => {
|
||||||
|
test("stitches bands in order including the final short band, preserving seam pixels", () => {
|
||||||
|
const dir = workspace()
|
||||||
|
const first = image(dir, "first.png", 2, 3, 11), second = image(dir, "second.png", 2, 2, 22)
|
||||||
|
const output = join(dir, "all.png")
|
||||||
|
stitchPngBands([{ file: first, height: 3 }, { file: second, height: 2 }], 2, 5, output)
|
||||||
|
expect(pngDimensions(output)).toEqual({ width: 2, height: 5 })
|
||||||
|
const png = PNG.sync.read(readFileSync(output))
|
||||||
|
expect(png.data[2 * 2 * 4]).toBe(11)
|
||||||
|
expect(png.data[3 * 2 * 4]).toBe(22)
|
||||||
|
expect(png.data[4 * 2 * 4]).toBe(22)
|
||||||
|
})
|
||||||
|
test("rejects mismatched dimensions and totals without publishing an image", () => {
|
||||||
|
const dir = workspace()
|
||||||
|
const first = image(dir, "first.png", 3, 2, 11), output = join(dir, "all.png")
|
||||||
|
expect(() => stitchPngBands([{ file: first, height: 2 }], 2, 2, output)).toThrow("截图尺寸")
|
||||||
|
expect(() => stitchPngBands([{ file: first, height: 2 }], 3, 3, output)).toThrow("分带高度")
|
||||||
|
expect(existsSync(output)).toBe(false)
|
||||||
|
})
|
||||||
|
test("rejects files masquerading as PNG output", () => {
|
||||||
|
const dir = workspace(), file = join(dir, "bad.png")
|
||||||
|
writeFileSync(file, "not a PNG")
|
||||||
|
expect(() => pngDimensions(file)).toThrow("有效的 PNG")
|
||||||
|
})
|
||||||
|
test("band displacement overrides the final stylesheet", () => {
|
||||||
|
const html = '<head><style>math{}</style><style>body{margin:0 auto}</style></head><body>report</body>'
|
||||||
|
expect(offsetReportBand(html, 14000)).toContain('<style>body{margin:0 auto}</style><style>body{margin-top:-14000px}</style></head>')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { closeSync, openSync, readFileSync, readSync, writeFileSync } from "node:fs"
|
||||||
|
import { PNG } from "pngjs"
|
||||||
|
import { CliError } from "../../../core/errors.js"
|
||||||
|
|
||||||
|
export type PngBand = { file: string; height: number }
|
||||||
|
|
||||||
|
export function pngDimensions(file: string): { width: number; height: number } {
|
||||||
|
const header = Buffer.alloc(24)
|
||||||
|
const descriptor = openSync(file, "r")
|
||||||
|
try {
|
||||||
|
if (readSync(descriptor, header, 0, header.length, 0) !== header.length ||
|
||||||
|
!header.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || header.toString("ascii", 12, 16) !== "IHDR") {
|
||||||
|
throw new CliError("浏览器未生成有效的 PNG 图片。", 1)
|
||||||
|
}
|
||||||
|
return { width: header.readUInt32BE(16), height: header.readUInt32BE(20) }
|
||||||
|
} finally { closeSync(descriptor) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按分带顺序拼接,逐带解码,避免同时保留所有分带的像素副本。 */
|
||||||
|
export function stitchPngBands(bands: PngBand[], width: number, height: number, output: string) {
|
||||||
|
if (!bands.length || bands.reduce((total, band) => total + band.height, 0) !== height) throw new CliError("PNG 分带高度与报告高度不一致。", 1)
|
||||||
|
const canvas = new PNG({ width, height })
|
||||||
|
let offset = 0
|
||||||
|
for (const band of bands) {
|
||||||
|
const image = PNG.sync.read(readFileSync(band.file))
|
||||||
|
if (image.width !== width || image.height !== band.height) throw new CliError("浏览器截图尺寸与请求不一致,未发布 PNG。", 1)
|
||||||
|
image.data.copy(canvas.data, offset * width * 4)
|
||||||
|
offset += image.height
|
||||||
|
}
|
||||||
|
writeFileSync(output, PNG.sync.write(canvas, { colorType: 2 }))
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import monthly from "../../../../report-templates/monthly.md" with { type: "text" };
|
import monthly from "../../../../report-templates/monthly.md" with { type: "text" };
|
||||||
import validate from "../../../../report-templates/validate.py" with { type: "text" };
|
import css from "../../../../report-templates/report.css" with { type: "text" };
|
||||||
import render from "../../../../report-templates/render.py" with { type: "text" };
|
|
||||||
import accuracy from "../../../../report-templates/assets/图1-准确率对比.svg" with { type: "text" };
|
import accuracy from "../../../../report-templates/assets/图1-准确率对比.svg" with { type: "text" };
|
||||||
import benefits from "../../../../report-templates/assets/图2-综合效益.svg" with { type: "text" };
|
import benefits from "../../../../report-templates/assets/图2-综合效益.svg" with { type: "text" };
|
||||||
import screenshot from "../../../../report-templates/assets/图3-示例截图.svg" with { type: "text" };
|
import screenshot from "../../../../report-templates/assets/图3-示例截图.svg" with { type: "text" };
|
||||||
@@ -9,7 +8,7 @@ import screenshot from "../../../../report-templates/assets/图3-示例截图.sv
|
|||||||
// Loading the built-in template never depends on cwd, a checkout, or skill installation.
|
// Loading the built-in template never depends on cwd, a checkout, or skill installation.
|
||||||
export const BUILTIN_TEMPLATE_PATH = "builtin:report-templates/monthly.md";
|
export const BUILTIN_TEMPLATE_PATH = "builtin:report-templates/monthly.md";
|
||||||
export const BUILTIN_MONTHLY_TEMPLATE = monthly;
|
export const BUILTIN_MONTHLY_TEMPLATE = monthly;
|
||||||
export const REPORT_SCRIPTS = { "validate.py": validate, "render.py": render };
|
export const REPORT_CSS = css;
|
||||||
export const REPORT_ASSETS: Record<string, string> = {
|
export const REPORT_ASSETS: Record<string, string> = {
|
||||||
"assets/图1-准确率对比.svg": accuracy,
|
"assets/图1-准确率对比.svg": accuracy,
|
||||||
"assets/图2-综合效益.svg": benefits,
|
"assets/图2-综合效益.svg": benefits,
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { afterEach, describe, expect, test } from "bun:test"
|
||||||
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
||||||
|
import { tmpdir } from "node:os"
|
||||||
|
import { join } from "node:path"
|
||||||
|
import { validateReportDocument } from "./validate.js"
|
||||||
|
|
||||||
|
const valid = "# 报告\n\n| 报告信息 | 内容 |\n| --- | --- |\n| 报告编号 | TEST |\n| 客户名称 | 企业 |\n| 统计期间 | 2026-08 |\n| 报告状态 | 草稿 |\n| 生成日期 | 2026-10-12 |\n"
|
||||||
|
const dirs: string[] = []
|
||||||
|
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
|
||||||
|
function check(content: string) {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), "seal-validator-test-"))
|
||||||
|
dirs.push(dir)
|
||||||
|
const file = join(dir, "report.md")
|
||||||
|
writeFileSync(file, content)
|
||||||
|
return validateReportDocument(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("native report validator", () => {
|
||||||
|
test("valid information and CRLF have the same clean result", () => {
|
||||||
|
expect(check(valid)).toMatchObject({ valid: true, tables: 1, figures: 0, issues: [] })
|
||||||
|
expect(check(valid.replaceAll("\n", "\r\n"))).toMatchObject({ valid: true, issues: [] })
|
||||||
|
})
|
||||||
|
test.each(["<!--slot:", "<!--/slot", "<!--@table", "<!-- render:stop", "{{value}}"])("rejects template traces: %s", (mark) => {
|
||||||
|
expect(check(valid + mark).issues).toContainEqual(expect.objectContaining({ code: "MK001" }))
|
||||||
|
})
|
||||||
|
test("reports frontmatter and unclosed code fences", () => {
|
||||||
|
expect(check("---\nx: y\n---\n" + valid + "\n```text\nunfinished").issues.map((issue) => issue.code)).toEqual(["FM001", "MD001"])
|
||||||
|
})
|
||||||
|
test("table columns respect escaped pipes and retain source line numbers", () => {
|
||||||
|
const content = valid + "\n| **标题** | 第二列 |\n| --- | --- |\n| a\\|b | good |\n| incomplete |\n"
|
||||||
|
const result = check(content)
|
||||||
|
expect(result.issues.map((issue) => issue.code)).toEqual(["TB001", "TB002"])
|
||||||
|
expect(result.issues[0]!.message).toContain(`第 ${content.split("\n").indexOf("| incomplete |") + 1} 行`)
|
||||||
|
})
|
||||||
|
test("validates heading depth and the seven section numbers", () => {
|
||||||
|
expect(check(valid + "\n### skipped\n## 2. only\n").issues.map((issue) => issue.code)).toEqual(["HD001", "HD002"])
|
||||||
|
expect(check(valid + [1, 2, 3, 4, 5, 6, 7].map((n) => `\n## ${n}. section`).join("")).valid).toBe(true)
|
||||||
|
})
|
||||||
|
test("identifies missing and empty report metadata", () => {
|
||||||
|
expect(check(valid.replace("| 报告编号 | TEST |\n", "")).issues).toContainEqual(expect.objectContaining({ code: "INFO001" }))
|
||||||
|
expect(check(valid.replace("| 客户名称 | 企业 |", "| 客户名称 | | ")).issues).toContainEqual(expect.objectContaining({ code: "INFO002" }))
|
||||||
|
expect(check("# Empty").issues).toEqual([{ level: "ERROR", code: "INFO001", message: "缺少「报告信息」表" }])
|
||||||
|
})
|
||||||
|
test("accepts remote/data images and returns a structured issue for malformed local URLs", () => {
|
||||||
|
const result = check(valid + "\n\n\n")
|
||||||
|
expect(result.figures).toBe(3)
|
||||||
|
expect(result.issues).toEqual([{ level: "ERROR", code: "IMG001", message: "图片不存在:bad%zz.png" }])
|
||||||
|
})
|
||||||
|
test("checks totals and percentages in both overview tables", () => {
|
||||||
|
const result = check(valid + "\n| 排名 | 失准类型 | 占比 | 张数 |\n| --- | --- | --- | --- |\n| TOP1 | 类型甲 | 10% | 5 |\n| 合计 | — | 100% | 10 |\n\n| 排名 | 风险类型 | 占比 | 张数 |\n| --- | --- | --- | --- |\n| TOP1 | 风险甲 | 10% | 5 |\n| 合计 | — | 100% | 10 |\n")
|
||||||
|
expect(result.issues.map((issue) => issue.code)).toEqual(["NM001", "NM003", "NM002", "NM003"])
|
||||||
|
})
|
||||||
|
test("checks subsection counts against the overview", () => {
|
||||||
|
const result = check(valid + "\n| 排名 | 失准类型 | 占比 | 张数 |\n| --- | --- | --- | --- |\n| TOP1 | 类型甲 | 100% | 5 |\n| 合计 | — | 100% | 5 |\n\n## 1. start\n### 2.1 TOP1 类型甲(4 张)\n")
|
||||||
|
expect(result.issues).toContainEqual(expect.objectContaining({ code: "NM001", message: "TOP1 小节标题写 4 张,总览表写 5 张" }))
|
||||||
|
})
|
||||||
|
test("checks detail classification counts against the narrative", () => {
|
||||||
|
const result = check(valid + "\n(2 / 3 笔),仅有 **2 笔\n\n| 单号 | 科目 | AI | 人工 | 原因分类 |\n| --- | --- | --- | --- | --- |\n| A | — | — | — | 依规正确 |\n| B | — | — | — | 失准 |\n")
|
||||||
|
expect(result.issues.map((issue) => issue.code)).toEqual(["NM004", "NM004", "NM004"])
|
||||||
|
})
|
||||||
|
test("checks formula arithmetic and numbers missing from the narrative", () => {
|
||||||
|
expect(check(valid + "\n1、2、50\n$$\\frac{1}{2} = 50\\%$$\n").valid).toBe(true)
|
||||||
|
expect(check(valid + "\n1、2、70\n$$\\frac{1}{2} = 70\\%$$\n").issues).toContainEqual(expect.objectContaining({ code: "NM005" }))
|
||||||
|
expect(check(valid + "\n$$123456$$\n").issues).toContainEqual(expect.objectContaining({ code: "NM005", message: "公式中的数值 123456 在正文别处找不到,可能与数据脱节" }))
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import { existsSync, readFileSync, realpathSync } from "node:fs"
|
||||||
|
import { dirname, resolve } from "node:path"
|
||||||
|
|
||||||
|
export type ReportIssue = { level: "ERROR" | "WARN"; code: string; message: string }
|
||||||
|
export type ReportValidation = { file: string; valid: boolean; tables: number; figures: number; issues: ReportIssue[] }
|
||||||
|
type ReportTable = { line: number; header: string[]; rows: Array<{ line: number; cells: string[] }> }
|
||||||
|
|
||||||
|
const sectionNumbers = ["1", "2", "3", "4", "5", "6", "7"]
|
||||||
|
const requiredInfoRows = ["报告编号", "客户名称", "统计期间", "报告状态", "生成日期"]
|
||||||
|
const forbiddenMarks: Array<[RegExp, string]> = [
|
||||||
|
[/<!--slot:/, "slot 标记"], [/<!--\/slot/, "slot 闭合"], [/<!--@/, "@table/@block 区域标记"],
|
||||||
|
[/<!-- render:stop/, "render:stop 标记"], [/\{\{/, "{{槽位}}"]
|
||||||
|
]
|
||||||
|
|
||||||
|
/** 按未转义的 | 拆单元格;\| 视为字面竖线。 */
|
||||||
|
function cells(line: string): string[] {
|
||||||
|
let text = line.trim()
|
||||||
|
if (text.startsWith("|")) text = text.slice(1)
|
||||||
|
if (text.endsWith("|") && !text.endsWith("\\|")) text = text.slice(0, -1)
|
||||||
|
return text.split(/(?<!\\)\|/).map((cell) => cell.replaceAll("\\|", "|").trim())
|
||||||
|
}
|
||||||
|
|
||||||
|
function tables(lines: string[]): ReportTable[] {
|
||||||
|
const result: ReportTable[] = []
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const separator = lines[i + 1]?.trim() ?? ""
|
||||||
|
if (!lines[i]!.startsWith("|") || !separator.includes("-") || !/^[|\-: ]+$/.test(separator)) continue
|
||||||
|
const table: ReportTable = { line: i + 1, header: cells(lines[i]!), rows: [] }
|
||||||
|
i += 2
|
||||||
|
while (i < lines.length && lines[i]!.startsWith("|")) {
|
||||||
|
table.rows.push({ line: i + 1, cells: cells(lines[i]!) })
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
result.push(table)
|
||||||
|
i--
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
function numeric(text: string, percent = false): number | null {
|
||||||
|
const match = text.match(percent ? /(\d+(?:\.\d+)?)\s*%/ : /(\d+(?:\.\d+)?)/)
|
||||||
|
return match ? Number(match[1]) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match the legacy validator's float representation in aggregate messages.
|
||||||
|
function decimal(value: number | null) { return value === null ? "None" : Number.isInteger(value) ? `${value}.0` : String(value) }
|
||||||
|
function list(values: string[]) { return `[${values.map((value) => `'${value}'`).join(", ")}]` }
|
||||||
|
|
||||||
|
/** AI 审核报告结构校验器:从纯 Markdown 正文推导结构与数值,保留原问题编号。 */
|
||||||
|
export function validateReportDocument(file: string): ReportValidation {
|
||||||
|
const path = resolve(file)
|
||||||
|
const text = readFileSync(path, "utf8").replace(/\r\n?/g, "\n")
|
||||||
|
const lines = text.split("\n")
|
||||||
|
const report: ReportValidation = { file: realpathSync(path), valid: true, tables: 0, figures: 0, issues: [] }
|
||||||
|
const error = (code: string, message: string) => {
|
||||||
|
report.valid = false
|
||||||
|
report.issues.push({ level: "ERROR", code, message })
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. 纯净性:单层纯 Markdown
|
||||||
|
if (text.startsWith("---\n")) error("FM001", "文件以 YAML frontmatter 开头;元数据请放正文「报告信息」表")
|
||||||
|
for (const [pattern, name] of forbiddenMarks) {
|
||||||
|
if (pattern.test(text)) error("MK001", `出现模板机制痕迹(${name}),模板应是纯 Markdown 文档`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 代码围栏
|
||||||
|
const fences = lines.filter((line) => line.startsWith("```"))
|
||||||
|
if (fences.length % 2) error("MD001", `代码围栏为奇数(${fences.length}),存在未闭合代码块`)
|
||||||
|
|
||||||
|
// 3. 表格列数与表头
|
||||||
|
const parsedTables = tables(lines)
|
||||||
|
report.tables = parsedTables.length
|
||||||
|
for (const table of parsedTables) {
|
||||||
|
for (const row of table.rows) {
|
||||||
|
if (row.cells.length !== table.header.length) error("TB001", `第 ${row.line} 行表格列数 ${row.cells.length} ≠ 表头 ${table.header.length} 列`)
|
||||||
|
}
|
||||||
|
if (table.header.some((cell) => cell.includes("**"))) error("TB002", `第 ${table.line} 行表头含加粗标记 **`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 标题层级与章节编号
|
||||||
|
let previous = 0
|
||||||
|
const seen: string[] = []
|
||||||
|
for (const line of lines) {
|
||||||
|
const heading = line.match(/^(#{1,6})\s+(.*)$/)
|
||||||
|
if (!heading) continue
|
||||||
|
const level = heading[1]!.length
|
||||||
|
if (previous && level > previous + 1) error("HD001", `标题层级跳级(${previous} → ${level}):${heading[2]!.slice(0, 40)}`)
|
||||||
|
previous = level
|
||||||
|
const number = heading[2]!.match(/^(\d+)\./)
|
||||||
|
if (level === 2 && number) seen.push(number[1]!)
|
||||||
|
}
|
||||||
|
if (seen.length && seen.join(",") !== sectionNumbers.join(",")) error("HD002", `## 章节编号应为 ${list(sectionNumbers)},实际 ${list(seen)}`)
|
||||||
|
|
||||||
|
const byHeader = (keyword: string) => parsedTables.find((table) => table.header.join("").replaceAll(" ", "").includes(keyword))
|
||||||
|
|
||||||
|
// 5. 报告信息表
|
||||||
|
const info = byHeader("报告信息")
|
||||||
|
if (!info) error("INFO001", "缺少「报告信息」表")
|
||||||
|
else {
|
||||||
|
const keys = new Set(info.rows.map((row) => row.cells[0]))
|
||||||
|
const missing = requiredInfoRows.filter((key) => !keys.has(key)).sort()
|
||||||
|
if (missing.length) error("INFO001", `报告信息表缺少:${missing.join(", ")}`)
|
||||||
|
const empty = info.rows.filter((row) => row.cells.length > 1 && !row.cells[1]!.trim()).map((row) => row.cells[0])
|
||||||
|
if (empty.length) error("INFO002", `报告信息表以下项为空:${empty.join(", ")}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. 图片可解析:http(s) 或存在的本地文件
|
||||||
|
for (const match of text.matchAll(/!\[[^\]]*\]\(([^)]+)\)/g)) {
|
||||||
|
const source = match[1]!.trim()
|
||||||
|
report.figures++
|
||||||
|
if (/^(?:https?:|data:)/.test(source)) continue
|
||||||
|
let decoded = source
|
||||||
|
try { decoded = decodeURIComponent(source) } catch { /* Preserve malformed paths as local validation issues. */ }
|
||||||
|
if (!existsSync(resolve(dirname(path), decoded))) error("IMG001", `图片不存在:${source}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. 数值自洽(全部从正文推导)
|
||||||
|
for (const [tag, keyword] of [["NM001", "失准类型"], ["NM002", "风险类型"]] as const) {
|
||||||
|
const table = byHeader(keyword)
|
||||||
|
if (!table) continue
|
||||||
|
const rows = table.rows.map((row) => row.cells)
|
||||||
|
const tops = rows.filter((row) => row.length > 3 && row[0]!.startsWith("TOP")).map((row) => ({ name: row[0]!, count: numeric(row[3]!) }))
|
||||||
|
const totals = rows.filter((row) => row.length > 3 && ["合计", "总计", "—"].includes(row[0]!)).map((row) => numeric(row[3]!))
|
||||||
|
if (tops.length && totals.length && tops.every((top) => top.count !== null)) {
|
||||||
|
const sum = tops.reduce((total, top) => total + top.count!, 0)
|
||||||
|
if (sum !== totals[0]) error(tag, `${keyword}各维度之和 ${decimal(sum)} ≠ 合计 ${decimal(totals[0]!)}`)
|
||||||
|
}
|
||||||
|
const base = totals[0]
|
||||||
|
for (const row of rows) {
|
||||||
|
if (row.length < 4) continue
|
||||||
|
const share = numeric(row[2]!, true), count = numeric(row[3]!)
|
||||||
|
if (share && count && base && row[0]!.startsWith("TOP") && Math.abs(count / base * 100 - share) > 0.15) {
|
||||||
|
error("NM003", `${keyword}「${row[1]}」占比 ${decimal(share)}% ≠ ${count.toFixed(0)}/${base.toFixed(0)} = ${(count / base * 100).toFixed(1)}%`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 小节标题里的张数与总览表一致
|
||||||
|
for (const top of tops) {
|
||||||
|
const section = keyword === "失准类型" ? "2" : "3"
|
||||||
|
const escaped = top.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
||||||
|
const match = text.match(new RegExp(`###\\s*${section}\\.\\d+\\s*${escaped}[^(]*((\\d+)\\s*张`))
|
||||||
|
if (match && top.count !== null && Number(match[1]) !== top.count) error(tag, `${top.name} 小节标题写 ${match[1]} 张,总览表写 ${top.count.toFixed(0)} 张`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NM004:§6 明细表的结论分类计数 = 正文数字
|
||||||
|
const detail = byHeader("原因分类")
|
||||||
|
if (detail) {
|
||||||
|
const correct = detail.rows.filter((row) => row.cells.length > 4 && row.cells[4]!.includes("依规正确")).length
|
||||||
|
const missed = detail.rows.filter((row) => row.cells.length > 4 && row.cells[4]!.includes("失准")).length
|
||||||
|
const counts = text.match(/((\d+)\s*\/\s*(\d+)\s*笔)/)
|
||||||
|
const miss = text.match(/仅有\s*\*{0,2}(\d+)\s*笔/)
|
||||||
|
if (counts && Number(counts[1]) !== correct) error("NM004", `正文称依规正确 ${counts[1]} 笔,明细表实际 ${correct} 行`)
|
||||||
|
if (counts && Number(counts[2]) !== detail.rows.length) error("NM004", `正文称合计 ${counts[2]} 笔,明细表实际 ${detail.rows.length} 行`)
|
||||||
|
if (miss && Number(miss[1]) !== missed) error("NM004", `正文称 AI 失准 ${miss[1]} 笔,明细表实际 ${missed} 行`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NM005:公式算术自洽,且代入值能在正文别处找到
|
||||||
|
const formulaLines = lines.filter((line) => line.trim().startsWith("$$"))
|
||||||
|
const outside = lines.filter((line) => !line.trim().startsWith("$$")).join("\n")
|
||||||
|
for (const line of formulaLines) {
|
||||||
|
for (const fraction of line.matchAll(/\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%/g)) {
|
||||||
|
const a = Number(fraction[1]), b = Number(fraction[2]), percent = Number(fraction[3])
|
||||||
|
if (!Number.isFinite(percent) || (b && Math.abs(a / b * 100 - percent) > 0.05)) {
|
||||||
|
error("NM005", `公式 ${a}/${b} = ${decimal(percent)}% 算术不成立(实为 ${(a / b * 100).toFixed(2)}%)`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const token of line.match(/\d+(?:\.\d+)?/g) ?? []) {
|
||||||
|
if (!outside.includes(token)) error("NM005", `公式中的数值 ${token} 在正文别处找不到,可能与数据脱节`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return report
|
||||||
|
}
|
||||||
Reference in new issue
Block a user