@hamsterbase/evidra 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/bin/evidra.mjs +2 -0
- package/dist/sdk/main.d.ts +176 -0
- package/dist/sdk/main.js +1322 -0
- package/dist/service/cli.js +2645 -0
- package/dist/types/modules/core/contracts/comparison.d.ts +41 -0
- package/dist/types/modules/core/contracts/config.d.ts +19 -0
- package/dist/types/modules/core/contracts/context.d.ts +6 -0
- package/dist/types/modules/core/contracts/functions/addCase.d.ts +128 -0
- package/dist/types/modules/core/contracts/functions/addTask.d.ts +14 -0
- package/dist/types/modules/core/contracts/functions/approve.d.ts +8 -0
- package/dist/types/modules/core/contracts/functions/baselineChanges.d.ts +14 -0
- package/dist/types/modules/core/contracts/functions/compare.d.ts +14 -0
- package/dist/types/modules/core/contracts/functions/compareTask.d.ts +6 -0
- package/dist/types/modules/core/contracts/functions/compareTasks.d.ts +18 -0
- package/dist/types/modules/core/contracts/functions/deleteBaselineFile.d.ts +8 -0
- package/dist/types/modules/core/contracts/functions/finishTask.d.ts +8 -0
- package/dist/types/modules/core/contracts/functions/getBaseline.d.ts +10 -0
- package/dist/types/modules/core/contracts/functions/getBaselineChanges.d.ts +6 -0
- package/dist/types/modules/core/contracts/functions/getGitChanges.d.ts +6 -0
- package/dist/types/modules/core/contracts/functions/getGitDiff.d.ts +8 -0
- package/dist/types/modules/core/contracts/functions/getTaskCase.d.ts +23 -0
- package/dist/types/modules/core/contracts/functions/getTaskTree.d.ts +21 -0
- package/dist/types/modules/core/contracts/functions/gitChanges.d.ts +25 -0
- package/dist/types/modules/core/contracts/functions/index.d.ts +18 -0
- package/dist/types/modules/core/contracts/functions/listBaselines.d.ts +5 -0
- package/dist/types/modules/core/contracts/functions/listRuns.d.ts +7 -0
- package/dist/types/modules/core/contracts/functions/listTaskSummaries.d.ts +15 -0
- package/dist/types/modules/core/contracts/functions/listTasks.d.ts +15 -0
- package/dist/types/modules/core/contracts/functions/loadConfig.d.ts +5 -0
- package/dist/types/modules/core/contracts/functions/readProjectInfo.d.ts +5 -0
- package/dist/types/modules/core/contracts/functions/readTaskReport.d.ts +6 -0
- package/dist/types/modules/core/contracts/functions/resolveConfig.d.ts +6 -0
- package/dist/types/modules/core/contracts/functions/reviewBaselineChanges.d.ts +9 -0
- package/dist/types/modules/core/contracts/functions/reviewCodeChanges.d.ts +9 -0
- package/dist/types/modules/core/contracts/functions/taskRecords.d.ts +6 -0
- package/dist/types/modules/core/contracts/functions/updateBaseline.d.ts +20 -0
- package/dist/types/modules/core/contracts/git.d.ts +14 -0
- package/dist/types/modules/core/contracts/imageDiffPool.d.ts +5 -0
- package/dist/types/modules/core/contracts/index.d.ts +30 -0
- package/dist/types/modules/core/contracts/internal/compare.d.ts +14 -0
- package/dist/types/modules/core/contracts/internal/getBaseline.d.ts +10 -0
- package/dist/types/modules/core/contracts/internal/listTasks.d.ts +12 -0
- package/dist/types/modules/core/contracts/internal/taskRecords.d.ts +6 -0
- package/dist/types/modules/core/contracts/internal/updateBaseline.d.ts +20 -0
- package/dist/types/modules/core/contracts/model.d.ts +80 -0
- package/dist/types/modules/core/contracts/report.d.ts +52 -0
- package/dist/types/modules/core/contracts/repository.d.ts +5 -0
- package/dist/types/modules/core/contracts/requests.d.ts +23 -0
- package/dist/types/modules/core/contracts/scanCases.d.ts +15 -0
- package/dist/types/modules/core/contracts/shared.d.ts +6 -0
- package/dist/types/modules/core/contracts/snapshots.d.ts +6 -0
- package/dist/types/modules/core/contracts/taskRecord.d.ts +76 -0
- package/dist/types/modules/core/implementations/Functions/addCase.d.ts +4 -0
- package/dist/types/modules/core/implementations/Functions/addTask.d.ts +4 -0
- package/dist/types/modules/core/implementations/Functions/approve.d.ts +6 -0
- package/dist/types/modules/core/implementations/Functions/compare.d.ts +15 -0
- package/dist/types/modules/core/implementations/Functions/compareTask.d.ts +3 -0
- package/dist/types/modules/core/implementations/Functions/compareTasks.d.ts +5 -0
- package/dist/types/modules/core/implementations/Functions/deleteBaselineFile.d.ts +4 -0
- package/dist/types/modules/core/implementations/Functions/finishTask.d.ts +4 -0
- package/dist/types/modules/core/implementations/Functions/getBaseline.d.ts +4 -0
- package/dist/types/modules/core/implementations/Functions/getBaselineChanges.d.ts +4 -0
- package/dist/types/modules/core/implementations/Functions/getGitChanges.d.ts +3 -0
- package/dist/types/modules/core/implementations/Functions/getGitDiff.d.ts +3 -0
- package/dist/types/modules/core/implementations/Functions/getTaskCase.d.ts +5 -0
- package/dist/types/modules/core/implementations/Functions/getTaskTree.d.ts +5 -0
- package/dist/types/modules/core/implementations/Functions/listBaselines.d.ts +3 -0
- package/dist/types/modules/core/implementations/Functions/listTaskSummaries.d.ts +2 -0
- package/dist/types/modules/core/implementations/Functions/listTasks.d.ts +4 -0
- package/dist/types/modules/core/implementations/Functions/loadConfig.d.ts +3 -0
- package/dist/types/modules/core/implementations/Functions/readProjectInfo.d.ts +3 -0
- package/dist/types/modules/core/implementations/Functions/readTaskReport.d.ts +3 -0
- package/dist/types/modules/core/implementations/Functions/resolveConfig.d.ts +9 -0
- package/dist/types/modules/core/implementations/Functions/reviewBaselineChanges.d.ts +4 -0
- package/dist/types/modules/core/implementations/Functions/reviewCodeChanges.d.ts +4 -0
- package/dist/types/modules/core/implementations/Functions/taskRecords.d.ts +4 -0
- package/dist/types/modules/core/implementations/Functions/updateBaseline.d.ts +5 -0
- package/dist/types/modules/core/implementations/Utils/assertNamespace.d.ts +1 -0
- package/dist/types/modules/core/implementations/Utils/canonical.d.ts +1 -0
- package/dist/types/modules/core/implementations/Utils/createTaskId.d.ts +1 -0
- package/dist/types/modules/core/implementations/Utils/deletionAllowed.d.ts +2 -0
- package/dist/types/modules/core/implementations/Utils/download.d.ts +3 -0
- package/dist/types/modules/core/implementations/Utils/hash.d.ts +1 -0
- package/dist/types/modules/core/implementations/Utils/imageDiffPool.d.ts +18 -0
- package/dist/types/modules/core/implementations/Utils/imageKey.d.ts +1 -0
- package/dist/types/modules/core/implementations/Utils/loadBaseline.d.ts +4 -0
- package/dist/types/modules/core/implementations/Utils/mapLimit.d.ts +1 -0
- package/dist/types/modules/core/implementations/Utils/observationKey.d.ts +1 -0
- package/dist/types/modules/core/implementations/Utils/pngSize.d.ts +4 -0
- package/dist/types/modules/core/implementations/Utils/readJson.d.ts +1 -0
- package/dist/types/modules/core/implementations/Utils/readTaskRecord.d.ts +2 -0
- package/dist/types/modules/core/implementations/Utils/scanCases.d.ts +9 -0
- package/dist/types/modules/core/implementations/Utils/taskDirectory.d.ts +1 -0
- package/dist/types/modules/core/implementations/Utils/toCase.d.ts +3 -0
- package/dist/types/modules/core/implementations/Utils/toObservation.d.ts +3 -0
- package/dist/types/modules/core/implementations/Utils/toSnapshot.d.ts +3 -0
- package/dist/types/modules/core/implementations/Utils/writeBytesAtomic.d.ts +1 -0
- package/dist/types/modules/core/implementations/Utils/writeJsonAtomic.d.ts +1 -0
- package/dist/types/modules/core/implementations/Utils/writeTextAtomic.d.ts +1 -0
- package/dist/types/modules/core/implementations/baselineChanges.d.ts +6 -0
- package/dist/types/modules/core/implementations/config.d.ts +6 -0
- package/dist/types/modules/core/implementations/content.d.ts +1 -0
- package/dist/types/modules/core/implementations/evidra.d.ts +31 -0
- package/dist/types/modules/core/implementations/git.d.ts +11 -0
- package/dist/types/modules/core/implementations/gitChanges.d.ts +29 -0
- package/dist/types/modules/core/implementations/index.d.ts +17 -0
- package/dist/types/modules/core/implementations/internal/compare.d.ts +15 -0
- package/dist/types/modules/core/implementations/internal/getBaseline.d.ts +4 -0
- package/dist/types/modules/core/implementations/internal/listTasks.d.ts +2 -0
- package/dist/types/modules/core/implementations/internal/taskRecords.d.ts +4 -0
- package/dist/types/modules/core/implementations/internal/updateBaseline.d.ts +5 -0
- package/dist/types/modules/core/implementations/paths.d.ts +48 -0
- package/dist/types/modules/core/implementations/report.d.ts +3 -0
- package/dist/types/modules/core/implementations/reportResources.d.ts +4 -0
- package/dist/types/modules/core/implementations/reportStatus.d.ts +10 -0
- package/dist/types/modules/core/implementations/reportTree.d.ts +5 -0
- package/dist/types/modules/core/implementations/repository.d.ts +10 -0
- package/dist/types/modules/core/implementations/requests.d.ts +13 -0
- package/dist/types/modules/core/implementations/snapshots.d.ts +11 -0
- package/dist/types/modules/core/implementations/storage/local.d.ts +3 -0
- package/dist/types/modules/core/implementations/storage/objects.d.ts +3 -0
- package/dist/types/modules/core/index.d.ts +21 -0
- package/dist/types/packages/sdk/src/index.d.ts +21 -0
- package/dist/types/packages/sdk/src/types.d.ts +9 -0
- package/dist/web/assets/InterVariable-DiVDrmQJ.woff2 +0 -0
- package/dist/web/assets/abap-08VXUWAP.js +1 -0
- package/dist/web/assets/apex-BWPQTe0t.js +1 -0
- package/dist/web/assets/azcli-Bc_sGQ0U.js +1 -0
- package/dist/web/assets/bat-i0X4ZdIN.js +1 -0
- package/dist/web/assets/bicep-B5-_aFwp.js +2 -0
- package/dist/web/assets/cameligo-DMUM7wLl.js +1 -0
- package/dist/web/assets/clojure-Cm7r79vr.js +1 -0
- package/dist/web/assets/codicon-DF1abBS2.ttf +0 -0
- package/dist/web/assets/coffee-Ba7i2nA0.js +1 -0
- package/dist/web/assets/cpp-C7h46wYY.js +1 -0
- package/dist/web/assets/csharp-BKxtCVv1.js +1 -0
- package/dist/web/assets/csp-bTuwJoIa.js +1 -0
- package/dist/web/assets/css-DIMkf-bt.js +3 -0
- package/dist/web/assets/css.worker-DwfUZ3fB.js +96 -0
- package/dist/web/assets/cssMode-C0YhK9yk.js +1 -0
- package/dist/web/assets/cypher-CVaqCwHa.js +1 -0
- package/dist/web/assets/dart-onAF5SnQ.js +1 -0
- package/dist/web/assets/dockerfile-DZFCIeNp.js +1 -0
- package/dist/web/assets/ecl-94qehhXe.js +1 -0
- package/dist/web/assets/editor-DjpsE8to.css +1 -0
- package/dist/web/assets/editor.api-CMNmRHg7.js +908 -0
- package/dist/web/assets/editor.worker-CRz__AKW.js +33 -0
- package/dist/web/assets/elixir-6RTg0lbw.js +1 -0
- package/dist/web/assets/flow9-C5_-GSwl.js +1 -0
- package/dist/web/assets/freemarker2-BPF-_qAr.js +3 -0
- package/dist/web/assets/fsharp-C8Ef5oNN.js +1 -0
- package/dist/web/assets/go-C-y9NEjX.js +1 -0
- package/dist/web/assets/graphql-fmXr3nnJ.js +1 -0
- package/dist/web/assets/handlebars-ZZYTfRBR.js +1 -0
- package/dist/web/assets/hcl-CpzslTdj.js +1 -0
- package/dist/web/assets/html-Dgtv0wV7.js +1 -0
- package/dist/web/assets/html.worker-D9ugpX4y.js +509 -0
- package/dist/web/assets/htmlMode-CE3TDKC3.js +1 -0
- package/dist/web/assets/index-D_0ZWPum.js +37 -0
- package/dist/web/assets/index-U9oKSlEO.css +2 -0
- package/dist/web/assets/ini-sBoK_t0W.js +1 -0
- package/dist/web/assets/java-BEtHBSE6.js +1 -0
- package/dist/web/assets/javascript-v3U6PHk8.js +1 -0
- package/dist/web/assets/json.worker-CV9fqkUp.js +65 -0
- package/dist/web/assets/jsonMode-CRbfEt8i.js +7 -0
- package/dist/web/assets/julia-Bri6UV-V.js +1 -0
- package/dist/web/assets/kotlin-BOotOW0E.js +1 -0
- package/dist/web/assets/less-B9JPFI3C.js +2 -0
- package/dist/web/assets/lexon-CfSJPG6W.js +1 -0
- package/dist/web/assets/liquid-D_mEV4oV.js +1 -0
- package/dist/web/assets/lspLanguageFeatures-DX6MhoAE.js +4 -0
- package/dist/web/assets/lua-CsQS60Ue.js +1 -0
- package/dist/web/assets/m3-D-oSqn_W.js +1 -0
- package/dist/web/assets/markdown-Cimd5fb3.js +1 -0
- package/dist/web/assets/mdx-BhVFxchM.js +1 -0
- package/dist/web/assets/mips-CIPQ_RoX.js +1 -0
- package/dist/web/assets/monaco-C2bEmNwl.js +58 -0
- package/dist/web/assets/monaco-n7clI0si.css +1 -0
- package/dist/web/assets/msdax-DauUninz.js +1 -0
- package/dist/web/assets/mysql-SOo6toE5.js +1 -0
- package/dist/web/assets/objective-c-FvmIjYaQ.js +1 -0
- package/dist/web/assets/pascal-DrH0SRf2.js +1 -0
- package/dist/web/assets/pascaligo-D-ptJ9y-.js +1 -0
- package/dist/web/assets/perl-oz_6vUea.js +1 -0
- package/dist/web/assets/pgsql-DTj74zXo.js +1 -0
- package/dist/web/assets/php-nr791fC2.js +1 -0
- package/dist/web/assets/pla-CopQ2nXW.js +1 -0
- package/dist/web/assets/postiats-43DmfD33.js +1 -0
- package/dist/web/assets/powerquery-D3hlyOfw.js +1 -0
- package/dist/web/assets/powershell-DmHpPYUd.js +1 -0
- package/dist/web/assets/protobuf-C531GsRP.js +2 -0
- package/dist/web/assets/pug-Z5eAx3Zn.js +1 -0
- package/dist/web/assets/python-BWAEzptE.js +1 -0
- package/dist/web/assets/qsharp-DkqhCAOL.js +1 -0
- package/dist/web/assets/r-BwWrilGY.js +1 -0
- package/dist/web/assets/razor-fGgHB_D8.js +1 -0
- package/dist/web/assets/redis-ClamHrr6.js +1 -0
- package/dist/web/assets/redshift-DT7zqm-g.js +1 -0
- package/dist/web/assets/restructuredtext-BYgofb2h.js +1 -0
- package/dist/web/assets/ruby-DezsRK8O.js +1 -0
- package/dist/web/assets/rust-DdL9SqIa.js +1 -0
- package/dist/web/assets/sb-CcwsVR0C.js +1 -0
- package/dist/web/assets/scala-DHpiXF5c.js +1 -0
- package/dist/web/assets/scheme-BeGwcela.js +1 -0
- package/dist/web/assets/scss-gp-XZpBa.js +3 -0
- package/dist/web/assets/shell-CC2rA5mh.js +1 -0
- package/dist/web/assets/solidity-BEEn4gHE.js +1 -0
- package/dist/web/assets/sophia-CRfGWb83.js +1 -0
- package/dist/web/assets/sparql-D_Lu-MrJ.js +1 -0
- package/dist/web/assets/sql-NEE52Syq.js +1 -0
- package/dist/web/assets/st-DbInun42.js +1 -0
- package/dist/web/assets/swift-Bxkupp3x.js +1 -0
- package/dist/web/assets/systemverilog-Bz4Y3fRF.js +1 -0
- package/dist/web/assets/tcl-DISqw1ZD.js +1 -0
- package/dist/web/assets/ts.worker-DIAQkoB3.js +67741 -0
- package/dist/web/assets/tsMode-Dhqndf6Y.js +11 -0
- package/dist/web/assets/twig-De2hgUGE.js +1 -0
- package/dist/web/assets/typescript-BdctO1F-.js +1 -0
- package/dist/web/assets/typespec-B8J7ngcE.js +1 -0
- package/dist/web/assets/vb-DV3o63ZY.js +1 -0
- package/dist/web/assets/wgsl-DpFanUEy.js +298 -0
- package/dist/web/assets/workers-CL1LWpiD.js +1 -0
- package/dist/web/assets/xml-h8WCDUbN.js +1 -0
- package/dist/web/assets/yaml-Dh4FUWeU.js +1 -0
- package/dist/web/index.html +13 -0
- package/package.json +78 -4
- package/skills/evidra/SKILL.md +112 -0
package/dist/sdk/main.js
ADDED
|
@@ -0,0 +1,1322 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { access, glob, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { format } from "date-fns";
|
|
7
|
+
import { customAlphabet } from "nanoid";
|
|
8
|
+
import pixelmatch from "pixelmatch";
|
|
9
|
+
import { PNG } from "pngjs";
|
|
10
|
+
import { Worker } from "node:worker_threads";
|
|
11
|
+
import { parseEnv } from "node:util";
|
|
12
|
+
// modules/core/contracts/functions/resolveConfig.ts
|
|
13
|
+
const ResolveConfigInputSchema = z.object({
|
|
14
|
+
repoRoot: z.string(),
|
|
15
|
+
namespace: z.string().optional()
|
|
16
|
+
});
|
|
17
|
+
// modules/core/contracts/functions/loadConfig.ts
|
|
18
|
+
const LoadConfigInputSchema = z.object({ repoRoot: z.string() });
|
|
19
|
+
// modules/core/contracts/config.ts
|
|
20
|
+
const NamespaceSchema = z.object({
|
|
21
|
+
id: z.string().regex(/^[A-Za-z0-9-]+$/),
|
|
22
|
+
name: z.string().trim().min(1)
|
|
23
|
+
});
|
|
24
|
+
const ConfigSchema = z.object({
|
|
25
|
+
reportDir: z.string().min(1).optional(),
|
|
26
|
+
storage: z.enum(["s3", "local"]).default("local"),
|
|
27
|
+
namespaces: z.array(NamespaceSchema)
|
|
28
|
+
});
|
|
29
|
+
// modules/core/implementations/config.ts
|
|
30
|
+
const CONFIG_NAME = "evidra.config.json";
|
|
31
|
+
function namespaceId(value) {
|
|
32
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9-]+$/.test(value)) throw new Error(`非法 namespace ID: ${String(value)}`);
|
|
33
|
+
}
|
|
34
|
+
function parseConfig(config) {
|
|
35
|
+
const value = ConfigSchema.parse(config);
|
|
36
|
+
const dir = value.reportDir ?? ".test-report";
|
|
37
|
+
if (path.isAbsolute(dir) || dir.split(/[\\/]/).some((part) => !part || part === "." || part === "..")) throw new Error("reportDir 必须是仓库内的相对目录");
|
|
38
|
+
const ids = /* @__PURE__ */ new Set();
|
|
39
|
+
for (const namespace of value.namespaces) {
|
|
40
|
+
namespaceId(namespace.id);
|
|
41
|
+
if (ids.has(namespace.id)) throw new Error(`重复 namespace: ${namespace.id}`);
|
|
42
|
+
ids.add(namespace.id);
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
reportDir: dir,
|
|
46
|
+
storage: value.storage,
|
|
47
|
+
namespaces: value.namespaces.map(({ id, name }) => ({
|
|
48
|
+
id,
|
|
49
|
+
name
|
|
50
|
+
}))
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
// modules/core/implementations/Functions/loadConfig.ts
|
|
54
|
+
async function loadConfig(input) {
|
|
55
|
+
const { repoRoot } = LoadConfigInputSchema.parse(input);
|
|
56
|
+
return parseConfig(JSON.parse(await readFile(path.join(repoRoot, CONFIG_NAME), "utf8")));
|
|
57
|
+
}
|
|
58
|
+
// modules/core/implementations/Functions/resolveConfig.ts
|
|
59
|
+
/** 解析显式仓库路径;指定 namespace 时额外校验其已注册。 */
|
|
60
|
+
async function resolveConfig(input) {
|
|
61
|
+
const { repoRoot, namespace } = ResolveConfigInputSchema.parse(input);
|
|
62
|
+
if (typeof repoRoot !== "string" || !path.isAbsolute(repoRoot)) throw new Error("repoRoot 必须是显式传入的绝对路径");
|
|
63
|
+
const config = await loadConfig({ repoRoot });
|
|
64
|
+
const namespaceList = config.namespaces;
|
|
65
|
+
if (namespace !== void 0 && !namespaceList.some((item) => item.id === namespace)) throw new Error(`未配置 namespace: ${namespace}`);
|
|
66
|
+
return {
|
|
67
|
+
absoluteReportPath: path.join(repoRoot, config.reportDir),
|
|
68
|
+
namespaceList
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
// modules/core/implementations/Utils/hash.ts
|
|
72
|
+
const hash = (value) => createHash("sha256").update(value).digest("hex");
|
|
73
|
+
// modules/core/implementations/Utils/writeBytesAtomic.ts
|
|
74
|
+
async function writeBytesAtomic(file, body) {
|
|
75
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
76
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
77
|
+
try {
|
|
78
|
+
await writeFile(temporary, body);
|
|
79
|
+
await rename(temporary, file);
|
|
80
|
+
} finally {
|
|
81
|
+
await rm(temporary, { force: true });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
// modules/core/implementations/storage/local.ts
|
|
85
|
+
function imageFile(reportDir, key) {
|
|
86
|
+
const root = path.resolve(reportDir, "objects");
|
|
87
|
+
const target = path.resolve(root, key);
|
|
88
|
+
if (!target.startsWith(root + path.sep)) throw new Error(`非法存储 key: ${key}`);
|
|
89
|
+
return target;
|
|
90
|
+
}
|
|
91
|
+
/** 任务图片仅写入本地文件,不读取远端配置。 */
|
|
92
|
+
async function writeTaskImage(reportDir, key, body) {
|
|
93
|
+
await writeBytesAtomic(imageFile(reportDir, key), body);
|
|
94
|
+
}
|
|
95
|
+
async function readTaskImage(reportDir, key) {
|
|
96
|
+
return await readFile(imageFile(reportDir, key));
|
|
97
|
+
}
|
|
98
|
+
/** 审批后的本地基线图片与任务图片分开保存,不使用下载缓存。 */
|
|
99
|
+
function createLocalStorage(reportDir) {
|
|
100
|
+
const file = (key) => path.join(reportDir, "baseline-assets", path.basename(key));
|
|
101
|
+
return {
|
|
102
|
+
async localPath(key) {
|
|
103
|
+
await this.download(key);
|
|
104
|
+
return file(key);
|
|
105
|
+
},
|
|
106
|
+
async upload(key, body) {
|
|
107
|
+
await writeBytesAtomic(file(key), body);
|
|
108
|
+
},
|
|
109
|
+
async download(key) {
|
|
110
|
+
try {
|
|
111
|
+
return await readFile(file(key));
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (error.code === "ENOENT") throw new Error(`本地基线图片不存在: ${key}`);
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
// modules/core/contracts/shared.ts
|
|
120
|
+
const IdSchema = z.string().regex(/^[A-Za-z0-9-]+$/, "只允许大小写字母、数字和中划线");
|
|
121
|
+
const NameSchema = z.string().trim().min(1);
|
|
122
|
+
const ColSchema = z.number().int("col 必须为 1 到 12 的整数").min(1, "col 必须为 1 到 12 的整数").max(12, "col 必须为 1 到 12 的整数");
|
|
123
|
+
const DateTimeSchema = z.iso.datetime({ offset: true });
|
|
124
|
+
const TaskPathSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}\/\d{2}-\d{2}-\d{2}-[A-Za-z0-9-]+$/, "taskPath 必须是 <yyyy-MM-dd>/<HH-mm-ss>-<taskId>");
|
|
125
|
+
// modules/core/contracts/functions/addCase.ts
|
|
126
|
+
const BytesSchema = z.custom((value) => value instanceof Uint8Array, { message: "图片 body 必须是 Uint8Array" });
|
|
127
|
+
const TreeSegmentSchema = z.object({
|
|
128
|
+
key: IdSchema,
|
|
129
|
+
display: NameSchema
|
|
130
|
+
});
|
|
131
|
+
const CaseResultSchema = z.object({
|
|
132
|
+
status: z.enum([
|
|
133
|
+
"passed",
|
|
134
|
+
"failed",
|
|
135
|
+
"skipped",
|
|
136
|
+
"interrupted"
|
|
137
|
+
]),
|
|
138
|
+
durationMs: z.number().int().nonnegative().optional(),
|
|
139
|
+
errors: z.array(z.string()).optional()
|
|
140
|
+
});
|
|
141
|
+
const SnapshotMetaSchema = z.object({
|
|
142
|
+
id: IdSchema,
|
|
143
|
+
name: NameSchema,
|
|
144
|
+
col: ColSchema.optional()
|
|
145
|
+
});
|
|
146
|
+
const SnapshotInputSchema = z.discriminatedUnion("type", [SnapshotMetaSchema.extend({
|
|
147
|
+
type: z.literal("text"),
|
|
148
|
+
body: z.string(),
|
|
149
|
+
language: z.string().optional()
|
|
150
|
+
}), SnapshotMetaSchema.extend({
|
|
151
|
+
type: z.literal("image"),
|
|
152
|
+
body: BytesSchema,
|
|
153
|
+
contentType: z.literal("image/png"),
|
|
154
|
+
maxDiffPixels: z.number({ error: "maxDiffPixels 仅支持图片,且必须是非负整数" }).int("maxDiffPixels 仅支持图片,且必须是非负整数").nonnegative("maxDiffPixels 仅支持图片,且必须是非负整数").optional()
|
|
155
|
+
})]);
|
|
156
|
+
const ObservationInputSchema = z.discriminatedUnion("type", [z.object({
|
|
157
|
+
name: NameSchema,
|
|
158
|
+
type: z.literal("text"),
|
|
159
|
+
body: z.string(),
|
|
160
|
+
language: z.string().optional()
|
|
161
|
+
}), z.object({
|
|
162
|
+
name: NameSchema,
|
|
163
|
+
type: z.literal("image"),
|
|
164
|
+
body: BytesSchema,
|
|
165
|
+
contentType: z.literal("image/png")
|
|
166
|
+
})]);
|
|
167
|
+
const CaseInputSchema = z.object({
|
|
168
|
+
id: IdSchema,
|
|
169
|
+
name: NameSchema,
|
|
170
|
+
treePath: z.array(TreeSegmentSchema),
|
|
171
|
+
snapshots: z.array(SnapshotInputSchema).min(1, "snapshots 不允许为空数组").nullable(),
|
|
172
|
+
result: CaseResultSchema,
|
|
173
|
+
observations: z.array(ObservationInputSchema).optional()
|
|
174
|
+
}).superRefine((value, ctx) => {
|
|
175
|
+
if (value.snapshots === null && value.result.status !== "failed") ctx.addIssue({
|
|
176
|
+
code: "custom",
|
|
177
|
+
path: ["snapshots"],
|
|
178
|
+
message: "snapshots 仅在用例失败时允许为 null"
|
|
179
|
+
});
|
|
180
|
+
if (value.snapshots) {
|
|
181
|
+
const ids = /* @__PURE__ */ new Set();
|
|
182
|
+
value.snapshots.forEach((snapshot, index) => {
|
|
183
|
+
if (ids.has(snapshot.id)) ctx.addIssue({
|
|
184
|
+
code: "custom",
|
|
185
|
+
path: [
|
|
186
|
+
"snapshots",
|
|
187
|
+
index,
|
|
188
|
+
"id"
|
|
189
|
+
],
|
|
190
|
+
message: `重复快照 ID: ${snapshot.id}`
|
|
191
|
+
});
|
|
192
|
+
ids.add(snapshot.id);
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
const AddCaseInputSchema = z.object({
|
|
197
|
+
repoRoot: z.string(),
|
|
198
|
+
taskId: IdSchema,
|
|
199
|
+
case: CaseInputSchema
|
|
200
|
+
});
|
|
201
|
+
// modules/core/implementations/Utils/pngSize.ts
|
|
202
|
+
const PNG_SIGNATURE = Buffer.from([
|
|
203
|
+
137,
|
|
204
|
+
80,
|
|
205
|
+
78,
|
|
206
|
+
71,
|
|
207
|
+
13,
|
|
208
|
+
10,
|
|
209
|
+
26,
|
|
210
|
+
10
|
|
211
|
+
]);
|
|
212
|
+
function pngSize(body) {
|
|
213
|
+
const bytes = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
|
|
214
|
+
if (bytes.length < 33 || !bytes.subarray(0, 8).equals(PNG_SIGNATURE) || bytes.readUInt32BE(8) !== 13 || bytes.toString("ascii", 12, 16) !== "IHDR") throw new Error("无效或截断的 PNG 头部");
|
|
215
|
+
const width = bytes.readUInt32BE(16);
|
|
216
|
+
const height = bytes.readUInt32BE(20);
|
|
217
|
+
if (!width || !height || width > 2147483647 || height > 2147483647) throw new Error("无效 PNG 图片尺寸");
|
|
218
|
+
return {
|
|
219
|
+
width,
|
|
220
|
+
height
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
// modules/core/implementations/paths.ts
|
|
224
|
+
/**
|
|
225
|
+
* 本地路径组装器。参数由 SDK 入口校验,这里只做字符串拼装。
|
|
226
|
+
*
|
|
227
|
+
* 任务:
|
|
228
|
+
* <root>/tasks/<yyyy-MM-dd>/<HH-mm-ss>-<taskId>/task.json
|
|
229
|
+
* <root>/tasks/<yyyy-MM-dd>/<HH-mm-ss>-<taskId>/cases/<time>-<idHash>.json
|
|
230
|
+
* <root>/tasks/<yyyy-MM-dd>/<HH-mm-ss>-<taskId>/cache/cases/<listingHash>.json
|
|
231
|
+
* <root>/tasks/_index/<taskId 前两位>/<taskId 剩余部分>
|
|
232
|
+
*
|
|
233
|
+
* 基线(按 keypath 拆分,无 namespace 级 baseline.json;casePath 最后一段是 caseId):
|
|
234
|
+
* <root>/baselines/<namespace>/<casePath...>/baseline.json
|
|
235
|
+
* 文本快照正文保存在基线 JSON 的 snapshots[].body 中。
|
|
236
|
+
*
|
|
237
|
+
* 缓存:
|
|
238
|
+
* <root>/cache/baselines/<namespace>/snapshot.json
|
|
239
|
+
* <root>/cache/comparisons/<namespace>/<taskId>/index.json
|
|
240
|
+
* <root>/cache/comparisons/<namespace>/<taskId>/diff/<caseId>/<snapshotId>-<contentHash>.png
|
|
241
|
+
* <root>/cache/downloads/<hash(objectKey)>.png
|
|
242
|
+
*
|
|
243
|
+
* 时间按本地时区拆分。
|
|
244
|
+
*/
|
|
245
|
+
const pathSchema = {
|
|
246
|
+
taskIndex(root, taskId) {
|
|
247
|
+
return path.join(root, "tasks", "_index", taskId.slice(0, 2), taskId.slice(2));
|
|
248
|
+
},
|
|
249
|
+
task(root, startedAt, taskId) {
|
|
250
|
+
const time = new Date(startedAt);
|
|
251
|
+
const taskPath = `${format(time, "yyyy-MM-dd")}/${format(time, "HH-mm-ss")}-${taskId}`;
|
|
252
|
+
const directory = path.join(root, "tasks", ...taskPath.split("/"));
|
|
253
|
+
return {
|
|
254
|
+
path: taskPath,
|
|
255
|
+
directory,
|
|
256
|
+
manifest: path.join(directory, "task.json")
|
|
257
|
+
};
|
|
258
|
+
},
|
|
259
|
+
baseline(root, namespace, casePath) {
|
|
260
|
+
const directory = path.join(root, "baselines", namespace, ...casePath);
|
|
261
|
+
return {
|
|
262
|
+
directory,
|
|
263
|
+
manifest: path.join(directory, "baseline.json")
|
|
264
|
+
};
|
|
265
|
+
},
|
|
266
|
+
cache(root) {
|
|
267
|
+
const directory = path.join(root, "cache");
|
|
268
|
+
return {
|
|
269
|
+
directory,
|
|
270
|
+
baseline(namespace) {
|
|
271
|
+
const baselineDirectory = path.join(directory, "baselines", namespace);
|
|
272
|
+
return {
|
|
273
|
+
directory: baselineDirectory,
|
|
274
|
+
snapshot: path.join(baselineDirectory, "snapshot.json")
|
|
275
|
+
};
|
|
276
|
+
},
|
|
277
|
+
comparison(namespace, taskId) {
|
|
278
|
+
return comparisonPaths(path.join(directory, "comparisons", namespace, taskId));
|
|
279
|
+
},
|
|
280
|
+
taskComparison(baseTaskId, taskId) {
|
|
281
|
+
return comparisonPaths(path.join(directory, "task-comparisons", baseTaskId, taskId));
|
|
282
|
+
},
|
|
283
|
+
download(hash) {
|
|
284
|
+
return path.join(directory, "downloads", `${hash}.png`);
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
function comparisonPaths(directory) {
|
|
290
|
+
const diffDirectory = path.join(directory, "diff");
|
|
291
|
+
return {
|
|
292
|
+
directory,
|
|
293
|
+
index: path.join(directory, "index.json"),
|
|
294
|
+
summary: path.join(directory, "summary.json"),
|
|
295
|
+
diff: (caseId, snapshotId, contentHash) => path.join(diffDirectory, caseId, `${snapshotId}-${contentHash}.png`)
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
// modules/core/implementations/Utils/readJson.ts
|
|
299
|
+
async function readJson(file) {
|
|
300
|
+
try {
|
|
301
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
302
|
+
} catch (error) {
|
|
303
|
+
if (error.code === "ENOENT") return null;
|
|
304
|
+
throw error;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
// modules/core/implementations/Utils/writeJsonAtomic.ts
|
|
308
|
+
async function writeJsonAtomic(file, value) {
|
|
309
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
310
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
311
|
+
try {
|
|
312
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
313
|
+
await rename(temporary, file);
|
|
314
|
+
} finally {
|
|
315
|
+
await rm(temporary, { force: true });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
// modules/core/implementations/Utils/readTaskRecord.ts
|
|
319
|
+
async function readTaskRecord(file) {
|
|
320
|
+
const manifest = JSON.parse(await readFile(file, "utf8"));
|
|
321
|
+
if ((manifest.formatVersion ?? 0) < 3) throw new Error("报告格式不支持,请重新运行测试");
|
|
322
|
+
const directory = path.join(path.dirname(file), "cases");
|
|
323
|
+
const files = (await readdir(directory)).filter((name) => name.endsWith(".json")).sort();
|
|
324
|
+
const listingHash = hash(JSON.stringify(files));
|
|
325
|
+
const cacheFile = path.join(path.dirname(file), "cache", "cases", `${listingHash}.json`);
|
|
326
|
+
let cases = await readJson(cacheFile);
|
|
327
|
+
if (!cases) {
|
|
328
|
+
cases = await Promise.all(files.map(async (name) => JSON.parse(await readFile(path.join(directory, name), "utf8"))));
|
|
329
|
+
await writeJsonAtomic(cacheFile, cases);
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
task: {
|
|
333
|
+
...manifest.task,
|
|
334
|
+
caseCount: cases.length
|
|
335
|
+
},
|
|
336
|
+
cases
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
// modules/core/implementations/internal/taskRecords.ts
|
|
340
|
+
/** 按 ID 索引读取任务;索引或任务不存在时返回 null,不扫描任务目录。 */
|
|
341
|
+
async function getTask(cwd, taskId) {
|
|
342
|
+
if (!/^[a-zA-Z0-9_-]{3,}$/.test(taskId)) return null;
|
|
343
|
+
let taskPath;
|
|
344
|
+
try {
|
|
345
|
+
taskPath = await readFile(pathSchema.taskIndex(cwd, taskId), "utf8");
|
|
346
|
+
} catch (error) {
|
|
347
|
+
if (error.code === "ENOENT") return null;
|
|
348
|
+
throw error;
|
|
349
|
+
}
|
|
350
|
+
if (!taskPath || taskPath.split("/").some((part) => !part || part === "." || part === "..") || path.isAbsolute(taskPath)) throw new Error("任务索引路径无效");
|
|
351
|
+
const record = await readTaskRecord(path.join(cwd, "tasks", ...taskPath.split("/"), "task.json")).catch((error) => {
|
|
352
|
+
if (error.code === "ENOENT") return null;
|
|
353
|
+
throw error;
|
|
354
|
+
});
|
|
355
|
+
if (!record || record.task.id !== taskId) return null;
|
|
356
|
+
return {
|
|
357
|
+
taskPath,
|
|
358
|
+
record
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
// modules/core/implementations/Utils/taskDirectory.ts
|
|
362
|
+
function taskDirectory(cwd, taskPath) {
|
|
363
|
+
return path.join(cwd, "tasks", ...taskPath.split("/"));
|
|
364
|
+
}
|
|
365
|
+
// modules/core/implementations/Utils/toObservation.ts
|
|
366
|
+
function toObservation(observation) {
|
|
367
|
+
if (observation.type === "text") return {
|
|
368
|
+
name: observation.name,
|
|
369
|
+
type: "text",
|
|
370
|
+
body: observation.body,
|
|
371
|
+
language: observation.language
|
|
372
|
+
};
|
|
373
|
+
return {
|
|
374
|
+
name: observation.name,
|
|
375
|
+
type: "image",
|
|
376
|
+
key: observation.key,
|
|
377
|
+
contentType: observation.contentType,
|
|
378
|
+
width: observation.width,
|
|
379
|
+
height: observation.height
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
// modules/core/implementations/Utils/toSnapshot.ts
|
|
383
|
+
function toSnapshot(snapshot) {
|
|
384
|
+
if (snapshot.type === "text") return {
|
|
385
|
+
id: snapshot.id,
|
|
386
|
+
name: snapshot.name,
|
|
387
|
+
type: "text",
|
|
388
|
+
body: snapshot.body,
|
|
389
|
+
language: snapshot.language,
|
|
390
|
+
col: snapshot.col
|
|
391
|
+
};
|
|
392
|
+
return {
|
|
393
|
+
id: snapshot.id,
|
|
394
|
+
name: snapshot.name,
|
|
395
|
+
type: "image",
|
|
396
|
+
key: snapshot.key,
|
|
397
|
+
contentType: snapshot.contentType,
|
|
398
|
+
width: snapshot.width,
|
|
399
|
+
height: snapshot.height,
|
|
400
|
+
maxDiffPixels: snapshot.maxDiffPixels,
|
|
401
|
+
col: snapshot.col
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
// modules/core/implementations/Utils/toCase.ts
|
|
405
|
+
function toCase(value) {
|
|
406
|
+
return {
|
|
407
|
+
id: value.id,
|
|
408
|
+
name: value.name,
|
|
409
|
+
treePath: value.treePath,
|
|
410
|
+
snapshots: value.snapshots === null ? null : value.snapshots.map(toSnapshot),
|
|
411
|
+
result: value.result,
|
|
412
|
+
observations: value.observations.map(toObservation)
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
// modules/core/implementations/Functions/addCase.ts
|
|
416
|
+
async function storeSnapshots(reportDir, namespace, caseId, inputs) {
|
|
417
|
+
const snapshots = [];
|
|
418
|
+
for (const input of inputs) {
|
|
419
|
+
if (input.type === "text") {
|
|
420
|
+
snapshots.push({
|
|
421
|
+
id: input.id,
|
|
422
|
+
name: input.name,
|
|
423
|
+
type: "text",
|
|
424
|
+
body: input.body,
|
|
425
|
+
language: input.language,
|
|
426
|
+
col: input.col
|
|
427
|
+
});
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
const body = Buffer.from(input.body.buffer, input.body.byteOffset, input.body.byteLength);
|
|
431
|
+
const { width, height } = pngSize(body);
|
|
432
|
+
const imageId = hash(body);
|
|
433
|
+
const key = [
|
|
434
|
+
"snapshots",
|
|
435
|
+
namespace,
|
|
436
|
+
caseId,
|
|
437
|
+
input.id,
|
|
438
|
+
`${imageId}.png`
|
|
439
|
+
].join("/");
|
|
440
|
+
await writeTaskImage(reportDir, key, body);
|
|
441
|
+
snapshots.push({
|
|
442
|
+
id: input.id,
|
|
443
|
+
name: input.name,
|
|
444
|
+
type: "image",
|
|
445
|
+
key,
|
|
446
|
+
contentType: "image/png",
|
|
447
|
+
width,
|
|
448
|
+
height,
|
|
449
|
+
maxDiffPixels: input.maxDiffPixels,
|
|
450
|
+
col: input.col
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
return snapshots;
|
|
454
|
+
}
|
|
455
|
+
async function storeObservations(reportDir, namespace, caseId, inputs) {
|
|
456
|
+
const observations = [];
|
|
457
|
+
for (const [index, input] of inputs.entries()) {
|
|
458
|
+
if (input.type === "text") {
|
|
459
|
+
observations.push({
|
|
460
|
+
name: input.name,
|
|
461
|
+
type: "text",
|
|
462
|
+
body: input.body,
|
|
463
|
+
language: input.language
|
|
464
|
+
});
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
const body = Buffer.from(input.body.buffer, input.body.byteOffset, input.body.byteLength);
|
|
468
|
+
const { width, height } = pngSize(body);
|
|
469
|
+
const imageId = hash(body);
|
|
470
|
+
const key = [
|
|
471
|
+
"snapshots",
|
|
472
|
+
namespace,
|
|
473
|
+
caseId,
|
|
474
|
+
"observations",
|
|
475
|
+
String(index),
|
|
476
|
+
`${imageId}.png`
|
|
477
|
+
].join("/");
|
|
478
|
+
await writeTaskImage(reportDir, key, body);
|
|
479
|
+
observations.push({
|
|
480
|
+
name: input.name,
|
|
481
|
+
type: "image",
|
|
482
|
+
key,
|
|
483
|
+
contentType: "image/png",
|
|
484
|
+
width,
|
|
485
|
+
height
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
return observations;
|
|
489
|
+
}
|
|
490
|
+
async function addCase(input) {
|
|
491
|
+
const parsed = AddCaseInputSchema.parse(input);
|
|
492
|
+
const { absoluteReportPath } = await resolveConfig({ repoRoot: parsed.repoRoot });
|
|
493
|
+
const found = await getTask(absoluteReportPath, parsed.taskId);
|
|
494
|
+
if (!found) throw new Error("任务不存在");
|
|
495
|
+
const directory = taskDirectory(absoluteReportPath, found.taskPath);
|
|
496
|
+
const record = found.record;
|
|
497
|
+
if (record.task.finishedAt) throw new Error("任务已经结束");
|
|
498
|
+
const value = parsed.case;
|
|
499
|
+
if (record.cases.some((item) => item.id === value.id)) throw new Error(`重复用例 ID: ${value.id}`);
|
|
500
|
+
const idHash = hash(value.id);
|
|
501
|
+
const reservations = path.join(directory, ".case-ids");
|
|
502
|
+
await mkdir(reservations, { recursive: true });
|
|
503
|
+
const reservation = path.join(reservations, idHash);
|
|
504
|
+
try {
|
|
505
|
+
await mkdir(reservation);
|
|
506
|
+
} catch (error) {
|
|
507
|
+
if (error.code === "EEXIST") throw new Error(`重复用例 ID: ${value.id}`);
|
|
508
|
+
throw error;
|
|
509
|
+
}
|
|
510
|
+
const order = Math.floor((performance.timeOrigin + performance.now()) * 1e3).toString();
|
|
511
|
+
try {
|
|
512
|
+
const snapshots = value.snapshots === null ? null : await storeSnapshots(absoluteReportPath, record.task.namespace, value.id, value.snapshots);
|
|
513
|
+
const observations = await storeObservations(absoluteReportPath, record.task.namespace, value.id, value.observations ?? []);
|
|
514
|
+
const stored = {
|
|
515
|
+
id: value.id,
|
|
516
|
+
name: value.name,
|
|
517
|
+
treePath: value.treePath,
|
|
518
|
+
snapshots,
|
|
519
|
+
result: value.result,
|
|
520
|
+
observations
|
|
521
|
+
};
|
|
522
|
+
if (JSON.parse(await readFile(path.join(directory, "task.json"), "utf8")).task.finishedAt) throw new Error("任务已经结束");
|
|
523
|
+
const body = JSON.stringify(stored);
|
|
524
|
+
await writeBytesAtomic(path.join(directory, "cases", `${order}-${idHash}.json`), Buffer.from(body));
|
|
525
|
+
return toCase(stored);
|
|
526
|
+
} catch (error) {
|
|
527
|
+
await rm(reservation, {
|
|
528
|
+
recursive: true,
|
|
529
|
+
force: true
|
|
530
|
+
});
|
|
531
|
+
throw error;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
// modules/core/contracts/functions/addTask.ts
|
|
535
|
+
const AddTaskInputSchema = z.object({
|
|
536
|
+
repoRoot: z.string(),
|
|
537
|
+
namespace: IdSchema,
|
|
538
|
+
name: NameSchema,
|
|
539
|
+
startedAt: DateTimeSchema,
|
|
540
|
+
coverage: z.enum(["partial", "complete"]).optional()
|
|
541
|
+
});
|
|
542
|
+
// modules/core/implementations/Utils/createTaskId.ts
|
|
543
|
+
const generate = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-", 6);
|
|
544
|
+
const createTaskId = () => generate();
|
|
545
|
+
// modules/core/implementations/Utils/writeTextAtomic.ts
|
|
546
|
+
async function writeTextAtomic(file, body) {
|
|
547
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
548
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
549
|
+
try {
|
|
550
|
+
await writeFile(temporary, body, "utf8");
|
|
551
|
+
await rename(temporary, file);
|
|
552
|
+
} finally {
|
|
553
|
+
await rm(temporary, { force: true });
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
// modules/core/implementations/Functions/addTask.ts
|
|
557
|
+
async function addTask(input) {
|
|
558
|
+
const value = AddTaskInputSchema.parse(input);
|
|
559
|
+
const { absoluteReportPath } = await resolveConfig({
|
|
560
|
+
repoRoot: value.repoRoot,
|
|
561
|
+
namespace: value.namespace
|
|
562
|
+
});
|
|
563
|
+
const startedAt = new Date(value.startedAt).toISOString();
|
|
564
|
+
const taskId = createTaskId();
|
|
565
|
+
const paths = pathSchema.task(absoluteReportPath, startedAt, taskId);
|
|
566
|
+
const task = {
|
|
567
|
+
id: taskId,
|
|
568
|
+
path: paths.path,
|
|
569
|
+
namespace: value.namespace,
|
|
570
|
+
name: value.name,
|
|
571
|
+
coverage: value.coverage ?? "partial",
|
|
572
|
+
status: "running",
|
|
573
|
+
startedAt,
|
|
574
|
+
caseCount: 0
|
|
575
|
+
};
|
|
576
|
+
try {
|
|
577
|
+
await access(paths.manifest);
|
|
578
|
+
throw new Error(`任务已存在: ${taskId}`);
|
|
579
|
+
} catch (error) {
|
|
580
|
+
if (error.code !== "ENOENT") throw error;
|
|
581
|
+
}
|
|
582
|
+
await mkdir(path.join(paths.directory, "cases"), { recursive: true });
|
|
583
|
+
await writeJsonAtomic(paths.manifest, {
|
|
584
|
+
formatVersion: 3,
|
|
585
|
+
task
|
|
586
|
+
});
|
|
587
|
+
await writeTextAtomic(pathSchema.taskIndex(absoluteReportPath, taskId), paths.path);
|
|
588
|
+
return task;
|
|
589
|
+
}
|
|
590
|
+
// modules/core/contracts/functions/finishTask.ts
|
|
591
|
+
const FinishTaskInputSchema = z.object({
|
|
592
|
+
repoRoot: z.string(),
|
|
593
|
+
taskId: IdSchema
|
|
594
|
+
});
|
|
595
|
+
// modules/core/implementations/Functions/finishTask.ts
|
|
596
|
+
async function finishTask(input) {
|
|
597
|
+
const value = FinishTaskInputSchema.parse(input);
|
|
598
|
+
const { absoluteReportPath } = await resolveConfig({ repoRoot: value.repoRoot });
|
|
599
|
+
const found = await getTask(absoluteReportPath, value.taskId);
|
|
600
|
+
if (!found) throw new Error("任务不存在");
|
|
601
|
+
const directory = taskDirectory(absoluteReportPath, found.taskPath);
|
|
602
|
+
const file = path.join(directory, "task.json");
|
|
603
|
+
const record = found.record;
|
|
604
|
+
if (record.task.finishedAt) throw new Error("任务已经结束");
|
|
605
|
+
const statuses = record.cases.map((item) => item.result.status);
|
|
606
|
+
record.task.status = statuses.includes("failed") ? "failed" : statuses.includes("interrupted") ? "interrupted" : statuses.length && statuses.every((status) => status === "skipped") ? "skipped" : "passed";
|
|
607
|
+
record.task.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
608
|
+
await writeJsonAtomic(file, {
|
|
609
|
+
formatVersion: 3,
|
|
610
|
+
task: record.task
|
|
611
|
+
});
|
|
612
|
+
return record.task;
|
|
613
|
+
}
|
|
614
|
+
// modules/core/contracts/functions/compareTask.ts
|
|
615
|
+
const CompareTaskInputSchema = z.object({
|
|
616
|
+
repoRoot: z.string(),
|
|
617
|
+
taskId: z.string()
|
|
618
|
+
});
|
|
619
|
+
// modules/core/contracts/internal/compare.ts
|
|
620
|
+
const CompareInputSchema = z.object({ taskId: z.string().min(1) });
|
|
621
|
+
// modules/core/implementations/Utils/deletionAllowed.ts
|
|
622
|
+
function deletionAllowed(record) {
|
|
623
|
+
return !!record.task.finishedAt && record.task.coverage === "complete";
|
|
624
|
+
}
|
|
625
|
+
// modules/core/implementations/Utils/download.ts
|
|
626
|
+
/** Storage owns the cache so it can isolate objects by S3 location. */
|
|
627
|
+
async function download(_cwd, storage, key) {
|
|
628
|
+
return Buffer.from(await storage.download(key));
|
|
629
|
+
}
|
|
630
|
+
// modules/core/implementations/Utils/imageDiffPool.ts
|
|
631
|
+
const require = createRequire(import.meta.url);
|
|
632
|
+
const pngjsPath = require.resolve("pngjs");
|
|
633
|
+
const pixelmatchPath = require.resolve("pixelmatch");
|
|
634
|
+
const WORKER_CODE = `
|
|
635
|
+
const { parentPort, workerData } = require('node:worker_threads');
|
|
636
|
+
const { PNG } = require(workerData.pngjsPath);
|
|
637
|
+
const pixelmatchModule = require(workerData.pixelmatchPath);
|
|
638
|
+
const pixelmatch = pixelmatchModule.default || pixelmatchModule;
|
|
639
|
+
|
|
640
|
+
parentPort.on('message', ({ id, oldBytes, newBytes }) => {
|
|
641
|
+
try {
|
|
642
|
+
const oldImage = PNG.sync.read(Buffer.from(oldBytes));
|
|
643
|
+
const newImage = PNG.sync.read(Buffer.from(newBytes));
|
|
644
|
+
if (oldImage.width !== newImage.width || oldImage.height !== newImage.height) {
|
|
645
|
+
parentPort.postMessage({ id, dimensionMismatch: true });
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
const diff = new PNG({ width: oldImage.width, height: oldImage.height });
|
|
649
|
+
const diffPixels = pixelmatch(
|
|
650
|
+
oldImage.data,
|
|
651
|
+
newImage.data,
|
|
652
|
+
diff.data,
|
|
653
|
+
diff.width,
|
|
654
|
+
diff.height,
|
|
655
|
+
{ threshold: 0.1 },
|
|
656
|
+
);
|
|
657
|
+
parentPort.postMessage({ id, diffPixels, png: PNG.sync.write(diff) });
|
|
658
|
+
} catch (error) {
|
|
659
|
+
parentPort.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
|
|
660
|
+
}
|
|
661
|
+
});
|
|
662
|
+
`;
|
|
663
|
+
var ImageDiffPool = class {
|
|
664
|
+
size;
|
|
665
|
+
workers = /* @__PURE__ */ new Set();
|
|
666
|
+
idle = [];
|
|
667
|
+
active = /* @__PURE__ */ new Map();
|
|
668
|
+
queue = [];
|
|
669
|
+
nextId = 0;
|
|
670
|
+
constructor(size) {
|
|
671
|
+
this.size = size;
|
|
672
|
+
}
|
|
673
|
+
compare(oldBytes, newBytes) {
|
|
674
|
+
this.ensureWorkers();
|
|
675
|
+
return new Promise((resolve, reject) => {
|
|
676
|
+
this.queue.push({
|
|
677
|
+
id: ++this.nextId,
|
|
678
|
+
oldBytes,
|
|
679
|
+
newBytes,
|
|
680
|
+
resolve,
|
|
681
|
+
reject
|
|
682
|
+
});
|
|
683
|
+
this.pump();
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
async close() {
|
|
687
|
+
const workers = [...this.workers];
|
|
688
|
+
this.workers.clear();
|
|
689
|
+
this.idle.length = 0;
|
|
690
|
+
await Promise.all(workers.map((worker) => worker.terminate()));
|
|
691
|
+
}
|
|
692
|
+
ensureWorkers() {
|
|
693
|
+
while (this.workers.size < this.size) this.addWorker();
|
|
694
|
+
}
|
|
695
|
+
addWorker() {
|
|
696
|
+
const worker = new Worker(WORKER_CODE, {
|
|
697
|
+
eval: true,
|
|
698
|
+
workerData: {
|
|
699
|
+
pngjsPath,
|
|
700
|
+
pixelmatchPath
|
|
701
|
+
}
|
|
702
|
+
});
|
|
703
|
+
worker.unref();
|
|
704
|
+
worker.on("message", (message) => this.handleResult(worker, message));
|
|
705
|
+
worker.on("error", (error) => this.failWorker(worker, error));
|
|
706
|
+
worker.on("exit", () => {
|
|
707
|
+
this.workers.delete(worker);
|
|
708
|
+
const index = this.idle.indexOf(worker);
|
|
709
|
+
if (index >= 0) this.idle.splice(index, 1);
|
|
710
|
+
const job = this.active.get(worker);
|
|
711
|
+
if (job) {
|
|
712
|
+
this.active.delete(worker);
|
|
713
|
+
job.reject(/* @__PURE__ */ new Error("image diff worker exited"));
|
|
714
|
+
}
|
|
715
|
+
if (this.queue.length) this.ensureWorkers();
|
|
716
|
+
this.pump();
|
|
717
|
+
});
|
|
718
|
+
this.workers.add(worker);
|
|
719
|
+
this.idle.push(worker);
|
|
720
|
+
}
|
|
721
|
+
handleResult(worker, message) {
|
|
722
|
+
const job = this.active.get(worker);
|
|
723
|
+
if (!job) return;
|
|
724
|
+
this.active.delete(worker);
|
|
725
|
+
worker.unref();
|
|
726
|
+
this.idle.push(worker);
|
|
727
|
+
if (message.error) job.reject(new Error(message.error));
|
|
728
|
+
else job.resolve(message);
|
|
729
|
+
this.pump();
|
|
730
|
+
}
|
|
731
|
+
failWorker(worker, error) {
|
|
732
|
+
const job = this.active.get(worker);
|
|
733
|
+
if (job) {
|
|
734
|
+
this.active.delete(worker);
|
|
735
|
+
job.reject(error);
|
|
736
|
+
}
|
|
737
|
+
this.workers.delete(worker);
|
|
738
|
+
const index = this.idle.indexOf(worker);
|
|
739
|
+
if (index >= 0) this.idle.splice(index, 1);
|
|
740
|
+
worker.terminate();
|
|
741
|
+
if (this.queue.length) this.ensureWorkers();
|
|
742
|
+
this.pump();
|
|
743
|
+
}
|
|
744
|
+
pump() {
|
|
745
|
+
while (this.idle.length && this.queue.length) {
|
|
746
|
+
const worker = this.idle.pop();
|
|
747
|
+
const job = this.queue.shift();
|
|
748
|
+
this.active.set(worker, job);
|
|
749
|
+
worker.ref();
|
|
750
|
+
worker.postMessage({
|
|
751
|
+
id: job.id,
|
|
752
|
+
oldBytes: job.oldBytes,
|
|
753
|
+
newBytes: job.newBytes
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
};
|
|
758
|
+
// modules/core/contracts/scanCases.ts
|
|
759
|
+
const ScanCasesInputSchema = z.object({ root: z.string().min(1) });
|
|
760
|
+
// modules/core/implementations/Utils/scanCases.ts
|
|
761
|
+
const BATCH_SIZE = 16;
|
|
762
|
+
/**
|
|
763
|
+
* 扫描 root 下所有 baseline.json,解析内容并计算稳定 hash。
|
|
764
|
+
* case 路径相对于 root;hash 输入为排序后的相对文件路径和解析后的 JSON。
|
|
765
|
+
*/
|
|
766
|
+
async function scanCases(input) {
|
|
767
|
+
const { root } = ScanCasesInputSchema.parse(input);
|
|
768
|
+
const files = await baselineFiles(root);
|
|
769
|
+
const cases = [];
|
|
770
|
+
for (let index = 0; index < files.length; index += BATCH_SIZE) {
|
|
771
|
+
const batch = await Promise.all(files.slice(index, index + BATCH_SIZE).map(async (file) => {
|
|
772
|
+
const baseline = JSON.parse(await readFile(path.join(root, file), "utf8"));
|
|
773
|
+
return {
|
|
774
|
+
file,
|
|
775
|
+
casePath: path.posix.dirname(file),
|
|
776
|
+
baseline
|
|
777
|
+
};
|
|
778
|
+
}));
|
|
779
|
+
for (const entry of batch) cases.push({
|
|
780
|
+
file: entry.file,
|
|
781
|
+
path: entry.casePath === "." ? "" : entry.casePath,
|
|
782
|
+
hash: createHash("sha256").update(entry.file).update("\0").update(JSON.stringify(entry.baseline)).digest("hex"),
|
|
783
|
+
baseline: entry.baseline
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
return { cases };
|
|
787
|
+
}
|
|
788
|
+
async function baselineFiles(root) {
|
|
789
|
+
const files = [];
|
|
790
|
+
for await (const file of glob("**/baseline*.json", {
|
|
791
|
+
cwd: root,
|
|
792
|
+
exclude: [
|
|
793
|
+
"**/node_modules/**",
|
|
794
|
+
"**/.git/**",
|
|
795
|
+
"**/cache/**"
|
|
796
|
+
]
|
|
797
|
+
})) if (/^baseline(?:-[a-f0-9]{64})?\.json$/.test(path.basename(file))) files.push(file.split(path.sep).join("/"));
|
|
798
|
+
files.sort();
|
|
799
|
+
return files;
|
|
800
|
+
}
|
|
801
|
+
// modules/core/implementations/Utils/loadBaseline.ts
|
|
802
|
+
function baselineVersion(baseline) {
|
|
803
|
+
return hash(JSON.stringify(baseline.files ?? [...baseline.cases.values()].sort((a, b) => a.path.localeCompare(b.path)).map((entry) => [entry.path, entry.hash])));
|
|
804
|
+
}
|
|
805
|
+
async function loadBaseline(baselineRoot, namespace) {
|
|
806
|
+
const scan = await scanCases({ root: path.join(baselineRoot, "baselines", namespace) });
|
|
807
|
+
const cases = /* @__PURE__ */ new Map();
|
|
808
|
+
for (const item of scan.cases) {
|
|
809
|
+
if (typeof item.baseline?.id !== "string" || !Array.isArray(item.baseline.snapshots)) continue;
|
|
810
|
+
if (cases.has(item.baseline.id)) continue;
|
|
811
|
+
cases.set(item.baseline.id, {
|
|
812
|
+
file: item.file,
|
|
813
|
+
path: item.path,
|
|
814
|
+
hash: item.hash,
|
|
815
|
+
baseline: item.baseline
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
return {
|
|
819
|
+
cases,
|
|
820
|
+
files: scan.cases.map((item) => item.file).sort()
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
// modules/core/implementations/Utils/mapLimit.ts
|
|
824
|
+
async function mapLimit(items, limit, fn) {
|
|
825
|
+
const results = new Array(items.length);
|
|
826
|
+
let next = 0;
|
|
827
|
+
const workers = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
|
|
828
|
+
while (true) {
|
|
829
|
+
const index = next++;
|
|
830
|
+
if (index >= items.length) return;
|
|
831
|
+
results[index] = await fn(items[index], index);
|
|
832
|
+
}
|
|
833
|
+
});
|
|
834
|
+
await Promise.all(workers);
|
|
835
|
+
return results;
|
|
836
|
+
}
|
|
837
|
+
// modules/core/implementations/internal/compare.ts
|
|
838
|
+
async function compare(input, cwd, baselineRoot, storage, concurrency = 1) {
|
|
839
|
+
const value = CompareInputSchema.parse(input);
|
|
840
|
+
const found = await getTask(cwd, value.taskId);
|
|
841
|
+
if (!found) throw new Error(`任务不存在: ${value.taskId}`);
|
|
842
|
+
const record = found.record;
|
|
843
|
+
const baseline = await loadBaseline(baselineRoot, record.task.namespace);
|
|
844
|
+
const pool = concurrency > 1 ? new ImageDiffPool(concurrency) : void 0;
|
|
845
|
+
try {
|
|
846
|
+
return await compareRecord(cwd, storage, record, baseline, {
|
|
847
|
+
concurrency,
|
|
848
|
+
pool
|
|
849
|
+
});
|
|
850
|
+
} finally {
|
|
851
|
+
await pool?.close();
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
async function compareRecord(cwd, storage, record, baseline, options = {}) {
|
|
855
|
+
const concurrency = Math.max(1, options.concurrency ?? 1);
|
|
856
|
+
const pool = options.pool;
|
|
857
|
+
const canDelete = deletionAllowed(record);
|
|
858
|
+
const cache = pathSchema.cache(cwd);
|
|
859
|
+
const paths = options.baseTaskId ? cache.taskComparison(options.baseTaskId, record.task.id) : cache.comparison(record.task.namespace, record.task.id);
|
|
860
|
+
const cachedIndex = await readJson(paths.index).catch(() => null);
|
|
861
|
+
const cachedCases = cachedIndex?.formatVersion === 4 ? cachedIndex.cases : {};
|
|
862
|
+
const nextCases = {};
|
|
863
|
+
const compareCase = async (current) => {
|
|
864
|
+
const currentHash = hash(JSON.stringify(current));
|
|
865
|
+
const old = baseline.cases.get(current.id);
|
|
866
|
+
const baselineHash = old?.hash ?? null;
|
|
867
|
+
const cachedCase = cachedCases[current.id];
|
|
868
|
+
if (cachedCase && await Promise.all(cachedCase.diff.snapshots.map(async (snapshot) => {
|
|
869
|
+
if (!snapshot.diffFile) return true;
|
|
870
|
+
return access(path.join(cwd, snapshot.diffFile)).then(() => true, () => false);
|
|
871
|
+
})).then((results) => results.every(Boolean)) && cachedCase?.currentHash === currentHash && cachedCase.baselineHash === baselineHash && cachedCase.canDelete === canDelete) return {
|
|
872
|
+
diff: cachedCase.diff,
|
|
873
|
+
cache: cachedCase
|
|
874
|
+
};
|
|
875
|
+
let diff;
|
|
876
|
+
if (current.snapshots === null || options.unavailableBaseCaseIds?.has(current.id)) diff = {
|
|
877
|
+
id: current.id,
|
|
878
|
+
current: toCase(current),
|
|
879
|
+
baseline: old?.baseline,
|
|
880
|
+
baselineHash: old?.hash,
|
|
881
|
+
change: "unavailable",
|
|
882
|
+
snapshots: []
|
|
883
|
+
};
|
|
884
|
+
else diff = await buildCaseDiff(cwd, storage, current, old, canDelete, (snapshotId, digest) => paths.diff(current.id, snapshotId, digest), concurrency, pool);
|
|
885
|
+
return {
|
|
886
|
+
diff,
|
|
887
|
+
cache: {
|
|
888
|
+
currentHash,
|
|
889
|
+
baselineHash,
|
|
890
|
+
canDelete,
|
|
891
|
+
diff
|
|
892
|
+
}
|
|
893
|
+
};
|
|
894
|
+
};
|
|
895
|
+
const results = await mapLimit(record.cases, concurrency, compareCase);
|
|
896
|
+
const cases = results.map((item) => item.diff);
|
|
897
|
+
for (const item of results) nextCases[item.diff.id] = item.cache;
|
|
898
|
+
if (canDelete) for (const [id, entry] of baseline.cases) {
|
|
899
|
+
if (record.cases.some((item) => item.id === id)) continue;
|
|
900
|
+
const cachedCase = cachedCases[id];
|
|
901
|
+
if (cachedCase?.currentHash === null && cachedCase.baselineHash === entry.hash && cachedCase.canDelete === true) {
|
|
902
|
+
cases.push(cachedCase.diff);
|
|
903
|
+
nextCases[id] = cachedCase;
|
|
904
|
+
continue;
|
|
905
|
+
}
|
|
906
|
+
const diff = deletedCaseDiff(entry);
|
|
907
|
+
cases.push(diff);
|
|
908
|
+
nextCases[id] = {
|
|
909
|
+
currentHash: null,
|
|
910
|
+
baselineHash: entry.hash,
|
|
911
|
+
canDelete: true,
|
|
912
|
+
diff
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
const baselineImages = /* @__PURE__ */ new Map();
|
|
916
|
+
async function prepareImage(image, current) {
|
|
917
|
+
if (image.type !== "image") return;
|
|
918
|
+
if (!image.key) throw new Error("图片缺少对象存储 key");
|
|
919
|
+
if (current) {
|
|
920
|
+
await readTaskImage(cwd, image.key);
|
|
921
|
+
image.url = path.resolve(cwd, "objects", image.key);
|
|
922
|
+
} else {
|
|
923
|
+
let pending = baselineImages.get(image.key);
|
|
924
|
+
if (!pending) {
|
|
925
|
+
const key = image.key;
|
|
926
|
+
pending = (async () => {
|
|
927
|
+
if (storage.localPath) return storage.localPath(key);
|
|
928
|
+
const file = path.join(cwd, "cache", "report-images", path.basename(key));
|
|
929
|
+
await writeBytesAtomic(file, await download(cwd, storage, key));
|
|
930
|
+
return file;
|
|
931
|
+
})();
|
|
932
|
+
baselineImages.set(key, pending);
|
|
933
|
+
}
|
|
934
|
+
image.url = await pending;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
await mapLimit(cases, concurrency, async (item) => {
|
|
938
|
+
for (const image of [...item.current?.snapshots ?? [], ...item.current?.observations ?? []]) await prepareImage(image, true);
|
|
939
|
+
for (const image of item.baseline?.snapshots ?? []) await prepareImage(image, false);
|
|
940
|
+
for (const snapshot of item.snapshots) {
|
|
941
|
+
if (snapshot.current) await prepareImage(snapshot.current, true);
|
|
942
|
+
if (snapshot.baseline) await prepareImage(snapshot.baseline, false);
|
|
943
|
+
}
|
|
944
|
+
});
|
|
945
|
+
const version = baselineVersion(baseline);
|
|
946
|
+
await writeJsonAtomic(paths.index, {
|
|
947
|
+
formatVersion: 4,
|
|
948
|
+
baselineVersion: version,
|
|
949
|
+
cases: nextCases
|
|
950
|
+
});
|
|
951
|
+
const summary = {
|
|
952
|
+
added: 0,
|
|
953
|
+
modified: 0,
|
|
954
|
+
deleted: 0,
|
|
955
|
+
same: 0,
|
|
956
|
+
unavailable: 0
|
|
957
|
+
};
|
|
958
|
+
for (const item of cases) summary[item.change] += 1;
|
|
959
|
+
await writeJsonAtomic(paths.summary, {
|
|
960
|
+
baselineVersion: version,
|
|
961
|
+
summary
|
|
962
|
+
});
|
|
963
|
+
return {
|
|
964
|
+
taskId: record.task.id,
|
|
965
|
+
namespace: record.task.namespace,
|
|
966
|
+
baselineVersion: version,
|
|
967
|
+
deletionAllowed: canDelete,
|
|
968
|
+
cases,
|
|
969
|
+
summary
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
async function buildCaseDiff(cwd, storage, current, old, canDelete, diffPath, concurrency, pool) {
|
|
973
|
+
const snapshots = await mapLimit(current.snapshots ?? [], concurrency, (snapshot) => {
|
|
974
|
+
const previous = old?.baseline.snapshots.find((item) => item.id === snapshot.id);
|
|
975
|
+
return compareSnapshot(cwd, storage, snapshot, previous, diffPath, pool);
|
|
976
|
+
});
|
|
977
|
+
if (canDelete) {
|
|
978
|
+
for (const previous of old?.baseline.snapshots ?? []) if (!current.snapshots?.some((item) => item.id === previous.id)) snapshots.push({
|
|
979
|
+
id: previous.id,
|
|
980
|
+
change: "deleted",
|
|
981
|
+
baseline: previous
|
|
982
|
+
});
|
|
983
|
+
}
|
|
984
|
+
const changed = snapshots.some((item) => item.change !== "same") || current.name !== old?.baseline.name || JSON.stringify(current.treePath) !== JSON.stringify(old?.baseline.treePath);
|
|
985
|
+
return {
|
|
986
|
+
id: current.id,
|
|
987
|
+
current: toCase(current),
|
|
988
|
+
baseline: old?.baseline,
|
|
989
|
+
baselineHash: old?.hash,
|
|
990
|
+
change: !old ? "added" : changed ? "modified" : "same",
|
|
991
|
+
snapshots
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
function deletedCaseDiff(entry) {
|
|
995
|
+
return {
|
|
996
|
+
id: entry.baseline.id,
|
|
997
|
+
change: "deleted",
|
|
998
|
+
baseline: entry.baseline,
|
|
999
|
+
baselineHash: entry.hash,
|
|
1000
|
+
snapshots: entry.baseline.snapshots.map((snapshot) => ({
|
|
1001
|
+
id: snapshot.id,
|
|
1002
|
+
change: "deleted",
|
|
1003
|
+
baseline: snapshot
|
|
1004
|
+
}))
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
async function compareSnapshot(cwd, storage, current, previous, diffPath, pool) {
|
|
1008
|
+
if (!previous) return {
|
|
1009
|
+
id: current.id,
|
|
1010
|
+
change: "added",
|
|
1011
|
+
current: toSnapshot(current)
|
|
1012
|
+
};
|
|
1013
|
+
const currentSnapshot = toSnapshot(current);
|
|
1014
|
+
let contentSame = current.type === "text" && previous.type === "text" && current.body === previous.body;
|
|
1015
|
+
const result = {
|
|
1016
|
+
id: current.id,
|
|
1017
|
+
change: "same",
|
|
1018
|
+
current: currentSnapshot,
|
|
1019
|
+
baseline: previous
|
|
1020
|
+
};
|
|
1021
|
+
if (current.type === "image" && previous.type === "image") {
|
|
1022
|
+
const tolerance = current.maxDiffPixels ?? previous.maxDiffPixels ?? 0;
|
|
1023
|
+
result.maxDiffPixels = tolerance;
|
|
1024
|
+
{
|
|
1025
|
+
if (!current.key || !previous.key) throw new Error("图片缺少对象存储 key");
|
|
1026
|
+
const [oldBytes, newBytes] = await Promise.all([download(cwd, storage, previous.key), readTaskImage(cwd, current.key)]);
|
|
1027
|
+
const diff = await imageDiff(oldBytes, newBytes, pool);
|
|
1028
|
+
if (!diff.dimensionMismatch && diff.diffPixels !== void 0) {
|
|
1029
|
+
result.diffPixels = diff.diffPixels;
|
|
1030
|
+
contentSame = result.diffPixels <= tolerance;
|
|
1031
|
+
if (diff.png) {
|
|
1032
|
+
const file = diffPath(current.id, hash(diff.png));
|
|
1033
|
+
await writeBytesAtomic(file, diff.png);
|
|
1034
|
+
result.diffFile = path.relative(cwd, file).split(path.sep).join("/");
|
|
1035
|
+
result.diffUrl = file;
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
result.contentSame = contentSame;
|
|
1040
|
+
if (tolerance !== (previous.maxDiffPixels ?? 0)) contentSame = false;
|
|
1041
|
+
} else if (current.type === "text" && previous.type === "text") result.contentSame = contentSame;
|
|
1042
|
+
const metadataSame = currentSnapshot.name === previous.name && currentSnapshot.type === previous.type && currentSnapshot.language === previous.language && currentSnapshot.contentType === previous.contentType && (currentSnapshot.col ?? 4) === (previous.col ?? 4) && (currentSnapshot.maxDiffPixels ?? previous.maxDiffPixels ?? 0) === (previous.maxDiffPixels ?? 0);
|
|
1043
|
+
result.change = contentSame && metadataSame ? "same" : "modified";
|
|
1044
|
+
return result;
|
|
1045
|
+
}
|
|
1046
|
+
async function imageDiff(oldBytes, newBytes, pool) {
|
|
1047
|
+
if (pool) try {
|
|
1048
|
+
return await pool.compare(oldBytes, newBytes);
|
|
1049
|
+
} catch {}
|
|
1050
|
+
return localImageDiff(oldBytes, newBytes);
|
|
1051
|
+
}
|
|
1052
|
+
function localImageDiff(oldBytes, newBytes) {
|
|
1053
|
+
const oldImage = PNG.sync.read(Buffer.from(oldBytes));
|
|
1054
|
+
const newImage = PNG.sync.read(Buffer.from(newBytes));
|
|
1055
|
+
if (oldImage.width !== newImage.width || oldImage.height !== newImage.height) return { dimensionMismatch: true };
|
|
1056
|
+
const diff = new PNG({
|
|
1057
|
+
width: oldImage.width,
|
|
1058
|
+
height: oldImage.height
|
|
1059
|
+
});
|
|
1060
|
+
return {
|
|
1061
|
+
diffPixels: pixelmatch(oldImage.data, newImage.data, diff.data, diff.width, diff.height, { threshold: .1 }),
|
|
1062
|
+
png: PNG.sync.write(diff)
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
// modules/core/implementations/Utils/getEnv.ts
|
|
1066
|
+
/** 逐项优先使用传入的进程变量,未定义时回退到文件;不修改输入或缓存结果。 */
|
|
1067
|
+
async function getEnv({ keys, processEnv, filePath }) {
|
|
1068
|
+
let fileEnv = {};
|
|
1069
|
+
try {
|
|
1070
|
+
fileEnv = parseEnv(await readFile(filePath, "utf8"));
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
if (error.code !== "ENOENT") throw error;
|
|
1073
|
+
}
|
|
1074
|
+
return Object.fromEntries(keys.map((key) => [key, processEnv[key] ?? fileEnv[key]]));
|
|
1075
|
+
}
|
|
1076
|
+
// modules/core/implementations/storage/s3.ts
|
|
1077
|
+
/** S3 保存基线图片,本地文件仅作为可清理的下载缓存。 */
|
|
1078
|
+
function createS3Storage(repoRoot, reportDir) {
|
|
1079
|
+
let config;
|
|
1080
|
+
async function loadStorageConfig() {
|
|
1081
|
+
const env = await getEnv({
|
|
1082
|
+
keys: [
|
|
1083
|
+
"ENDPOINT",
|
|
1084
|
+
"BUCKET",
|
|
1085
|
+
"REGION",
|
|
1086
|
+
"PREFIX",
|
|
1087
|
+
"ACCESS_KEY",
|
|
1088
|
+
"SECRET_KEY"
|
|
1089
|
+
].map((name) => `EVIDRA_S3_${name}`),
|
|
1090
|
+
processEnv: process.env,
|
|
1091
|
+
filePath: path.join(repoRoot, ".evidra.env.local")
|
|
1092
|
+
});
|
|
1093
|
+
const required = (name) => {
|
|
1094
|
+
const value = env[`EVIDRA_S3_${name}`]?.trim();
|
|
1095
|
+
if (!value) throw new Error(`缺少 EVIDRA_S3_${name}`);
|
|
1096
|
+
return value;
|
|
1097
|
+
};
|
|
1098
|
+
const endpoint = required("ENDPOINT"), bucket = required("BUCKET"), region = required("REGION");
|
|
1099
|
+
const prefix = required("PREFIX").replace(/^\/+|\/+$/g, "");
|
|
1100
|
+
const { S3Client, GetObjectCommand, PutObjectCommand } = await import("@aws-sdk/client-s3");
|
|
1101
|
+
return {
|
|
1102
|
+
client: new S3Client({
|
|
1103
|
+
endpoint,
|
|
1104
|
+
region,
|
|
1105
|
+
forcePathStyle: true,
|
|
1106
|
+
credentials: {
|
|
1107
|
+
accessKeyId: required("ACCESS_KEY"),
|
|
1108
|
+
secretAccessKey: required("SECRET_KEY")
|
|
1109
|
+
}
|
|
1110
|
+
}),
|
|
1111
|
+
bucket,
|
|
1112
|
+
prefix,
|
|
1113
|
+
endpoint,
|
|
1114
|
+
region,
|
|
1115
|
+
GetObjectCommand,
|
|
1116
|
+
PutObjectCommand
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1120
|
+
async function location(key) {
|
|
1121
|
+
const remote = await (config ??= loadStorageConfig());
|
|
1122
|
+
const objectKey = remote.prefix && !key.startsWith(remote.prefix + "/") ? `${remote.prefix}/${key}` : key;
|
|
1123
|
+
const identity = [
|
|
1124
|
+
remote.endpoint,
|
|
1125
|
+
remote.bucket,
|
|
1126
|
+
remote.region,
|
|
1127
|
+
remote.prefix
|
|
1128
|
+
];
|
|
1129
|
+
return {
|
|
1130
|
+
remote,
|
|
1131
|
+
objectKey,
|
|
1132
|
+
file: path.join(reportDir, "cache", "objects", hash(JSON.stringify(identity)), path.basename(key))
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
return {
|
|
1136
|
+
async localPath(key) {
|
|
1137
|
+
await this.download(key);
|
|
1138
|
+
return (await location(key)).file;
|
|
1139
|
+
},
|
|
1140
|
+
async upload(key, body) {
|
|
1141
|
+
const { remote, objectKey, file } = await location(key);
|
|
1142
|
+
await remote.client.send(new remote.PutObjectCommand({
|
|
1143
|
+
Bucket: remote.bucket,
|
|
1144
|
+
Key: objectKey,
|
|
1145
|
+
Body: body,
|
|
1146
|
+
ContentType: "image/png"
|
|
1147
|
+
}));
|
|
1148
|
+
await writeBytesAtomic(file, body);
|
|
1149
|
+
},
|
|
1150
|
+
async download(key) {
|
|
1151
|
+
if (pending.has(key)) return pending.get(key);
|
|
1152
|
+
const next = (async () => {
|
|
1153
|
+
const { remote, objectKey, file } = await location(key);
|
|
1154
|
+
try {
|
|
1155
|
+
return await readFile(file);
|
|
1156
|
+
} catch (error) {
|
|
1157
|
+
if (error.code !== "ENOENT") throw error;
|
|
1158
|
+
}
|
|
1159
|
+
const bytes = await (await remote.client.send(new remote.GetObjectCommand({
|
|
1160
|
+
Bucket: remote.bucket,
|
|
1161
|
+
Key: objectKey
|
|
1162
|
+
}))).Body?.transformToByteArray();
|
|
1163
|
+
if (!bytes) throw new Error(`S3 对象为空: ${key}`);
|
|
1164
|
+
await writeBytesAtomic(file, bytes);
|
|
1165
|
+
return bytes;
|
|
1166
|
+
})();
|
|
1167
|
+
pending.set(key, next);
|
|
1168
|
+
try {
|
|
1169
|
+
return await next;
|
|
1170
|
+
} finally {
|
|
1171
|
+
pending.delete(key);
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
// modules/core/implementations/storage/objects.ts
|
|
1177
|
+
/** 按仓库配置惰性选择存储;Local 不读取 S3 环境配置。 */
|
|
1178
|
+
function createStorage(repoRoot, reportDir) {
|
|
1179
|
+
let storage;
|
|
1180
|
+
function resolveStorage() {
|
|
1181
|
+
return storage ??= loadConfig({ repoRoot }).then((config) => config.storage === "local" ? createLocalStorage(reportDir) : createS3Storage(repoRoot, reportDir));
|
|
1182
|
+
}
|
|
1183
|
+
return {
|
|
1184
|
+
async localPath(key) {
|
|
1185
|
+
return (await resolveStorage()).localPath(key);
|
|
1186
|
+
},
|
|
1187
|
+
async upload(key, body) {
|
|
1188
|
+
return (await resolveStorage()).upload(key, body);
|
|
1189
|
+
},
|
|
1190
|
+
async download(key) {
|
|
1191
|
+
return (await resolveStorage()).download(key);
|
|
1192
|
+
}
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
// modules/core/implementations/repository.ts
|
|
1196
|
+
async function reportRoot(root) {
|
|
1197
|
+
return path.join(root, (await loadConfig({ repoRoot: root })).reportDir);
|
|
1198
|
+
}
|
|
1199
|
+
function storageFor(reportDir, repoRoot) {
|
|
1200
|
+
return createStorage(repoRoot, reportDir);
|
|
1201
|
+
}
|
|
1202
|
+
// modules/core/implementations/Functions/compareTask.ts
|
|
1203
|
+
async function compareTask(input) {
|
|
1204
|
+
const { repoRoot: root, taskId } = CompareTaskInputSchema.parse(input);
|
|
1205
|
+
const reportDir = await reportRoot(root);
|
|
1206
|
+
return compare({ taskId }, reportDir, reportDir, storageFor(reportDir, root));
|
|
1207
|
+
}
|
|
1208
|
+
z.object({
|
|
1209
|
+
repoRoot: z.string(),
|
|
1210
|
+
taskId: z.string(),
|
|
1211
|
+
baselineVersion: z.string(),
|
|
1212
|
+
caseIds: z.array(z.string())
|
|
1213
|
+
});
|
|
1214
|
+
// modules/core/contracts/internal/updateBaseline.ts
|
|
1215
|
+
const CaseVersionSchema = z.object({
|
|
1216
|
+
id: IdSchema,
|
|
1217
|
+
baselineHash: z.string().nullable()
|
|
1218
|
+
});
|
|
1219
|
+
z.object({
|
|
1220
|
+
taskPath: TaskPathSchema,
|
|
1221
|
+
baselineVersion: z.string().optional(),
|
|
1222
|
+
cases: z.array(CaseVersionSchema).min(1)
|
|
1223
|
+
}).superRefine((value, ctx) => {
|
|
1224
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1225
|
+
value.cases.forEach((item, index) => {
|
|
1226
|
+
if (ids.has(item.id)) ctx.addIssue({
|
|
1227
|
+
code: "custom",
|
|
1228
|
+
path: [
|
|
1229
|
+
"cases",
|
|
1230
|
+
index,
|
|
1231
|
+
"id"
|
|
1232
|
+
],
|
|
1233
|
+
message: "case 不能重复"
|
|
1234
|
+
});
|
|
1235
|
+
ids.add(item.id);
|
|
1236
|
+
});
|
|
1237
|
+
});
|
|
1238
|
+
z.object({
|
|
1239
|
+
repoRoot: z.string(),
|
|
1240
|
+
ref: z.string(),
|
|
1241
|
+
version: z.string(),
|
|
1242
|
+
items: z.array(z.string()).min(1),
|
|
1243
|
+
reviewed: z.boolean()
|
|
1244
|
+
});
|
|
1245
|
+
z.object({
|
|
1246
|
+
repoRoot: z.string(),
|
|
1247
|
+
ref: z.string()
|
|
1248
|
+
});
|
|
1249
|
+
z.object({
|
|
1250
|
+
repoRoot: z.string(),
|
|
1251
|
+
ref: z.string(),
|
|
1252
|
+
version: z.string(),
|
|
1253
|
+
items: z.array(z.string()).min(1),
|
|
1254
|
+
reviewed: z.boolean()
|
|
1255
|
+
});
|
|
1256
|
+
z.object({
|
|
1257
|
+
repoRoot: z.string(),
|
|
1258
|
+
ref: z.string()
|
|
1259
|
+
});
|
|
1260
|
+
z.object({
|
|
1261
|
+
repoRoot: z.string(),
|
|
1262
|
+
namespace: z.string(),
|
|
1263
|
+
file: z.string(),
|
|
1264
|
+
version: z.string()
|
|
1265
|
+
});
|
|
1266
|
+
z.object({
|
|
1267
|
+
repoRoot: z.string(),
|
|
1268
|
+
baseTaskId: z.string().regex(/^[a-zA-Z0-9_-]{3,}$/),
|
|
1269
|
+
taskId: z.string().regex(/^[a-zA-Z0-9_-]{3,}$/)
|
|
1270
|
+
});
|
|
1271
|
+
z.object({
|
|
1272
|
+
repoRoot: z.string(),
|
|
1273
|
+
ref: z.string(),
|
|
1274
|
+
file: z.string(),
|
|
1275
|
+
version: z.string().optional()
|
|
1276
|
+
});
|
|
1277
|
+
z.object({ repoRoot: z.string() });
|
|
1278
|
+
z.object({ limit: z.number().int().min(1).max(100).optional() });
|
|
1279
|
+
z.object({ repoRoot: z.string() });
|
|
1280
|
+
z.object({ repoRoot: z.string() });
|
|
1281
|
+
z.object({
|
|
1282
|
+
repoRoot: z.string(),
|
|
1283
|
+
taskId: z.string()
|
|
1284
|
+
});
|
|
1285
|
+
// packages/sdk/main.ts
|
|
1286
|
+
async function createEvidra(options) {
|
|
1287
|
+
const repoRoot = options?.repoRoot;
|
|
1288
|
+
const { absoluteReportPath: reportDir } = await resolveConfig({ repoRoot });
|
|
1289
|
+
return {
|
|
1290
|
+
repoRoot,
|
|
1291
|
+
reportDir,
|
|
1292
|
+
async start(input) {
|
|
1293
|
+
return { taskId: (await addTask({
|
|
1294
|
+
repoRoot,
|
|
1295
|
+
namespace: input.namespace,
|
|
1296
|
+
name: input.name,
|
|
1297
|
+
startedAt: input.startedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
1298
|
+
coverage: input.coverage
|
|
1299
|
+
})).id };
|
|
1300
|
+
},
|
|
1301
|
+
async case(id, input) {
|
|
1302
|
+
await addCase({
|
|
1303
|
+
repoRoot,
|
|
1304
|
+
taskId: id,
|
|
1305
|
+
case: input
|
|
1306
|
+
});
|
|
1307
|
+
},
|
|
1308
|
+
async finish(id) {
|
|
1309
|
+
await finishTask({
|
|
1310
|
+
repoRoot,
|
|
1311
|
+
taskId: id
|
|
1312
|
+
});
|
|
1313
|
+
},
|
|
1314
|
+
async compare(taskId) {
|
|
1315
|
+
return compareTask({
|
|
1316
|
+
repoRoot,
|
|
1317
|
+
taskId
|
|
1318
|
+
});
|
|
1319
|
+
}
|
|
1320
|
+
};
|
|
1321
|
+
}
|
|
1322
|
+
export { createEvidra };
|