@hamsterbase/evidra 0.11.0 → 0.12.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/dist/sdk/conformance-rules.js +1103 -814
- package/dist/sdk/conformance.js +1 -5
- package/dist/sdk/index-lcSI6COn.d.ts +108 -0
- package/dist/sdk/index.d.ts +2 -10
- package/dist/sdk/rules.d.ts +236 -154
- package/dist/sdk/runner-Dcqs9-Dm.js +191 -0
- package/dist/service/cli.js +2689 -268
- package/package.json +2 -3
- package/skills/evidra/SKILL.md +3 -2
- package/skills/evidra-share/scripts/named-tunnel.mjs +14 -2
- package/skills/evidra-share/scripts/share.sh +12 -7
- package/dist/sdk/types--o0ku6ya.d.ts +0 -21
- package/packages/conformance/rules/baseline-max-diff-pixels/RULE.md +0 -21
- package/packages/conformance/rules/commit-message/RULE.md +0 -29
- package/packages/conformance/rules/duplicate-localization/RULE.md +0 -37
- package/packages/conformance/rules/e2e-scenarios-structure/RULE.md +0 -39
- package/packages/conformance/rules/index.md +0 -18
- package/packages/conformance/rules/same-dir-import-only/RULE.md +0 -35
- package/packages/conformance/rules/single-component-file/RULE.md +0 -33
- package/packages/conformance/rules/source-locale-defaults/RULE.md +0 -48
- package/packages/conformance/rules/sync-locales/RULE.md +0 -45
- package/packages/conformance/rules/ui-scenarios-structure/RULE.md +0 -43
|
@@ -1,56 +1,30 @@
|
|
|
1
|
+
import { n as ruleOptionsToJsonSchema, r as defineRule, t as renderRuleDoc } from "./runner-Dcqs9-Dm.js";
|
|
1
2
|
import path from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
2
4
|
import { glob, readFile, stat } from "node:fs/promises";
|
|
3
5
|
import { promisify } from "node:util";
|
|
4
6
|
import { promises } from "node:fs";
|
|
5
7
|
import { execFile } from "node:child_process";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
6
9
|
import { parseSync } from "oxc-parser";
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
},
|
|
26
|
-
sameDirImportOnly: {
|
|
27
|
-
id: "same-dir-import-only",
|
|
28
|
-
displayName: "限制跨目录引用"
|
|
29
|
-
},
|
|
30
|
-
singleComponentFile: {
|
|
31
|
-
id: "single-component-file",
|
|
32
|
-
displayName: "单文件单组件"
|
|
33
|
-
},
|
|
34
|
-
sourceLocaleDefaults: {
|
|
35
|
-
id: "source-locale-defaults",
|
|
36
|
-
displayName: "检查源语言默认文案"
|
|
37
|
-
},
|
|
38
|
-
syncLocales: {
|
|
39
|
-
id: "sync-locales",
|
|
40
|
-
displayName: "同步本地化文件"
|
|
41
|
-
},
|
|
42
|
-
uiScenariosStructure: {
|
|
43
|
-
id: "ui-scenarios-structure",
|
|
44
|
-
displayName: "检查界面场景结构"
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
// packages/conformance/rules/baseline-max-diff-pixels/index.ts
|
|
48
|
-
function baselineMaxDiffPixels(options) {
|
|
49
|
-
const rule = builtinRules.baselineMaxDiffPixels;
|
|
50
|
-
const task = async ({ projectRoot }) => {
|
|
51
|
-
const { baselineDir, maxDiffPixels } = options;
|
|
52
|
-
if (typeof baselineDir !== "string" || !baselineDir.trim()) throw new Error("baselineDir 必须指定基线目录");
|
|
53
|
-
if (!Number.isSafeInteger(maxDiffPixels) || maxDiffPixels < 0) throw new Error("maxDiffPixels 必须是非负整数");
|
|
10
|
+
import { tsImport } from "tsx/esm/api";
|
|
11
|
+
// packages/conformance/rules/baseline-max-diff-pixels.ts
|
|
12
|
+
const optionsSchema$9 = z.object({
|
|
13
|
+
baselineDir: z.string().trim().min(1).describe("基线 JSON 目录,支持绝对路径或相对 projectRoot 的路径。"),
|
|
14
|
+
maxDiffPixels: z.number().int().nonnegative().describe("每张基线图片允许配置的最大差异像素数;阈值等于上限时通过,未配置时按 0 处理。")
|
|
15
|
+
});
|
|
16
|
+
const baselineMaxDiffPixels = defineRule({
|
|
17
|
+
id: "baseline-max-diff-pixels",
|
|
18
|
+
displayName: "限制基线允许差异像素",
|
|
19
|
+
exportName: "baselineMaxDiffPixels",
|
|
20
|
+
summary: "递归检查指定基线目录,确保每张图片快照的 `maxDiffPixels` 在项目允许的上限内。",
|
|
21
|
+
optionsSchema: optionsSchema$9,
|
|
22
|
+
examples: [{ options: {
|
|
23
|
+
baselineDir: ".report/baselines",
|
|
24
|
+
maxDiffPixels: 20
|
|
25
|
+
} }],
|
|
26
|
+
notes: "读取基线 JSON 中的图片快照元数据,适用于本地或 S3 图片存储。超过上限时,报告会列出基线文件、用例、快照和实际阈值。需要调整单张快照的阈值时,在测试上报配置中设置 `maxDiffPixels`,重新上报后由用户审核基线。",
|
|
27
|
+
async run({ projectRoot }, { baselineDir, maxDiffPixels }) {
|
|
54
28
|
const root = path.resolve(projectRoot, baselineDir);
|
|
55
29
|
if (!(await stat(root)).isDirectory()) throw new Error(`基线路径必须是目录:${root}`);
|
|
56
30
|
const files = [];
|
|
@@ -86,30 +60,35 @@ function baselineMaxDiffPixels(options) {
|
|
|
86
60
|
}
|
|
87
61
|
}
|
|
88
62
|
return {
|
|
89
|
-
name:
|
|
63
|
+
name: "baseline-max-diff-pixels",
|
|
90
64
|
success: findings.length === 0,
|
|
91
65
|
messages: [`检查了 ${imageCount} 张基线图片,maxDiffPixels 上限为 ${maxDiffPixels}。`, ...findings].join("\n"),
|
|
92
66
|
howToFix: findings.length ? "检查报告中的文件和快照。需要调整阈值时,从测试上报配置设置 maxDiffPixels,重新上报后由用户审核基线。" : ""
|
|
93
67
|
};
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
// packages/conformance/rules/commit-message.ts
|
|
71
|
+
const optionsSchema$8 = z.object({
|
|
72
|
+
forbiddenPrefixes: z.array(z.string()).readonly().default(["```"]).describe("禁止的提交标题前缀;传入空数组时不限制前缀。"),
|
|
73
|
+
base: z.string().trim().min(1).optional().describe("比较基准,例如 CI 中的 \"origin/main\";指定时仅检查 `base..HEAD`,默认使用 upstream。")
|
|
74
|
+
});
|
|
101
75
|
const execFileAsync = promisify(execFile);
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
76
|
+
const commitMessage = defineRule({
|
|
77
|
+
id: "commit-message",
|
|
78
|
+
displayName: "检查提交标题",
|
|
79
|
+
exportName: "commitMessage",
|
|
80
|
+
summary: "检查 Git 提交标题是否以禁止的前缀开头,避免将 Markdown 代码块标记误作提交标题。",
|
|
81
|
+
optionsSchema: optionsSchema$8,
|
|
82
|
+
examples: [{ options: { forbiddenPrefixes: ["```"] } }],
|
|
83
|
+
notes: "指定 `base` 时检查 `base..HEAD`;否则有 upstream 时检查 `upstream..HEAD`;两者都没有时只检查尚未推送到任何远端的提交(`HEAD --not --remotes`),仓库没有远端时等同于全部历史。CI 的 detached HEAD 没有 upstream,应配置 `base`。Git 执行错误作为任务失败。",
|
|
84
|
+
async run(common, options) {
|
|
85
|
+
const { commits, scope } = await collectCommitSubjects(common.projectRoot, options.base);
|
|
86
|
+
const violations = commits.filter((commit) => options.forbiddenPrefixes.some((prefix) => commit.subject.startsWith(prefix)));
|
|
108
87
|
const lines = [`扫描${scope} ${commits.length} 个提交 message。`];
|
|
109
88
|
if (violations.length === 0) {
|
|
110
89
|
lines.push("未发现以禁止的前缀开头的提交 message。");
|
|
111
90
|
return {
|
|
112
|
-
name:
|
|
91
|
+
name: "commit-message",
|
|
113
92
|
success: true,
|
|
114
93
|
messages: lines.join("\n"),
|
|
115
94
|
howToFix: ""
|
|
@@ -118,17 +97,13 @@ function commitMessage(config = {}) {
|
|
|
118
97
|
lines.push(`发现 ${violations.length} 个提交 message 以禁止的前缀开头:`);
|
|
119
98
|
for (const violation of violations) lines.push(` - ${violation.hash.slice(0, 7)} ${violation.subject}`);
|
|
120
99
|
return {
|
|
121
|
-
name:
|
|
100
|
+
name: "commit-message",
|
|
122
101
|
success: false,
|
|
123
102
|
messages: lines.join("\n"),
|
|
124
103
|
howToFix: "修改对应提交 message,移除禁止的前缀。"
|
|
125
104
|
};
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
...rule,
|
|
129
|
-
readme: { builtin: rule.id }
|
|
130
|
-
});
|
|
131
|
-
}
|
|
105
|
+
}
|
|
106
|
+
});
|
|
132
107
|
async function collectCommitSubjects(repoRoot, base) {
|
|
133
108
|
const upstream = base ?? await readUpstream(repoRoot);
|
|
134
109
|
const logArgs = ["log", "--format=%x1e%H%x00%s"];
|
|
@@ -170,8 +145,13 @@ async function readUpstream(repoRoot) {
|
|
|
170
145
|
return;
|
|
171
146
|
}
|
|
172
147
|
}
|
|
173
|
-
// packages/conformance/rules/
|
|
174
|
-
const
|
|
148
|
+
// packages/conformance/rules/conformance-rule-format.ts
|
|
149
|
+
const optionsSchema$7 = z.object({
|
|
150
|
+
rulesDir: z.string().trim().min(1).describe("存放规约单文件的目录,支持绝对路径或相对 projectRoot 的路径。"),
|
|
151
|
+
entryFile: z.string().trim().min(1).optional().describe("可选的规约汇总入口文件路径(例如 packages/conformance/rules.ts);配置后同时检查所有规约均已具名导出并注册到 builtinRules。")
|
|
152
|
+
});
|
|
153
|
+
const KEBAB_FILE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.ts$/;
|
|
154
|
+
const SKIP_AST_KEYS$7 = /* @__PURE__ */ new Set([
|
|
175
155
|
"loc",
|
|
176
156
|
"range",
|
|
177
157
|
"start",
|
|
@@ -180,17 +160,295 @@ const SKIP_AST_KEYS$6 = /* @__PURE__ */ new Set([
|
|
|
180
160
|
"leadingComments",
|
|
181
161
|
"trailingComments"
|
|
182
162
|
]);
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
163
|
+
const conformanceRuleFormat = defineRule({
|
|
164
|
+
id: "conformance-rule-format",
|
|
165
|
+
displayName: "检查规约格式",
|
|
166
|
+
exportName: "conformanceRuleFormat",
|
|
167
|
+
summary: "检查规约目录是否遵循单文件自治格式:文件名与导出名一致、无手写 Markdown、规约间零依赖,且通过 defineRule 与 Zod Schema 推导文档。",
|
|
168
|
+
optionsSchema: optionsSchema$7,
|
|
169
|
+
examples: [{ options: {
|
|
170
|
+
rulesDir: "packages/conformance/rules",
|
|
171
|
+
entryFile: "packages/conformance/rules.ts"
|
|
172
|
+
} }],
|
|
173
|
+
notes: "每条规约须为 `rulesDir` 下独立的 kebab-case `.ts` 文件(不含子目录和 `.md` 文件),不得导入或转导出 `rulesDir` 内的其他文件,须导出同名 camelCase 工厂函数,通过 `defineRule` 提供完整的 `id`、`displayName`、`exportName`、`summary`、字段均带 `.describe()` 的 Zod `optionsSchema` 以及能通过校验的 `examples`。配置 `entryFile` 时会同步检查入口导出与 `builtinRules` 注册表。",
|
|
174
|
+
async run(context, options) {
|
|
175
|
+
const repoRoot = context.projectRoot;
|
|
176
|
+
const rulesDir = path.resolve(repoRoot, options.rulesDir);
|
|
177
|
+
const violations = [];
|
|
178
|
+
const dirEntries = await readDirIfExists$4(rulesDir);
|
|
179
|
+
if (!dirEntries) return {
|
|
180
|
+
name: "conformance-rule-format",
|
|
181
|
+
success: false,
|
|
182
|
+
messages: `规约目录不存在:${path.relative(repoRoot, rulesDir)}`,
|
|
183
|
+
howToFix: "确认 rulesDir 指向有效的规约目录。"
|
|
184
|
+
};
|
|
185
|
+
const ruleFiles = [];
|
|
186
|
+
for (const entry of dirEntries) {
|
|
187
|
+
if (entry.name.startsWith(".")) continue;
|
|
188
|
+
const full = path.join(rulesDir, entry.name);
|
|
189
|
+
const relative = path.relative(repoRoot, full);
|
|
190
|
+
if (entry.isDirectory()) {
|
|
191
|
+
violations.push(` - ${relative} 规约目录不允许子目录,每条规约须为单个 .ts 文件`);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (!entry.isFile()) continue;
|
|
195
|
+
if (path.extname(entry.name).toLowerCase() === ".md") {
|
|
196
|
+
violations.push(` - ${relative} 不允许手写 Markdown 文档,规约文档须由定义与 Zod Schema 自动推导`);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (!KEBAB_FILE_PATTERN.test(entry.name)) {
|
|
200
|
+
violations.push(` - ${relative} 规约文件名须为 kebab-case .ts(例如 my-rule.ts)`);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
ruleFiles.push(full);
|
|
204
|
+
}
|
|
205
|
+
ruleFiles.sort((left, right) => left.localeCompare(right));
|
|
206
|
+
const loadedRules = [];
|
|
207
|
+
const seenDisplayNames = /* @__PURE__ */ new Map();
|
|
208
|
+
for (const file of ruleFiles) {
|
|
209
|
+
const relative = path.relative(repoRoot, file);
|
|
210
|
+
const ruleId = path.basename(file, ".ts");
|
|
211
|
+
const expectedExportName = kebabToCamel(ruleId);
|
|
212
|
+
const source = await parseSourceFile$7(file);
|
|
213
|
+
walk$7(source.program, (node) => {
|
|
214
|
+
const specifier = readImportSpecifier$1(node);
|
|
215
|
+
if (!specifier || !specifier.startsWith("./") && !specifier.startsWith("../")) return;
|
|
216
|
+
if (isInsidePath$4(path.resolve(path.dirname(file), specifier), rulesDir)) violations.push(` - ${relative}:${lineOf$4(source, node)} 规约之间禁止互相依赖或共享代码,不得引用 '${specifier}'`);
|
|
217
|
+
});
|
|
218
|
+
let moduleExports;
|
|
219
|
+
try {
|
|
220
|
+
moduleExports = await tsImport(pathToFileURL(file).href, import.meta.url);
|
|
221
|
+
} catch (error) {
|
|
222
|
+
violations.push(` - ${relative} 加载规约模块失败:${error instanceof Error ? error.message : String(error)}`);
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
const exported = moduleExports[expectedExportName];
|
|
226
|
+
if (typeof exported !== "function") {
|
|
227
|
+
violations.push(` - ${relative} 必须具名导出规约工厂函数 ${expectedExportName}`);
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
const meta = exported.meta;
|
|
231
|
+
if (!isRecord(meta)) {
|
|
232
|
+
violations.push(` - ${relative} 导出的 ${expectedExportName} 必须通过 defineRule 定义并附带 meta`);
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
const ruleDoc = meta;
|
|
236
|
+
if (ruleDoc.id !== ruleId) violations.push(` - ${relative} meta.id 须与文件名一致(期望 '${ruleId}',实际 '${String(ruleDoc.id)}')`);
|
|
237
|
+
if (ruleDoc.exportName !== expectedExportName) violations.push(` - ${relative} meta.exportName 须与导出名一致(期望 '${expectedExportName}',实际 '${String(ruleDoc.exportName)}')`);
|
|
238
|
+
if (typeof ruleDoc.displayName !== "string" || !ruleDoc.displayName.trim()) violations.push(` - ${relative} meta.displayName 必须是非空字符串`);
|
|
239
|
+
else {
|
|
240
|
+
const existingFile = seenDisplayNames.get(ruleDoc.displayName);
|
|
241
|
+
if (existingFile) violations.push(` - ${relative} meta.displayName '${ruleDoc.displayName}' 与 ${existingFile} 重复`);
|
|
242
|
+
else seenDisplayNames.set(ruleDoc.displayName, relative);
|
|
243
|
+
}
|
|
244
|
+
if (typeof ruleDoc.summary !== "string" || !ruleDoc.summary.trim()) violations.push(` - ${relative} meta.summary 必须是非空字符串`);
|
|
245
|
+
let schemaValid = false;
|
|
246
|
+
if (!isZodSchema(ruleDoc.optionsSchema)) violations.push(` - ${relative} meta.optionsSchema 必须是有效的 Zod Schema`);
|
|
247
|
+
else try {
|
|
248
|
+
const jsonSchema = ruleOptionsToJsonSchema(ruleDoc.optionsSchema);
|
|
249
|
+
if (jsonSchema.type !== "object") violations.push(` - ${relative} meta.optionsSchema 顶层必须是 z.object(...)`);
|
|
250
|
+
else {
|
|
251
|
+
schemaValid = true;
|
|
252
|
+
for (const missingPath of findMissingDescriptions(jsonSchema)) violations.push(` - ${relative} 配置项 '${missingPath}' 缺少 .describe(...) 说明,无法生成完整参数文档`);
|
|
253
|
+
}
|
|
254
|
+
} catch (error) {
|
|
255
|
+
violations.push(` - ${relative} meta.optionsSchema 无法转换为文档 Schema:${error instanceof Error ? error.message : String(error)}`);
|
|
256
|
+
}
|
|
257
|
+
if (!Array.isArray(ruleDoc.examples) || ruleDoc.examples.length === 0) violations.push(` - ${relative} meta.examples 至少需要提供 1 个配置示例`);
|
|
258
|
+
else if (schemaValid && isZodSchema(ruleDoc.optionsSchema)) {
|
|
259
|
+
for (const [index, example] of ruleDoc.examples.entries()) {
|
|
260
|
+
if (!isRecord(example) || !("options" in example)) {
|
|
261
|
+
violations.push(` - ${relative} meta.examples[${index}] 必须包含 options 字段`);
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
const parsed = ruleDoc.optionsSchema.safeParse(example.options);
|
|
265
|
+
if (!parsed.success) violations.push(` - ${relative} meta.examples[${index}].options 未通过 optionsSchema 校验:${z.prettifyError(parsed.error)}`);
|
|
266
|
+
}
|
|
267
|
+
const firstExample = ruleDoc.examples[0];
|
|
268
|
+
if (isRecord(firstExample) && "options" in firstExample) try {
|
|
269
|
+
const task = exported(firstExample.options);
|
|
270
|
+
if (typeof task !== "function" || task.id !== ruleId || task.doc !== meta) violations.push(` - ${relative} 调用 ${expectedExportName}(example.options) 未返回带 id 与 doc 的有效 RuleTask`);
|
|
271
|
+
} catch (error) {
|
|
272
|
+
violations.push(` - ${relative} 使用示例参数调用 ${expectedExportName} 失败:${error instanceof Error ? error.message : String(error)}`);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (schemaValid && Array.isArray(ruleDoc.examples) && ruleDoc.examples.length > 0) try {
|
|
276
|
+
if (!renderRuleDoc(ruleDoc).includes(`# ${expectedExportName}`)) violations.push(` - ${relative} 推导出的文档缺少标题 '# ${expectedExportName}'`);
|
|
277
|
+
} catch (error) {
|
|
278
|
+
violations.push(` - ${relative} 推导规约文档失败:${error instanceof Error ? error.message : String(error)}`);
|
|
279
|
+
}
|
|
280
|
+
loadedRules.push({
|
|
281
|
+
id: ruleId,
|
|
282
|
+
exportName: expectedExportName,
|
|
283
|
+
file: relative
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
if (options.entryFile) await validateEntryFile(repoRoot, path.resolve(repoRoot, options.entryFile), loadedRules, violations);
|
|
287
|
+
const lines = [`检查了 ${path.relative(repoRoot, rulesDir)} 下 ${ruleFiles.length} 个规约文件。`];
|
|
288
|
+
if (violations.length === 0) {
|
|
289
|
+
lines.push("所有规约均符合单文件、零依赖与 Zod 文档推导格式。");
|
|
290
|
+
return {
|
|
291
|
+
name: "conformance-rule-format",
|
|
292
|
+
success: true,
|
|
293
|
+
messages: lines.join("\n"),
|
|
294
|
+
howToFix: ""
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
lines.push(`发现 ${violations.length} 处规约格式违规:`, ...violations);
|
|
298
|
+
return {
|
|
299
|
+
name: "conformance-rule-format",
|
|
300
|
+
success: false,
|
|
301
|
+
messages: lines.join("\n"),
|
|
302
|
+
howToFix: "按规约格式修正:每条规约使用单个 kebab-case .ts 文件、通过 defineRule 与带 .describe() 的 Zod Schema 定义、提供合法 examples、移除手写 Markdown 与规约间引用,并同步入口导出。"
|
|
192
303
|
};
|
|
193
|
-
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
async function validateEntryFile(repoRoot, entryPath, loadedRules, violations) {
|
|
307
|
+
const relative = path.relative(repoRoot, entryPath);
|
|
308
|
+
let entryModule;
|
|
309
|
+
try {
|
|
310
|
+
entryModule = await tsImport(pathToFileURL(entryPath).href, import.meta.url);
|
|
311
|
+
} catch (error) {
|
|
312
|
+
violations.push(` - ${relative} 无法加载规约入口文件:${error instanceof Error ? error.message : String(error)}`);
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
for (const rule of loadedRules) {
|
|
316
|
+
const exported = entryModule[rule.exportName];
|
|
317
|
+
const meta = isRecord(exported?.meta) ? exported.meta ?? void 0 : void 0;
|
|
318
|
+
if (typeof exported !== "function" || meta?.id !== rule.id) violations.push(` - ${relative} 缺少或未正确导出规约 ${rule.exportName}(来自 ${rule.file})`);
|
|
319
|
+
}
|
|
320
|
+
if (!("builtinRules" in entryModule)) return;
|
|
321
|
+
const catalog = entryModule.builtinRules;
|
|
322
|
+
if (!Array.isArray(catalog)) {
|
|
323
|
+
violations.push(` - ${relative} 导出的 builtinRules 必须是规约数组`);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
const expectedIds = new Set(loadedRules.map((rule) => rule.id));
|
|
327
|
+
const registeredIds = /* @__PURE__ */ new Set();
|
|
328
|
+
for (const [index, item] of catalog.entries()) {
|
|
329
|
+
const meta = isRecord(item?.meta) ? item.meta : void 0;
|
|
330
|
+
const id = typeof meta?.id === "string" ? meta.id : void 0;
|
|
331
|
+
if (typeof item !== "function" || !id) {
|
|
332
|
+
violations.push(` - ${relative} builtinRules[${index}] 不是通过 defineRule 定义的有效规约`);
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (registeredIds.has(id)) {
|
|
336
|
+
violations.push(` - ${relative} builtinRules 中重复注册了规约 '${id}'`);
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
registeredIds.add(id);
|
|
340
|
+
if (!expectedIds.has(id)) violations.push(` - ${relative} builtinRules 包含未在 rulesDir 中找到的规约 '${id}'`);
|
|
341
|
+
}
|
|
342
|
+
for (const rule of loadedRules) if (!registeredIds.has(rule.id)) violations.push(` - ${relative} builtinRules 未注册规约 '${rule.id}'`);
|
|
343
|
+
}
|
|
344
|
+
function findMissingDescriptions(schema, prefix = "") {
|
|
345
|
+
const missing = [];
|
|
346
|
+
const properties = schema.properties ?? {};
|
|
347
|
+
for (const [key, prop] of Object.entries(properties)) {
|
|
348
|
+
const fieldPath = prefix ? `${prefix}.${key}` : key;
|
|
349
|
+
if (typeof prop.description !== "string" || !prop.description.trim()) missing.push(fieldPath);
|
|
350
|
+
if (prop.type === "object" && prop.properties) missing.push(...findMissingDescriptions(prop, fieldPath));
|
|
351
|
+
else if (prop.type === "array" && prop.items?.type === "object" && prop.items.properties) missing.push(...findMissingDescriptions(prop.items, `${fieldPath}[]`));
|
|
352
|
+
}
|
|
353
|
+
return missing;
|
|
354
|
+
}
|
|
355
|
+
function isZodSchema(value) {
|
|
356
|
+
return isRecord(value) && "_zod" in value && typeof value.safeParse === "function";
|
|
357
|
+
}
|
|
358
|
+
function isRecord(value) {
|
|
359
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
360
|
+
}
|
|
361
|
+
function kebabToCamel(value) {
|
|
362
|
+
return value.replace(/-([a-z0-9])/g, (_, char) => char.toUpperCase());
|
|
363
|
+
}
|
|
364
|
+
async function readDirIfExists$4(dir) {
|
|
365
|
+
try {
|
|
366
|
+
return await promises.readdir(dir, { withFileTypes: true });
|
|
367
|
+
} catch (error) {
|
|
368
|
+
if (error.code === "ENOENT") return void 0;
|
|
369
|
+
throw error;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
function isInsidePath$4(filePath, dir) {
|
|
373
|
+
const relative = path.relative(dir, filePath);
|
|
374
|
+
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
375
|
+
}
|
|
376
|
+
async function parseSourceFile$7(file) {
|
|
377
|
+
const code = await promises.readFile(file, "utf8");
|
|
378
|
+
const lineStarts = [0];
|
|
379
|
+
for (let index = 0; index < code.length; index += 1) if (code[index] === "\n") lineStarts.push(index + 1);
|
|
380
|
+
const parsed = parseSync(file, code);
|
|
381
|
+
if (parsed.errors.length) throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
|
|
382
|
+
return {
|
|
383
|
+
file,
|
|
384
|
+
program: parsed.program,
|
|
385
|
+
lineStarts
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
function walk$7(node, visit) {
|
|
389
|
+
if (!node || typeof node !== "object") return;
|
|
390
|
+
const current = node;
|
|
391
|
+
if (typeof current.type === "string") visit(current);
|
|
392
|
+
for (const key of Object.keys(current)) {
|
|
393
|
+
if (SKIP_AST_KEYS$7.has(key)) continue;
|
|
394
|
+
const value = current[key];
|
|
395
|
+
if (Array.isArray(value)) for (const child of value) walk$7(child, visit);
|
|
396
|
+
else if (value && typeof value === "object") walk$7(value, visit);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
function lineOf$4(source, node) {
|
|
400
|
+
if (typeof node.start !== "number") return 0;
|
|
401
|
+
let low = 0;
|
|
402
|
+
let high = source.lineStarts.length - 1;
|
|
403
|
+
while (low <= high) {
|
|
404
|
+
const mid = Math.floor((low + high) / 2);
|
|
405
|
+
if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
|
|
406
|
+
else high = mid - 1;
|
|
407
|
+
}
|
|
408
|
+
return high + 1;
|
|
409
|
+
}
|
|
410
|
+
function readImportSpecifier$1(node) {
|
|
411
|
+
if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ImportExpression") {
|
|
412
|
+
const source = node.source;
|
|
413
|
+
if (source && (source.type === "Literal" || source.type === "StringLiteral") && typeof source.value === "string") return source.value;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
// packages/conformance/rules/duplicate-localization.ts
|
|
417
|
+
const optionsSchema$6 = z.object({
|
|
418
|
+
scanRoot: z.string().trim().min(1).describe("递归扫描的源码目录,支持绝对路径或相对 projectRoot 的路径。"),
|
|
419
|
+
excludeDirs: z.array(z.string()).readonly().default([]).describe("扫描时跳过的子目录及其后代;路径相对 projectRoot 解析,也支持绝对路径。"),
|
|
420
|
+
skipDirNames: z.array(z.string()).readonly().default([
|
|
421
|
+
"node_modules",
|
|
422
|
+
"dist",
|
|
423
|
+
"coverage"
|
|
424
|
+
]).describe("按目录名跳过;传入时替换默认列表,隐藏目录始终跳过。"),
|
|
425
|
+
callName: z.string().trim().min(1).default("localize").describe("本地化函数名;仅匹配直接调用,不匹配对象成员调用。"),
|
|
426
|
+
keyArgument: z.number().int().nonnegative().default(0).describe("key 所在的参数下标,从 0 开始。"),
|
|
427
|
+
valueArgument: z.number().int().nonnegative().default(1).describe("默认文案所在的参数下标,从 0 开始。")
|
|
428
|
+
});
|
|
429
|
+
const SKIP_AST_KEYS$6 = /* @__PURE__ */ new Set([
|
|
430
|
+
"loc",
|
|
431
|
+
"range",
|
|
432
|
+
"start",
|
|
433
|
+
"end",
|
|
434
|
+
"parent",
|
|
435
|
+
"leadingComments",
|
|
436
|
+
"trailingComments"
|
|
437
|
+
]);
|
|
438
|
+
const duplicateLocalization = defineRule({
|
|
439
|
+
id: "duplicate-localization",
|
|
440
|
+
displayName: "检查本地化键与默认文案",
|
|
441
|
+
exportName: "duplicateLocalization",
|
|
442
|
+
summary: "检查同一个本地化 key 是否绑定不同默认文案,并拒绝 key 或文案使用模板字符串。相同 key 与相同文案允许重复。",
|
|
443
|
+
optionsSchema: optionsSchema$6,
|
|
444
|
+
examples: [{ options: {
|
|
445
|
+
scanRoot: "src",
|
|
446
|
+
callName: "t"
|
|
447
|
+
} }],
|
|
448
|
+
notes: "变量参数会被跳过。相同 key 与相同默认文案允许重复。",
|
|
449
|
+
async run(common, config) {
|
|
450
|
+
const repoRoot = common.projectRoot;
|
|
451
|
+
const files = await collectSourceFiles$2(path.resolve(repoRoot, config.scanRoot), config.excludeDirs.map((dir) => path.resolve(repoRoot, dir)), config.skipDirNames);
|
|
194
452
|
const keys = /* @__PURE__ */ new Map();
|
|
195
453
|
const conflicts = [];
|
|
196
454
|
const templateLiterals = [];
|
|
@@ -198,9 +456,9 @@ function duplicateLocalization(config) {
|
|
|
198
456
|
const { ast, code } = await parseSourceFile$6(file);
|
|
199
457
|
const lineStarts = collectLineStarts$1(code);
|
|
200
458
|
walk$6(ast.program, (node) => {
|
|
201
|
-
if (!isLocalizeCall$1(node, config.callName
|
|
202
|
-
const keyNode = node.arguments[config.keyArgument
|
|
203
|
-
const valueNode = node.arguments[config.valueArgument
|
|
459
|
+
if (!isLocalizeCall$1(node, config.callName)) return;
|
|
460
|
+
const keyNode = node.arguments[config.keyArgument];
|
|
461
|
+
const valueNode = node.arguments[config.valueArgument];
|
|
204
462
|
const location = locationFor$1(file, node, lineStarts);
|
|
205
463
|
if (isTemplateLiteral(keyNode) || isTemplateLiteral(valueNode)) {
|
|
206
464
|
templateLiterals.push({ location });
|
|
@@ -232,35 +490,27 @@ function duplicateLocalization(config) {
|
|
|
232
490
|
if (templateLiterals.length > 0) {
|
|
233
491
|
success = false;
|
|
234
492
|
lines.push(`Found ${templateLiterals.length} localize() call(s) using template literals:`);
|
|
235
|
-
for (const item of templateLiterals) lines.push(` - ${relativeLocation$1(
|
|
493
|
+
for (const item of templateLiterals) lines.push(` - ${relativeLocation$1(repoRoot, item.location)}`);
|
|
236
494
|
}
|
|
237
495
|
if (conflicts.length > 0) {
|
|
238
496
|
success = false;
|
|
239
497
|
lines.push(`Found ${conflicts.length} duplicate localization key(s) with different values:`);
|
|
240
498
|
for (const conflict of conflicts) {
|
|
241
499
|
lines.push(` - '${conflict.key}'`);
|
|
242
|
-
lines.push(` current: '${conflict.current.value}' at ${relativeLocation$1(
|
|
243
|
-
lines.push(` previously: '${conflict.previous.value}' at ${relativeLocation$1(
|
|
500
|
+
lines.push(` current: '${conflict.current.value}' at ${relativeLocation$1(repoRoot, conflict.current.location)}`);
|
|
501
|
+
lines.push(` previously: '${conflict.previous.value}' at ${relativeLocation$1(repoRoot, conflict.previous.location)}`);
|
|
244
502
|
}
|
|
245
503
|
}
|
|
246
504
|
if (success) lines.push("No duplicate localization keys found.");
|
|
247
505
|
return {
|
|
248
|
-
name:
|
|
506
|
+
name: "duplicate-localization",
|
|
249
507
|
success,
|
|
250
508
|
messages: lines.join("\n"),
|
|
251
509
|
howToFix: success ? "" : "Replace template literals with string literals, and unify duplicate keys to share a single default message."
|
|
252
510
|
};
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
readme: { builtin: rule.id }
|
|
257
|
-
});
|
|
258
|
-
}
|
|
259
|
-
async function collectSourceFiles$2(root, excludeDirs, skipDirNames = [
|
|
260
|
-
"node_modules",
|
|
261
|
-
"dist",
|
|
262
|
-
"coverage"
|
|
263
|
-
]) {
|
|
511
|
+
}
|
|
512
|
+
});
|
|
513
|
+
async function collectSourceFiles$2(root, excludeDirs, skipDirNames) {
|
|
264
514
|
const out = [];
|
|
265
515
|
const resolvedExcludeDirs = excludeDirs.map((item) => path.resolve(item));
|
|
266
516
|
async function visit(dir) {
|
|
@@ -340,7 +590,16 @@ function isTemplateLiteral(node) {
|
|
|
340
590
|
function isExcluded$2(filePath, excludeDirs) {
|
|
341
591
|
return excludeDirs.some((dir) => filePath === dir || filePath.startsWith(dir + path.sep));
|
|
342
592
|
}
|
|
343
|
-
// packages/conformance/rules/
|
|
593
|
+
// packages/conformance/rules/e2e-scenarios-structure.ts
|
|
594
|
+
const optionsSchema$5 = z.object({
|
|
595
|
+
root: z.string().trim().min(1).describe("场景根目录,支持绝对路径或相对 projectRoot 的路径;仅检查此目录直接包含的入口文件。"),
|
|
596
|
+
name: z.string().trim().min(1).optional().describe("结果名与展示名,同一仓库检查多个测试根目录时用于区分,默认 e2e-scenarios-structure。"),
|
|
597
|
+
entrySuffix: z.string().min(1).default(".spec.ts").describe("入口文件后缀。"),
|
|
598
|
+
sharedDir: z.string().trim().min(1).default("shared").describe("多个入口共用 helper 的目录名,相对 root。"),
|
|
599
|
+
utilsDir: z.string().trim().min(1).default("utils").describe("各入口专属 helper 的目录名,相对 root;入口只能导入自身同名子目录。"),
|
|
600
|
+
strictRoot: z.boolean().default(false).describe("是否要求 root 只包含入口文件和配置的两类 helper 目录;隐藏条目始终跳过。"),
|
|
601
|
+
sharedThreshold: z.number().int().min(1).default(3).describe("helper 被多少个入口使用时建议移到共用目录;仅影响违规时的修复建议。")
|
|
602
|
+
});
|
|
344
603
|
const SKIP_AST_KEYS$5 = /* @__PURE__ */ new Set([
|
|
345
604
|
"loc",
|
|
346
605
|
"range",
|
|
@@ -350,173 +609,180 @@ const SKIP_AST_KEYS$5 = /* @__PURE__ */ new Set([
|
|
|
350
609
|
"leadingComments",
|
|
351
610
|
"trailingComments"
|
|
352
611
|
]);
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
612
|
+
const DEFAULT_SKIP_DIR_NAMES$1 = [
|
|
613
|
+
"node_modules",
|
|
614
|
+
"dist",
|
|
615
|
+
"coverage"
|
|
616
|
+
];
|
|
617
|
+
const e2eScenariosStructure = defineRule({
|
|
618
|
+
id: "e2e-scenarios-structure",
|
|
619
|
+
displayName: "检查端到端场景结构",
|
|
620
|
+
exportName: "e2eScenariosStructure",
|
|
621
|
+
summary: "检查 e2e 场景的目录和引用边界。入口只描述测试流程,不定义函数声明或绑定到变量的辅助函数。",
|
|
622
|
+
optionsSchema: optionsSchema$5,
|
|
623
|
+
examples: [{ options: { root: "tests/e2e" } }],
|
|
624
|
+
notes: "直接传给测试调用或截图步骤的内联回调允许保留。入口只允许引用自身同名的 utils 子目录;shared 和 utils 不能互相 import/export,两类 helper 目录名可配置。只检查 root 直接包含的入口文件,递归检查 helper 目录。",
|
|
625
|
+
resolveDisplayName: (options) => options.name ?? "检查端到端场景结构",
|
|
626
|
+
async run(context, options) {
|
|
627
|
+
const ruleName = options.name ?? "e2e-scenarios-structure";
|
|
628
|
+
const repoRoot = context.projectRoot;
|
|
629
|
+
const entrySuffix = options.entrySuffix;
|
|
630
|
+
const strictRoot = options.strictRoot;
|
|
631
|
+
const root = path.resolve(repoRoot, options.root);
|
|
632
|
+
const sharedName = options.sharedDir;
|
|
633
|
+
const utilsName = options.utilsDir;
|
|
634
|
+
const threshold = options.sharedThreshold;
|
|
635
|
+
const sharedRoot = path.join(root, sharedName);
|
|
636
|
+
const utilsRoot = path.join(root, utilsName);
|
|
637
|
+
const utilsPrefix = `./${utilsName}/`;
|
|
638
|
+
const at = (file, line) => formatLocation$3(repoRoot, file, line);
|
|
639
|
+
const violations = [];
|
|
640
|
+
const entries = await readDirIfExists$3(root);
|
|
641
|
+
if (!entries) return {
|
|
642
|
+
name: ruleName,
|
|
643
|
+
success: false,
|
|
644
|
+
messages: `场景根目录不存在:${path.relative(repoRoot, root)}`,
|
|
645
|
+
howToFix: "确认传入的场景根目录路径。"
|
|
362
646
|
};
|
|
363
|
-
const
|
|
364
|
-
const
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
if (
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
const
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
const
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
if (
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
key,
|
|
392
|
-
|
|
647
|
+
const entryFiles = [];
|
|
648
|
+
for (const entry of entries) {
|
|
649
|
+
if (entry.name.startsWith(".")) continue;
|
|
650
|
+
const full = path.join(root, entry.name);
|
|
651
|
+
if (entry.name === sharedName || entry.name === utilsName) {
|
|
652
|
+
if (!entry.isDirectory()) violations.push(` - ${at(full, 1)} ${entry.name} 必须是目录`);
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
if (entry.isFile() && entry.name.endsWith(entrySuffix)) {
|
|
656
|
+
entryFiles.push(full);
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
659
|
+
if (strictRoot) violations.push(` - ${at(full, 1)} 根目录只允许 *${entrySuffix} 入口与 ${sharedName}/${utilsName} 目录`);
|
|
660
|
+
}
|
|
661
|
+
entryFiles.sort((left, right) => left.localeCompare(right));
|
|
662
|
+
const usages = /* @__PURE__ */ new Map();
|
|
663
|
+
const importViolations = [];
|
|
664
|
+
for (const file of entryFiles) {
|
|
665
|
+
const source = await parseSourceFile$5(file);
|
|
666
|
+
const entryName = path.basename(file, entrySuffix);
|
|
667
|
+
walk$5(source.program, (node) => {
|
|
668
|
+
const functionName = readFunctionName$1(node);
|
|
669
|
+
if (functionName) violations.push(` - ${at(file, lineOf$3(source, node))} 入口内定义辅助函数 ${functionName}`);
|
|
670
|
+
});
|
|
671
|
+
const expected = `${utilsPrefix}${entryName}`;
|
|
672
|
+
for (const entry of collectImports$1(source, utilsPrefix)) {
|
|
673
|
+
for (const importedName of entry.importedNames) {
|
|
674
|
+
const key = `${entry.specifier}#${importedName}`;
|
|
675
|
+
usages.set(key, (usages.get(key) ?? /* @__PURE__ */ new Set()).add(file));
|
|
676
|
+
}
|
|
677
|
+
if (entry.specifier === expected || entry.specifier.startsWith(`${expected}/`)) continue;
|
|
678
|
+
importViolations.push({
|
|
679
|
+
file,
|
|
680
|
+
entry,
|
|
681
|
+
expected
|
|
393
682
|
});
|
|
394
683
|
}
|
|
395
|
-
if (untranslated.length > 0) untranslatedByLocale.set(locale, untranslated);
|
|
396
684
|
}
|
|
397
|
-
const
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
lines.push(`Locale files are out of sync with source. Updated ${changedFiles.length} file(s):`);
|
|
404
|
-
for (const file of changedFiles) lines.push(` - ${path.relative(options.repoRoot, file)}`);
|
|
405
|
-
howToFix.push("Locale files have been regenerated - commit them, then run the check again.");
|
|
406
|
-
} else lines.push("Locale files are in sync with source.");
|
|
407
|
-
for (const [locale, entries] of untranslatedByLocale) {
|
|
408
|
-
lines.push(`Found ${entries.length} untranslated key(s) in ${locale}:`);
|
|
409
|
-
for (const entry of entries) lines.push(` - '${entry.key}' (default: '${entry.defaultMessage}')`);
|
|
685
|
+
for (const { file, entry, expected } of importViolations) {
|
|
686
|
+
violations.push(` - ${at(file, entry.line)} 导入 '${entry.specifier}',入口只能导入 ${expected}/... 或 ./${sharedName}/...`);
|
|
687
|
+
for (const importedName of entry.importedNames) {
|
|
688
|
+
const count = usages.get(`${entry.specifier}#${importedName}`)?.size ?? 0;
|
|
689
|
+
violations.push(count >= threshold ? ` ${importedName} 已被 ${count} 个入口使用,建议移到 ${sharedName}。` : ` ${importedName} 被 ${count} 个入口使用,建议在各入口的 ${utilsName} 目录分别实现。`);
|
|
690
|
+
}
|
|
410
691
|
}
|
|
411
|
-
|
|
692
|
+
const helperFiles = [...await collectFiles$3(sharedRoot), ...await collectFiles$3(utilsRoot)];
|
|
693
|
+
for (const file of helperFiles) {
|
|
694
|
+
const fromArea = isInsidePath$3(file, sharedRoot) ? sharedName : utilsName;
|
|
695
|
+
const source = await parseSourceFile$5(file);
|
|
696
|
+
for (const node of source.program.body) {
|
|
697
|
+
const specifier = readModuleSpecifier$1(node);
|
|
698
|
+
if (!specifier?.startsWith(".")) continue;
|
|
699
|
+
const target = path.resolve(path.dirname(file), specifier);
|
|
700
|
+
const toArea = isInsidePath$3(target, sharedRoot) ? sharedName : isInsidePath$3(target, utilsRoot) ? utilsName : void 0;
|
|
701
|
+
if (!toArea || toArea === fromArea) continue;
|
|
702
|
+
violations.push(` - ${at(file, lineOf$3(source, node))} ${fromArea} 不能引用 ${toArea} '${specifier}'`);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
const rules = [
|
|
706
|
+
"入口文件内不定义辅助函数",
|
|
707
|
+
`入口只能导入 ${utilsPrefix}<入口名> 或 ./${sharedName}`,
|
|
708
|
+
`${sharedName} 与 ${utilsName} 互不引用`,
|
|
709
|
+
strictRoot ? `根目录只放入口与 ${sharedName}/${utilsName}` : void 0
|
|
710
|
+
].filter(Boolean);
|
|
711
|
+
const lines = [`扫描 ${path.relative(repoRoot, root)} 下 ${entryFiles.length} 个入口。`, `规则:${rules.join(";")}。`];
|
|
712
|
+
const success = violations.length === 0;
|
|
713
|
+
if (success) lines.push("未发现结构违规。");
|
|
714
|
+
else lines.push(`发现 ${violations.filter((line) => line.startsWith(" - ")).length} 处违规:`, ...violations);
|
|
412
715
|
return {
|
|
413
716
|
name: ruleName,
|
|
414
717
|
success,
|
|
415
718
|
messages: lines.join("\n"),
|
|
416
|
-
howToFix:
|
|
417
|
-
};
|
|
418
|
-
};
|
|
419
|
-
return Object.assign(task, {
|
|
420
|
-
...rule,
|
|
421
|
-
readme: { builtin: rule.id }
|
|
422
|
-
});
|
|
423
|
-
}
|
|
424
|
-
function mergeDefaultLocale(oldConfig, newLocale, metadataKey) {
|
|
425
|
-
const result = {};
|
|
426
|
-
for (const [key, value] of newLocale) {
|
|
427
|
-
const existing = oldConfig[key];
|
|
428
|
-
if (!value && existing) result[key] = existing;
|
|
429
|
-
else result[key] = {
|
|
430
|
-
defaultMessage: value,
|
|
431
|
-
content: value
|
|
719
|
+
howToFix: success ? "" : `helper 移出入口文件:被 ${threshold} 个及以上入口使用的放到 ${sharedName},其余放到 ${utilsName}/<入口名>;${sharedName} 与 ${utilsName} 不要互相引用。`
|
|
432
720
|
};
|
|
433
721
|
}
|
|
434
|
-
|
|
722
|
+
});
|
|
723
|
+
function readFunctionName$1(node) {
|
|
724
|
+
if (node.type === "FunctionDeclaration") return readName$3(node.id) ?? "匿名函数";
|
|
725
|
+
if (node.type === "VariableDeclarator" && isFunctionLike$2(node.init)) return readName$3(node.id) ?? "匿名函数";
|
|
435
726
|
}
|
|
436
|
-
function
|
|
437
|
-
const
|
|
438
|
-
for (const
|
|
439
|
-
if (
|
|
440
|
-
const
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
content: current
|
|
449
|
-
};
|
|
450
|
-
else if (current.defaultMessage !== defaultMessage) result[key] = {
|
|
451
|
-
defaultMessage,
|
|
452
|
-
content: ""
|
|
453
|
-
};
|
|
454
|
-
else result[key] = current;
|
|
455
|
-
}
|
|
456
|
-
return sortObject(result, metadataKey);
|
|
457
|
-
}
|
|
458
|
-
function sortObject(obj, metadataKey) {
|
|
459
|
-
const sorted = metadataKey ? { [metadataKey]: "true" } : {};
|
|
460
|
-
const keys = Object.keys(obj).filter((key) => key !== metadataKey).sort((a, b) => a.localeCompare(b));
|
|
461
|
-
for (const key of keys) sorted[key] = obj[key];
|
|
462
|
-
return sorted;
|
|
463
|
-
}
|
|
464
|
-
async function readLocaleFile(filePath, metadataKey) {
|
|
465
|
-
let content;
|
|
466
|
-
try {
|
|
467
|
-
content = await promises.readFile(filePath, "utf8");
|
|
468
|
-
} catch (error) {
|
|
469
|
-
if (hasCode(error, "ENOENT")) return metadataKey ? { [metadataKey]: "true" } : {};
|
|
470
|
-
throw error;
|
|
471
|
-
}
|
|
472
|
-
const json = JSON.parse(content);
|
|
473
|
-
if (metadataKey && !json[metadataKey]) throw new Error(`${filePath} is missing metadata ${metadataKey}.`);
|
|
474
|
-
return json;
|
|
475
|
-
}
|
|
476
|
-
async function writeIfChanged(filePath, value) {
|
|
477
|
-
const next = `${JSON.stringify(value, null, 2)}\n`;
|
|
478
|
-
let prev = "";
|
|
479
|
-
try {
|
|
480
|
-
prev = await promises.readFile(filePath, "utf8");
|
|
481
|
-
} catch (error) {
|
|
482
|
-
if (!hasCode(error, "ENOENT")) throw error;
|
|
727
|
+
function collectImports$1(source, prefix) {
|
|
728
|
+
const imports = [];
|
|
729
|
+
for (const node of source.program.body) {
|
|
730
|
+
if (node.type !== "ImportDeclaration") continue;
|
|
731
|
+
const specifier = readModuleSpecifier$1(node);
|
|
732
|
+
if (!specifier?.startsWith(prefix)) continue;
|
|
733
|
+
const importedNames = (node.specifiers ?? []).map((item) => item.type === "ImportDefaultSpecifier" ? "default" : item.type === "ImportNamespaceSpecifier" ? "*" : readName$3(item.imported) ?? readName$3(item.local) ?? "anonymous");
|
|
734
|
+
imports.push({
|
|
735
|
+
specifier,
|
|
736
|
+
importedNames,
|
|
737
|
+
line: lineOf$3(source, node)
|
|
738
|
+
});
|
|
483
739
|
}
|
|
484
|
-
|
|
485
|
-
await promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
486
|
-
await promises.writeFile(filePath, next);
|
|
487
|
-
return true;
|
|
740
|
+
return imports;
|
|
488
741
|
}
|
|
489
|
-
async function
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
"coverage"
|
|
493
|
-
]) {
|
|
494
|
-
const out = [];
|
|
495
|
-
const resolvedExcludeDirs = excludeDirs.map((item) => path.resolve(item));
|
|
742
|
+
async function collectFiles$3(root) {
|
|
743
|
+
const files = [];
|
|
744
|
+
const skipDirNames = new Set(DEFAULT_SKIP_DIR_NAMES$1);
|
|
496
745
|
async function visit(dir) {
|
|
497
|
-
const entries = await
|
|
498
|
-
for (const entry of entries) {
|
|
746
|
+
const entries = await readDirIfExists$3(dir);
|
|
747
|
+
for (const entry of entries ?? []) {
|
|
499
748
|
const full = path.join(dir, entry.name);
|
|
500
749
|
if (entry.isDirectory()) {
|
|
501
|
-
if (entry.name.startsWith(".")) continue;
|
|
502
|
-
if (skipDirNames.includes(entry.name)) continue;
|
|
503
|
-
if (isExcluded$1(full, resolvedExcludeDirs)) continue;
|
|
750
|
+
if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
|
|
504
751
|
await visit(full);
|
|
505
752
|
continue;
|
|
506
753
|
}
|
|
507
|
-
if (
|
|
508
|
-
if (!full.endsWith(".ts") && !full.endsWith(".tsx")) continue;
|
|
509
|
-
out.push(full);
|
|
754
|
+
if (entry.isFile() && [".ts", ".tsx"].some((extension) => full.endsWith(extension))) files.push(full);
|
|
510
755
|
}
|
|
511
756
|
}
|
|
512
757
|
await visit(root);
|
|
513
|
-
return
|
|
758
|
+
return files.sort((left, right) => left.localeCompare(right));
|
|
759
|
+
}
|
|
760
|
+
async function readDirIfExists$3(dir) {
|
|
761
|
+
try {
|
|
762
|
+
return await promises.readdir(dir, { withFileTypes: true });
|
|
763
|
+
} catch (error) {
|
|
764
|
+
if (error.code === "ENOENT") return void 0;
|
|
765
|
+
throw error;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
function isInsidePath$3(filePath, dir) {
|
|
769
|
+
const relative = path.relative(dir, filePath);
|
|
770
|
+
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
771
|
+
}
|
|
772
|
+
function formatLocation$3(repoRoot, file, line) {
|
|
773
|
+
return `${path.relative(repoRoot, file)}:${line}`;
|
|
514
774
|
}
|
|
515
775
|
async function parseSourceFile$5(file) {
|
|
516
776
|
const code = await promises.readFile(file, "utf8");
|
|
517
|
-
const
|
|
518
|
-
|
|
519
|
-
|
|
777
|
+
const lineStarts = [0];
|
|
778
|
+
for (let index = 0; index < code.length; index += 1) if (code[index] === "\n") lineStarts.push(index + 1);
|
|
779
|
+
const parsed = parseSync(file, code);
|
|
780
|
+
if (parsed.errors.length) throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
|
|
781
|
+
return {
|
|
782
|
+
file,
|
|
783
|
+
program: parsed.program,
|
|
784
|
+
lineStarts
|
|
785
|
+
};
|
|
520
786
|
}
|
|
521
787
|
function walk$5(node, visit) {
|
|
522
788
|
if (!node || typeof node !== "object") return;
|
|
@@ -529,21 +795,51 @@ function walk$5(node, visit) {
|
|
|
529
795
|
else if (value && typeof value === "object") walk$5(value, visit);
|
|
530
796
|
}
|
|
531
797
|
}
|
|
532
|
-
function
|
|
533
|
-
|
|
798
|
+
function lineOf$3(source, node) {
|
|
799
|
+
if (typeof node.start !== "number") return 0;
|
|
800
|
+
let low = 0;
|
|
801
|
+
let high = source.lineStarts.length - 1;
|
|
802
|
+
while (low <= high) {
|
|
803
|
+
const mid = Math.floor((low + high) / 2);
|
|
804
|
+
if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
|
|
805
|
+
else high = mid - 1;
|
|
806
|
+
}
|
|
807
|
+
return high + 1;
|
|
534
808
|
}
|
|
535
809
|
function readStringLiteral$4(node) {
|
|
536
810
|
if (!node) return void 0;
|
|
537
|
-
if (node.type === "Literal" && typeof node.value === "string") return node.value;
|
|
538
|
-
if (node.type === "StringLiteral" && typeof node.value === "string") return node.value;
|
|
811
|
+
if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") return node.value;
|
|
539
812
|
}
|
|
540
|
-
function
|
|
541
|
-
|
|
813
|
+
function readName$3(node) {
|
|
814
|
+
if (!node) return void 0;
|
|
815
|
+
if (typeof node.name === "string") return node.name;
|
|
816
|
+
if (typeof node.value === "string") return node.value;
|
|
542
817
|
}
|
|
543
|
-
function
|
|
544
|
-
|
|
818
|
+
function isFunctionLike$2(node) {
|
|
819
|
+
if (node && [
|
|
820
|
+
"ParenthesizedExpression",
|
|
821
|
+
"TSAsExpression",
|
|
822
|
+
"TSSatisfiesExpression",
|
|
823
|
+
"TSTypeAssertion",
|
|
824
|
+
"TSNonNullExpression"
|
|
825
|
+
].includes(node.type ?? "")) return isFunctionLike$2(node.expression);
|
|
826
|
+
return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
|
|
545
827
|
}
|
|
546
|
-
|
|
828
|
+
function readModuleSpecifier$1(node) {
|
|
829
|
+
if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") return readStringLiteral$4(node.source);
|
|
830
|
+
}
|
|
831
|
+
// packages/conformance/rules/same-dir-import-only.ts
|
|
832
|
+
const optionsSchema$4 = z.object({
|
|
833
|
+
scanRoot: z.string().trim().min(1).describe("递归扫描的源码目录,支持绝对路径或相对 projectRoot 的路径。"),
|
|
834
|
+
excludeDirs: z.array(z.string()).readonly().default([]).describe("扫描时跳过的子目录及其后代;路径相对 projectRoot 解析,也支持绝对路径。"),
|
|
835
|
+
skipDirNames: z.array(z.string()).readonly().default([
|
|
836
|
+
"node_modules",
|
|
837
|
+
"dist",
|
|
838
|
+
"coverage"
|
|
839
|
+
]).describe("按目录名跳过;传入时替换默认列表,隐藏目录始终跳过。"),
|
|
840
|
+
marker: z.string().trim().min(1).default("@import-scope same-dir").describe("标记内部实现的注释文本,注释去除首尾空白后须与之完全相同。"),
|
|
841
|
+
aliases: z.record(z.string(), z.string()).readonly().default({}).describe("导入前缀到目录的映射;目录相对 projectRoot 解析,也支持绝对路径,例如 `{ \"@/\": \"src\" }`。")
|
|
842
|
+
});
|
|
547
843
|
const SKIP_AST_KEYS$4 = /* @__PURE__ */ new Set([
|
|
548
844
|
"loc",
|
|
549
845
|
"range",
|
|
@@ -559,22 +855,24 @@ const ESM_SOURCE_EXTENSIONS = {
|
|
|
559
855
|
".js": [".ts", ".tsx"],
|
|
560
856
|
".jsx": [".tsx"]
|
|
561
857
|
};
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
const
|
|
858
|
+
const sameDirImportOnly = defineRule({
|
|
859
|
+
id: "same-dir-import-only",
|
|
860
|
+
displayName: "限制跨目录引用",
|
|
861
|
+
exportName: "sameDirImportOnly",
|
|
862
|
+
summary: "为带指定注释的内部文件限制直接引用范围:只有同一目录的文件可以导入或转导出它,外部通过未标记的公开入口访问。",
|
|
863
|
+
optionsSchema: optionsSchema$4,
|
|
864
|
+
examples: [{ options: {
|
|
865
|
+
scanRoot: "src",
|
|
866
|
+
aliases: { "@/": "src" }
|
|
867
|
+
} }],
|
|
868
|
+
notes: "检查 `.ts` / `.tsx` 中的 `import`、`export from` 和字符串形式的动态 `import()`,解析相对路径、已配置前缀及目录 `index`。扫描范围之外的目标和计算路径不检查。",
|
|
869
|
+
async run(common, config) {
|
|
870
|
+
const repoRoot = common.projectRoot;
|
|
871
|
+
const aliases = Object.entries(config.aliases).sort(([a], [b]) => b.length - a.length).map(([prefix, target]) => [prefix, path.resolve(repoRoot, target)]);
|
|
872
|
+
const files = await collectSourceFiles$1(path.resolve(repoRoot, config.scanRoot), config.excludeDirs.map((dir) => path.resolve(repoRoot, dir)), config.skipDirNames);
|
|
575
873
|
const sourceFiles = await Promise.all(files.map(parseSourceFile$4));
|
|
576
874
|
const sourceFileSet = new Set(sourceFiles.map((item) => item.file));
|
|
577
|
-
const protectedFiles = new Set(sourceFiles.filter((file) => hasSameDirMarker(file, marker)).map((sourceFile) => sourceFile.file));
|
|
875
|
+
const protectedFiles = new Set(sourceFiles.filter((file) => hasSameDirMarker(file, config.marker)).map((sourceFile) => sourceFile.file));
|
|
578
876
|
const violations = [];
|
|
579
877
|
for (const sourceFile of sourceFiles) for (const importEntry of collectImportEntries(sourceFile)) {
|
|
580
878
|
const target = resolveImportTarget(importEntry.importer, importEntry.specifier, aliases, sourceFileSet);
|
|
@@ -588,11 +886,11 @@ function sameDirImportOnly(config) {
|
|
|
588
886
|
location: importEntry.location
|
|
589
887
|
});
|
|
590
888
|
}
|
|
591
|
-
const lines = [`Scanned ${files.length} file(s) for files marked with '${marker}'.`, `Protected files: ${protectedFiles.size}`];
|
|
889
|
+
const lines = [`Scanned ${files.length} file(s) for files marked with '${config.marker}'.`, `Protected files: ${protectedFiles.size}`];
|
|
592
890
|
if (violations.length === 0) {
|
|
593
891
|
lines.push("No cross-directory imports of protected files found.");
|
|
594
892
|
return {
|
|
595
|
-
name:
|
|
893
|
+
name: "same-dir-import-only",
|
|
596
894
|
success: true,
|
|
597
895
|
messages: lines.join("\n"),
|
|
598
896
|
howToFix: ""
|
|
@@ -600,26 +898,18 @@ function sameDirImportOnly(config) {
|
|
|
600
898
|
}
|
|
601
899
|
lines.push(`Found ${violations.length} cross-directory import(s) of protected files:`);
|
|
602
900
|
for (const violation of violations) {
|
|
603
|
-
lines.push(` - ${relativeLocation(
|
|
604
|
-
lines.push(` protected file: ${path.relative(
|
|
901
|
+
lines.push(` - ${relativeLocation(repoRoot, violation.location)} imports '${violation.specifier}'`);
|
|
902
|
+
lines.push(` protected file: ${path.relative(repoRoot, violation.target)}`);
|
|
605
903
|
}
|
|
606
904
|
return {
|
|
607
|
-
name:
|
|
905
|
+
name: "same-dir-import-only",
|
|
608
906
|
success: false,
|
|
609
907
|
messages: lines.join("\n"),
|
|
610
|
-
howToFix: `Only import files marked with '${marker}' from files in the same directory, or move shared API into an unmarked file.`
|
|
908
|
+
howToFix: `Only import files marked with '${config.marker}' from files in the same directory, or move shared API into an unmarked file.`
|
|
611
909
|
};
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
readme: { builtin: rule.id }
|
|
616
|
-
});
|
|
617
|
-
}
|
|
618
|
-
async function collectSourceFiles(root, excludeDirs, skipDirNames = [
|
|
619
|
-
"node_modules",
|
|
620
|
-
"dist",
|
|
621
|
-
"coverage"
|
|
622
|
-
]) {
|
|
910
|
+
}
|
|
911
|
+
});
|
|
912
|
+
async function collectSourceFiles$1(root, excludeDirs, skipDirNames) {
|
|
623
913
|
const out = [];
|
|
624
914
|
const resolvedExcludeDirs = excludeDirs.map((item) => path.resolve(item));
|
|
625
915
|
async function visit(dir) {
|
|
@@ -629,7 +919,7 @@ async function collectSourceFiles(root, excludeDirs, skipDirNames = [
|
|
|
629
919
|
if (entry.isDirectory()) {
|
|
630
920
|
if (entry.name.startsWith(".")) continue;
|
|
631
921
|
if (skipDirNames.includes(entry.name)) continue;
|
|
632
|
-
if (isExcluded(full, resolvedExcludeDirs)) continue;
|
|
922
|
+
if (isExcluded$1(full, resolvedExcludeDirs)) continue;
|
|
633
923
|
await visit(full);
|
|
634
924
|
continue;
|
|
635
925
|
}
|
|
@@ -730,10 +1020,20 @@ function relativeLocation(repoRoot, location) {
|
|
|
730
1020
|
const line = location.slice(index + 1);
|
|
731
1021
|
return `${path.relative(repoRoot, file)}:${line}`;
|
|
732
1022
|
}
|
|
733
|
-
function isExcluded(filePath, excludeDirs) {
|
|
1023
|
+
function isExcluded$1(filePath, excludeDirs) {
|
|
734
1024
|
return excludeDirs.some((dir) => filePath === dir || filePath.startsWith(dir + path.sep));
|
|
735
1025
|
}
|
|
736
|
-
// packages/conformance/rules/
|
|
1026
|
+
// packages/conformance/rules/single-component-file.ts
|
|
1027
|
+
const optionsSchema$3 = z.object({
|
|
1028
|
+
scanRoot: z.string().trim().min(1).describe("递归扫描的源码目录,支持绝对路径或相对 projectRoot 的路径。"),
|
|
1029
|
+
excludeDirs: z.array(z.string()).readonly().default([]).describe("扫描时跳过的子目录及其后代;路径相对 projectRoot 解析,也支持绝对路径。"),
|
|
1030
|
+
skipDirNames: z.array(z.string()).readonly().default([
|
|
1031
|
+
"node_modules",
|
|
1032
|
+
"dist",
|
|
1033
|
+
"coverage"
|
|
1034
|
+
]).describe("按目录名跳过;传入时替换默认列表,隐藏目录始终跳过。"),
|
|
1035
|
+
componentWrappers: z.array(z.string().trim().min(1)).readonly().default(["memo", "forwardRef"]).describe("识别组件时使用的高阶函数名;传入时替换默认列表,直接函数和类组件仍会检查。")
|
|
1036
|
+
});
|
|
737
1037
|
const SKIP_AST_KEYS$3 = /* @__PURE__ */ new Set([
|
|
738
1038
|
"loc",
|
|
739
1039
|
"range",
|
|
@@ -743,6 +1043,109 @@ const SKIP_AST_KEYS$3 = /* @__PURE__ */ new Set([
|
|
|
743
1043
|
"leadingComments",
|
|
744
1044
|
"trailingComments"
|
|
745
1045
|
]);
|
|
1046
|
+
const singleComponentFile = defineRule({
|
|
1047
|
+
id: "single-component-file",
|
|
1048
|
+
displayName: "单文件单组件",
|
|
1049
|
+
exportName: "singleComponentFile",
|
|
1050
|
+
summary: "每个 TSX 文件最多定义一个组件,避免同一文件隐藏多个组件或 JSX 渲染函数。",
|
|
1051
|
+
optionsSchema: optionsSchema$3,
|
|
1052
|
+
examples: [{ options: { scanRoot: "src" } }],
|
|
1053
|
+
notes: "函数、类、匿名默认导出及高阶函数内返回 JSX 的函数计为组件,同名定义只计一次。",
|
|
1054
|
+
async run(context, options) {
|
|
1055
|
+
const wrappers = new Set(options.componentWrappers);
|
|
1056
|
+
const files = await collectFiles$2(context.projectRoot, options, [".tsx"]);
|
|
1057
|
+
const findings = [];
|
|
1058
|
+
for (const file of files) {
|
|
1059
|
+
const source = await parseSourceFile$3(file);
|
|
1060
|
+
const components = /* @__PURE__ */ new Map();
|
|
1061
|
+
walk$3(source.program, (node) => {
|
|
1062
|
+
const name = readComponentName(node, wrappers);
|
|
1063
|
+
if (name && !components.has(name)) components.set(name, lineOf$2(source, node));
|
|
1064
|
+
});
|
|
1065
|
+
if (components.size <= 1) continue;
|
|
1066
|
+
findings.push(` - ${path.relative(context.projectRoot, file)}`);
|
|
1067
|
+
for (const [name, line] of components) findings.push(` ${name} 位于 ${formatLocation$2(context.projectRoot, file, line)}`);
|
|
1068
|
+
}
|
|
1069
|
+
const lines = [`扫描 ${files.length} 个 TSX 文件。`];
|
|
1070
|
+
if (findings.length === 0) {
|
|
1071
|
+
lines.push("未发现包含多个组件的 TSX 文件。");
|
|
1072
|
+
return {
|
|
1073
|
+
name: "single-component-file",
|
|
1074
|
+
success: true,
|
|
1075
|
+
messages: lines.join("\n"),
|
|
1076
|
+
howToFix: ""
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
lines.push("以下 TSX 文件包含多个组件:", ...findings);
|
|
1080
|
+
return {
|
|
1081
|
+
name: "single-component-file",
|
|
1082
|
+
success: false,
|
|
1083
|
+
messages: lines.join("\n"),
|
|
1084
|
+
howToFix: "把多出的组件移到各自的 TSX 文件,每个文件只保留一个组件。"
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
});
|
|
1088
|
+
function readComponentName(node, wrappers) {
|
|
1089
|
+
if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
|
|
1090
|
+
const name = readName$2(node.id);
|
|
1091
|
+
return name && containsJsx(node.body) ? name : void 0;
|
|
1092
|
+
}
|
|
1093
|
+
if (node.type === "VariableDeclarator") {
|
|
1094
|
+
const name = readName$2(node.id);
|
|
1095
|
+
return name && isComponentInitializer(node.init, wrappers) ? name : void 0;
|
|
1096
|
+
}
|
|
1097
|
+
if (node.type === "ExportDefaultDeclaration") {
|
|
1098
|
+
const declaration = node.declaration;
|
|
1099
|
+
if (!declaration || readName$2(declaration.id)) return void 0;
|
|
1100
|
+
return (isFunctionLike$1(declaration) || declaration.type === "ClassDeclaration") && containsJsx(declaration) || isComponentInitializer(declaration, wrappers) ? "default export" : void 0;
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
function isComponentInitializer(node, wrappers) {
|
|
1104
|
+
if (!node) return false;
|
|
1105
|
+
if (isFunctionLike$1(node)) return containsJsx(node.body);
|
|
1106
|
+
if (node.type !== "CallExpression" && node.type !== "NewExpression") return false;
|
|
1107
|
+
const callee = node.callee;
|
|
1108
|
+
const calleeName = callee?.type === "Identifier" ? callee.name : readName$2(callee?.property);
|
|
1109
|
+
if (!calleeName || !wrappers.has(calleeName)) return false;
|
|
1110
|
+
return (node.arguments ?? []).some((argument) => isFunctionLike$1(argument) && containsJsx(argument.body));
|
|
1111
|
+
}
|
|
1112
|
+
async function collectFiles$2(repoRoot, options, extensions) {
|
|
1113
|
+
const files = [];
|
|
1114
|
+
const excludeDirs = options.excludeDirs.map((dir) => path.resolve(repoRoot, dir));
|
|
1115
|
+
const skipDirNames = new Set(options.skipDirNames);
|
|
1116
|
+
async function visit(dir) {
|
|
1117
|
+
const entries = await readDirIfExists$2(dir);
|
|
1118
|
+
for (const entry of entries ?? []) {
|
|
1119
|
+
const full = path.join(dir, entry.name);
|
|
1120
|
+
if (entry.isDirectory()) {
|
|
1121
|
+
if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
|
|
1122
|
+
if (excludeDirs.some((excluded) => isInsidePath$2(full, excluded))) continue;
|
|
1123
|
+
await visit(full);
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
if (entry.isFile() && extensions.some((extension) => full.endsWith(extension))) files.push(full);
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
const scanRoot = path.resolve(repoRoot, options.scanRoot);
|
|
1130
|
+
await promises.access(scanRoot);
|
|
1131
|
+
await visit(scanRoot);
|
|
1132
|
+
return files.sort((left, right) => left.localeCompare(right));
|
|
1133
|
+
}
|
|
1134
|
+
async function readDirIfExists$2(dir) {
|
|
1135
|
+
try {
|
|
1136
|
+
return await promises.readdir(dir, { withFileTypes: true });
|
|
1137
|
+
} catch (error) {
|
|
1138
|
+
if (error.code === "ENOENT") return void 0;
|
|
1139
|
+
throw error;
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
function isInsidePath$2(filePath, dir) {
|
|
1143
|
+
const relative = path.relative(dir, filePath);
|
|
1144
|
+
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
1145
|
+
}
|
|
1146
|
+
function formatLocation$2(repoRoot, file, line) {
|
|
1147
|
+
return `${path.relative(repoRoot, file)}:${line}`;
|
|
1148
|
+
}
|
|
746
1149
|
async function parseSourceFile$3(file) {
|
|
747
1150
|
const code = await promises.readFile(file, "utf8");
|
|
748
1151
|
const lineStarts = [0];
|
|
@@ -755,7 +1158,6 @@ async function parseSourceFile$3(file) {
|
|
|
755
1158
|
lineStarts
|
|
756
1159
|
};
|
|
757
1160
|
}
|
|
758
|
-
/** 深度优先遍历所有 AST 节点。 */
|
|
759
1161
|
function walk$3(node, visit) {
|
|
760
1162
|
if (!node || typeof node !== "object") return;
|
|
761
1163
|
const current = node;
|
|
@@ -767,8 +1169,7 @@ function walk$3(node, visit) {
|
|
|
767
1169
|
else if (value && typeof value === "object") walk$3(value, visit);
|
|
768
1170
|
}
|
|
769
1171
|
}
|
|
770
|
-
|
|
771
|
-
function lineOf$3(source, node) {
|
|
1172
|
+
function lineOf$2(source, node) {
|
|
772
1173
|
if (typeof node.start !== "number") return 0;
|
|
773
1174
|
let low = 0;
|
|
774
1175
|
let high = source.lineStarts.length - 1;
|
|
@@ -779,81 +1180,76 @@ function lineOf$3(source, node) {
|
|
|
779
1180
|
}
|
|
780
1181
|
return high + 1;
|
|
781
1182
|
}
|
|
782
|
-
function
|
|
783
|
-
if (!node) return void 0;
|
|
784
|
-
if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") return node.value;
|
|
785
|
-
}
|
|
786
|
-
/** 标识符名或字符串形式的导入导出名。 */
|
|
787
|
-
function readName$3(node) {
|
|
1183
|
+
function readName$2(node) {
|
|
788
1184
|
if (!node) return void 0;
|
|
789
1185
|
if (typeof node.name === "string") return node.name;
|
|
790
1186
|
if (typeof node.value === "string") return node.value;
|
|
791
1187
|
}
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
"node_modules",
|
|
795
|
-
"dist",
|
|
796
|
-
"coverage"
|
|
797
|
-
];
|
|
798
|
-
/**
|
|
799
|
-
* 递归收集指定扩展名的文件,相对路径基于 repoRoot 解析;扫描根目录不存在时报错。
|
|
800
|
-
* 结果按路径排序,保证输出稳定。
|
|
801
|
-
*/
|
|
802
|
-
async function collectFiles$3(repoRoot, options, extensions) {
|
|
803
|
-
const files = [];
|
|
804
|
-
const excludeDirs = (options.excludeDirs ?? []).map((dir) => path.resolve(repoRoot, dir));
|
|
805
|
-
const skipDirNames = new Set(options.skipDirNames ?? DEFAULT_SKIP_DIR_NAMES$3);
|
|
806
|
-
async function visit(dir) {
|
|
807
|
-
const entries = await readDirIfExists$3(dir);
|
|
808
|
-
for (const entry of entries ?? []) {
|
|
809
|
-
const full = path.join(dir, entry.name);
|
|
810
|
-
if (entry.isDirectory()) {
|
|
811
|
-
if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
|
|
812
|
-
if (excludeDirs.some((excluded) => isInsidePath$3(full, excluded))) continue;
|
|
813
|
-
await visit(full);
|
|
814
|
-
continue;
|
|
815
|
-
}
|
|
816
|
-
if (entry.isFile() && extensions.some((extension) => full.endsWith(extension))) files.push(full);
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
await promises.access(path.resolve(repoRoot, options.scanRoot));
|
|
820
|
-
await visit(path.resolve(repoRoot, options.scanRoot));
|
|
821
|
-
return files.sort((left, right) => left.localeCompare(right));
|
|
822
|
-
}
|
|
823
|
-
async function readDirIfExists$3(dir) {
|
|
824
|
-
try {
|
|
825
|
-
return await promises.readdir(dir, { withFileTypes: true });
|
|
826
|
-
} catch (error) {
|
|
827
|
-
if (error.code === "ENOENT") return void 0;
|
|
828
|
-
throw error;
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
function isInsidePath$3(filePath, dir) {
|
|
832
|
-
const relative = path.relative(dir, filePath);
|
|
833
|
-
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
1188
|
+
function isFunctionLike$1(node) {
|
|
1189
|
+
return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
|
|
834
1190
|
}
|
|
835
|
-
function
|
|
836
|
-
|
|
1191
|
+
function containsJsx(node) {
|
|
1192
|
+
let found = false;
|
|
1193
|
+
walk$3(node, (current) => {
|
|
1194
|
+
if (current.type === "JSXElement" || current.type === "JSXFragment") found = true;
|
|
1195
|
+
});
|
|
1196
|
+
return found;
|
|
837
1197
|
}
|
|
838
|
-
// packages/conformance/rules/source-locale-defaults
|
|
1198
|
+
// packages/conformance/rules/source-locale-defaults.ts
|
|
1199
|
+
const localizationCallSchema = z.object({
|
|
1200
|
+
name: z.string().trim().min(1).describe("函数名,例如 localize。"),
|
|
1201
|
+
valueArgument: z.number().int().nonnegative().describe("默认文案所在的参数位置,从 0 开始。"),
|
|
1202
|
+
member: z.boolean().default(false).describe("是否同时匹配成员调用,例如 nls.format();默认只匹配直接调用。")
|
|
1203
|
+
}).meta({ tsType: "LocalizationCall" });
|
|
1204
|
+
const optionsSchema$2 = z.object({
|
|
1205
|
+
scanRoot: z.string().trim().min(1).describe("递归扫描的源码目录,支持绝对路径或相对 projectRoot 的路径。"),
|
|
1206
|
+
excludeDirs: z.array(z.string()).readonly().default([]).describe("扫描时跳过的子目录及其后代;路径相对 projectRoot 解析,也支持绝对路径。"),
|
|
1207
|
+
skipDirNames: z.array(z.string()).readonly().default([
|
|
1208
|
+
"node_modules",
|
|
1209
|
+
"dist",
|
|
1210
|
+
"coverage"
|
|
1211
|
+
]).describe("按目录名跳过;传入时替换默认列表,隐藏目录始终跳过。"),
|
|
1212
|
+
calls: z.array(localizationCallSchema).readonly().describe("需要检查的本地化调用列表;只检查指定参数中的字符串字面量,空数组表示不匹配任何调用。"),
|
|
1213
|
+
pattern: z.instanceof(RegExp).meta({ tsType: "RegExp" }).describe("匹配即判为违规的正则表达式,例如 CJK_PATTERN;每次匹配独立执行,不改变传入正则的状态。")
|
|
1214
|
+
});
|
|
839
1215
|
/** 汉字、CJK 标点和全角字符;可用于检查英文默认文案。 */
|
|
840
1216
|
const CJK_PATTERN = /[\u4e00-\u9fff\u3400-\u4dbf\u3000-\u303f\uff00-\uffef]/;
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
1217
|
+
const SKIP_AST_KEYS$2 = /* @__PURE__ */ new Set([
|
|
1218
|
+
"loc",
|
|
1219
|
+
"range",
|
|
1220
|
+
"start",
|
|
1221
|
+
"end",
|
|
1222
|
+
"parent",
|
|
1223
|
+
"leadingComments",
|
|
1224
|
+
"trailingComments"
|
|
1225
|
+
]);
|
|
1226
|
+
const sourceLocaleDefaults = defineRule({
|
|
1227
|
+
id: "source-locale-defaults",
|
|
1228
|
+
displayName: "检查源语言默认文案",
|
|
1229
|
+
exportName: "sourceLocaleDefaults",
|
|
1230
|
+
summary: "检查本地化默认文案是否包含指定禁止字符,便于要求源码使用源语言、翻译存放在语言文件中。",
|
|
1231
|
+
optionsSchema: optionsSchema$2,
|
|
1232
|
+
examples: [{ options: {
|
|
1233
|
+
scanRoot: "src",
|
|
1234
|
+
calls: [{
|
|
1235
|
+
name: "localize",
|
|
1236
|
+
valueArgument: 1
|
|
1237
|
+
}],
|
|
1238
|
+
pattern: /[\u4e00-\u9fff]/
|
|
1239
|
+
} }],
|
|
1240
|
+
notes: "`CJK_PATTERN` 匹配汉字、CJK 标点及全角字符,不是完整的中日韩文字检测。",
|
|
1241
|
+
async run(context, options) {
|
|
1242
|
+
const files = await collectFiles$1(context.projectRoot, options, [".ts", ".tsx"]);
|
|
847
1243
|
const findings = [];
|
|
848
1244
|
for (const file of files) {
|
|
849
|
-
const source = await parseSourceFile$
|
|
850
|
-
walk$
|
|
1245
|
+
const source = await parseSourceFile$2(file);
|
|
1246
|
+
walk$2(source.program, (node) => {
|
|
851
1247
|
if (node.type !== "CallExpression") return;
|
|
852
1248
|
const call = matchCall(options.calls, node.callee);
|
|
853
1249
|
if (!call) return;
|
|
854
1250
|
const value = readStringLiteral$2(node.arguments?.[call.valueArgument]);
|
|
855
1251
|
if (value === void 0 || !new RegExp(options.pattern.source, options.pattern.flags).test(value)) return;
|
|
856
|
-
findings.push(` - ${call.name}() 文案 '${value}' 位于 ${formatLocation$
|
|
1252
|
+
findings.push(` - ${call.name}() 文案 '${value}' 位于 ${formatLocation$1(context.projectRoot, file, lineOf$1(source, node))}`);
|
|
857
1253
|
});
|
|
858
1254
|
}
|
|
859
1255
|
const names = options.calls.map((call) => `${call.name}()`).join("、");
|
|
@@ -861,7 +1257,7 @@ function sourceLocaleDefaults(options) {
|
|
|
861
1257
|
if (findings.length === 0) {
|
|
862
1258
|
lines.push("未发现违规文案。");
|
|
863
1259
|
return {
|
|
864
|
-
name:
|
|
1260
|
+
name: "source-locale-defaults",
|
|
865
1261
|
success: true,
|
|
866
1262
|
messages: lines.join("\n"),
|
|
867
1263
|
howToFix: ""
|
|
@@ -869,119 +1265,44 @@ function sourceLocaleDefaults(options) {
|
|
|
869
1265
|
}
|
|
870
1266
|
lines.push(`发现 ${findings.length} 处违规文案:`, ...findings);
|
|
871
1267
|
return {
|
|
872
|
-
name:
|
|
1268
|
+
name: "source-locale-defaults",
|
|
873
1269
|
success: false,
|
|
874
1270
|
messages: lines.join("\n"),
|
|
875
1271
|
howToFix: "默认文案改用源语言,其他语言的翻译写入语言文件。"
|
|
876
1272
|
};
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
...rule,
|
|
880
|
-
readme: { builtin: rule.id }
|
|
881
|
-
});
|
|
882
|
-
}
|
|
1273
|
+
}
|
|
1274
|
+
});
|
|
883
1275
|
function matchCall(calls, callee) {
|
|
884
1276
|
if (!callee) return void 0;
|
|
885
1277
|
if (callee.type === "Identifier") return calls.find((call) => call.name === callee.name);
|
|
886
1278
|
if (callee.type === "MemberExpression" || callee.type === "StaticMemberExpression") {
|
|
887
|
-
const name = readName$
|
|
1279
|
+
const name = readName$1(callee.property);
|
|
888
1280
|
return calls.find((call) => call.member && call.name === name);
|
|
889
1281
|
}
|
|
890
1282
|
}
|
|
891
|
-
|
|
892
|
-
const SKIP_AST_KEYS$2 = /* @__PURE__ */ new Set([
|
|
893
|
-
"loc",
|
|
894
|
-
"range",
|
|
895
|
-
"start",
|
|
896
|
-
"end",
|
|
897
|
-
"parent",
|
|
898
|
-
"leadingComments",
|
|
899
|
-
"trailingComments"
|
|
900
|
-
]);
|
|
901
|
-
async function parseSourceFile$2(file) {
|
|
902
|
-
const code = await promises.readFile(file, "utf8");
|
|
903
|
-
const lineStarts = [0];
|
|
904
|
-
for (let index = 0; index < code.length; index += 1) if (code[index] === "\n") lineStarts.push(index + 1);
|
|
905
|
-
const parsed = parseSync(file, code);
|
|
906
|
-
if (parsed.errors.length) throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
|
|
907
|
-
return {
|
|
908
|
-
file,
|
|
909
|
-
program: parsed.program,
|
|
910
|
-
lineStarts
|
|
911
|
-
};
|
|
912
|
-
}
|
|
913
|
-
/** 深度优先遍历所有 AST 节点。 */
|
|
914
|
-
function walk$2(node, visit) {
|
|
915
|
-
if (!node || typeof node !== "object") return;
|
|
916
|
-
const current = node;
|
|
917
|
-
if (typeof current.type === "string") visit(current);
|
|
918
|
-
for (const key of Object.keys(current)) {
|
|
919
|
-
if (SKIP_AST_KEYS$2.has(key)) continue;
|
|
920
|
-
const value = current[key];
|
|
921
|
-
if (Array.isArray(value)) for (const child of value) walk$2(child, visit);
|
|
922
|
-
else if (value && typeof value === "object") walk$2(value, visit);
|
|
923
|
-
}
|
|
924
|
-
}
|
|
925
|
-
/** 节点所在行(从 1 开始)。 */
|
|
926
|
-
function lineOf$2(source, node) {
|
|
927
|
-
if (typeof node.start !== "number") return 0;
|
|
928
|
-
let low = 0;
|
|
929
|
-
let high = source.lineStarts.length - 1;
|
|
930
|
-
while (low <= high) {
|
|
931
|
-
const mid = Math.floor((low + high) / 2);
|
|
932
|
-
if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
|
|
933
|
-
else high = mid - 1;
|
|
934
|
-
}
|
|
935
|
-
return high + 1;
|
|
936
|
-
}
|
|
937
|
-
/** 标识符名或字符串形式的导入导出名。 */
|
|
938
|
-
function readName$2(node) {
|
|
939
|
-
if (!node) return void 0;
|
|
940
|
-
if (typeof node.name === "string") return node.name;
|
|
941
|
-
if (typeof node.value === "string") return node.value;
|
|
942
|
-
}
|
|
943
|
-
function isFunctionLike$2(node) {
|
|
944
|
-
return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
|
|
945
|
-
}
|
|
946
|
-
function containsJsx(node) {
|
|
947
|
-
let found = false;
|
|
948
|
-
walk$2(node, (current) => {
|
|
949
|
-
if (current.type === "JSXElement" || current.type === "JSXFragment") found = true;
|
|
950
|
-
});
|
|
951
|
-
return found;
|
|
952
|
-
}
|
|
953
|
-
// packages/conformance/rules/single-component-file/files.ts
|
|
954
|
-
const DEFAULT_SKIP_DIR_NAMES$2 = [
|
|
955
|
-
"node_modules",
|
|
956
|
-
"dist",
|
|
957
|
-
"coverage"
|
|
958
|
-
];
|
|
959
|
-
/**
|
|
960
|
-
* 递归收集指定扩展名的文件,相对路径基于 repoRoot 解析;扫描根目录不存在时报错。
|
|
961
|
-
* 结果按路径排序,保证输出稳定。
|
|
962
|
-
*/
|
|
963
|
-
async function collectFiles$2(repoRoot, options, extensions) {
|
|
1283
|
+
async function collectFiles$1(repoRoot, options, extensions) {
|
|
964
1284
|
const files = [];
|
|
965
|
-
const excludeDirs =
|
|
966
|
-
const skipDirNames = new Set(options.skipDirNames
|
|
1285
|
+
const excludeDirs = options.excludeDirs.map((dir) => path.resolve(repoRoot, dir));
|
|
1286
|
+
const skipDirNames = new Set(options.skipDirNames);
|
|
967
1287
|
async function visit(dir) {
|
|
968
|
-
const entries = await readDirIfExists$
|
|
1288
|
+
const entries = await readDirIfExists$1(dir);
|
|
969
1289
|
for (const entry of entries ?? []) {
|
|
970
1290
|
const full = path.join(dir, entry.name);
|
|
971
1291
|
if (entry.isDirectory()) {
|
|
972
1292
|
if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
|
|
973
|
-
if (excludeDirs.some((excluded) => isInsidePath$
|
|
1293
|
+
if (excludeDirs.some((excluded) => isInsidePath$1(full, excluded))) continue;
|
|
974
1294
|
await visit(full);
|
|
975
1295
|
continue;
|
|
976
1296
|
}
|
|
977
1297
|
if (entry.isFile() && extensions.some((extension) => full.endsWith(extension))) files.push(full);
|
|
978
1298
|
}
|
|
979
1299
|
}
|
|
980
|
-
|
|
981
|
-
await
|
|
1300
|
+
const scanRoot = path.resolve(repoRoot, options.scanRoot);
|
|
1301
|
+
await promises.access(scanRoot);
|
|
1302
|
+
await visit(scanRoot);
|
|
982
1303
|
return files.sort((left, right) => left.localeCompare(right));
|
|
983
1304
|
}
|
|
984
|
-
async function readDirIfExists$
|
|
1305
|
+
async function readDirIfExists$1(dir) {
|
|
985
1306
|
try {
|
|
986
1307
|
return await promises.readdir(dir, { withFileTypes: true });
|
|
987
1308
|
} catch (error) {
|
|
@@ -989,91 +1310,14 @@ async function readDirIfExists$2(dir) {
|
|
|
989
1310
|
throw error;
|
|
990
1311
|
}
|
|
991
1312
|
}
|
|
992
|
-
function isInsidePath$
|
|
1313
|
+
function isInsidePath$1(filePath, dir) {
|
|
993
1314
|
const relative = path.relative(dir, filePath);
|
|
994
1315
|
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
995
1316
|
}
|
|
996
|
-
function formatLocation$
|
|
1317
|
+
function formatLocation$1(repoRoot, file, line) {
|
|
997
1318
|
return `${path.relative(repoRoot, file)}:${line}`;
|
|
998
1319
|
}
|
|
999
|
-
|
|
1000
|
-
/** 每个 TSX 文件只定义一个返回 JSX 的组件。 */
|
|
1001
|
-
function singleComponentFile(options) {
|
|
1002
|
-
const rule = builtinRules.singleComponentFile;
|
|
1003
|
-
const ruleName = rule.id;
|
|
1004
|
-
const task = async (context) => {
|
|
1005
|
-
const wrappers = new Set(options.componentWrappers ?? ["memo", "forwardRef"]);
|
|
1006
|
-
const files = await collectFiles$2(context.projectRoot, options, [".tsx"]);
|
|
1007
|
-
const findings = [];
|
|
1008
|
-
for (const file of files) {
|
|
1009
|
-
const source = await parseSourceFile$2(file);
|
|
1010
|
-
const components = /* @__PURE__ */ new Map();
|
|
1011
|
-
walk$2(source.program, (node) => {
|
|
1012
|
-
const name = readComponentName(node, wrappers);
|
|
1013
|
-
if (name && !components.has(name)) components.set(name, lineOf$2(source, node));
|
|
1014
|
-
});
|
|
1015
|
-
if (components.size <= 1) continue;
|
|
1016
|
-
findings.push(` - ${path.relative(context.projectRoot, file)}`);
|
|
1017
|
-
for (const [name, line] of components) findings.push(` ${name} 位于 ${formatLocation$2(context.projectRoot, file, line)}`);
|
|
1018
|
-
}
|
|
1019
|
-
const lines = [`扫描 ${files.length} 个 TSX 文件。`];
|
|
1020
|
-
if (findings.length === 0) {
|
|
1021
|
-
lines.push("未发现包含多个组件的 TSX 文件。");
|
|
1022
|
-
return {
|
|
1023
|
-
name: ruleName,
|
|
1024
|
-
success: true,
|
|
1025
|
-
messages: lines.join("\n"),
|
|
1026
|
-
howToFix: ""
|
|
1027
|
-
};
|
|
1028
|
-
}
|
|
1029
|
-
lines.push("以下 TSX 文件包含多个组件:", ...findings);
|
|
1030
|
-
return {
|
|
1031
|
-
name: ruleName,
|
|
1032
|
-
success: false,
|
|
1033
|
-
messages: lines.join("\n"),
|
|
1034
|
-
howToFix: "把多出的组件移到各自的 TSX 文件,每个文件只保留一个组件。"
|
|
1035
|
-
};
|
|
1036
|
-
};
|
|
1037
|
-
return Object.assign(task, {
|
|
1038
|
-
...rule,
|
|
1039
|
-
readme: { builtin: rule.id }
|
|
1040
|
-
});
|
|
1041
|
-
}
|
|
1042
|
-
function readComponentName(node, wrappers) {
|
|
1043
|
-
if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
|
|
1044
|
-
const name = readName$2(node.id);
|
|
1045
|
-
return name && containsJsx(node.body) ? name : void 0;
|
|
1046
|
-
}
|
|
1047
|
-
if (node.type === "VariableDeclarator") {
|
|
1048
|
-
const name = readName$2(node.id);
|
|
1049
|
-
return name && isComponentInitializer(node.init, wrappers) ? name : void 0;
|
|
1050
|
-
}
|
|
1051
|
-
if (node.type === "ExportDefaultDeclaration") {
|
|
1052
|
-
const declaration = node.declaration;
|
|
1053
|
-
if (!declaration || readName$2(declaration.id)) return void 0;
|
|
1054
|
-
return (isFunctionLike$2(declaration) || declaration.type === "ClassDeclaration") && containsJsx(declaration) || isComponentInitializer(declaration, wrappers) ? "default export" : void 0;
|
|
1055
|
-
}
|
|
1056
|
-
}
|
|
1057
|
-
function isComponentInitializer(node, wrappers) {
|
|
1058
|
-
if (!node) return false;
|
|
1059
|
-
if (isFunctionLike$2(node)) return containsJsx(node.body);
|
|
1060
|
-
if (node.type !== "CallExpression" && node.type !== "NewExpression") return false;
|
|
1061
|
-
const callee = node.callee;
|
|
1062
|
-
const calleeName = callee?.type === "Identifier" ? callee.name : readName$2(callee?.property);
|
|
1063
|
-
if (!calleeName || !wrappers.has(calleeName)) return false;
|
|
1064
|
-
return (node.arguments ?? []).some((argument) => isFunctionLike$2(argument) && containsJsx(argument.body));
|
|
1065
|
-
}
|
|
1066
|
-
// packages/conformance/rules/e2e-scenarios-structure/ast.ts
|
|
1067
|
-
const SKIP_AST_KEYS$1 = /* @__PURE__ */ new Set([
|
|
1068
|
-
"loc",
|
|
1069
|
-
"range",
|
|
1070
|
-
"start",
|
|
1071
|
-
"end",
|
|
1072
|
-
"parent",
|
|
1073
|
-
"leadingComments",
|
|
1074
|
-
"trailingComments"
|
|
1075
|
-
]);
|
|
1076
|
-
async function parseSourceFile$1(file) {
|
|
1320
|
+
async function parseSourceFile$2(file) {
|
|
1077
1321
|
const code = await promises.readFile(file, "utf8");
|
|
1078
1322
|
const lineStarts = [0];
|
|
1079
1323
|
for (let index = 0; index < code.length; index += 1) if (code[index] === "\n") lineStarts.push(index + 1);
|
|
@@ -1085,19 +1329,17 @@ async function parseSourceFile$1(file) {
|
|
|
1085
1329
|
lineStarts
|
|
1086
1330
|
};
|
|
1087
1331
|
}
|
|
1088
|
-
|
|
1089
|
-
function walk$1(node, visit) {
|
|
1332
|
+
function walk$2(node, visit) {
|
|
1090
1333
|
if (!node || typeof node !== "object") return;
|
|
1091
1334
|
const current = node;
|
|
1092
1335
|
if (typeof current.type === "string") visit(current);
|
|
1093
1336
|
for (const key of Object.keys(current)) {
|
|
1094
|
-
if (SKIP_AST_KEYS$
|
|
1337
|
+
if (SKIP_AST_KEYS$2.has(key)) continue;
|
|
1095
1338
|
const value = current[key];
|
|
1096
|
-
if (Array.isArray(value)) for (const child of value) walk$
|
|
1097
|
-
else if (value && typeof value === "object") walk$
|
|
1339
|
+
if (Array.isArray(value)) for (const child of value) walk$2(child, visit);
|
|
1340
|
+
else if (value && typeof value === "object") walk$2(value, visit);
|
|
1098
1341
|
}
|
|
1099
1342
|
}
|
|
1100
|
-
/** 节点所在行(从 1 开始)。 */
|
|
1101
1343
|
function lineOf$1(source, node) {
|
|
1102
1344
|
if (typeof node.start !== "number") return 0;
|
|
1103
1345
|
let low = 0;
|
|
@@ -1109,331 +1351,280 @@ function lineOf$1(source, node) {
|
|
|
1109
1351
|
}
|
|
1110
1352
|
return high + 1;
|
|
1111
1353
|
}
|
|
1112
|
-
function readStringLiteral$
|
|
1354
|
+
function readStringLiteral$2(node) {
|
|
1113
1355
|
if (!node) return void 0;
|
|
1114
1356
|
if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") return node.value;
|
|
1115
1357
|
}
|
|
1116
|
-
/** 标识符名或字符串形式的导入导出名。 */
|
|
1117
1358
|
function readName$1(node) {
|
|
1118
1359
|
if (!node) return void 0;
|
|
1119
1360
|
if (typeof node.name === "string") return node.name;
|
|
1120
1361
|
if (typeof node.value === "string") return node.value;
|
|
1121
1362
|
}
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
"
|
|
1128
|
-
"
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
"
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
}
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
}
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
const sharedRoot = path.join(root, sharedName);
|
|
1196
|
-
const utilsRoot = path.join(root, utilsName);
|
|
1197
|
-
const utilsPrefix = `./${utilsName}/`;
|
|
1198
|
-
const at = (file, line) => formatLocation$1(repoRoot, file, line);
|
|
1199
|
-
const violations = [];
|
|
1200
|
-
const entries = await readDirIfExists$1(root);
|
|
1201
|
-
if (!entries) return {
|
|
1202
|
-
name: ruleName,
|
|
1203
|
-
success: false,
|
|
1204
|
-
messages: `场景根目录不存在:${path.relative(repoRoot, root)}`,
|
|
1205
|
-
howToFix: "确认传入的场景根目录路径。"
|
|
1206
|
-
};
|
|
1207
|
-
const entryFiles = [];
|
|
1208
|
-
for (const entry of entries) {
|
|
1209
|
-
if (entry.name.startsWith(".")) continue;
|
|
1210
|
-
const full = path.join(root, entry.name);
|
|
1211
|
-
if (entry.name === sharedName || entry.name === utilsName) {
|
|
1212
|
-
if (!entry.isDirectory()) violations.push(` - ${at(full, 1)} ${entry.name} 必须是目录`);
|
|
1213
|
-
continue;
|
|
1214
|
-
}
|
|
1215
|
-
if (entry.isFile() && entry.name.endsWith(entrySuffix)) {
|
|
1216
|
-
entryFiles.push(full);
|
|
1217
|
-
continue;
|
|
1218
|
-
}
|
|
1219
|
-
if (strictRoot) violations.push(` - ${at(full, 1)} 根目录只允许 *${entrySuffix} 入口与 ${sharedName}/${utilsName} 目录`);
|
|
1220
|
-
}
|
|
1221
|
-
entryFiles.sort((left, right) => left.localeCompare(right));
|
|
1222
|
-
const usages = /* @__PURE__ */ new Map();
|
|
1223
|
-
const importViolations = [];
|
|
1224
|
-
for (const file of entryFiles) {
|
|
1225
|
-
const source = await parseSourceFile$1(file);
|
|
1226
|
-
const entryName = path.basename(file, entrySuffix);
|
|
1227
|
-
walk$1(source.program, (node) => {
|
|
1228
|
-
const functionName = readFunctionName$1(node);
|
|
1229
|
-
if (functionName) violations.push(` - ${at(file, lineOf$1(source, node))} 入口内定义辅助函数 ${functionName}`);
|
|
1230
|
-
});
|
|
1231
|
-
const expected = `${utilsPrefix}${entryName}`;
|
|
1232
|
-
for (const entry of collectImports$1(source, utilsPrefix)) {
|
|
1233
|
-
for (const importedName of entry.importedNames) {
|
|
1234
|
-
const key = `${entry.specifier}#${importedName}`;
|
|
1235
|
-
usages.set(key, (usages.get(key) ?? /* @__PURE__ */ new Set()).add(file));
|
|
1236
|
-
}
|
|
1237
|
-
if (entry.specifier === expected || entry.specifier.startsWith(`${expected}/`)) continue;
|
|
1238
|
-
importViolations.push({
|
|
1239
|
-
file,
|
|
1240
|
-
entry,
|
|
1241
|
-
expected
|
|
1363
|
+
// packages/conformance/rules/sync-locales.ts
|
|
1364
|
+
const optionsSchema$1 = z.object({
|
|
1365
|
+
scanRoot: z.string().trim().min(1).describe("递归扫描的源码目录,支持绝对路径或相对 projectRoot 的路径。"),
|
|
1366
|
+
excludeDirs: z.array(z.string()).readonly().default([]).describe("扫描时跳过的子目录及其后代;路径相对 projectRoot 解析,也支持绝对路径。"),
|
|
1367
|
+
skipDirNames: z.array(z.string()).readonly().default([
|
|
1368
|
+
"node_modules",
|
|
1369
|
+
"dist",
|
|
1370
|
+
"coverage"
|
|
1371
|
+
]).describe("按目录名跳过;传入时替换默认列表,隐藏目录始终跳过。"),
|
|
1372
|
+
callName: z.string().trim().min(1).default("localize").describe("本地化函数名;仅匹配直接调用,不匹配对象成员调用。"),
|
|
1373
|
+
keyArgument: z.number().int().nonnegative().default(0).describe("key 所在的参数下标,从 0 开始;非字符串字面量会被跳过。"),
|
|
1374
|
+
valueArgument: z.number().int().nonnegative().default(1).describe("默认文案所在的参数下标,从 0 开始。"),
|
|
1375
|
+
localesDir: z.string().trim().min(1).describe("语言文件目录,支持绝对路径或相对 projectRoot 的路径;缺失时自动创建。"),
|
|
1376
|
+
defaultLocale: z.string().trim().min(1).describe("源语言标识,例如 en-US,对应 localesDir 下的 en-US.json。"),
|
|
1377
|
+
otherLocales: z.array(z.string().trim().min(1)).readonly().describe("需要同步并检查翻译的其他语言标识;不包含 defaultLocale,空数组表示仅同步源语言。"),
|
|
1378
|
+
metadataKey: z.string().trim().min(1).optional().describe("生成器元数据键,默认不写入;兼容 i18n-ease 时设为 __i18n_ease__,已有文件必须包含此键。")
|
|
1379
|
+
});
|
|
1380
|
+
const SKIP_AST_KEYS$1 = /* @__PURE__ */ new Set([
|
|
1381
|
+
"loc",
|
|
1382
|
+
"range",
|
|
1383
|
+
"start",
|
|
1384
|
+
"end",
|
|
1385
|
+
"parent",
|
|
1386
|
+
"leadingComments",
|
|
1387
|
+
"trailingComments"
|
|
1388
|
+
]);
|
|
1389
|
+
const syncLocales = defineRule({
|
|
1390
|
+
id: "sync-locales",
|
|
1391
|
+
displayName: "同步本地化文件",
|
|
1392
|
+
exportName: "syncLocales",
|
|
1393
|
+
summary: "从源码本地化调用同步 JSON 语言文件并检查未翻译条目。此规约会写文件,发生更新时本次检查失败,提醒审查并提交变化。",
|
|
1394
|
+
optionsSchema: optionsSchema$1,
|
|
1395
|
+
examples: [{ options: {
|
|
1396
|
+
scanRoot: "src",
|
|
1397
|
+
localesDir: "locales",
|
|
1398
|
+
defaultLocale: "en",
|
|
1399
|
+
otherLocales: ["zh"]
|
|
1400
|
+
} }],
|
|
1401
|
+
notes: "会写入 `localesDir` 中配置的语言文件,后续任务可读取这些变化。语言文件为 key 到字符串或 `{ defaultMessage, content }` 的映射;同步后统一生成对象形式,移除不再使用的 key,源文案改变时清空对应译文。",
|
|
1402
|
+
async run(common, config) {
|
|
1403
|
+
const repoRoot = common.projectRoot;
|
|
1404
|
+
const scanRoot = path.resolve(repoRoot, config.scanRoot);
|
|
1405
|
+
const excludeDirs = config.excludeDirs.map((dir) => path.resolve(repoRoot, dir));
|
|
1406
|
+
const localesDir = path.resolve(repoRoot, config.localesDir);
|
|
1407
|
+
const files = await collectSourceFiles(scanRoot, excludeDirs, config.skipDirNames);
|
|
1408
|
+
const sourceLocale = /* @__PURE__ */ new Map();
|
|
1409
|
+
for (const file of files) walk$1((await parseSourceFile$1(file)).program, (node) => {
|
|
1410
|
+
if (!isLocalizeCall(node, config.callName)) return;
|
|
1411
|
+
const key = readStringLiteral$1(node.arguments[config.keyArgument]);
|
|
1412
|
+
if (key === void 0) return;
|
|
1413
|
+
const value = readStringLiteral$1(node.arguments[config.valueArgument]);
|
|
1414
|
+
const existing = sourceLocale.get(key);
|
|
1415
|
+
if (existing === void 0 || !existing && value) sourceLocale.set(key, value ?? "");
|
|
1416
|
+
});
|
|
1417
|
+
const defaultPath = path.join(localesDir, `${config.defaultLocale}.json`);
|
|
1418
|
+
const defaultMerged = mergeDefaultLocale(await readLocaleFile(defaultPath, config.metadataKey), sourceLocale, config.metadataKey);
|
|
1419
|
+
const changedFiles = [];
|
|
1420
|
+
if (await writeIfChanged(defaultPath, defaultMerged)) changedFiles.push(defaultPath);
|
|
1421
|
+
const untranslatedByLocale = /* @__PURE__ */ new Map();
|
|
1422
|
+
for (const locale of config.otherLocales) {
|
|
1423
|
+
const localePath = path.join(localesDir, `${locale}.json`);
|
|
1424
|
+
const merged = mergeOtherLocale(await readLocaleFile(localePath, config.metadataKey), defaultMerged, config.metadataKey);
|
|
1425
|
+
if (await writeIfChanged(localePath, merged)) changedFiles.push(localePath);
|
|
1426
|
+
const untranslated = [];
|
|
1427
|
+
for (const [key, value] of Object.entries(merged)) {
|
|
1428
|
+
if (key === config.metadataKey) continue;
|
|
1429
|
+
if (typeof value === "object" && !value.content) untranslated.push({
|
|
1430
|
+
key,
|
|
1431
|
+
defaultMessage: value.defaultMessage
|
|
1432
|
+
});
|
|
1433
|
+
else if (typeof value === "string" && !value) untranslated.push({
|
|
1434
|
+
key,
|
|
1435
|
+
defaultMessage: ""
|
|
1242
1436
|
});
|
|
1243
1437
|
}
|
|
1438
|
+
if (untranslated.length > 0) untranslatedByLocale.set(locale, untranslated);
|
|
1244
1439
|
}
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
if (!specifier?.startsWith(".")) continue;
|
|
1259
|
-
const target = path.resolve(path.dirname(file), specifier);
|
|
1260
|
-
const toArea = isInsidePath$1(target, sharedRoot) ? sharedName : isInsidePath$1(target, utilsRoot) ? utilsName : void 0;
|
|
1261
|
-
if (!toArea || toArea === fromArea) continue;
|
|
1262
|
-
violations.push(` - ${at(file, lineOf$1(source, node))} ${fromArea} 不能引用 ${toArea} '${specifier}'`);
|
|
1263
|
-
}
|
|
1440
|
+
const lines = [`Localization sync: scanned ${files.length} file(s), ${sourceLocale.size} key(s) in source.`];
|
|
1441
|
+
const hasOutOfSyncFiles = changedFiles.length > 0;
|
|
1442
|
+
const hasUntranslatedKeys = untranslatedByLocale.size > 0;
|
|
1443
|
+
const howToFix = [];
|
|
1444
|
+
const success = !hasOutOfSyncFiles && !hasUntranslatedKeys;
|
|
1445
|
+
if (hasOutOfSyncFiles) {
|
|
1446
|
+
lines.push(`Locale files are out of sync with source. Updated ${changedFiles.length} file(s):`);
|
|
1447
|
+
for (const file of changedFiles) lines.push(` - ${path.relative(repoRoot, file)}`);
|
|
1448
|
+
howToFix.push("Locale files have been regenerated - commit them, then run the check again.");
|
|
1449
|
+
} else lines.push("Locale files are in sync with source.");
|
|
1450
|
+
for (const [locale, entries] of untranslatedByLocale) {
|
|
1451
|
+
lines.push(`Found ${entries.length} untranslated key(s) in ${locale}:`);
|
|
1452
|
+
for (const entry of entries) lines.push(` - '${entry.key}' (default: '${entry.defaultMessage}')`);
|
|
1264
1453
|
}
|
|
1265
|
-
|
|
1266
|
-
"入口文件内不定义辅助函数",
|
|
1267
|
-
`入口只能导入 ${utilsPrefix}<入口名> 或 ./${sharedName}`,
|
|
1268
|
-
`${sharedName} 与 ${utilsName} 互不引用`,
|
|
1269
|
-
strictRoot ? `根目录只放入口与 ${sharedName}/${utilsName}` : void 0
|
|
1270
|
-
].filter(Boolean);
|
|
1271
|
-
const lines = [`扫描 ${path.relative(repoRoot, root)} 下 ${entryFiles.length} 个入口。`, `规则:${rules.join(";")}。`];
|
|
1272
|
-
const success = violations.length === 0;
|
|
1273
|
-
if (success) lines.push("未发现结构违规。");
|
|
1274
|
-
else lines.push(`发现 ${violations.filter((line) => line.startsWith(" - ")).length} 处违规:`, ...violations);
|
|
1454
|
+
if (hasUntranslatedKeys) howToFix.push("Translate the listed key(s) in non-default locale files, then run the check again.");
|
|
1275
1455
|
return {
|
|
1276
|
-
name:
|
|
1456
|
+
name: "sync-locales",
|
|
1277
1457
|
success,
|
|
1278
1458
|
messages: lines.join("\n"),
|
|
1279
|
-
howToFix:
|
|
1459
|
+
howToFix: howToFix.join(" ")
|
|
1280
1460
|
};
|
|
1281
|
-
}
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1461
|
+
}
|
|
1462
|
+
});
|
|
1463
|
+
function mergeDefaultLocale(oldConfig, newLocale, metadataKey) {
|
|
1464
|
+
const result = {};
|
|
1465
|
+
for (const [key, value] of newLocale) {
|
|
1466
|
+
const existing = oldConfig[key];
|
|
1467
|
+
if (!value && existing) result[key] = existing;
|
|
1468
|
+
else result[key] = {
|
|
1469
|
+
defaultMessage: value,
|
|
1470
|
+
content: value
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
return sortObject(result, metadataKey);
|
|
1474
|
+
}
|
|
1475
|
+
function mergeOtherLocale(oldConfig, defaultConfig, metadataKey) {
|
|
1476
|
+
const result = {};
|
|
1477
|
+
for (const [key, defaultValue] of Object.entries(defaultConfig)) {
|
|
1478
|
+
if (key === metadataKey) continue;
|
|
1479
|
+
const defaultMessage = typeof defaultValue === "string" ? defaultValue : defaultValue.defaultMessage;
|
|
1480
|
+
const current = oldConfig[key];
|
|
1481
|
+
if (!current) result[key] = {
|
|
1482
|
+
defaultMessage,
|
|
1483
|
+
content: ""
|
|
1484
|
+
};
|
|
1485
|
+
else if (typeof current === "string") result[key] = {
|
|
1486
|
+
defaultMessage,
|
|
1487
|
+
content: current
|
|
1488
|
+
};
|
|
1489
|
+
else if (current.defaultMessage !== defaultMessage) result[key] = {
|
|
1490
|
+
defaultMessage,
|
|
1491
|
+
content: ""
|
|
1492
|
+
};
|
|
1493
|
+
else result[key] = current;
|
|
1494
|
+
}
|
|
1495
|
+
return sortObject(result, metadataKey);
|
|
1496
|
+
}
|
|
1497
|
+
function sortObject(obj, metadataKey) {
|
|
1498
|
+
const sorted = metadataKey ? { [metadataKey]: "true" } : {};
|
|
1499
|
+
const keys = Object.keys(obj).filter((key) => key !== metadataKey).sort((a, b) => a.localeCompare(b));
|
|
1500
|
+
for (const key of keys) sorted[key] = obj[key];
|
|
1501
|
+
return sorted;
|
|
1502
|
+
}
|
|
1503
|
+
async function readLocaleFile(filePath, metadataKey) {
|
|
1504
|
+
let content;
|
|
1505
|
+
try {
|
|
1506
|
+
content = await promises.readFile(filePath, "utf8");
|
|
1507
|
+
} catch (error) {
|
|
1508
|
+
if (hasCode(error, "ENOENT")) return metadataKey ? { [metadataKey]: "true" } : {};
|
|
1509
|
+
throw error;
|
|
1510
|
+
}
|
|
1511
|
+
const json = JSON.parse(content);
|
|
1512
|
+
if (metadataKey && !json[metadataKey]) throw new Error(`${filePath} is missing metadata ${metadataKey}.`);
|
|
1513
|
+
return json;
|
|
1287
1514
|
}
|
|
1288
|
-
function
|
|
1289
|
-
|
|
1290
|
-
|
|
1515
|
+
async function writeIfChanged(filePath, value) {
|
|
1516
|
+
const next = `${JSON.stringify(value, null, 2)}\n`;
|
|
1517
|
+
let prev = "";
|
|
1518
|
+
try {
|
|
1519
|
+
prev = await promises.readFile(filePath, "utf8");
|
|
1520
|
+
} catch (error) {
|
|
1521
|
+
if (!hasCode(error, "ENOENT")) throw error;
|
|
1522
|
+
}
|
|
1523
|
+
if (prev === next) return false;
|
|
1524
|
+
await promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
1525
|
+
await promises.writeFile(filePath, next);
|
|
1526
|
+
return true;
|
|
1291
1527
|
}
|
|
1292
|
-
function
|
|
1293
|
-
const
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
const
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1528
|
+
async function collectSourceFiles(root, excludeDirs, skipDirNames) {
|
|
1529
|
+
const out = [];
|
|
1530
|
+
const resolvedExcludeDirs = excludeDirs.map((item) => path.resolve(item));
|
|
1531
|
+
async function visit(dir) {
|
|
1532
|
+
const entries = await promises.readdir(dir, { withFileTypes: true });
|
|
1533
|
+
for (const entry of entries) {
|
|
1534
|
+
const full = path.join(dir, entry.name);
|
|
1535
|
+
if (entry.isDirectory()) {
|
|
1536
|
+
if (entry.name.startsWith(".")) continue;
|
|
1537
|
+
if (skipDirNames.includes(entry.name)) continue;
|
|
1538
|
+
if (isExcluded(full, resolvedExcludeDirs)) continue;
|
|
1539
|
+
await visit(full);
|
|
1540
|
+
continue;
|
|
1541
|
+
}
|
|
1542
|
+
if (!entry.isFile()) continue;
|
|
1543
|
+
if (!full.endsWith(".ts") && !full.endsWith(".tsx")) continue;
|
|
1544
|
+
out.push(full);
|
|
1545
|
+
}
|
|
1304
1546
|
}
|
|
1305
|
-
|
|
1547
|
+
await visit(root);
|
|
1548
|
+
return out.sort();
|
|
1306
1549
|
}
|
|
1307
|
-
|
|
1308
|
-
const SKIP_AST_KEYS = /* @__PURE__ */ new Set([
|
|
1309
|
-
"loc",
|
|
1310
|
-
"range",
|
|
1311
|
-
"start",
|
|
1312
|
-
"end",
|
|
1313
|
-
"parent",
|
|
1314
|
-
"leadingComments",
|
|
1315
|
-
"trailingComments"
|
|
1316
|
-
]);
|
|
1317
|
-
async function parseSourceFile(file) {
|
|
1550
|
+
async function parseSourceFile$1(file) {
|
|
1318
1551
|
const code = await promises.readFile(file, "utf8");
|
|
1319
|
-
const
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
if (parsed.errors.length) throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
|
|
1323
|
-
return {
|
|
1324
|
-
file,
|
|
1325
|
-
program: parsed.program,
|
|
1326
|
-
lineStarts
|
|
1327
|
-
};
|
|
1552
|
+
const ast = parseSync(file, code);
|
|
1553
|
+
if (ast.errors.length) throw new Error(`${file}: ${ast.errors.map((error) => error.message).join("; ")}`);
|
|
1554
|
+
return ast;
|
|
1328
1555
|
}
|
|
1329
|
-
|
|
1330
|
-
function walk(node, visit) {
|
|
1556
|
+
function walk$1(node, visit) {
|
|
1331
1557
|
if (!node || typeof node !== "object") return;
|
|
1332
1558
|
const current = node;
|
|
1333
1559
|
if (typeof current.type === "string") visit(current);
|
|
1334
1560
|
for (const key of Object.keys(current)) {
|
|
1335
|
-
if (SKIP_AST_KEYS.has(key)) continue;
|
|
1561
|
+
if (SKIP_AST_KEYS$1.has(key)) continue;
|
|
1336
1562
|
const value = current[key];
|
|
1337
|
-
if (Array.isArray(value)) for (const child of value) walk(child, visit);
|
|
1338
|
-
else if (value && typeof value === "object") walk(value, visit);
|
|
1339
|
-
}
|
|
1340
|
-
}
|
|
1341
|
-
/** 节点所在行(从 1 开始)。 */
|
|
1342
|
-
function lineOf(source, node) {
|
|
1343
|
-
if (typeof node.start !== "number") return 0;
|
|
1344
|
-
let low = 0;
|
|
1345
|
-
let high = source.lineStarts.length - 1;
|
|
1346
|
-
while (low <= high) {
|
|
1347
|
-
const mid = Math.floor((low + high) / 2);
|
|
1348
|
-
if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
|
|
1349
|
-
else high = mid - 1;
|
|
1563
|
+
if (Array.isArray(value)) for (const child of value) walk$1(child, visit);
|
|
1564
|
+
else if (value && typeof value === "object") walk$1(value, visit);
|
|
1350
1565
|
}
|
|
1351
|
-
return high + 1;
|
|
1352
1566
|
}
|
|
1353
|
-
function
|
|
1354
|
-
|
|
1355
|
-
if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") return node.value;
|
|
1567
|
+
function isLocalizeCall(node, name) {
|
|
1568
|
+
return node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === name;
|
|
1356
1569
|
}
|
|
1357
|
-
|
|
1358
|
-
function readName(node) {
|
|
1570
|
+
function readStringLiteral$1(node) {
|
|
1359
1571
|
if (!node) return void 0;
|
|
1360
|
-
if (typeof node.
|
|
1361
|
-
if (typeof node.value === "string") return node.value;
|
|
1572
|
+
if (node.type === "Literal" && typeof node.value === "string") return node.value;
|
|
1573
|
+
if (node.type === "StringLiteral" && typeof node.value === "string") return node.value;
|
|
1362
1574
|
}
|
|
1363
|
-
function
|
|
1364
|
-
|
|
1365
|
-
"ParenthesizedExpression",
|
|
1366
|
-
"TSAsExpression",
|
|
1367
|
-
"TSSatisfiesExpression",
|
|
1368
|
-
"TSTypeAssertion",
|
|
1369
|
-
"TSNonNullExpression"
|
|
1370
|
-
].includes(node.type ?? "")) return isFunctionLike(node.expression);
|
|
1371
|
-
return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
|
|
1575
|
+
function isExcluded(filePath, excludeDirs) {
|
|
1576
|
+
return excludeDirs.some((dir) => filePath === dir || filePath.startsWith(dir + path.sep));
|
|
1372
1577
|
}
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") return readStringLiteral(node.source);
|
|
1578
|
+
function hasCode(error, code) {
|
|
1579
|
+
return Boolean(error && typeof error === "object" && "code" in error && error.code === code);
|
|
1376
1580
|
}
|
|
1377
|
-
// packages/conformance/rules/ui-scenarios-structure
|
|
1581
|
+
// packages/conformance/rules/ui-scenarios-structure.ts
|
|
1582
|
+
const optionsSchema = z.object({
|
|
1583
|
+
root: z.string().trim().min(1).describe("场景根目录,支持绝对路径或相对 projectRoot 的路径;仅检查此目录直接包含的入口文件。"),
|
|
1584
|
+
name: z.string().trim().min(1).optional().describe("结果名与展示名,同一仓库检查多个测试根目录时用于区分,默认 ui-scenarios-structure。"),
|
|
1585
|
+
entrySuffix: z.string().min(1).default(".ts").describe("入口文件后缀。"),
|
|
1586
|
+
sharedDir: z.string().trim().min(1).default("shared").describe("多个入口共用 helper 的目录名,相对 root。"),
|
|
1587
|
+
utilsDir: z.string().trim().min(1).default("utils").describe("各入口专属 helper 的目录名,相对 root;入口只能导入自身同名子目录。"),
|
|
1588
|
+
exportName: z.string().trim().min(1).default("lint").describe("每个入口必须提供的具名导出;可导出函数或数据,只有该导出对应的顶层函数允许在入口中定义。"),
|
|
1589
|
+
strictRoot: z.boolean().default(true).describe("是否要求 root 只包含入口文件和配置的两类 helper 目录;隐藏条目始终跳过。"),
|
|
1590
|
+
sharedThreshold: z.number().int().min(1).default(3).describe("helper 被多少个入口使用时建议移到共用目录;仅影响违规时的修复建议。")
|
|
1591
|
+
});
|
|
1592
|
+
const SKIP_AST_KEYS = /* @__PURE__ */ new Set([
|
|
1593
|
+
"loc",
|
|
1594
|
+
"range",
|
|
1595
|
+
"start",
|
|
1596
|
+
"end",
|
|
1597
|
+
"parent",
|
|
1598
|
+
"leadingComments",
|
|
1599
|
+
"trailingComments"
|
|
1600
|
+
]);
|
|
1378
1601
|
const DEFAULT_SKIP_DIR_NAMES = [
|
|
1379
1602
|
"node_modules",
|
|
1380
1603
|
"dist",
|
|
1381
1604
|
"coverage"
|
|
1382
1605
|
];
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
continue;
|
|
1398
|
-
}
|
|
1399
|
-
if (entry.isFile() && [".ts", ".tsx"].some((extension) => full.endsWith(extension))) files.push(full);
|
|
1400
|
-
}
|
|
1401
|
-
}
|
|
1402
|
-
await visit(root);
|
|
1403
|
-
return files.sort((left, right) => left.localeCompare(right));
|
|
1404
|
-
}
|
|
1405
|
-
async function readDirIfExists(dir) {
|
|
1406
|
-
try {
|
|
1407
|
-
return await promises.readdir(dir, { withFileTypes: true });
|
|
1408
|
-
} catch (error) {
|
|
1409
|
-
if (error.code === "ENOENT") return void 0;
|
|
1410
|
-
throw error;
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
function isInsidePath(filePath, dir) {
|
|
1414
|
-
const relative = path.relative(dir, filePath);
|
|
1415
|
-
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
1416
|
-
}
|
|
1417
|
-
function formatLocation(repoRoot, file, line) {
|
|
1418
|
-
return `${path.relative(repoRoot, file)}:${line}`;
|
|
1419
|
-
}
|
|
1420
|
-
// packages/conformance/rules/ui-scenarios-structure/index.ts
|
|
1421
|
-
/**
|
|
1422
|
-
* 场景目录结构:入口文件只组织用例,helper 放在 utils/<入口名>(专属)或 shared(共用),
|
|
1423
|
-
* 且 shared 与 utils 互不引用。
|
|
1424
|
-
*/
|
|
1425
|
-
function uiScenariosStructure(options) {
|
|
1426
|
-
const rule = builtinRules.uiScenariosStructure;
|
|
1427
|
-
const ruleName = options.name ?? rule.id;
|
|
1428
|
-
const task = async (context) => {
|
|
1606
|
+
const uiScenariosStructure = defineRule({
|
|
1607
|
+
id: "ui-scenarios-structure",
|
|
1608
|
+
displayName: "检查界面场景结构",
|
|
1609
|
+
exportName: "uiScenariosStructure",
|
|
1610
|
+
summary: "检查截图场景的目录和引用边界,并要求每个入口提供指定的具名导出。允许该导出对应的顶层函数,禁止其他函数声明或绑定到变量的辅助函数。",
|
|
1611
|
+
optionsSchema,
|
|
1612
|
+
examples: [{ options: {
|
|
1613
|
+
root: "tests/screenshots",
|
|
1614
|
+
exportName: "scenarios"
|
|
1615
|
+
} }],
|
|
1616
|
+
notes: "`exportName` 默认 `lint`。例如 `export function scenarios() {}`、`export const scenarios = () => []`、`const build = () => []; export { build as scenarios }` 都可以作为入口,也可以导出数据对象或数组。仅豁免对应的顶层函数,入口内部定义的具名 helper 仍会报错;类型导出不算运行时入口。\n\n直接传给测试调用或截图步骤的内联回调允许保留。入口只允许引用自身同名的 utils 子目录;shared 和 utils 不能互相 import/export,两类 helper 目录名可配置。只检查 root 直接包含的入口文件,递归检查 helper 目录。",
|
|
1617
|
+
resolveDisplayName: (options) => options.name ?? "检查界面场景结构",
|
|
1618
|
+
async run(context, options) {
|
|
1619
|
+
const ruleName = options.name ?? "ui-scenarios-structure";
|
|
1429
1620
|
const repoRoot = context.projectRoot;
|
|
1430
|
-
const entrySuffix = options.entrySuffix
|
|
1431
|
-
const strictRoot = options.strictRoot
|
|
1432
|
-
const exportName = options.exportName
|
|
1621
|
+
const entrySuffix = options.entrySuffix;
|
|
1622
|
+
const strictRoot = options.strictRoot;
|
|
1623
|
+
const exportName = options.exportName;
|
|
1433
1624
|
const root = path.resolve(repoRoot, options.root);
|
|
1434
|
-
const sharedName = options.sharedDir
|
|
1435
|
-
const utilsName = options.utilsDir
|
|
1436
|
-
const threshold = options.sharedThreshold
|
|
1625
|
+
const sharedName = options.sharedDir;
|
|
1626
|
+
const utilsName = options.utilsDir;
|
|
1627
|
+
const threshold = options.sharedThreshold;
|
|
1437
1628
|
const sharedRoot = path.join(root, sharedName);
|
|
1438
1629
|
const utilsRoot = path.join(root, utilsName);
|
|
1439
1630
|
const utilsPrefix = `./${utilsName}/`;
|
|
@@ -1522,13 +1713,8 @@ function uiScenariosStructure(options) {
|
|
|
1522
1713
|
messages: lines.join("\n"),
|
|
1523
1714
|
howToFix: success ? "" : `helper 移出入口文件:被 ${threshold} 个及以上入口使用的放到 ${sharedName},其余放到 ${utilsName}/<入口名>;${sharedName} 与 ${utilsName} 不要互相引用。`
|
|
1524
1715
|
};
|
|
1525
|
-
}
|
|
1526
|
-
|
|
1527
|
-
...rule,
|
|
1528
|
-
displayName: options.name ?? rule.displayName,
|
|
1529
|
-
readme: { builtin: rule.id }
|
|
1530
|
-
});
|
|
1531
|
-
}
|
|
1716
|
+
}
|
|
1717
|
+
});
|
|
1532
1718
|
function readFunctionName(node) {
|
|
1533
1719
|
if (node.type === "FunctionDeclaration") return readName(node.id) ?? "匿名函数";
|
|
1534
1720
|
if (node.type === "VariableDeclarator" && isFunctionLike(node.init)) return readName(node.id) ?? "匿名函数";
|
|
@@ -1593,4 +1779,107 @@ function collectImports(source, prefix) {
|
|
|
1593
1779
|
}
|
|
1594
1780
|
return imports;
|
|
1595
1781
|
}
|
|
1596
|
-
|
|
1782
|
+
async function collectFiles(root) {
|
|
1783
|
+
const files = [];
|
|
1784
|
+
const skipDirNames = new Set(DEFAULT_SKIP_DIR_NAMES);
|
|
1785
|
+
async function visit(dir) {
|
|
1786
|
+
const entries = await readDirIfExists(dir);
|
|
1787
|
+
for (const entry of entries ?? []) {
|
|
1788
|
+
const full = path.join(dir, entry.name);
|
|
1789
|
+
if (entry.isDirectory()) {
|
|
1790
|
+
if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
|
|
1791
|
+
await visit(full);
|
|
1792
|
+
continue;
|
|
1793
|
+
}
|
|
1794
|
+
if (entry.isFile() && [".ts", ".tsx"].some((extension) => full.endsWith(extension))) files.push(full);
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
await visit(root);
|
|
1798
|
+
return files.sort((left, right) => left.localeCompare(right));
|
|
1799
|
+
}
|
|
1800
|
+
async function readDirIfExists(dir) {
|
|
1801
|
+
try {
|
|
1802
|
+
return await promises.readdir(dir, { withFileTypes: true });
|
|
1803
|
+
} catch (error) {
|
|
1804
|
+
if (error.code === "ENOENT") return void 0;
|
|
1805
|
+
throw error;
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
function isInsidePath(filePath, dir) {
|
|
1809
|
+
const relative = path.relative(dir, filePath);
|
|
1810
|
+
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
1811
|
+
}
|
|
1812
|
+
function formatLocation(repoRoot, file, line) {
|
|
1813
|
+
return `${path.relative(repoRoot, file)}:${line}`;
|
|
1814
|
+
}
|
|
1815
|
+
async function parseSourceFile(file) {
|
|
1816
|
+
const code = await promises.readFile(file, "utf8");
|
|
1817
|
+
const lineStarts = [0];
|
|
1818
|
+
for (let index = 0; index < code.length; index += 1) if (code[index] === "\n") lineStarts.push(index + 1);
|
|
1819
|
+
const parsed = parseSync(file, code);
|
|
1820
|
+
if (parsed.errors.length) throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
|
|
1821
|
+
return {
|
|
1822
|
+
file,
|
|
1823
|
+
program: parsed.program,
|
|
1824
|
+
lineStarts
|
|
1825
|
+
};
|
|
1826
|
+
}
|
|
1827
|
+
function walk(node, visit) {
|
|
1828
|
+
if (!node || typeof node !== "object") return;
|
|
1829
|
+
const current = node;
|
|
1830
|
+
if (typeof current.type === "string") visit(current);
|
|
1831
|
+
for (const key of Object.keys(current)) {
|
|
1832
|
+
if (SKIP_AST_KEYS.has(key)) continue;
|
|
1833
|
+
const value = current[key];
|
|
1834
|
+
if (Array.isArray(value)) for (const child of value) walk(child, visit);
|
|
1835
|
+
else if (value && typeof value === "object") walk(value, visit);
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
function lineOf(source, node) {
|
|
1839
|
+
if (typeof node.start !== "number") return 0;
|
|
1840
|
+
let low = 0;
|
|
1841
|
+
let high = source.lineStarts.length - 1;
|
|
1842
|
+
while (low <= high) {
|
|
1843
|
+
const mid = Math.floor((low + high) / 2);
|
|
1844
|
+
if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
|
|
1845
|
+
else high = mid - 1;
|
|
1846
|
+
}
|
|
1847
|
+
return high + 1;
|
|
1848
|
+
}
|
|
1849
|
+
function readStringLiteral(node) {
|
|
1850
|
+
if (!node) return void 0;
|
|
1851
|
+
if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") return node.value;
|
|
1852
|
+
}
|
|
1853
|
+
function readName(node) {
|
|
1854
|
+
if (!node) return void 0;
|
|
1855
|
+
if (typeof node.name === "string") return node.name;
|
|
1856
|
+
if (typeof node.value === "string") return node.value;
|
|
1857
|
+
}
|
|
1858
|
+
function isFunctionLike(node) {
|
|
1859
|
+
if (node && [
|
|
1860
|
+
"ParenthesizedExpression",
|
|
1861
|
+
"TSAsExpression",
|
|
1862
|
+
"TSSatisfiesExpression",
|
|
1863
|
+
"TSTypeAssertion",
|
|
1864
|
+
"TSNonNullExpression"
|
|
1865
|
+
].includes(node.type ?? "")) return isFunctionLike(node.expression);
|
|
1866
|
+
return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
|
|
1867
|
+
}
|
|
1868
|
+
function readModuleSpecifier(node) {
|
|
1869
|
+
if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") return readStringLiteral(node.source);
|
|
1870
|
+
}
|
|
1871
|
+
// packages/conformance/rules.ts
|
|
1872
|
+
/** 所有内置规约,按稳定 ID 排序,供工作台目录与文档推导使用。 */
|
|
1873
|
+
const builtinRules = [
|
|
1874
|
+
baselineMaxDiffPixels,
|
|
1875
|
+
commitMessage,
|
|
1876
|
+
conformanceRuleFormat,
|
|
1877
|
+
duplicateLocalization,
|
|
1878
|
+
e2eScenariosStructure,
|
|
1879
|
+
sameDirImportOnly,
|
|
1880
|
+
singleComponentFile,
|
|
1881
|
+
sourceLocaleDefaults,
|
|
1882
|
+
syncLocales,
|
|
1883
|
+
uiScenariosStructure
|
|
1884
|
+
];
|
|
1885
|
+
export { CJK_PATTERN, baselineMaxDiffPixels, builtinRules, commitMessage, conformanceRuleFormat, duplicateLocalization, e2eScenariosStructure, sameDirImportOnly, singleComponentFile, sourceLocaleDefaults, syncLocales, uiScenariosStructure };
|