@boringparts/lioni 0.0.0-stage → 0.4.2

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.
@@ -0,0 +1,233 @@
1
+ import { F as QaSuppressionFormatError, M as stableStringify, N as StandardSchemaContractError, R as validateQaSuppression, p as validateUpdatePlan, s as validateFrameworkConfig, v as validateComparisonBaseline, z as validateQaSuppressionFile } from "./dist-BjI3h4o3.js";
2
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { pathToFileURL } from "node:url";
6
+ import { isMap, isScalar, isSeq, parseDocument } from "yaml";
7
+ // ../../packages/core/dist/node/qa-suppressions.js
8
+ const EMPTY_QA_SUPPRESSION_FILE = "format: lioni.qa-suppressions/v1\nsuppressions: []\n";
9
+ /** 为指定路径创建可手工维护的 YAML 豁免存储。 */
10
+ function createFileQaSuppressionStore(filePath) {
11
+ const resolvedFilePath = path.resolve(filePath);
12
+ return {
13
+ async load() {
14
+ return (await readQaSuppressionFile(resolvedFilePath))?.value.suppressions ?? [];
15
+ },
16
+ async upsert(suppression) {
17
+ validateQaSuppression(suppression);
18
+ const parsed = await readQaSuppressionFile(resolvedFilePath);
19
+ const current = parsed?.value.suppressions ?? [];
20
+ const idIndex = current.findIndex(({ id }) => id === suppression.id);
21
+ const next = [...current];
22
+ if (idIndex === -1) next.push(suppression);
23
+ else next[idIndex] = suppression;
24
+ validateQaSuppressionFile({
25
+ format: "lioni.qa-suppressions/v1",
26
+ suppressions: next
27
+ });
28
+ const existing = idIndex === -1 ? void 0 : current[idIndex];
29
+ if (existing !== void 0 && sameSuppression(existing, suppression)) return;
30
+ const document = parsed?.document ?? parseEmptyQaSuppressionFile();
31
+ const suppressionSequence = document.get("suppressions", true);
32
+ if (!isSeq(suppressionSequence)) throw invalidFile(resolvedFilePath, "suppressions 必须是 YAML 序列。");
33
+ if (idIndex === -1) suppressionSequence.add(document.createNode(suppression));
34
+ else {
35
+ const suppressionNode = suppressionSequence.items[idIndex];
36
+ if (!isMap(suppressionNode)) throw invalidFile(resolvedFilePath, "豁免记录必须是 YAML 映射。");
37
+ setString(suppressionNode, "reason", suppression.reason);
38
+ setString(suppressionNode, "checkId", suppression.checkId);
39
+ setString(suppressionNode, "sourceKey", suppression.sourceKey);
40
+ setString(suppressionNode, "language", suppression.language);
41
+ setString(suppressionNode, "inputFingerprint", suppression.inputFingerprint);
42
+ const summaryNode = suppressionNode.get("fingerprintSummary", true);
43
+ if (isMap(summaryNode)) {
44
+ setString(summaryNode, "version", suppression.fingerprintSummary.version);
45
+ setString(summaryNode, "inputFingerprint", suppression.fingerprintSummary.inputFingerprint);
46
+ } else suppressionNode.set("fingerprintSummary", document.createNode(suppression.fingerprintSummary));
47
+ }
48
+ const serializedValue = document.toJS({ maxAliasCount: 100 });
49
+ validateQaSuppressionFile(serializedValue);
50
+ await writeQaSuppressionDocument(resolvedFilePath, document.toString());
51
+ }
52
+ };
53
+ }
54
+ /** 将 Node 配置文件路径解析为同目录下的默认豁免文件路径。 */
55
+ function resolveDefaultQaSuppressionFilePath(configPath) {
56
+ const absoluteConfigPath = path.resolve(process.cwd(), configPath);
57
+ return path.join(path.dirname(absoluteConfigPath), "lioni.suppressions.yaml");
58
+ }
59
+ /** 根据 Node 配置文件位置创建默认 YAML 豁免存储。 */
60
+ function createDefaultQaSuppressionStore(configPath) {
61
+ return createFileQaSuppressionStore(resolveDefaultQaSuppressionFilePath(configPath));
62
+ }
63
+ async function readQaSuppressionFile(filePath) {
64
+ let contents;
65
+ try {
66
+ contents = await readFile(filePath, "utf8");
67
+ } catch (error) {
68
+ if (isMissingFile$1(error)) return void 0;
69
+ throw error;
70
+ }
71
+ const document = parseDocument(contents, {
72
+ uniqueKeys: true,
73
+ version: "1.2",
74
+ schema: "core"
75
+ });
76
+ if (document.errors.length > 0) throw new QaSuppressionFormatError("invalid", `QA 豁免文件不是有效 YAML:${filePath}。${document.errors[0]?.message ?? ""}`, { cause: document.errors[0] });
77
+ const value = document.toJS({ maxAliasCount: 100 });
78
+ validateQaSuppressionFile(value);
79
+ return {
80
+ document,
81
+ value
82
+ };
83
+ }
84
+ function parseEmptyQaSuppressionFile() {
85
+ return parseDocument(EMPTY_QA_SUPPRESSION_FILE, {
86
+ uniqueKeys: true,
87
+ version: "1.2",
88
+ schema: "core"
89
+ });
90
+ }
91
+ function setString(mapping, key, value) {
92
+ if (!isMap(mapping)) return;
93
+ const current = mapping.get(key, true);
94
+ if (isScalar(current)) current.value = value;
95
+ else mapping.set(key, value);
96
+ }
97
+ function sameSuppression(current, next) {
98
+ return current.id === next.id && current.reason === next.reason && current.checkId === next.checkId && current.sourceKey === next.sourceKey && current.language === next.language && current.inputFingerprint === next.inputFingerprint && current.fingerprintSummary.version === next.fingerprintSummary.version && current.fingerprintSummary.inputFingerprint === next.fingerprintSummary.inputFingerprint;
99
+ }
100
+ async function writeQaSuppressionDocument(filePath, contents) {
101
+ const directory = path.dirname(filePath);
102
+ const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
103
+ let moved = false;
104
+ try {
105
+ await mkdir(directory, { recursive: true });
106
+ await writeFile(temporaryPath, contents, "utf8");
107
+ await rename(temporaryPath, filePath);
108
+ moved = true;
109
+ } finally {
110
+ if (!moved) await unlink(temporaryPath).catch(ignoreMissingFile$1);
111
+ }
112
+ }
113
+ function invalidFile(filePath, message) {
114
+ return new QaSuppressionFormatError("invalid", `QA 豁免文件格式无效:${filePath}。${message}`);
115
+ }
116
+ function isMissingFile$1(error) {
117
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
118
+ }
119
+ function ignoreMissingFile$1(error) {
120
+ if (error.code !== "ENOENT") throw error;
121
+ }
122
+ // ../../packages/core/dist/node/index.js
123
+ var __rewriteRelativeImportExtension = function(path, preserveJsx) {
124
+ if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
125
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
126
+ });
127
+ return path;
128
+ };
129
+ /** 从 Node.js 配置模块加载并验证默认导出的宿主配置。 */
130
+ async function loadConfig(configPath) {
131
+ const absoluteConfigPath = path.resolve(process.cwd(), configPath);
132
+ const configModule = await import(__rewriteRelativeImportExtension(pathToFileURL(absoluteConfigPath).href));
133
+ if (configModule.default === void 0) throw new TypeError("宿主配置必须默认导出配置对象。");
134
+ const loadedConfig = configModule.default;
135
+ validateFrameworkConfig(loadedConfig);
136
+ return loadedConfig.quality?.suppressionStore === void 0 ? {
137
+ ...loadedConfig,
138
+ quality: {
139
+ ...loadedConfig.quality,
140
+ suppressionStore: createDefaultQaSuppressionStore(absoluteConfigPath)
141
+ }
142
+ } : loadedConfig;
143
+ }
144
+ /** 为 Node.js 宿主创建文件比较基线存储。 */
145
+ function createFileComparisonBaselineStore(filePath) {
146
+ return {
147
+ async load() {
148
+ return await readComparisonBaselineFile(filePath);
149
+ },
150
+ async save(baseline) {
151
+ validateComparisonBaseline(baseline);
152
+ const contents = `${stableStringify(baseline)}\n`;
153
+ const existing = await readComparisonBaselineFile(filePath);
154
+ if (existing !== void 0 && stableStringify(existing) === stableStringify(baseline)) return;
155
+ const directory = path.dirname(filePath);
156
+ const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
157
+ let moved = false;
158
+ try {
159
+ await mkdir(directory, { recursive: true });
160
+ await writeFile(temporaryPath, contents, "utf8");
161
+ await rename(temporaryPath, filePath);
162
+ moved = true;
163
+ } finally {
164
+ if (!moved) await unlink(temporaryPath).catch(ignoreMissingFile);
165
+ }
166
+ }
167
+ };
168
+ }
169
+ async function readComparisonBaselineFile(filePath) {
170
+ let contents;
171
+ try {
172
+ contents = await readFile(filePath, "utf8");
173
+ } catch (error) {
174
+ if (isMissingFile(error)) return void 0;
175
+ throw error;
176
+ }
177
+ let value;
178
+ try {
179
+ value = JSON.parse(contents);
180
+ } catch (error) {
181
+ throw new StandardSchemaContractError("比较基线文件", "invalid-json", `比较基线文件不是有效 JSON:${filePath}`, void 0, { cause: error });
182
+ }
183
+ validateComparisonBaseline(value);
184
+ return value;
185
+ }
186
+ /** 为 Node.js 宿主创建文件更新计划存储。 */
187
+ function createFileUpdatePlanStore(filePath) {
188
+ return {
189
+ async load() {
190
+ let contents;
191
+ try {
192
+ contents = await readFile(filePath, "utf8");
193
+ } catch (error) {
194
+ if (isMissingFile(error)) return void 0;
195
+ throw error;
196
+ }
197
+ let value;
198
+ try {
199
+ value = JSON.parse(contents);
200
+ } catch (error) {
201
+ throw new StandardSchemaContractError("更新计划文件", "invalid-json", `更新计划文件不是有效 JSON:${filePath}`, void 0, { cause: error });
202
+ }
203
+ validateUpdatePlan(value);
204
+ return value;
205
+ },
206
+ async save(plan) {
207
+ validateUpdatePlan(plan);
208
+ const serialized = JSON.stringify(plan, null, 2);
209
+ if (serialized === void 0) throw new TypeError("更新计划必须可序列化为 JSON。");
210
+ const contents = `${serialized}\n`;
211
+ const roundTripped = JSON.parse(contents);
212
+ validateUpdatePlan(roundTripped);
213
+ const directory = path.dirname(filePath);
214
+ const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
215
+ let moved = false;
216
+ try {
217
+ await mkdir(directory, { recursive: true });
218
+ await writeFile(temporaryPath, contents, "utf8");
219
+ await rename(temporaryPath, filePath);
220
+ moved = true;
221
+ } finally {
222
+ if (!moved) await unlink(temporaryPath).catch(ignoreMissingFile);
223
+ }
224
+ }
225
+ };
226
+ }
227
+ function isMissingFile(error) {
228
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
229
+ }
230
+ function ignoreMissingFile(error) {
231
+ if (error.code !== "ENOENT") throw error;
232
+ }
233
+ export { createFileQaSuppressionStore as a, createDefaultQaSuppressionStore as i, createFileUpdatePlanStore as n, resolveDefaultQaSuppressionFilePath as o, loadConfig as r, createFileComparisonBaselineStore as t };
package/dist/node.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { Ln as JsonValue, T as FrameworkConfig, Vt as QualityCheckResultCache, W as TranslationUnitInput, Yt as QaSuppressionStore, h as Termbase, ln as UpdatePlanStore, ot as ComparisonBaselineStore } from "./yaml-Dn7jqV-s.js";
2
+ /** 为指定路径创建可手工维护的 YAML 豁免存储。 */
3
+ export declare function createFileQaSuppressionStore(filePath: string): QaSuppressionStore;
4
+ /** 将 Node 配置文件路径解析为同目录下的默认豁免文件路径。 */
5
+ export declare function resolveDefaultQaSuppressionFilePath(configPath: string): string;
6
+ /** 根据 Node 配置文件位置创建默认 YAML 豁免存储。 */
7
+ export declare function createDefaultQaSuppressionStore(configPath: string): QaSuppressionStore;
8
+ /**
9
+ * 在专用目录内按键保存独立缓存条目。
10
+ * 目录可由多个实例共用;文件系统错误按缓存未命中处理。
11
+ */
12
+ export declare function createDirectoryQualityCheckResultCache(cacheDirectory: string): QualityCheckResultCache;
13
+ /** 解析配置文件同目录 `.lioni/cache/quality-results` 下的默认缓存目录。 */
14
+ export declare function resolveDefaultQualityCheckResultCacheDirectory(configPath: string): string;
15
+ /** 根据 Node.js 配置文件位置创建默认目录结果缓存;不会自动装配到 QA。 */
16
+ export declare function createDefaultDirectoryQualityCheckResultCache(configPath: string): QualityCheckResultCache;
17
+ type RuntimeFrameworkConfig = FrameworkConfig<TranslationUnitInput, unknown, JsonValue, unknown>;
18
+ /** 从 Node.js 配置模块加载并验证默认导出的宿主配置。 */
19
+ export declare function loadConfig(configPath: string): Promise<RuntimeFrameworkConfig>;
20
+ /** 为 Node.js 宿主创建文件比较基线存储。 */
21
+ export declare function createFileComparisonBaselineStore<TUnit extends TranslationUnitInput = TranslationUnitInput, TTranslation = unknown, TBody = JsonValue, TUnavailable = never>(filePath: string): ComparisonBaselineStore<TUnit, TTranslation, TBody, TUnavailable>;
22
+ /** 为 Node.js 宿主创建文件更新计划存储。 */
23
+ export declare function createFileUpdatePlanStore(filePath: string): UpdatePlanStore;
24
+ /** 读取完整术语目录并返回经过原生模型校验的术语库。 */
25
+ export declare function loadTermbaseYaml(directory: string | URL): Promise<Termbase>;
26
+ export type { UpdatePlanStore };
package/dist/node.js ADDED
@@ -0,0 +1,108 @@
1
+ import { M as stableStringify, V as isRecord, j as isCachedQualityFindings } from "./dist-BjI3h4o3.js";
2
+ import { a as createFileQaSuppressionStore, i as createDefaultQaSuppressionStore, n as createFileUpdatePlanStore, o as resolveDefaultQaSuppressionFilePath, r as loadConfig, t as createFileComparisonBaselineStore } from "./node-Bb9WsnGu.js";
3
+ import { n as parseTermbaseYaml } from "./yaml-DX1EEaWD.js";
4
+ import { mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { fileURLToPath } from "node:url";
8
+ // ../../packages/core/dist/node/quality-cache.js
9
+ const QUALITY_CACHE_ENTRY_FORMAT = "lioni.qa-cache-entry/v2";
10
+ /**
11
+ * 在专用目录内按键保存独立缓存条目。
12
+ * 目录可由多个实例共用;文件系统错误按缓存未命中处理。
13
+ */
14
+ function createDirectoryQualityCheckResultCache(cacheDirectory) {
15
+ const resolvedDirectory = path.resolve(cacheDirectory);
16
+ return {
17
+ async get(key) {
18
+ if (!isCacheKey(key)) return void 0;
19
+ let contents;
20
+ try {
21
+ contents = await readFile(entryPathForKey(resolvedDirectory, key), "utf8");
22
+ } catch {
23
+ return;
24
+ }
25
+ let value;
26
+ try {
27
+ value = JSON.parse(contents);
28
+ } catch {
29
+ return;
30
+ }
31
+ return isQualityCacheEntry(value, key) ? value.outcome : void 0;
32
+ },
33
+ async set(key, outcome) {
34
+ if (!isCacheKey(key) || !isCachedQualityFindings(outcome)) return;
35
+ const entry = {
36
+ format: QUALITY_CACHE_ENTRY_FORMAT,
37
+ key,
38
+ outcome,
39
+ contentDigest: contentDigest(key, outcome)
40
+ };
41
+ const entryPath = entryPathForKey(resolvedDirectory, key);
42
+ const temporaryPath = `${entryPath}.${process.pid}.${randomUUID()}.tmp`;
43
+ let moved = false;
44
+ try {
45
+ await mkdir(resolvedDirectory, { recursive: true });
46
+ await writeFile(temporaryPath, `${JSON.stringify(entry)}\n`, "utf8");
47
+ await rename(temporaryPath, entryPath);
48
+ moved = true;
49
+ } catch {} finally {
50
+ if (!moved) await unlink(temporaryPath).catch(() => void 0);
51
+ }
52
+ }
53
+ };
54
+ }
55
+ /** 解析配置文件同目录 `.lioni/cache/quality-results` 下的默认缓存目录。 */
56
+ function resolveDefaultQualityCheckResultCacheDirectory(configPath) {
57
+ const absoluteConfigPath = path.resolve(process.cwd(), configPath);
58
+ return path.join(path.dirname(absoluteConfigPath), ".lioni", "cache", "quality-results");
59
+ }
60
+ /** 根据 Node.js 配置文件位置创建默认目录结果缓存;不会自动装配到 QA。 */
61
+ function createDefaultDirectoryQualityCheckResultCache(configPath) {
62
+ return createDirectoryQualityCheckResultCache(resolveDefaultQualityCheckResultCacheDirectory(configPath));
63
+ }
64
+ function entryPathForKey(directory, key) {
65
+ const filename = createHash("sha256").update(key, "utf16le").digest("hex");
66
+ return path.join(directory, `${filename}.json`);
67
+ }
68
+ function isQualityCacheEntry(value, expectedKey) {
69
+ return isRecord(value) && value.format === QUALITY_CACHE_ENTRY_FORMAT && value.key === expectedKey && isCachedQualityFindings(value.outcome) && isContentDigest(value.contentDigest) && value.contentDigest === contentDigest(value.key, value.outcome);
70
+ }
71
+ function contentDigest(key, outcome) {
72
+ const content = stableStringify({
73
+ key,
74
+ outcome
75
+ });
76
+ return `sha256:${createHash("sha256").update(content).digest("hex")}`;
77
+ }
78
+ function isContentDigest(value) {
79
+ return typeof value === "string" && /^sha256:[a-f0-9]{64}$/u.test(value);
80
+ }
81
+ function isCacheKey(value) {
82
+ return typeof value === "string" && value.length > 0;
83
+ }
84
+ // ../../packages/terminology/dist/node.js
85
+ /** 读取默认术语目录:concepts.yaml 和任意数量的 <language>.yaml 文件。 */
86
+ async function readTermbaseYamlFiles(directory) {
87
+ const directoryPath = directory instanceof URL ? fileURLToPath(directory) : path.resolve(directory);
88
+ const yamlNames = (await readdir(directoryPath)).filter((name) => name.endsWith(".yaml"));
89
+ if (!yamlNames.includes("concepts.yaml")) throw new TypeError(`术语目录缺少 concepts.yaml:${directoryPath}`);
90
+ const concepts = await readFile(path.join(directoryPath, "concepts.yaml"), "utf8");
91
+ const languages = Object.create(null);
92
+ for (const name of yamlNames) {
93
+ if (name === "concepts.yaml") continue;
94
+ const language = name.slice(0, -5);
95
+ if (!language) throw new TypeError(`术语语言文件名无效:${name}`);
96
+ languages[language] = await readFile(path.join(directoryPath, name), "utf8");
97
+ }
98
+ return {
99
+ concepts,
100
+ languages
101
+ };
102
+ }
103
+ /** 读取完整术语目录并返回经过原生模型校验的术语库。 */
104
+ async function loadTermbaseYaml(directory) {
105
+ const files = await readTermbaseYamlFiles(directory);
106
+ return parseTermbaseYaml(files);
107
+ }
108
+ export { createDefaultDirectoryQualityCheckResultCache, createDefaultQaSuppressionStore, createDirectoryQualityCheckResultCache, createFileComparisonBaselineStore, createFileQaSuppressionStore, createFileUpdatePlanStore, loadConfig, loadTermbaseYaml, resolveDefaultQaSuppressionFilePath, resolveDefaultQualityCheckResultCacheDirectory };
@@ -0,0 +1,93 @@
1
+ // ../../packages/core/dist/quality/report.js
2
+ const severityText = {
3
+ error: "错误",
4
+ warning: "警告",
5
+ info: "提示"
6
+ };
7
+ /**
8
+ * 判断本次质量检查是否足以通过。
9
+ * 完整空项目可正常结束;有检查对象时仍须运行检查并通过现有错误门禁。
10
+ */
11
+ function isQualityReportPassing(report) {
12
+ return decideQualityReport(report).passed;
13
+ }
14
+ /** 返回可供脚本按报告结果分支处理的结论。 */
15
+ function decideQualityReport(report) {
16
+ const activeErrorCount = report.diagnostics.filter((diagnostic) => diagnostic.severity === "error" && diagnostic.handling.status === "active").length;
17
+ let status;
18
+ if (!report.readCoverage.associations.some((a) => a.subjectSelected) && report.progress === void 0) status = "no-candidates";
19
+ else if (report.checks.length === 0 && !isEmptyProjectRun(report)) status = "no-checks";
20
+ else if (activeErrorCount > 0) status = "failed";
21
+ else status = "passed";
22
+ return {
23
+ status,
24
+ passed: status === "passed",
25
+ activeErrorCount
26
+ };
27
+ }
28
+ /** 生成可供 CLI 与 SDK 脚本共用的简体中文质量报告。 */
29
+ function formatQualityReport(report, options) {
30
+ const maxPerCheck = options?.maxPerCheck;
31
+ if (maxPerCheck !== void 0 && (!Number.isInteger(maxPerCheck) || maxPerCheck < 1)) throw new RangeError("maxPerCheck 必须是正整数。");
32
+ const activeDiagnostics = report.diagnostics.filter(({ handling }) => handling.status === "active");
33
+ const suppressedCount = report.diagnostics.length - activeDiagnostics.length;
34
+ const readLanguages = report.readCoverage.translations.map(({ language }) => language);
35
+ const candidateLanguages = report.candidates.map(({ language }) => language);
36
+ const decision = decideQualityReport(report);
37
+ const { configuredCount, selectedIds, evaluatedCount } = report.checkScope;
38
+ const checkScope = configuredCount === 0 ? "配置 0 项,本次无检查项" : `配置 ${configuredCount} 项,本次${selectedIds.length === configuredCount ? "全量" : "子集"} ${selectedIds.length} 项(${selectedIds.join("、")})`;
39
+ const lines = [
40
+ `质量结论:${decision.passed ? "通过" : "未通过"}`,
41
+ `语言范围:${readLanguages.length === 0 ? "无译文语言" : `读取 ${readLanguages.join("、")}`};所选候选语言 ${candidateLanguages.length === 0 ? "无" : [...new Set(candidateLanguages)].join("、")}`,
42
+ `检查项范围:${checkScope};运行了 ${evaluatedCount} 项检查`,
43
+ `送检范围:${report.readCoverage.associations.filter((a) => a.subjectSelected).length} 项,其中 ${report.candidates.length} 项提供了译文`,
44
+ ...(report.progress ?? []).map(({ language, completed, total, percentage }) => `翻译进度 ${language}:${completed}/${total}${percentage === void 0 ? "" : `(${formatPercentage(percentage, completed === total)}%)`}`),
45
+ `有效问题:错误 ${countSeverity(activeDiagnostics, "error")},警告 ${countSeverity(activeDiagnostics, "warning")},提示 ${countSeverity(activeDiagnostics, "info")};已豁免 ${suppressedCount}`
46
+ ];
47
+ const selectedSeverities = options?.severities === void 0 ? void 0 : new Set(options.severities);
48
+ const matchingDiagnostics = selectedSeverities === void 0 ? report.diagnostics : report.diagnostics.filter(({ severity }) => selectedSeverities.has(severity));
49
+ if (report.diagnostics.length === 0) lines.push("问题:无");
50
+ else if (matchingDiagnostics.length === 0) lines.push("问题:按所选严重度无匹配明细");
51
+ else lines.push("问题:", ...formatDiagnosticDetails(matchingDiagnostics, maxPerCheck));
52
+ return lines.join("\n");
53
+ }
54
+ function formatDiagnosticDetails(diagnostics, maxPerCheck) {
55
+ if (maxPerCheck === void 0) return diagnostics.map(formatDiagnostic);
56
+ const grouped = /* @__PURE__ */ new Map();
57
+ for (const diagnostic of diagnostics) {
58
+ const items = grouped.get(diagnostic.checkId);
59
+ if (items === void 0) grouped.set(diagnostic.checkId, [diagnostic]);
60
+ else items.push(diagnostic);
61
+ }
62
+ const lines = [];
63
+ for (const [checkId, items] of grouped) {
64
+ const shown = items.slice(0, maxPerCheck);
65
+ const omittedCount = items.length - shown.length;
66
+ lines.push(...shown.map(formatDiagnostic));
67
+ if (omittedCount > 0) lines.push(`- ${checkId}:另有 ${omittedCount} 条匹配明细因上限(${maxPerCheck})被省略`);
68
+ }
69
+ return lines;
70
+ }
71
+ /** 显示到小数点后两位,仅在所有检查对象均已完成时显示 100%。 */
72
+ function formatPercentage(percentage, complete) {
73
+ return complete ? 100 : Math.min(99.99, Number(percentage.toFixed(2)));
74
+ }
75
+ function isEmptyProjectRun(report) {
76
+ return report.progress?.every(({ total }) => total === 0) === true;
77
+ }
78
+ function countSeverity(diagnostics, severity) {
79
+ return diagnostics.filter((diagnostic) => diagnostic.severity === severity).length;
80
+ }
81
+ function formatDiagnostic(diagnostic) {
82
+ const language = diagnostic.object.language ?? diagnostic.location.language ?? "原文";
83
+ const range = displayRange(diagnostic.location.range);
84
+ const key = diagnostic.location.key === void 0 ? "" : `,位置键 ${diagnostic.location.key}`;
85
+ const suppression = diagnostic.handling.status === "suppressed" ? `(已豁免:${diagnostic.handling.reason})` : "";
86
+ return `- [${severityText[diagnostic.severity]}] ${diagnostic.checkId} ${diagnostic.object.key}(${language},${range}${key}):${diagnostic.message}${suppression}`;
87
+ }
88
+ function displayRange(range) {
89
+ if (typeof range === "string") return range;
90
+ if (range === null || range === void 0) return "位置未知";
91
+ return JSON.stringify(range) ?? "位置未知";
92
+ }
93
+ export { formatQualityReport as n, isQualityReportPassing as r, decideQualityReport as t };