@hamsterbase/evidra 0.11.1 → 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/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
package/dist/service/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// packages/service/src/cli.ts
|
|
2
2
|
import { cac } from "cac";
|
|
3
3
|
import { customAlphabet as customAlphabet2 } from "nanoid";
|
|
4
|
-
import
|
|
4
|
+
import path45 from "node:path";
|
|
5
5
|
import { parseArgs } from "node:util";
|
|
6
6
|
|
|
7
7
|
// modules/core/implementations/Functions/resolveConfig.ts
|
|
@@ -1500,15 +1500,15 @@ async function worktreeSide(repo, file) {
|
|
|
1500
1500
|
const relative = path18.relative(repo, parent);
|
|
1501
1501
|
if (relative === ".." || relative.startsWith(`..${path18.sep}`) || path18.isAbsolute(relative))
|
|
1502
1502
|
throw new Error("\u6587\u4EF6\u4E0D\u5728\u4ED3\u5E93\u5185");
|
|
1503
|
-
const
|
|
1504
|
-
if (
|
|
1505
|
-
if (
|
|
1503
|
+
const stat5 = await lstat(absolute);
|
|
1504
|
+
if (stat5.isSymbolicLink()) return { mode: "120000", hash: hash(await readlink(absolute)) };
|
|
1505
|
+
if (stat5.isDirectory()) {
|
|
1506
1506
|
const commit = (await git(absolute, ["rev-parse", "HEAD"])).trim();
|
|
1507
1507
|
return { mode: "160000", hash: hash(`Subproject commit ${commit}
|
|
1508
1508
|
`) };
|
|
1509
1509
|
}
|
|
1510
1510
|
return {
|
|
1511
|
-
mode:
|
|
1511
|
+
mode: stat5.mode & 73 ? "100755" : "100644",
|
|
1512
1512
|
hash: await fileDigest(absolute)
|
|
1513
1513
|
};
|
|
1514
1514
|
}
|
|
@@ -2025,12 +2025,12 @@ async function getGitDiff(input) {
|
|
|
2025
2025
|
const relative = path24.relative(repo, parent);
|
|
2026
2026
|
if (relative === ".." || relative.startsWith(`..${path24.sep}`) || path24.isAbsolute(relative))
|
|
2027
2027
|
throw new Error("\u6587\u4EF6\u4E0D\u5728\u4ED3\u5E93\u5185");
|
|
2028
|
-
const
|
|
2029
|
-
if (
|
|
2030
|
-
else if (
|
|
2028
|
+
const stat5 = await lstat2(absolute);
|
|
2029
|
+
if (stat5.isSymbolicLink()) modified = await readlink2(absolute);
|
|
2030
|
+
else if (stat5.isDirectory())
|
|
2031
2031
|
modified = `Subproject commit ${(await git(absolute, ["rev-parse", "HEAD"])).trim()}
|
|
2032
2032
|
`;
|
|
2033
|
-
else if (
|
|
2033
|
+
else if (stat5.size > MAX_BYTES) tooLarge = true;
|
|
2034
2034
|
else modified = await readFile10(absolute, "utf8");
|
|
2035
2035
|
}
|
|
2036
2036
|
const isBinary = original.includes("\0") || modified.includes("\0");
|
|
@@ -2769,275 +2769,2696 @@ import { serveStatic } from "@hono/node-server/serve-static";
|
|
|
2769
2769
|
import { Hono as Hono2 } from "hono";
|
|
2770
2770
|
import { csrf } from "hono/csrf";
|
|
2771
2771
|
import { HTTPException } from "hono/http-exception";
|
|
2772
|
-
import { existsSync
|
|
2773
|
-
import { stat as
|
|
2774
|
-
import
|
|
2775
|
-
import { z as
|
|
2772
|
+
import { existsSync } from "node:fs";
|
|
2773
|
+
import { stat as stat4 } from "node:fs/promises";
|
|
2774
|
+
import path42 from "node:path";
|
|
2775
|
+
import { z as z40 } from "zod";
|
|
2776
2776
|
|
|
2777
2777
|
// packages/service/src/conformance.ts
|
|
2778
|
-
import {
|
|
2779
|
-
import
|
|
2780
|
-
import path32 from "node:path";
|
|
2778
|
+
import { readFile as readFile13, realpath as realpath4, stat as stat3 } from "node:fs/promises";
|
|
2779
|
+
import path41 from "node:path";
|
|
2781
2780
|
import { Hono } from "hono";
|
|
2782
2781
|
|
|
2783
|
-
// packages/conformance/
|
|
2784
|
-
|
|
2785
|
-
baselineMaxDiffPixels: { id: "baseline-max-diff-pixels", displayName: "\u9650\u5236\u57FA\u7EBF\u5141\u8BB8\u5DEE\u5F02\u50CF\u7D20" },
|
|
2786
|
-
commitMessage: { id: "commit-message", displayName: "\u68C0\u67E5\u63D0\u4EA4\u6807\u9898" },
|
|
2787
|
-
duplicateLocalization: { id: "duplicate-localization", displayName: "\u68C0\u67E5\u672C\u5730\u5316\u952E\u4E0E\u9ED8\u8BA4\u6587\u6848" },
|
|
2788
|
-
e2eScenariosStructure: { id: "e2e-scenarios-structure", displayName: "\u68C0\u67E5\u7AEF\u5230\u7AEF\u573A\u666F\u7ED3\u6784" },
|
|
2789
|
-
sameDirImportOnly: { id: "same-dir-import-only", displayName: "\u9650\u5236\u8DE8\u76EE\u5F55\u5F15\u7528" },
|
|
2790
|
-
singleComponentFile: { id: "single-component-file", displayName: "\u5355\u6587\u4EF6\u5355\u7EC4\u4EF6" },
|
|
2791
|
-
sourceLocaleDefaults: { id: "source-locale-defaults", displayName: "\u68C0\u67E5\u6E90\u8BED\u8A00\u9ED8\u8BA4\u6587\u6848" },
|
|
2792
|
-
syncLocales: { id: "sync-locales", displayName: "\u540C\u6B65\u672C\u5730\u5316\u6587\u4EF6" },
|
|
2793
|
-
uiScenariosStructure: { id: "ui-scenarios-structure", displayName: "\u68C0\u67E5\u754C\u9762\u573A\u666F\u7ED3\u6784" }
|
|
2794
|
-
};
|
|
2795
|
-
|
|
2796
|
-
// packages/conformance/runner/load.ts
|
|
2797
|
-
import { access as access2 } from "node:fs/promises";
|
|
2782
|
+
// packages/conformance/rules/baseline-max-diff-pixels.ts
|
|
2783
|
+
import { glob as glob2, readFile as readFile12, stat as stat2 } from "node:fs/promises";
|
|
2798
2784
|
import path31 from "node:path";
|
|
2799
|
-
import {
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
2785
|
+
import { z as z30 } from "zod";
|
|
2786
|
+
|
|
2787
|
+
// packages/conformance/runner/rule.ts
|
|
2788
|
+
import { z as z28 } from "zod";
|
|
2789
|
+
function defineRule(definition2) {
|
|
2790
|
+
const meta = {
|
|
2791
|
+
id: definition2.id,
|
|
2792
|
+
displayName: definition2.displayName,
|
|
2793
|
+
exportName: definition2.exportName,
|
|
2794
|
+
...definition2.importFrom ? { importFrom: definition2.importFrom } : {},
|
|
2795
|
+
summary: definition2.summary,
|
|
2796
|
+
optionsSchema: definition2.optionsSchema,
|
|
2797
|
+
examples: definition2.examples,
|
|
2798
|
+
...definition2.notes ? { notes: definition2.notes } : {}
|
|
2799
|
+
};
|
|
2800
|
+
const factory = ((rawOptions) => {
|
|
2801
|
+
const parsed = definition2.optionsSchema.safeParse(rawOptions ?? {});
|
|
2802
|
+
if (!parsed.success) {
|
|
2803
|
+
throw new Error(`${definition2.id} \u914D\u7F6E\u65E0\u6548\uFF1A
|
|
2804
|
+
${z28.prettifyError(parsed.error)}`);
|
|
2805
|
+
}
|
|
2806
|
+
const options = parsed.data;
|
|
2807
|
+
const task = (common) => definition2.run(common, options);
|
|
2808
|
+
return Object.assign(task, {
|
|
2809
|
+
id: definition2.id,
|
|
2810
|
+
displayName: definition2.resolveDisplayName?.(options) ?? definition2.displayName,
|
|
2811
|
+
doc: meta
|
|
2812
|
+
});
|
|
2813
|
+
});
|
|
2814
|
+
return Object.assign(factory, { meta });
|
|
2815
|
+
}
|
|
2816
|
+
|
|
2817
|
+
// packages/conformance/runner/doc.ts
|
|
2818
|
+
import { z as z29 } from "zod";
|
|
2819
|
+
var DEFAULT_IMPORT_FROM = "@hamsterbase/evidra/conformance-rules";
|
|
2820
|
+
var IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
2821
|
+
function ruleOptionsToJsonSchema(schema) {
|
|
2822
|
+
return z29.toJSONSchema(schema, {
|
|
2823
|
+
io: "input",
|
|
2824
|
+
unrepresentable: "any",
|
|
2825
|
+
override(context) {
|
|
2826
|
+
const meta = context.zodSchema.meta?.();
|
|
2827
|
+
if (meta && typeof meta.tsType === "string") {
|
|
2828
|
+
context.jsonSchema.tsType = meta.tsType;
|
|
2829
|
+
}
|
|
2830
|
+
}
|
|
2831
|
+
});
|
|
2832
|
+
}
|
|
2833
|
+
function renderRuleDoc(doc) {
|
|
2834
|
+
const schema = ruleOptionsToJsonSchema(doc.optionsSchema);
|
|
2835
|
+
const sections = [
|
|
2836
|
+
`# ${doc.exportName}`,
|
|
2837
|
+
doc.summary.trim(),
|
|
2838
|
+
`\u89C4\u7EA6 ID\uFF1A${inlineCode(doc.id)}`,
|
|
2839
|
+
renderUsageSection(doc, schema),
|
|
2840
|
+
renderOptionsSection(schema)
|
|
2841
|
+
];
|
|
2842
|
+
const notes = doc.notes?.trim();
|
|
2843
|
+
if (notes) {
|
|
2844
|
+
sections.push(`## \u8BF4\u660E
|
|
2845
|
+
|
|
2846
|
+
${notes}`);
|
|
2808
2847
|
}
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2848
|
+
return `${sections.join("\n\n")}
|
|
2849
|
+
`;
|
|
2850
|
+
}
|
|
2851
|
+
function renderUsageSection(doc, schema) {
|
|
2852
|
+
const importFrom = doc.importFrom ?? DEFAULT_IMPORT_FROM;
|
|
2853
|
+
const hasRequired = (schema.required?.length ?? 0) > 0;
|
|
2854
|
+
const blocks = doc.examples.map((example) => {
|
|
2855
|
+
const call = formatExampleCall(doc.exportName, example.options, hasRequired);
|
|
2856
|
+
const rulesLine = call.includes("\n") ? ` rules: [
|
|
2857
|
+
${indentLines(call, 4)},
|
|
2858
|
+
],` : ` rules: [${call}],`;
|
|
2859
|
+
const snippet = [
|
|
2860
|
+
`import { defineConfig } from '@hamsterbase/evidra/conformance';`,
|
|
2861
|
+
`import { ${doc.exportName} } from '${importFrom}';`,
|
|
2862
|
+
"",
|
|
2863
|
+
"export default defineConfig({",
|
|
2864
|
+
rulesLine,
|
|
2865
|
+
"});"
|
|
2866
|
+
].join("\n");
|
|
2867
|
+
const heading = example.title?.trim() ? `### ${example.title.trim()}
|
|
2868
|
+
|
|
2869
|
+
` : "";
|
|
2870
|
+
return `${heading}${codeFence("ts", snippet)}`;
|
|
2871
|
+
});
|
|
2872
|
+
return `## \u7528\u6CD5
|
|
2873
|
+
|
|
2874
|
+
${blocks.join("\n\n")}`;
|
|
2875
|
+
}
|
|
2876
|
+
function renderOptionsSection(schema) {
|
|
2877
|
+
const lines = renderProperties(schema, 0);
|
|
2878
|
+
if (lines.length === 0) {
|
|
2879
|
+
return "## \u53C2\u6570\n\n\u6B64\u89C4\u7EA6\u65E0\u9700\u914D\u7F6E\u53C2\u6570\u3002";
|
|
2880
|
+
}
|
|
2881
|
+
return `## \u53C2\u6570
|
|
2882
|
+
|
|
2883
|
+
${lines.join("\n")}`;
|
|
2884
|
+
}
|
|
2885
|
+
function renderProperties(schema, depth) {
|
|
2886
|
+
const properties = schema.properties ?? {};
|
|
2887
|
+
const required = new Set(schema.required ?? []);
|
|
2888
|
+
const indent = " ".repeat(depth);
|
|
2889
|
+
const lines = [];
|
|
2890
|
+
for (const [key, prop] of Object.entries(properties)) {
|
|
2891
|
+
const tags = [inlineCode(formatSchemaType(prop))];
|
|
2892
|
+
const constraints = formatConstraints(prop);
|
|
2893
|
+
if (constraints) tags.push(constraints);
|
|
2894
|
+
tags.push(required.has(key) ? "\u5FC5\u586B" : "\u53EF\u9009");
|
|
2895
|
+
if (prop.default !== void 0) {
|
|
2896
|
+
tags.push(`\u9ED8\u8BA4 ${inlineCode(formatTsValue(prop.default))}`);
|
|
2897
|
+
}
|
|
2898
|
+
const description = prop.description?.trim() ?? "";
|
|
2899
|
+
lines.push(
|
|
2900
|
+
`${indent}- ${inlineCode(key)}\uFF08${tags.join("\uFF0C")}\uFF09${description ? `\uFF1A${description}` : ""}`
|
|
2816
2901
|
);
|
|
2902
|
+
if (prop.type === "object" && prop.properties) {
|
|
2903
|
+
lines.push(...renderProperties(prop, depth + 1));
|
|
2904
|
+
} else if (prop.type === "array" && prop.items?.type === "object" && prop.items.properties) {
|
|
2905
|
+
lines.push(...renderProperties(prop.items, depth + 1));
|
|
2906
|
+
}
|
|
2817
2907
|
}
|
|
2818
|
-
|
|
2819
|
-
|
|
2908
|
+
return lines;
|
|
2909
|
+
}
|
|
2910
|
+
function formatSchemaType(node) {
|
|
2911
|
+
if (node.tsType) return node.tsType;
|
|
2912
|
+
if (node.const !== void 0) return formatTsValue(node.const);
|
|
2913
|
+
if (node.enum?.length) return node.enum.map((item) => formatTsValue(item)).join(" | ");
|
|
2914
|
+
if (node.anyOf?.length) return node.anyOf.map(formatSchemaType).join(" | ");
|
|
2915
|
+
if (node.oneOf?.length) return node.oneOf.map(formatSchemaType).join(" | ");
|
|
2916
|
+
if (Array.isArray(node.type)) {
|
|
2917
|
+
return node.type.join(" | ");
|
|
2820
2918
|
}
|
|
2821
|
-
|
|
2822
|
-
|
|
2919
|
+
if (node.type === "array") {
|
|
2920
|
+
const itemType = node.items ? formatSchemaType(node.items) : "unknown";
|
|
2921
|
+
const wrapped = itemType.includes(" | ") ? `(${itemType})[]` : `${itemType}[]`;
|
|
2922
|
+
return node.readOnly ? `readonly ${wrapped}` : wrapped;
|
|
2923
|
+
}
|
|
2924
|
+
if (node.type === "object") {
|
|
2925
|
+
if (node.properties) return "object";
|
|
2926
|
+
if (node.additionalProperties && typeof node.additionalProperties === "object") {
|
|
2927
|
+
const valueType = formatSchemaType(node.additionalProperties);
|
|
2928
|
+
const recordType = `Record<string, ${valueType}>`;
|
|
2929
|
+
return node.readOnly ? `Readonly<${recordType}>` : recordType;
|
|
2930
|
+
}
|
|
2931
|
+
return "Record<string, unknown>";
|
|
2932
|
+
}
|
|
2933
|
+
if (typeof node.type === "string") return node.type;
|
|
2934
|
+
return "unknown";
|
|
2823
2935
|
}
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
async function listRules(root) {
|
|
2832
|
-
const config = await loadConformanceConfig(root);
|
|
2833
|
-
const entries2 = /* @__PURE__ */ new Map();
|
|
2834
|
-
for (const [index, task] of (config?.rules ?? []).entries()) {
|
|
2835
|
-
const builtin = typeof task.readme === "object" ? task.readme?.builtin : void 0;
|
|
2836
|
-
const id = builtin || task.id?.trim() || task.name || `rule-${index + 1}`;
|
|
2837
|
-
if (entries2.has(id)) continue;
|
|
2838
|
-
const bundled = catalog.find((rule) => rule.id === id);
|
|
2839
|
-
entries2.set(id, {
|
|
2840
|
-
id,
|
|
2841
|
-
displayName: task.displayName?.trim() || bundled?.displayName || task.name || `\u81EA\u5B9A\u4E49\u89C4\u7EA6 ${index + 1}`,
|
|
2842
|
-
enabled: true,
|
|
2843
|
-
readme: task.readme ?? (bundled && { builtin: bundled.id })
|
|
2844
|
-
});
|
|
2936
|
+
function formatConstraints(node) {
|
|
2937
|
+
const parts = [];
|
|
2938
|
+
if (node.type === "string") {
|
|
2939
|
+
if (node.minLength === 1) parts.push("\u975E\u7A7A");
|
|
2940
|
+
else if (typeof node.minLength === "number" && node.minLength > 1)
|
|
2941
|
+
parts.push(`\u957F\u5EA6 >= ${node.minLength}`);
|
|
2942
|
+
if (typeof node.maxLength === "number") parts.push(`\u957F\u5EA6 <= ${node.maxLength}`);
|
|
2845
2943
|
}
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
entries2.set(rule.id, { ...rule, enabled: false, readme: { builtin: rule.id } });
|
|
2944
|
+
if (node.type === "integer" || node.type === "number") {
|
|
2945
|
+
if (typeof node.minimum === "number" && node.minimum !== Number.MIN_SAFE_INTEGER) {
|
|
2946
|
+
parts.push(`>= ${node.minimum}`);
|
|
2850
2947
|
}
|
|
2948
|
+
if (typeof node.maximum === "number" && node.maximum !== Number.MAX_SAFE_INTEGER) {
|
|
2949
|
+
parts.push(`<= ${node.maximum}`);
|
|
2950
|
+
}
|
|
2951
|
+
if (typeof node.exclusiveMinimum === "number") parts.push(`> ${node.exclusiveMinimum}`);
|
|
2952
|
+
if (typeof node.exclusiveMaximum === "number") parts.push(`< ${node.exclusiveMaximum}`);
|
|
2851
2953
|
}
|
|
2852
|
-
return
|
|
2954
|
+
return parts.join("\uFF0C");
|
|
2853
2955
|
}
|
|
2854
|
-
function
|
|
2855
|
-
|
|
2856
|
-
|
|
2956
|
+
function formatExampleCall(exportName, options, hasRequired) {
|
|
2957
|
+
if (!hasRequired && options !== null && typeof options === "object" && !Array.isArray(options) && Object.keys(options).length === 0) {
|
|
2958
|
+
return `${exportName}()`;
|
|
2959
|
+
}
|
|
2960
|
+
return `${exportName}(${formatTsValue(options, 0)})`;
|
|
2857
2961
|
}
|
|
2858
|
-
|
|
2859
|
-
if (
|
|
2860
|
-
|
|
2861
|
-
if (
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
if (
|
|
2869
|
-
|
|
2962
|
+
function formatTsValue(value, indent = 0) {
|
|
2963
|
+
if (value instanceof RegExp) return value.toString();
|
|
2964
|
+
if (typeof value === "string") return formatString(value);
|
|
2965
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
2966
|
+
if (value === null) return "null";
|
|
2967
|
+
if (value === void 0) return "undefined";
|
|
2968
|
+
if (Array.isArray(value)) {
|
|
2969
|
+
if (value.length === 0) return "[]";
|
|
2970
|
+
const inlineItems = value.map((item) => formatTsValue(item, indent + 2));
|
|
2971
|
+
const singleLine = `[${inlineItems.join(", ")}]`;
|
|
2972
|
+
if (singleLine.length <= 60 && !singleLine.includes("\n")) return singleLine;
|
|
2973
|
+
const pad = " ".repeat(indent + 2);
|
|
2974
|
+
const closePad = " ".repeat(indent);
|
|
2975
|
+
return `[
|
|
2976
|
+
${inlineItems.map((item) => `${pad}${item},`).join("\n")}
|
|
2977
|
+
${closePad}]`;
|
|
2978
|
+
}
|
|
2979
|
+
if (typeof value === "object") {
|
|
2980
|
+
const entries2 = Object.entries(value).filter(
|
|
2981
|
+
([, entryValue]) => entryValue !== void 0
|
|
2982
|
+
);
|
|
2983
|
+
if (entries2.length === 0) return "{}";
|
|
2984
|
+
const inlinePairs = entries2.map(
|
|
2985
|
+
([key, entryValue]) => `${formatObjectKey(key)}: ${formatTsValue(entryValue, indent + 2)}`
|
|
2986
|
+
);
|
|
2987
|
+
const singleLine = `{ ${inlinePairs.join(", ")} }`;
|
|
2988
|
+
if (singleLine.length <= 60 && !singleLine.includes("\n")) return singleLine;
|
|
2989
|
+
const pad = " ".repeat(indent + 2);
|
|
2990
|
+
const closePad = " ".repeat(indent);
|
|
2991
|
+
return `{
|
|
2992
|
+
${inlinePairs.map((pair) => `${pad}${pair},`).join("\n")}
|
|
2993
|
+
${closePad}}`;
|
|
2870
2994
|
}
|
|
2995
|
+
return String(value);
|
|
2871
2996
|
}
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
if (!readme || !builtinDirectory) return null;
|
|
2875
|
-
return await resolveMarkdown(builtinDirectory, path32.join(readme.builtin, "README.md")) ?? resolveMarkdown(builtinDirectory, path32.join(readme.builtin, "RULE.md"));
|
|
2997
|
+
function formatObjectKey(key) {
|
|
2998
|
+
return IDENTIFIER_PATTERN.test(key) ? key : formatString(key);
|
|
2876
2999
|
}
|
|
2877
|
-
function
|
|
2878
|
-
const
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
|
|
2900
|
-
return
|
|
3000
|
+
function formatString(value) {
|
|
3001
|
+
const escaped = value.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll("\n", "\\n").replaceAll("\r", "\\r").replaceAll(" ", "\\t");
|
|
3002
|
+
return `'${escaped}'`;
|
|
3003
|
+
}
|
|
3004
|
+
function indentLines(text, spaces) {
|
|
3005
|
+
const pad = " ".repeat(spaces);
|
|
3006
|
+
return text.split("\n").map((line) => `${pad}${line}`).join("\n");
|
|
3007
|
+
}
|
|
3008
|
+
function inlineCode(value) {
|
|
3009
|
+
let maxTicks = 0;
|
|
3010
|
+
for (const match of value.matchAll(/`+/g)) {
|
|
3011
|
+
if (match[0].length > maxTicks) maxTicks = match[0].length;
|
|
3012
|
+
}
|
|
3013
|
+
const ticks = "`".repeat(maxTicks + 1);
|
|
3014
|
+
const needsPadding = value.startsWith("`") || value.endsWith("`") || value.startsWith(" ") && value.endsWith(" ") && value.trim().length > 0;
|
|
3015
|
+
return needsPadding ? `${ticks} ${value} ${ticks}` : `${ticks}${value}${ticks}`;
|
|
3016
|
+
}
|
|
3017
|
+
function codeFence(language, code) {
|
|
3018
|
+
let maxTicks = 0;
|
|
3019
|
+
for (const match of code.matchAll(/`+/g)) {
|
|
3020
|
+
if (match[0].length > maxTicks) maxTicks = match[0].length;
|
|
3021
|
+
}
|
|
3022
|
+
const fence = "`".repeat(Math.max(3, maxTicks + 1));
|
|
3023
|
+
return `${fence}${language}
|
|
3024
|
+
${code}
|
|
3025
|
+
${fence}`;
|
|
2901
3026
|
}
|
|
2902
3027
|
|
|
2903
|
-
// packages/
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
var
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
3028
|
+
// packages/conformance/rules/baseline-max-diff-pixels.ts
|
|
3029
|
+
var optionsSchema = z30.object({
|
|
3030
|
+
baselineDir: z30.string().trim().min(1).describe("\u57FA\u7EBF JSON \u76EE\u5F55\uFF0C\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9 projectRoot \u7684\u8DEF\u5F84\u3002"),
|
|
3031
|
+
maxDiffPixels: z30.number().int().nonnegative().describe("\u6BCF\u5F20\u57FA\u7EBF\u56FE\u7247\u5141\u8BB8\u914D\u7F6E\u7684\u6700\u5927\u5DEE\u5F02\u50CF\u7D20\u6570\uFF1B\u9608\u503C\u7B49\u4E8E\u4E0A\u9650\u65F6\u901A\u8FC7\uFF0C\u672A\u914D\u7F6E\u65F6\u6309 0 \u5904\u7406\u3002")
|
|
3032
|
+
});
|
|
3033
|
+
var baselineMaxDiffPixels = defineRule({
|
|
3034
|
+
id: "baseline-max-diff-pixels",
|
|
3035
|
+
displayName: "\u9650\u5236\u57FA\u7EBF\u5141\u8BB8\u5DEE\u5F02\u50CF\u7D20",
|
|
3036
|
+
exportName: "baselineMaxDiffPixels",
|
|
3037
|
+
summary: "\u9012\u5F52\u68C0\u67E5\u6307\u5B9A\u57FA\u7EBF\u76EE\u5F55\uFF0C\u786E\u4FDD\u6BCF\u5F20\u56FE\u7247\u5FEB\u7167\u7684 `maxDiffPixels` \u5728\u9879\u76EE\u5141\u8BB8\u7684\u4E0A\u9650\u5185\u3002",
|
|
3038
|
+
optionsSchema,
|
|
3039
|
+
examples: [{ options: { baselineDir: ".report/baselines", maxDiffPixels: 20 } }],
|
|
3040
|
+
notes: "\u8BFB\u53D6\u57FA\u7EBF JSON \u4E2D\u7684\u56FE\u7247\u5FEB\u7167\u5143\u6570\u636E\uFF0C\u9002\u7528\u4E8E\u672C\u5730\u6216 S3 \u56FE\u7247\u5B58\u50A8\u3002\u8D85\u8FC7\u4E0A\u9650\u65F6\uFF0C\u62A5\u544A\u4F1A\u5217\u51FA\u57FA\u7EBF\u6587\u4EF6\u3001\u7528\u4F8B\u3001\u5FEB\u7167\u548C\u5B9E\u9645\u9608\u503C\u3002\u9700\u8981\u8C03\u6574\u5355\u5F20\u5FEB\u7167\u7684\u9608\u503C\u65F6\uFF0C\u5728\u6D4B\u8BD5\u4E0A\u62A5\u914D\u7F6E\u4E2D\u8BBE\u7F6E `maxDiffPixels`\uFF0C\u91CD\u65B0\u4E0A\u62A5\u540E\u7531\u7528\u6237\u5BA1\u6838\u57FA\u7EBF\u3002",
|
|
3041
|
+
async run({ projectRoot }, { baselineDir, maxDiffPixels }) {
|
|
3042
|
+
const root = path31.resolve(projectRoot, baselineDir);
|
|
3043
|
+
if (!(await stat2(root)).isDirectory()) throw new Error(`\u57FA\u7EBF\u8DEF\u5F84\u5FC5\u987B\u662F\u76EE\u5F55\uFF1A${root}`);
|
|
3044
|
+
const files = [];
|
|
3045
|
+
for await (const file of glob2("**/baseline*.json", {
|
|
3046
|
+
cwd: root,
|
|
3047
|
+
exclude: ["**/node_modules/**", "**/.git/**", "**/cache/**"]
|
|
3048
|
+
})) {
|
|
3049
|
+
if (/^baseline(?:-[a-f0-9]{64})?\.json$/.test(path31.basename(file))) files.push(file);
|
|
2920
3050
|
}
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
3051
|
+
files.sort();
|
|
3052
|
+
let imageCount = 0;
|
|
3053
|
+
const findings = [];
|
|
3054
|
+
for (const file of files) {
|
|
3055
|
+
const baselinePath = path31.join(root, file);
|
|
3056
|
+
const relative = path31.relative(projectRoot, baselinePath);
|
|
3057
|
+
let baseline;
|
|
3058
|
+
try {
|
|
3059
|
+
baseline = JSON.parse(await readFile12(baselinePath, "utf8"));
|
|
3060
|
+
} catch (error) {
|
|
3061
|
+
findings.push(`${relative} \u65E0\u6CD5\u8BFB\u53D6\u57FA\u7EBF\uFF1A${String(error)}`);
|
|
3062
|
+
continue;
|
|
3063
|
+
}
|
|
3064
|
+
if (!Array.isArray(baseline?.snapshots)) continue;
|
|
3065
|
+
for (const snapshot of baseline.snapshots) {
|
|
3066
|
+
if (snapshot?.type !== "image") continue;
|
|
3067
|
+
imageCount++;
|
|
3068
|
+
const tolerance = snapshot.maxDiffPixels ?? 0;
|
|
3069
|
+
const label = `${relative} / ${baseline.name || baseline.id} / ${snapshot.name || snapshot.id}`;
|
|
3070
|
+
if (!Number.isSafeInteger(tolerance) || tolerance < 0) {
|
|
3071
|
+
findings.push(`${label} \u7684 maxDiffPixels \u65E0\u6548\uFF08${String(tolerance)}\uFF09`);
|
|
3072
|
+
} else if (tolerance > maxDiffPixels) {
|
|
3073
|
+
findings.push(`${label} \u7684 maxDiffPixels \u4E3A ${tolerance}\uFF0C\u8D85\u8FC7\u4E0A\u9650 ${maxDiffPixels}`);
|
|
3074
|
+
}
|
|
3075
|
+
}
|
|
2929
3076
|
}
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
3077
|
+
return {
|
|
3078
|
+
name: "baseline-max-diff-pixels",
|
|
3079
|
+
success: findings.length === 0,
|
|
3080
|
+
messages: [
|
|
3081
|
+
`\u68C0\u67E5\u4E86 ${imageCount} \u5F20\u57FA\u7EBF\u56FE\u7247\uFF0CmaxDiffPixels \u4E0A\u9650\u4E3A ${maxDiffPixels}\u3002`,
|
|
3082
|
+
...findings
|
|
3083
|
+
].join("\n"),
|
|
3084
|
+
howToFix: findings.length ? "\u68C0\u67E5\u62A5\u544A\u4E2D\u7684\u6587\u4EF6\u548C\u5FEB\u7167\u3002\u9700\u8981\u8C03\u6574\u9608\u503C\u65F6\uFF0C\u4ECE\u6D4B\u8BD5\u4E0A\u62A5\u914D\u7F6E\u8BBE\u7F6E maxDiffPixels\uFF0C\u91CD\u65B0\u4E0A\u62A5\u540E\u7531\u7528\u6237\u5BA1\u6838\u57FA\u7EBF\u3002" : ""
|
|
3085
|
+
};
|
|
2937
3086
|
}
|
|
2938
|
-
|
|
2939
|
-
}
|
|
3087
|
+
});
|
|
2940
3088
|
|
|
2941
|
-
// packages/
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
3089
|
+
// packages/conformance/rules/commit-message.ts
|
|
3090
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
3091
|
+
import { promisify } from "node:util";
|
|
3092
|
+
import { z as z31 } from "zod";
|
|
3093
|
+
var optionsSchema2 = z31.object({
|
|
3094
|
+
forbiddenPrefixes: z31.array(z31.string()).readonly().default(["```"]).describe("\u7981\u6B62\u7684\u63D0\u4EA4\u6807\u9898\u524D\u7F00\uFF1B\u4F20\u5165\u7A7A\u6570\u7EC4\u65F6\u4E0D\u9650\u5236\u524D\u7F00\u3002"),
|
|
3095
|
+
base: z31.string().trim().min(1).optional().describe(
|
|
3096
|
+
'\u6BD4\u8F83\u57FA\u51C6\uFF0C\u4F8B\u5982 CI \u4E2D\u7684 "origin/main"\uFF1B\u6307\u5B9A\u65F6\u4EC5\u68C0\u67E5 `base..HEAD`\uFF0C\u9ED8\u8BA4\u4F7F\u7528 upstream\u3002'
|
|
3097
|
+
)
|
|
3098
|
+
});
|
|
3099
|
+
var execFileAsync = promisify(execFile2);
|
|
3100
|
+
var commitMessage = defineRule({
|
|
3101
|
+
id: "commit-message",
|
|
3102
|
+
displayName: "\u68C0\u67E5\u63D0\u4EA4\u6807\u9898",
|
|
3103
|
+
exportName: "commitMessage",
|
|
3104
|
+
summary: "\u68C0\u67E5 Git \u63D0\u4EA4\u6807\u9898\u662F\u5426\u4EE5\u7981\u6B62\u7684\u524D\u7F00\u5F00\u5934\uFF0C\u907F\u514D\u5C06 Markdown \u4EE3\u7801\u5757\u6807\u8BB0\u8BEF\u4F5C\u63D0\u4EA4\u6807\u9898\u3002",
|
|
3105
|
+
optionsSchema: optionsSchema2,
|
|
3106
|
+
examples: [{ options: { forbiddenPrefixes: ["```"] } }],
|
|
3107
|
+
notes: "\u6307\u5B9A `base` \u65F6\u68C0\u67E5 `base..HEAD`\uFF1B\u5426\u5219\u6709 upstream \u65F6\u68C0\u67E5 `upstream..HEAD`\uFF1B\u4E24\u8005\u90FD\u6CA1\u6709\u65F6\u53EA\u68C0\u67E5\u5C1A\u672A\u63A8\u9001\u5230\u4EFB\u4F55\u8FDC\u7AEF\u7684\u63D0\u4EA4\uFF08`HEAD --not --remotes`\uFF09\uFF0C\u4ED3\u5E93\u6CA1\u6709\u8FDC\u7AEF\u65F6\u7B49\u540C\u4E8E\u5168\u90E8\u5386\u53F2\u3002CI \u7684 detached HEAD \u6CA1\u6709 upstream\uFF0C\u5E94\u914D\u7F6E `base`\u3002Git \u6267\u884C\u9519\u8BEF\u4F5C\u4E3A\u4EFB\u52A1\u5931\u8D25\u3002",
|
|
3108
|
+
async run(common, options) {
|
|
3109
|
+
const { commits, scope } = await collectCommitSubjects(common.projectRoot, options.base);
|
|
3110
|
+
const violations = commits.filter(
|
|
3111
|
+
(commit) => options.forbiddenPrefixes.some((prefix) => commit.subject.startsWith(prefix))
|
|
2962
3112
|
);
|
|
2963
|
-
|
|
3113
|
+
const lines = [`\u626B\u63CF${scope} ${commits.length} \u4E2A\u63D0\u4EA4 message\u3002`];
|
|
3114
|
+
if (violations.length === 0) {
|
|
3115
|
+
lines.push("\u672A\u53D1\u73B0\u4EE5\u7981\u6B62\u7684\u524D\u7F00\u5F00\u5934\u7684\u63D0\u4EA4 message\u3002");
|
|
3116
|
+
return {
|
|
3117
|
+
name: "commit-message",
|
|
3118
|
+
success: true,
|
|
3119
|
+
messages: lines.join("\n"),
|
|
3120
|
+
howToFix: ""
|
|
3121
|
+
};
|
|
3122
|
+
}
|
|
3123
|
+
lines.push(`\u53D1\u73B0 ${violations.length} \u4E2A\u63D0\u4EA4 message \u4EE5\u7981\u6B62\u7684\u524D\u7F00\u5F00\u5934\uFF1A`);
|
|
3124
|
+
for (const violation of violations) {
|
|
3125
|
+
lines.push(` - ${violation.hash.slice(0, 7)} ${violation.subject}`);
|
|
3126
|
+
}
|
|
3127
|
+
return {
|
|
3128
|
+
name: "commit-message",
|
|
3129
|
+
success: false,
|
|
3130
|
+
messages: lines.join("\n"),
|
|
3131
|
+
howToFix: "\u4FEE\u6539\u5BF9\u5E94\u63D0\u4EA4 message\uFF0C\u79FB\u9664\u7981\u6B62\u7684\u524D\u7F00\u3002"
|
|
3132
|
+
};
|
|
3133
|
+
}
|
|
3134
|
+
});
|
|
3135
|
+
async function collectCommitSubjects(repoRoot, base) {
|
|
3136
|
+
const upstream = base ?? await readUpstream(repoRoot);
|
|
3137
|
+
const logArgs = ["log", "--format=%x1e%H%x00%s"];
|
|
3138
|
+
const scope = upstream ? `\u5F53\u524D\u5206\u652F\u76F8\u5BF9 ${upstream} \u7684` : "\u672A\u63A8\u9001\u5230\u8FDC\u7AEF\u7684";
|
|
3139
|
+
logArgs.push(...upstream ? [`${upstream}..HEAD`] : ["HEAD", "--not", "--remotes"]);
|
|
3140
|
+
const { stdout } = await execFileAsync("git", logArgs, {
|
|
3141
|
+
cwd: repoRoot,
|
|
3142
|
+
encoding: "utf8",
|
|
3143
|
+
maxBuffer: 1024 * 1024 * 16
|
|
2964
3144
|
});
|
|
2965
|
-
const url = `http://${options.host ?? "127.0.0.1"}:${address.port}`;
|
|
2966
3145
|
return {
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
}
|
|
2974
|
-
}
|
|
3146
|
+
scope,
|
|
3147
|
+
commits: stdout.split("").map((record) => record.trimEnd()).filter((record) => record.length > 0).map((record) => {
|
|
3148
|
+
const separatorIndex = record.indexOf("\0");
|
|
3149
|
+
return {
|
|
3150
|
+
hash: record.slice(0, separatorIndex),
|
|
3151
|
+
subject: record.slice(separatorIndex + 1)
|
|
3152
|
+
};
|
|
3153
|
+
})
|
|
2975
3154
|
};
|
|
2976
3155
|
}
|
|
2977
|
-
function
|
|
2978
|
-
|
|
2979
|
-
|
|
2980
|
-
|
|
2981
|
-
|
|
2982
|
-
|
|
2983
|
-
|
|
2984
|
-
|
|
2985
|
-
|
|
2986
|
-
|
|
2987
|
-
|
|
3156
|
+
async function readUpstream(repoRoot) {
|
|
3157
|
+
try {
|
|
3158
|
+
const { stdout } = await execFileAsync(
|
|
3159
|
+
"git",
|
|
3160
|
+
["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
|
|
3161
|
+
{
|
|
3162
|
+
cwd: repoRoot,
|
|
3163
|
+
encoding: "utf8"
|
|
3164
|
+
}
|
|
3165
|
+
);
|
|
3166
|
+
return stdout.trim() || void 0;
|
|
3167
|
+
} catch {
|
|
3168
|
+
return void 0;
|
|
2988
3169
|
}
|
|
2989
3170
|
}
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
)
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3171
|
+
|
|
3172
|
+
// packages/conformance/rules/conformance-rule-format.ts
|
|
3173
|
+
import { promises as fs } from "node:fs";
|
|
3174
|
+
import path32 from "node:path";
|
|
3175
|
+
import { pathToFileURL } from "node:url";
|
|
3176
|
+
import { parseSync } from "oxc-parser";
|
|
3177
|
+
import { tsImport } from "tsx/esm/api";
|
|
3178
|
+
import { z as z32 } from "zod";
|
|
3179
|
+
var optionsSchema3 = z32.object({
|
|
3180
|
+
rulesDir: z32.string().trim().min(1).describe("\u5B58\u653E\u89C4\u7EA6\u5355\u6587\u4EF6\u7684\u76EE\u5F55\uFF0C\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9 projectRoot \u7684\u8DEF\u5F84\u3002"),
|
|
3181
|
+
entryFile: z32.string().trim().min(1).optional().describe(
|
|
3182
|
+
"\u53EF\u9009\u7684\u89C4\u7EA6\u6C47\u603B\u5165\u53E3\u6587\u4EF6\u8DEF\u5F84\uFF08\u4F8B\u5982 packages/conformance/rules.ts\uFF09\uFF1B\u914D\u7F6E\u540E\u540C\u65F6\u68C0\u67E5\u6240\u6709\u89C4\u7EA6\u5747\u5DF2\u5177\u540D\u5BFC\u51FA\u5E76\u6CE8\u518C\u5230 builtinRules\u3002"
|
|
3183
|
+
)
|
|
3184
|
+
});
|
|
3185
|
+
var KEBAB_FILE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.ts$/;
|
|
3186
|
+
var SKIP_AST_KEYS = /* @__PURE__ */ new Set([
|
|
3187
|
+
"loc",
|
|
3188
|
+
"range",
|
|
3189
|
+
"start",
|
|
3190
|
+
"end",
|
|
3191
|
+
"parent",
|
|
3192
|
+
"leadingComments",
|
|
3193
|
+
"trailingComments"
|
|
3194
|
+
]);
|
|
3195
|
+
var conformanceRuleFormat = defineRule({
|
|
3196
|
+
id: "conformance-rule-format",
|
|
3197
|
+
displayName: "\u68C0\u67E5\u89C4\u7EA6\u683C\u5F0F",
|
|
3198
|
+
exportName: "conformanceRuleFormat",
|
|
3199
|
+
summary: "\u68C0\u67E5\u89C4\u7EA6\u76EE\u5F55\u662F\u5426\u9075\u5FAA\u5355\u6587\u4EF6\u81EA\u6CBB\u683C\u5F0F\uFF1A\u6587\u4EF6\u540D\u4E0E\u5BFC\u51FA\u540D\u4E00\u81F4\u3001\u65E0\u624B\u5199 Markdown\u3001\u89C4\u7EA6\u95F4\u96F6\u4F9D\u8D56\uFF0C\u4E14\u901A\u8FC7 defineRule \u4E0E Zod Schema \u63A8\u5BFC\u6587\u6863\u3002",
|
|
3200
|
+
optionsSchema: optionsSchema3,
|
|
3201
|
+
examples: [
|
|
3202
|
+
{
|
|
3203
|
+
options: {
|
|
3204
|
+
rulesDir: "packages/conformance/rules",
|
|
3205
|
+
entryFile: "packages/conformance/rules.ts"
|
|
3206
|
+
}
|
|
3207
|
+
}
|
|
3208
|
+
],
|
|
3209
|
+
notes: "\u6BCF\u6761\u89C4\u7EA6\u987B\u4E3A `rulesDir` \u4E0B\u72EC\u7ACB\u7684 kebab-case `.ts` \u6587\u4EF6\uFF08\u4E0D\u542B\u5B50\u76EE\u5F55\u548C `.md` \u6587\u4EF6\uFF09\uFF0C\u4E0D\u5F97\u5BFC\u5165\u6216\u8F6C\u5BFC\u51FA `rulesDir` \u5185\u7684\u5176\u4ED6\u6587\u4EF6\uFF0C\u987B\u5BFC\u51FA\u540C\u540D camelCase \u5DE5\u5382\u51FD\u6570\uFF0C\u901A\u8FC7 `defineRule` \u63D0\u4F9B\u5B8C\u6574\u7684 `id`\u3001`displayName`\u3001`exportName`\u3001`summary`\u3001\u5B57\u6BB5\u5747\u5E26 `.describe()` \u7684 Zod `optionsSchema` \u4EE5\u53CA\u80FD\u901A\u8FC7\u6821\u9A8C\u7684 `examples`\u3002\u914D\u7F6E `entryFile` \u65F6\u4F1A\u540C\u6B65\u68C0\u67E5\u5165\u53E3\u5BFC\u51FA\u4E0E `builtinRules` \u6CE8\u518C\u8868\u3002",
|
|
3210
|
+
async run(context, options) {
|
|
3211
|
+
const repoRoot = context.projectRoot;
|
|
3212
|
+
const rulesDir = path32.resolve(repoRoot, options.rulesDir);
|
|
3213
|
+
const violations = [];
|
|
3214
|
+
const dirEntries = await readDirIfExists(rulesDir);
|
|
3215
|
+
if (!dirEntries) {
|
|
3216
|
+
return {
|
|
3217
|
+
name: "conformance-rule-format",
|
|
3218
|
+
success: false,
|
|
3219
|
+
messages: `\u89C4\u7EA6\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${path32.relative(repoRoot, rulesDir)}`,
|
|
3220
|
+
howToFix: "\u786E\u8BA4 rulesDir \u6307\u5411\u6709\u6548\u7684\u89C4\u7EA6\u76EE\u5F55\u3002"
|
|
3221
|
+
};
|
|
3222
|
+
}
|
|
3223
|
+
const ruleFiles = [];
|
|
3224
|
+
for (const entry of dirEntries) {
|
|
3225
|
+
if (entry.name.startsWith(".")) continue;
|
|
3226
|
+
const full = path32.join(rulesDir, entry.name);
|
|
3227
|
+
const relative = path32.relative(repoRoot, full);
|
|
3228
|
+
if (entry.isDirectory()) {
|
|
3229
|
+
violations.push(` - ${relative} \u89C4\u7EA6\u76EE\u5F55\u4E0D\u5141\u8BB8\u5B50\u76EE\u5F55\uFF0C\u6BCF\u6761\u89C4\u7EA6\u987B\u4E3A\u5355\u4E2A .ts \u6587\u4EF6`);
|
|
3230
|
+
continue;
|
|
3231
|
+
}
|
|
3232
|
+
if (!entry.isFile()) continue;
|
|
3233
|
+
if (path32.extname(entry.name).toLowerCase() === ".md") {
|
|
3234
|
+
violations.push(
|
|
3235
|
+
` - ${relative} \u4E0D\u5141\u8BB8\u624B\u5199 Markdown \u6587\u6863\uFF0C\u89C4\u7EA6\u6587\u6863\u987B\u7531\u5B9A\u4E49\u4E0E Zod Schema \u81EA\u52A8\u63A8\u5BFC`
|
|
3236
|
+
);
|
|
3237
|
+
continue;
|
|
3238
|
+
}
|
|
3239
|
+
if (!KEBAB_FILE_PATTERN.test(entry.name)) {
|
|
3240
|
+
violations.push(` - ${relative} \u89C4\u7EA6\u6587\u4EF6\u540D\u987B\u4E3A kebab-case .ts\uFF08\u4F8B\u5982 my-rule.ts\uFF09`);
|
|
3241
|
+
continue;
|
|
3242
|
+
}
|
|
3243
|
+
ruleFiles.push(full);
|
|
3244
|
+
}
|
|
3245
|
+
ruleFiles.sort((left, right) => left.localeCompare(right));
|
|
3246
|
+
const loadedRules = [];
|
|
3247
|
+
const seenDisplayNames = /* @__PURE__ */ new Map();
|
|
3248
|
+
for (const file of ruleFiles) {
|
|
3249
|
+
const relative = path32.relative(repoRoot, file);
|
|
3250
|
+
const ruleId = path32.basename(file, ".ts");
|
|
3251
|
+
const expectedExportName = kebabToCamel(ruleId);
|
|
3252
|
+
const source = await parseSourceFile(file);
|
|
3253
|
+
walk(source.program, (node) => {
|
|
3254
|
+
const specifier = readImportSpecifier(node);
|
|
3255
|
+
if (!specifier || !specifier.startsWith("./") && !specifier.startsWith("../")) return;
|
|
3256
|
+
const target = path32.resolve(path32.dirname(file), specifier);
|
|
3257
|
+
if (isInsidePath(target, rulesDir)) {
|
|
3258
|
+
violations.push(
|
|
3259
|
+
` - ${relative}:${lineOf(source, node)} \u89C4\u7EA6\u4E4B\u95F4\u7981\u6B62\u4E92\u76F8\u4F9D\u8D56\u6216\u5171\u4EAB\u4EE3\u7801\uFF0C\u4E0D\u5F97\u5F15\u7528 '${specifier}'`
|
|
3260
|
+
);
|
|
3261
|
+
}
|
|
3262
|
+
});
|
|
3263
|
+
let moduleExports;
|
|
3264
|
+
try {
|
|
3265
|
+
moduleExports = await tsImport(pathToFileURL(file).href, import.meta.url);
|
|
3266
|
+
} catch (error) {
|
|
3267
|
+
violations.push(
|
|
3268
|
+
` - ${relative} \u52A0\u8F7D\u89C4\u7EA6\u6A21\u5757\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`
|
|
3269
|
+
);
|
|
3270
|
+
continue;
|
|
3271
|
+
}
|
|
3272
|
+
const exported = moduleExports[expectedExportName];
|
|
3273
|
+
if (typeof exported !== "function") {
|
|
3274
|
+
violations.push(` - ${relative} \u5FC5\u987B\u5177\u540D\u5BFC\u51FA\u89C4\u7EA6\u5DE5\u5382\u51FD\u6570 ${expectedExportName}`);
|
|
3275
|
+
continue;
|
|
3276
|
+
}
|
|
3277
|
+
const meta = exported.meta;
|
|
3278
|
+
if (!isRecord(meta)) {
|
|
3279
|
+
violations.push(
|
|
3280
|
+
` - ${relative} \u5BFC\u51FA\u7684 ${expectedExportName} \u5FC5\u987B\u901A\u8FC7 defineRule \u5B9A\u4E49\u5E76\u9644\u5E26 meta`
|
|
3281
|
+
);
|
|
3282
|
+
continue;
|
|
3283
|
+
}
|
|
3284
|
+
const ruleDoc = meta;
|
|
3285
|
+
if (ruleDoc.id !== ruleId) {
|
|
3286
|
+
violations.push(
|
|
3287
|
+
` - ${relative} meta.id \u987B\u4E0E\u6587\u4EF6\u540D\u4E00\u81F4\uFF08\u671F\u671B '${ruleId}'\uFF0C\u5B9E\u9645 '${String(ruleDoc.id)}'\uFF09`
|
|
3288
|
+
);
|
|
3289
|
+
}
|
|
3290
|
+
if (ruleDoc.exportName !== expectedExportName) {
|
|
3291
|
+
violations.push(
|
|
3292
|
+
` - ${relative} meta.exportName \u987B\u4E0E\u5BFC\u51FA\u540D\u4E00\u81F4\uFF08\u671F\u671B '${expectedExportName}'\uFF0C\u5B9E\u9645 '${String(ruleDoc.exportName)}'\uFF09`
|
|
3293
|
+
);
|
|
3294
|
+
}
|
|
3295
|
+
if (typeof ruleDoc.displayName !== "string" || !ruleDoc.displayName.trim()) {
|
|
3296
|
+
violations.push(` - ${relative} meta.displayName \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32`);
|
|
3297
|
+
} else {
|
|
3298
|
+
const existingFile = seenDisplayNames.get(ruleDoc.displayName);
|
|
3299
|
+
if (existingFile) {
|
|
3300
|
+
violations.push(
|
|
3301
|
+
` - ${relative} meta.displayName '${ruleDoc.displayName}' \u4E0E ${existingFile} \u91CD\u590D`
|
|
3302
|
+
);
|
|
3303
|
+
} else {
|
|
3304
|
+
seenDisplayNames.set(ruleDoc.displayName, relative);
|
|
3305
|
+
}
|
|
3306
|
+
}
|
|
3307
|
+
if (typeof ruleDoc.summary !== "string" || !ruleDoc.summary.trim()) {
|
|
3308
|
+
violations.push(` - ${relative} meta.summary \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32`);
|
|
3309
|
+
}
|
|
3310
|
+
let schemaValid = false;
|
|
3311
|
+
if (!isZodSchema(ruleDoc.optionsSchema)) {
|
|
3312
|
+
violations.push(` - ${relative} meta.optionsSchema \u5FC5\u987B\u662F\u6709\u6548\u7684 Zod Schema`);
|
|
3313
|
+
} else {
|
|
3314
|
+
try {
|
|
3315
|
+
const jsonSchema = ruleOptionsToJsonSchema(ruleDoc.optionsSchema);
|
|
3316
|
+
if (jsonSchema.type !== "object") {
|
|
3317
|
+
violations.push(` - ${relative} meta.optionsSchema \u9876\u5C42\u5FC5\u987B\u662F z.object(...)`);
|
|
3318
|
+
} else {
|
|
3319
|
+
schemaValid = true;
|
|
3320
|
+
for (const missingPath of findMissingDescriptions(jsonSchema)) {
|
|
3321
|
+
violations.push(
|
|
3322
|
+
` - ${relative} \u914D\u7F6E\u9879 '${missingPath}' \u7F3A\u5C11 .describe(...) \u8BF4\u660E\uFF0C\u65E0\u6CD5\u751F\u6210\u5B8C\u6574\u53C2\u6570\u6587\u6863`
|
|
3323
|
+
);
|
|
3324
|
+
}
|
|
3325
|
+
}
|
|
3326
|
+
} catch (error) {
|
|
3327
|
+
violations.push(
|
|
3328
|
+
` - ${relative} meta.optionsSchema \u65E0\u6CD5\u8F6C\u6362\u4E3A\u6587\u6863 Schema\uFF1A${error instanceof Error ? error.message : String(error)}`
|
|
3329
|
+
);
|
|
3330
|
+
}
|
|
3331
|
+
}
|
|
3332
|
+
if (!Array.isArray(ruleDoc.examples) || ruleDoc.examples.length === 0) {
|
|
3333
|
+
violations.push(` - ${relative} meta.examples \u81F3\u5C11\u9700\u8981\u63D0\u4F9B 1 \u4E2A\u914D\u7F6E\u793A\u4F8B`);
|
|
3334
|
+
} else if (schemaValid && isZodSchema(ruleDoc.optionsSchema)) {
|
|
3335
|
+
for (const [index, example] of ruleDoc.examples.entries()) {
|
|
3336
|
+
if (!isRecord(example) || !("options" in example)) {
|
|
3337
|
+
violations.push(` - ${relative} meta.examples[${index}] \u5FC5\u987B\u5305\u542B options \u5B57\u6BB5`);
|
|
3338
|
+
continue;
|
|
3339
|
+
}
|
|
3340
|
+
const parsed = ruleDoc.optionsSchema.safeParse(example.options);
|
|
3341
|
+
if (!parsed.success) {
|
|
3342
|
+
violations.push(
|
|
3343
|
+
` - ${relative} meta.examples[${index}].options \u672A\u901A\u8FC7 optionsSchema \u6821\u9A8C\uFF1A${z32.prettifyError(parsed.error)}`
|
|
3344
|
+
);
|
|
3345
|
+
}
|
|
3346
|
+
}
|
|
3347
|
+
const firstExample = ruleDoc.examples[0];
|
|
3348
|
+
if (isRecord(firstExample) && "options" in firstExample) {
|
|
3349
|
+
try {
|
|
3350
|
+
const task = exported(firstExample.options);
|
|
3351
|
+
if (typeof task !== "function" || task.id !== ruleId || task.doc !== meta) {
|
|
3352
|
+
violations.push(
|
|
3353
|
+
` - ${relative} \u8C03\u7528 ${expectedExportName}(example.options) \u672A\u8FD4\u56DE\u5E26 id \u4E0E doc \u7684\u6709\u6548 RuleTask`
|
|
3354
|
+
);
|
|
3355
|
+
}
|
|
3356
|
+
} catch (error) {
|
|
3357
|
+
violations.push(
|
|
3358
|
+
` - ${relative} \u4F7F\u7528\u793A\u4F8B\u53C2\u6570\u8C03\u7528 ${expectedExportName} \u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`
|
|
3359
|
+
);
|
|
3360
|
+
}
|
|
3361
|
+
}
|
|
3362
|
+
}
|
|
3363
|
+
if (schemaValid && Array.isArray(ruleDoc.examples) && ruleDoc.examples.length > 0) {
|
|
3364
|
+
try {
|
|
3365
|
+
const markdown = renderRuleDoc(ruleDoc);
|
|
3366
|
+
if (!markdown.includes(`# ${expectedExportName}`)) {
|
|
3367
|
+
violations.push(` - ${relative} \u63A8\u5BFC\u51FA\u7684\u6587\u6863\u7F3A\u5C11\u6807\u9898 '# ${expectedExportName}'`);
|
|
3368
|
+
}
|
|
3369
|
+
} catch (error) {
|
|
3370
|
+
violations.push(
|
|
3371
|
+
` - ${relative} \u63A8\u5BFC\u89C4\u7EA6\u6587\u6863\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`
|
|
3372
|
+
);
|
|
3373
|
+
}
|
|
3374
|
+
}
|
|
3375
|
+
loadedRules.push({ id: ruleId, exportName: expectedExportName, file: relative });
|
|
3376
|
+
}
|
|
3377
|
+
if (options.entryFile) {
|
|
3378
|
+
await validateEntryFile(
|
|
3379
|
+
repoRoot,
|
|
3380
|
+
path32.resolve(repoRoot, options.entryFile),
|
|
3381
|
+
loadedRules,
|
|
3382
|
+
violations
|
|
3383
|
+
);
|
|
3384
|
+
}
|
|
3385
|
+
const lines = [
|
|
3386
|
+
`\u68C0\u67E5\u4E86 ${path32.relative(repoRoot, rulesDir)} \u4E0B ${ruleFiles.length} \u4E2A\u89C4\u7EA6\u6587\u4EF6\u3002`
|
|
3387
|
+
];
|
|
3388
|
+
if (violations.length === 0) {
|
|
3389
|
+
lines.push("\u6240\u6709\u89C4\u7EA6\u5747\u7B26\u5408\u5355\u6587\u4EF6\u3001\u96F6\u4F9D\u8D56\u4E0E Zod \u6587\u6863\u63A8\u5BFC\u683C\u5F0F\u3002");
|
|
3390
|
+
return {
|
|
3391
|
+
name: "conformance-rule-format",
|
|
3392
|
+
success: true,
|
|
3393
|
+
messages: lines.join("\n"),
|
|
3394
|
+
howToFix: ""
|
|
3395
|
+
};
|
|
3396
|
+
}
|
|
3397
|
+
lines.push(`\u53D1\u73B0 ${violations.length} \u5904\u89C4\u7EA6\u683C\u5F0F\u8FDD\u89C4\uFF1A`, ...violations);
|
|
3398
|
+
return {
|
|
3399
|
+
name: "conformance-rule-format",
|
|
3400
|
+
success: false,
|
|
3401
|
+
messages: lines.join("\n"),
|
|
3402
|
+
howToFix: "\u6309\u89C4\u7EA6\u683C\u5F0F\u4FEE\u6B63\uFF1A\u6BCF\u6761\u89C4\u7EA6\u4F7F\u7528\u5355\u4E2A kebab-case .ts \u6587\u4EF6\u3001\u901A\u8FC7 defineRule \u4E0E\u5E26 .describe() \u7684 Zod Schema \u5B9A\u4E49\u3001\u63D0\u4F9B\u5408\u6CD5 examples\u3001\u79FB\u9664\u624B\u5199 Markdown \u4E0E\u89C4\u7EA6\u95F4\u5F15\u7528\uFF0C\u5E76\u540C\u6B65\u5165\u53E3\u5BFC\u51FA\u3002"
|
|
3403
|
+
};
|
|
3404
|
+
}
|
|
3405
|
+
});
|
|
3406
|
+
async function validateEntryFile(repoRoot, entryPath, loadedRules, violations) {
|
|
3407
|
+
const relative = path32.relative(repoRoot, entryPath);
|
|
3408
|
+
let entryModule;
|
|
3409
|
+
try {
|
|
3410
|
+
entryModule = await tsImport(pathToFileURL(entryPath).href, import.meta.url);
|
|
3411
|
+
} catch (error) {
|
|
3412
|
+
violations.push(
|
|
3413
|
+
` - ${relative} \u65E0\u6CD5\u52A0\u8F7D\u89C4\u7EA6\u5165\u53E3\u6587\u4EF6\uFF1A${error instanceof Error ? error.message : String(error)}`
|
|
3414
|
+
);
|
|
3415
|
+
return;
|
|
3416
|
+
}
|
|
3417
|
+
for (const rule of loadedRules) {
|
|
3418
|
+
const exported = entryModule[rule.exportName];
|
|
3419
|
+
const meta = isRecord(exported?.meta) ? exported.meta ?? void 0 : void 0;
|
|
3420
|
+
if (typeof exported !== "function" || meta?.id !== rule.id) {
|
|
3421
|
+
violations.push(
|
|
3422
|
+
` - ${relative} \u7F3A\u5C11\u6216\u672A\u6B63\u786E\u5BFC\u51FA\u89C4\u7EA6 ${rule.exportName}\uFF08\u6765\u81EA ${rule.file}\uFF09`
|
|
3423
|
+
);
|
|
3424
|
+
}
|
|
3425
|
+
}
|
|
3426
|
+
if (!("builtinRules" in entryModule)) return;
|
|
3427
|
+
const catalog2 = entryModule.builtinRules;
|
|
3428
|
+
if (!Array.isArray(catalog2)) {
|
|
3429
|
+
violations.push(` - ${relative} \u5BFC\u51FA\u7684 builtinRules \u5FC5\u987B\u662F\u89C4\u7EA6\u6570\u7EC4`);
|
|
3430
|
+
return;
|
|
3431
|
+
}
|
|
3432
|
+
const expectedIds = new Set(loadedRules.map((rule) => rule.id));
|
|
3433
|
+
const registeredIds = /* @__PURE__ */ new Set();
|
|
3434
|
+
for (const [index, item] of catalog2.entries()) {
|
|
3435
|
+
const meta = isRecord(item?.meta) ? item.meta : void 0;
|
|
3436
|
+
const id = typeof meta?.id === "string" ? meta.id : void 0;
|
|
3437
|
+
if (typeof item !== "function" || !id) {
|
|
3438
|
+
violations.push(` - ${relative} builtinRules[${index}] \u4E0D\u662F\u901A\u8FC7 defineRule \u5B9A\u4E49\u7684\u6709\u6548\u89C4\u7EA6`);
|
|
3439
|
+
continue;
|
|
3440
|
+
}
|
|
3441
|
+
if (registeredIds.has(id)) {
|
|
3442
|
+
violations.push(` - ${relative} builtinRules \u4E2D\u91CD\u590D\u6CE8\u518C\u4E86\u89C4\u7EA6 '${id}'`);
|
|
3443
|
+
continue;
|
|
3444
|
+
}
|
|
3445
|
+
registeredIds.add(id);
|
|
3446
|
+
if (!expectedIds.has(id)) {
|
|
3447
|
+
violations.push(` - ${relative} builtinRules \u5305\u542B\u672A\u5728 rulesDir \u4E2D\u627E\u5230\u7684\u89C4\u7EA6 '${id}'`);
|
|
3448
|
+
}
|
|
3449
|
+
}
|
|
3450
|
+
for (const rule of loadedRules) {
|
|
3451
|
+
if (!registeredIds.has(rule.id)) {
|
|
3452
|
+
violations.push(` - ${relative} builtinRules \u672A\u6CE8\u518C\u89C4\u7EA6 '${rule.id}'`);
|
|
3453
|
+
}
|
|
3454
|
+
}
|
|
3455
|
+
}
|
|
3456
|
+
function findMissingDescriptions(schema, prefix = "") {
|
|
3457
|
+
const missing = [];
|
|
3458
|
+
const properties = schema.properties ?? {};
|
|
3459
|
+
for (const [key, prop] of Object.entries(properties)) {
|
|
3460
|
+
const fieldPath = prefix ? `${prefix}.${key}` : key;
|
|
3461
|
+
if (typeof prop.description !== "string" || !prop.description.trim()) {
|
|
3462
|
+
missing.push(fieldPath);
|
|
3463
|
+
}
|
|
3464
|
+
if (prop.type === "object" && prop.properties) {
|
|
3465
|
+
missing.push(...findMissingDescriptions(prop, fieldPath));
|
|
3466
|
+
} else if (prop.type === "array" && prop.items?.type === "object" && prop.items.properties) {
|
|
3467
|
+
missing.push(...findMissingDescriptions(prop.items, `${fieldPath}[]`));
|
|
3468
|
+
}
|
|
3469
|
+
}
|
|
3470
|
+
return missing;
|
|
3471
|
+
}
|
|
3472
|
+
function isZodSchema(value) {
|
|
3473
|
+
return isRecord(value) && "_zod" in value && typeof value.safeParse === "function";
|
|
3474
|
+
}
|
|
3475
|
+
function isRecord(value) {
|
|
3476
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3477
|
+
}
|
|
3478
|
+
function kebabToCamel(value) {
|
|
3479
|
+
return value.replace(/-([a-z0-9])/g, (_, char) => char.toUpperCase());
|
|
3480
|
+
}
|
|
3481
|
+
async function readDirIfExists(dir) {
|
|
3482
|
+
try {
|
|
3483
|
+
return await fs.readdir(dir, { withFileTypes: true });
|
|
3484
|
+
} catch (error) {
|
|
3485
|
+
if (error.code === "ENOENT") return void 0;
|
|
3486
|
+
throw error;
|
|
3487
|
+
}
|
|
3488
|
+
}
|
|
3489
|
+
function isInsidePath(filePath, dir) {
|
|
3490
|
+
const relative = path32.relative(dir, filePath);
|
|
3491
|
+
return relative === "" || !relative.startsWith("..") && !path32.isAbsolute(relative);
|
|
3492
|
+
}
|
|
3493
|
+
async function parseSourceFile(file) {
|
|
3494
|
+
const code = await fs.readFile(file, "utf8");
|
|
3495
|
+
const lineStarts = [0];
|
|
3496
|
+
for (let index = 0; index < code.length; index += 1) {
|
|
3497
|
+
if (code[index] === "\n") lineStarts.push(index + 1);
|
|
3498
|
+
}
|
|
3499
|
+
const parsed = parseSync(file, code);
|
|
3500
|
+
if (parsed.errors.length)
|
|
3501
|
+
throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
|
|
3502
|
+
return { file, program: parsed.program, lineStarts };
|
|
3503
|
+
}
|
|
3504
|
+
function walk(node, visit) {
|
|
3505
|
+
if (!node || typeof node !== "object") return;
|
|
3506
|
+
const current = node;
|
|
3507
|
+
if (typeof current.type === "string") visit(current);
|
|
3508
|
+
for (const key of Object.keys(current)) {
|
|
3509
|
+
if (SKIP_AST_KEYS.has(key)) continue;
|
|
3510
|
+
const value = current[key];
|
|
3511
|
+
if (Array.isArray(value)) {
|
|
3512
|
+
for (const child of value) walk(child, visit);
|
|
3513
|
+
} else if (value && typeof value === "object") {
|
|
3514
|
+
walk(value, visit);
|
|
3515
|
+
}
|
|
3516
|
+
}
|
|
3517
|
+
}
|
|
3518
|
+
function lineOf(source, node) {
|
|
3519
|
+
if (typeof node.start !== "number") return 0;
|
|
3520
|
+
let low = 0;
|
|
3521
|
+
let high = source.lineStarts.length - 1;
|
|
3522
|
+
while (low <= high) {
|
|
3523
|
+
const mid = Math.floor((low + high) / 2);
|
|
3524
|
+
if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
|
|
3525
|
+
else high = mid - 1;
|
|
3526
|
+
}
|
|
3527
|
+
return high + 1;
|
|
3528
|
+
}
|
|
3529
|
+
function readImportSpecifier(node) {
|
|
3530
|
+
if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ImportExpression") {
|
|
3531
|
+
const source = node.source;
|
|
3532
|
+
if (source && (source.type === "Literal" || source.type === "StringLiteral") && typeof source.value === "string") {
|
|
3533
|
+
return source.value;
|
|
3534
|
+
}
|
|
3535
|
+
}
|
|
3536
|
+
return void 0;
|
|
3537
|
+
}
|
|
3538
|
+
|
|
3539
|
+
// packages/conformance/rules/duplicate-localization.ts
|
|
3540
|
+
import { promises as fs2 } from "node:fs";
|
|
3541
|
+
import path33 from "node:path";
|
|
3542
|
+
import { parseSync as parseSync2 } from "oxc-parser";
|
|
3543
|
+
import { z as z33 } from "zod";
|
|
3544
|
+
var optionsSchema4 = z33.object({
|
|
3545
|
+
scanRoot: z33.string().trim().min(1).describe("\u9012\u5F52\u626B\u63CF\u7684\u6E90\u7801\u76EE\u5F55\uFF0C\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9 projectRoot \u7684\u8DEF\u5F84\u3002"),
|
|
3546
|
+
excludeDirs: z33.array(z33.string()).readonly().default([]).describe("\u626B\u63CF\u65F6\u8DF3\u8FC7\u7684\u5B50\u76EE\u5F55\u53CA\u5176\u540E\u4EE3\uFF1B\u8DEF\u5F84\u76F8\u5BF9 projectRoot \u89E3\u6790\uFF0C\u4E5F\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u3002"),
|
|
3547
|
+
skipDirNames: z33.array(z33.string()).readonly().default(["node_modules", "dist", "coverage"]).describe("\u6309\u76EE\u5F55\u540D\u8DF3\u8FC7\uFF1B\u4F20\u5165\u65F6\u66FF\u6362\u9ED8\u8BA4\u5217\u8868\uFF0C\u9690\u85CF\u76EE\u5F55\u59CB\u7EC8\u8DF3\u8FC7\u3002"),
|
|
3548
|
+
callName: z33.string().trim().min(1).default("localize").describe("\u672C\u5730\u5316\u51FD\u6570\u540D\uFF1B\u4EC5\u5339\u914D\u76F4\u63A5\u8C03\u7528\uFF0C\u4E0D\u5339\u914D\u5BF9\u8C61\u6210\u5458\u8C03\u7528\u3002"),
|
|
3549
|
+
keyArgument: z33.number().int().nonnegative().default(0).describe("key \u6240\u5728\u7684\u53C2\u6570\u4E0B\u6807\uFF0C\u4ECE 0 \u5F00\u59CB\u3002"),
|
|
3550
|
+
valueArgument: z33.number().int().nonnegative().default(1).describe("\u9ED8\u8BA4\u6587\u6848\u6240\u5728\u7684\u53C2\u6570\u4E0B\u6807\uFF0C\u4ECE 0 \u5F00\u59CB\u3002")
|
|
3551
|
+
});
|
|
3552
|
+
var SKIP_AST_KEYS2 = /* @__PURE__ */ new Set([
|
|
3553
|
+
"loc",
|
|
3554
|
+
"range",
|
|
3555
|
+
"start",
|
|
3556
|
+
"end",
|
|
3557
|
+
"parent",
|
|
3558
|
+
"leadingComments",
|
|
3559
|
+
"trailingComments"
|
|
3560
|
+
]);
|
|
3561
|
+
var duplicateLocalization = defineRule({
|
|
3562
|
+
id: "duplicate-localization",
|
|
3563
|
+
displayName: "\u68C0\u67E5\u672C\u5730\u5316\u952E\u4E0E\u9ED8\u8BA4\u6587\u6848",
|
|
3564
|
+
exportName: "duplicateLocalization",
|
|
3565
|
+
summary: "\u68C0\u67E5\u540C\u4E00\u4E2A\u672C\u5730\u5316 key \u662F\u5426\u7ED1\u5B9A\u4E0D\u540C\u9ED8\u8BA4\u6587\u6848\uFF0C\u5E76\u62D2\u7EDD key \u6216\u6587\u6848\u4F7F\u7528\u6A21\u677F\u5B57\u7B26\u4E32\u3002\u76F8\u540C key \u4E0E\u76F8\u540C\u6587\u6848\u5141\u8BB8\u91CD\u590D\u3002",
|
|
3566
|
+
optionsSchema: optionsSchema4,
|
|
3567
|
+
examples: [{ options: { scanRoot: "src", callName: "t" } }],
|
|
3568
|
+
notes: "\u53D8\u91CF\u53C2\u6570\u4F1A\u88AB\u8DF3\u8FC7\u3002\u76F8\u540C key \u4E0E\u76F8\u540C\u9ED8\u8BA4\u6587\u6848\u5141\u8BB8\u91CD\u590D\u3002",
|
|
3569
|
+
async run(common, config) {
|
|
3570
|
+
const repoRoot = common.projectRoot;
|
|
3571
|
+
const scanRoot = path33.resolve(repoRoot, config.scanRoot);
|
|
3572
|
+
const excludeDirs = config.excludeDirs.map((dir) => path33.resolve(repoRoot, dir));
|
|
3573
|
+
const files = await collectSourceFiles(scanRoot, excludeDirs, config.skipDirNames);
|
|
3574
|
+
const keys = /* @__PURE__ */ new Map();
|
|
3575
|
+
const conflicts = [];
|
|
3576
|
+
const templateLiterals = [];
|
|
3577
|
+
for (const file of files) {
|
|
3578
|
+
const { ast, code } = await parseSourceFile2(file);
|
|
3579
|
+
const lineStarts = collectLineStarts(code);
|
|
3580
|
+
walk2(ast.program, (node) => {
|
|
3581
|
+
if (!isLocalizeCall(node, config.callName)) return;
|
|
3582
|
+
const keyNode = node.arguments[config.keyArgument];
|
|
3583
|
+
const valueNode = node.arguments[config.valueArgument];
|
|
3584
|
+
const location = locationFor(file, node, lineStarts);
|
|
3585
|
+
if (isTemplateLiteral(keyNode) || isTemplateLiteral(valueNode)) {
|
|
3586
|
+
templateLiterals.push({ location });
|
|
3587
|
+
return;
|
|
3588
|
+
}
|
|
3589
|
+
const key = readStringLiteral(keyNode);
|
|
3590
|
+
const value = readStringLiteral(valueNode);
|
|
3591
|
+
if (key === void 0 || value === void 0) return;
|
|
3592
|
+
const existing = keys.get(key);
|
|
3593
|
+
if (!existing) {
|
|
3594
|
+
keys.set(key, { value, location });
|
|
3595
|
+
return;
|
|
3596
|
+
}
|
|
3597
|
+
if (existing.value !== value) {
|
|
3598
|
+
conflicts.push({ key, current: { value, location }, previous: existing });
|
|
3599
|
+
}
|
|
3600
|
+
});
|
|
3601
|
+
}
|
|
3602
|
+
const lines = [`Localization keys: ${keys.size}`];
|
|
3603
|
+
let success = true;
|
|
3604
|
+
if (templateLiterals.length > 0) {
|
|
3605
|
+
success = false;
|
|
3606
|
+
lines.push(`Found ${templateLiterals.length} localize() call(s) using template literals:`);
|
|
3607
|
+
for (const item of templateLiterals) {
|
|
3608
|
+
lines.push(` - ${relativeLocation(repoRoot, item.location)}`);
|
|
3609
|
+
}
|
|
3610
|
+
}
|
|
3611
|
+
if (conflicts.length > 0) {
|
|
3612
|
+
success = false;
|
|
3613
|
+
lines.push(`Found ${conflicts.length} duplicate localization key(s) with different values:`);
|
|
3614
|
+
for (const conflict of conflicts) {
|
|
3615
|
+
lines.push(` - '${conflict.key}'`);
|
|
3616
|
+
lines.push(
|
|
3617
|
+
` current: '${conflict.current.value}' at ${relativeLocation(
|
|
3618
|
+
repoRoot,
|
|
3619
|
+
conflict.current.location
|
|
3620
|
+
)}`
|
|
3621
|
+
);
|
|
3622
|
+
lines.push(
|
|
3623
|
+
` previously: '${conflict.previous.value}' at ${relativeLocation(
|
|
3624
|
+
repoRoot,
|
|
3625
|
+
conflict.previous.location
|
|
3626
|
+
)}`
|
|
3627
|
+
);
|
|
3628
|
+
}
|
|
3629
|
+
}
|
|
3630
|
+
if (success) {
|
|
3631
|
+
lines.push("No duplicate localization keys found.");
|
|
3632
|
+
}
|
|
3633
|
+
return {
|
|
3634
|
+
name: "duplicate-localization",
|
|
3635
|
+
success,
|
|
3636
|
+
messages: lines.join("\n"),
|
|
3637
|
+
howToFix: success ? "" : "Replace template literals with string literals, and unify duplicate keys to share a single default message."
|
|
3638
|
+
};
|
|
3639
|
+
}
|
|
3640
|
+
});
|
|
3641
|
+
async function collectSourceFiles(root, excludeDirs, skipDirNames) {
|
|
3642
|
+
const out = [];
|
|
3643
|
+
const resolvedExcludeDirs = excludeDirs.map((item) => path33.resolve(item));
|
|
3644
|
+
async function visit(dir) {
|
|
3645
|
+
const entries2 = await fs2.readdir(dir, { withFileTypes: true });
|
|
3646
|
+
for (const entry of entries2) {
|
|
3647
|
+
const full = path33.join(dir, entry.name);
|
|
3648
|
+
if (entry.isDirectory()) {
|
|
3649
|
+
if (entry.name.startsWith(".")) continue;
|
|
3650
|
+
if (skipDirNames.includes(entry.name)) continue;
|
|
3651
|
+
if (isExcluded(full, resolvedExcludeDirs)) continue;
|
|
3652
|
+
await visit(full);
|
|
3653
|
+
continue;
|
|
3654
|
+
}
|
|
3655
|
+
if (!entry.isFile()) continue;
|
|
3656
|
+
if (!full.endsWith(".ts") && !full.endsWith(".tsx")) continue;
|
|
3657
|
+
out.push(full);
|
|
3658
|
+
}
|
|
3659
|
+
}
|
|
3660
|
+
await visit(root);
|
|
3661
|
+
return out.sort();
|
|
3662
|
+
}
|
|
3663
|
+
async function parseSourceFile2(file) {
|
|
3664
|
+
const code = await fs2.readFile(file, "utf8");
|
|
3665
|
+
const ast = parseSync2(file, code);
|
|
3666
|
+
if (ast.errors.length)
|
|
3667
|
+
throw new Error(`${file}: ${ast.errors.map((error) => error.message).join("; ")}`);
|
|
3668
|
+
return { ast, code };
|
|
3669
|
+
}
|
|
3670
|
+
function walk2(node, visit) {
|
|
3671
|
+
if (!node || typeof node !== "object") return;
|
|
3672
|
+
const current = node;
|
|
3673
|
+
if (typeof current.type === "string") visit(current);
|
|
3674
|
+
for (const key of Object.keys(current)) {
|
|
3675
|
+
if (SKIP_AST_KEYS2.has(key)) continue;
|
|
3676
|
+
const value = current[key];
|
|
3677
|
+
if (Array.isArray(value)) {
|
|
3678
|
+
for (const child of value) walk2(child, visit);
|
|
3679
|
+
} else if (value && typeof value === "object") {
|
|
3680
|
+
walk2(value, visit);
|
|
3681
|
+
}
|
|
3682
|
+
}
|
|
3683
|
+
}
|
|
3684
|
+
function locationFor(file, node, lineStarts) {
|
|
3685
|
+
if (node.loc?.start.line) return `${file}:${node.loc.start.line}`;
|
|
3686
|
+
const offset = node.start ?? 0;
|
|
3687
|
+
let low = 0;
|
|
3688
|
+
let high = lineStarts.length - 1;
|
|
3689
|
+
while (low < high) {
|
|
3690
|
+
const mid = Math.ceil((low + high) / 2);
|
|
3691
|
+
if (lineStarts[mid] <= offset) low = mid;
|
|
3692
|
+
else high = mid - 1;
|
|
3693
|
+
}
|
|
3694
|
+
return `${file}:${low + 1}`;
|
|
3695
|
+
}
|
|
3696
|
+
function collectLineStarts(code) {
|
|
3697
|
+
const starts = [0];
|
|
3698
|
+
for (let index = code.indexOf("\n"); index !== -1; index = code.indexOf("\n", index + 1)) {
|
|
3699
|
+
starts.push(index + 1);
|
|
3700
|
+
}
|
|
3701
|
+
return starts;
|
|
3702
|
+
}
|
|
3703
|
+
function relativeLocation(repoRoot, location) {
|
|
3704
|
+
const index = location.lastIndexOf(":");
|
|
3705
|
+
if (index === -1) return path33.relative(repoRoot, location);
|
|
3706
|
+
const file = location.slice(0, index);
|
|
3707
|
+
const line = location.slice(index + 1);
|
|
3708
|
+
return `${path33.relative(repoRoot, file)}:${line}`;
|
|
3709
|
+
}
|
|
3710
|
+
function isLocalizeCall(node, name) {
|
|
3711
|
+
return node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === name;
|
|
3712
|
+
}
|
|
3713
|
+
function readStringLiteral(node) {
|
|
3714
|
+
if (!node) return void 0;
|
|
3715
|
+
if (node.type === "Literal" && typeof node.value === "string") return node.value;
|
|
3716
|
+
if (node.type === "StringLiteral" && typeof node.value === "string") return node.value;
|
|
3717
|
+
return void 0;
|
|
3718
|
+
}
|
|
3719
|
+
function isTemplateLiteral(node) {
|
|
3720
|
+
return node?.type === "TemplateLiteral";
|
|
3721
|
+
}
|
|
3722
|
+
function isExcluded(filePath, excludeDirs) {
|
|
3723
|
+
return excludeDirs.some((dir) => filePath === dir || filePath.startsWith(dir + path33.sep));
|
|
3724
|
+
}
|
|
3725
|
+
|
|
3726
|
+
// packages/conformance/rules/e2e-scenarios-structure.ts
|
|
3727
|
+
import { promises as fs3 } from "node:fs";
|
|
3728
|
+
import path34 from "node:path";
|
|
3729
|
+
import { parseSync as parseSync3 } from "oxc-parser";
|
|
3730
|
+
import { z as z34 } from "zod";
|
|
3731
|
+
var optionsSchema5 = z34.object({
|
|
3732
|
+
root: z34.string().trim().min(1).describe(
|
|
3733
|
+
"\u573A\u666F\u6839\u76EE\u5F55\uFF0C\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9 projectRoot \u7684\u8DEF\u5F84\uFF1B\u4EC5\u68C0\u67E5\u6B64\u76EE\u5F55\u76F4\u63A5\u5305\u542B\u7684\u5165\u53E3\u6587\u4EF6\u3002"
|
|
3734
|
+
),
|
|
3735
|
+
name: z34.string().trim().min(1).optional().describe(
|
|
3736
|
+
"\u7ED3\u679C\u540D\u4E0E\u5C55\u793A\u540D\uFF0C\u540C\u4E00\u4ED3\u5E93\u68C0\u67E5\u591A\u4E2A\u6D4B\u8BD5\u6839\u76EE\u5F55\u65F6\u7528\u4E8E\u533A\u5206\uFF0C\u9ED8\u8BA4 e2e-scenarios-structure\u3002"
|
|
3737
|
+
),
|
|
3738
|
+
entrySuffix: z34.string().min(1).default(".spec.ts").describe("\u5165\u53E3\u6587\u4EF6\u540E\u7F00\u3002"),
|
|
3739
|
+
sharedDir: z34.string().trim().min(1).default("shared").describe("\u591A\u4E2A\u5165\u53E3\u5171\u7528 helper \u7684\u76EE\u5F55\u540D\uFF0C\u76F8\u5BF9 root\u3002"),
|
|
3740
|
+
utilsDir: z34.string().trim().min(1).default("utils").describe("\u5404\u5165\u53E3\u4E13\u5C5E helper \u7684\u76EE\u5F55\u540D\uFF0C\u76F8\u5BF9 root\uFF1B\u5165\u53E3\u53EA\u80FD\u5BFC\u5165\u81EA\u8EAB\u540C\u540D\u5B50\u76EE\u5F55\u3002"),
|
|
3741
|
+
strictRoot: z34.boolean().default(false).describe("\u662F\u5426\u8981\u6C42 root \u53EA\u5305\u542B\u5165\u53E3\u6587\u4EF6\u548C\u914D\u7F6E\u7684\u4E24\u7C7B helper \u76EE\u5F55\uFF1B\u9690\u85CF\u6761\u76EE\u59CB\u7EC8\u8DF3\u8FC7\u3002"),
|
|
3742
|
+
sharedThreshold: z34.number().int().min(1).default(3).describe("helper \u88AB\u591A\u5C11\u4E2A\u5165\u53E3\u4F7F\u7528\u65F6\u5EFA\u8BAE\u79FB\u5230\u5171\u7528\u76EE\u5F55\uFF1B\u4EC5\u5F71\u54CD\u8FDD\u89C4\u65F6\u7684\u4FEE\u590D\u5EFA\u8BAE\u3002")
|
|
3743
|
+
});
|
|
3744
|
+
var SKIP_AST_KEYS3 = /* @__PURE__ */ new Set([
|
|
3745
|
+
"loc",
|
|
3746
|
+
"range",
|
|
3747
|
+
"start",
|
|
3748
|
+
"end",
|
|
3749
|
+
"parent",
|
|
3750
|
+
"leadingComments",
|
|
3751
|
+
"trailingComments"
|
|
3752
|
+
]);
|
|
3753
|
+
var DEFAULT_SKIP_DIR_NAMES = ["node_modules", "dist", "coverage"];
|
|
3754
|
+
var e2eScenariosStructure = defineRule({
|
|
3755
|
+
id: "e2e-scenarios-structure",
|
|
3756
|
+
displayName: "\u68C0\u67E5\u7AEF\u5230\u7AEF\u573A\u666F\u7ED3\u6784",
|
|
3757
|
+
exportName: "e2eScenariosStructure",
|
|
3758
|
+
summary: "\u68C0\u67E5 e2e \u573A\u666F\u7684\u76EE\u5F55\u548C\u5F15\u7528\u8FB9\u754C\u3002\u5165\u53E3\u53EA\u63CF\u8FF0\u6D4B\u8BD5\u6D41\u7A0B\uFF0C\u4E0D\u5B9A\u4E49\u51FD\u6570\u58F0\u660E\u6216\u7ED1\u5B9A\u5230\u53D8\u91CF\u7684\u8F85\u52A9\u51FD\u6570\u3002",
|
|
3759
|
+
optionsSchema: optionsSchema5,
|
|
3760
|
+
examples: [{ options: { root: "tests/e2e" } }],
|
|
3761
|
+
notes: "\u76F4\u63A5\u4F20\u7ED9\u6D4B\u8BD5\u8C03\u7528\u6216\u622A\u56FE\u6B65\u9AA4\u7684\u5185\u8054\u56DE\u8C03\u5141\u8BB8\u4FDD\u7559\u3002\u5165\u53E3\u53EA\u5141\u8BB8\u5F15\u7528\u81EA\u8EAB\u540C\u540D\u7684 utils \u5B50\u76EE\u5F55\uFF1Bshared \u548C utils \u4E0D\u80FD\u4E92\u76F8 import/export\uFF0C\u4E24\u7C7B helper \u76EE\u5F55\u540D\u53EF\u914D\u7F6E\u3002\u53EA\u68C0\u67E5 root \u76F4\u63A5\u5305\u542B\u7684\u5165\u53E3\u6587\u4EF6\uFF0C\u9012\u5F52\u68C0\u67E5 helper \u76EE\u5F55\u3002",
|
|
3762
|
+
resolveDisplayName: (options) => options.name ?? "\u68C0\u67E5\u7AEF\u5230\u7AEF\u573A\u666F\u7ED3\u6784",
|
|
3763
|
+
async run(context, options) {
|
|
3764
|
+
const ruleName = options.name ?? "e2e-scenarios-structure";
|
|
3765
|
+
const repoRoot = context.projectRoot;
|
|
3766
|
+
const entrySuffix = options.entrySuffix;
|
|
3767
|
+
const strictRoot = options.strictRoot;
|
|
3768
|
+
const root = path34.resolve(repoRoot, options.root);
|
|
3769
|
+
const sharedName = options.sharedDir;
|
|
3770
|
+
const utilsName = options.utilsDir;
|
|
3771
|
+
const threshold = options.sharedThreshold;
|
|
3772
|
+
const sharedRoot = path34.join(root, sharedName);
|
|
3773
|
+
const utilsRoot = path34.join(root, utilsName);
|
|
3774
|
+
const utilsPrefix = `./${utilsName}/`;
|
|
3775
|
+
const at = (file, line) => formatLocation(repoRoot, file, line);
|
|
3776
|
+
const violations = [];
|
|
3777
|
+
const entries2 = await readDirIfExists2(root);
|
|
3778
|
+
if (!entries2) {
|
|
3779
|
+
return {
|
|
3780
|
+
name: ruleName,
|
|
3781
|
+
success: false,
|
|
3782
|
+
messages: `\u573A\u666F\u6839\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${path34.relative(repoRoot, root)}`,
|
|
3783
|
+
howToFix: "\u786E\u8BA4\u4F20\u5165\u7684\u573A\u666F\u6839\u76EE\u5F55\u8DEF\u5F84\u3002"
|
|
3784
|
+
};
|
|
3785
|
+
}
|
|
3786
|
+
const entryFiles = [];
|
|
3787
|
+
for (const entry of entries2) {
|
|
3788
|
+
if (entry.name.startsWith(".")) continue;
|
|
3789
|
+
const full = path34.join(root, entry.name);
|
|
3790
|
+
if (entry.name === sharedName || entry.name === utilsName) {
|
|
3791
|
+
if (!entry.isDirectory()) violations.push(` - ${at(full, 1)} ${entry.name} \u5FC5\u987B\u662F\u76EE\u5F55`);
|
|
3792
|
+
continue;
|
|
3793
|
+
}
|
|
3794
|
+
if (entry.isFile() && entry.name.endsWith(entrySuffix)) {
|
|
3795
|
+
entryFiles.push(full);
|
|
3796
|
+
continue;
|
|
3797
|
+
}
|
|
3798
|
+
if (strictRoot) {
|
|
3799
|
+
violations.push(
|
|
3800
|
+
` - ${at(full, 1)} \u6839\u76EE\u5F55\u53EA\u5141\u8BB8 *${entrySuffix} \u5165\u53E3\u4E0E ${sharedName}/${utilsName} \u76EE\u5F55`
|
|
3801
|
+
);
|
|
3802
|
+
}
|
|
3803
|
+
}
|
|
3804
|
+
entryFiles.sort((left, right) => left.localeCompare(right));
|
|
3805
|
+
const usages = /* @__PURE__ */ new Map();
|
|
3806
|
+
const importViolations = [];
|
|
3807
|
+
for (const file of entryFiles) {
|
|
3808
|
+
const source = await parseSourceFile3(file);
|
|
3809
|
+
const entryName = path34.basename(file, entrySuffix);
|
|
3810
|
+
walk3(source.program, (node) => {
|
|
3811
|
+
const functionName = readFunctionName(node);
|
|
3812
|
+
if (functionName) {
|
|
3813
|
+
violations.push(
|
|
3814
|
+
` - ${at(file, lineOf2(source, node))} \u5165\u53E3\u5185\u5B9A\u4E49\u8F85\u52A9\u51FD\u6570 ${functionName}`
|
|
3815
|
+
);
|
|
3816
|
+
}
|
|
3817
|
+
});
|
|
3818
|
+
const expected = `${utilsPrefix}${entryName}`;
|
|
3819
|
+
for (const entry of collectImports(source, utilsPrefix)) {
|
|
3820
|
+
for (const importedName of entry.importedNames) {
|
|
3821
|
+
const key = `${entry.specifier}#${importedName}`;
|
|
3822
|
+
usages.set(key, (usages.get(key) ?? /* @__PURE__ */ new Set()).add(file));
|
|
3823
|
+
}
|
|
3824
|
+
if (entry.specifier === expected || entry.specifier.startsWith(`${expected}/`)) continue;
|
|
3825
|
+
importViolations.push({ file, entry, expected });
|
|
3826
|
+
}
|
|
3827
|
+
}
|
|
3828
|
+
for (const { file, entry, expected } of importViolations) {
|
|
3829
|
+
violations.push(
|
|
3830
|
+
` - ${at(file, entry.line)} \u5BFC\u5165 '${entry.specifier}'\uFF0C\u5165\u53E3\u53EA\u80FD\u5BFC\u5165 ${expected}/... \u6216 ./${sharedName}/...`
|
|
3831
|
+
);
|
|
3832
|
+
for (const importedName of entry.importedNames) {
|
|
3833
|
+
const count = usages.get(`${entry.specifier}#${importedName}`)?.size ?? 0;
|
|
3834
|
+
violations.push(
|
|
3835
|
+
count >= threshold ? ` ${importedName} \u5DF2\u88AB ${count} \u4E2A\u5165\u53E3\u4F7F\u7528\uFF0C\u5EFA\u8BAE\u79FB\u5230 ${sharedName}\u3002` : ` ${importedName} \u88AB ${count} \u4E2A\u5165\u53E3\u4F7F\u7528\uFF0C\u5EFA\u8BAE\u5728\u5404\u5165\u53E3\u7684 ${utilsName} \u76EE\u5F55\u5206\u522B\u5B9E\u73B0\u3002`
|
|
3836
|
+
);
|
|
3837
|
+
}
|
|
3838
|
+
}
|
|
3839
|
+
const helperFiles = [...await collectFiles(sharedRoot), ...await collectFiles(utilsRoot)];
|
|
3840
|
+
for (const file of helperFiles) {
|
|
3841
|
+
const fromArea = isInsidePath2(file, sharedRoot) ? sharedName : utilsName;
|
|
3842
|
+
const source = await parseSourceFile3(file);
|
|
3843
|
+
for (const node of source.program.body) {
|
|
3844
|
+
const specifier = readModuleSpecifier(node);
|
|
3845
|
+
if (!specifier?.startsWith(".")) continue;
|
|
3846
|
+
const target = path34.resolve(path34.dirname(file), specifier);
|
|
3847
|
+
const toArea = isInsidePath2(target, sharedRoot) ? sharedName : isInsidePath2(target, utilsRoot) ? utilsName : void 0;
|
|
3848
|
+
if (!toArea || toArea === fromArea) continue;
|
|
3849
|
+
violations.push(
|
|
3850
|
+
` - ${at(file, lineOf2(source, node))} ${fromArea} \u4E0D\u80FD\u5F15\u7528 ${toArea} '${specifier}'`
|
|
3851
|
+
);
|
|
3852
|
+
}
|
|
3853
|
+
}
|
|
3854
|
+
const rules = [
|
|
3855
|
+
"\u5165\u53E3\u6587\u4EF6\u5185\u4E0D\u5B9A\u4E49\u8F85\u52A9\u51FD\u6570",
|
|
3856
|
+
`\u5165\u53E3\u53EA\u80FD\u5BFC\u5165 ${utilsPrefix}<\u5165\u53E3\u540D> \u6216 ./${sharedName}`,
|
|
3857
|
+
`${sharedName} \u4E0E ${utilsName} \u4E92\u4E0D\u5F15\u7528`,
|
|
3858
|
+
strictRoot ? `\u6839\u76EE\u5F55\u53EA\u653E\u5165\u53E3\u4E0E ${sharedName}/${utilsName}` : void 0
|
|
3859
|
+
].filter(Boolean);
|
|
3860
|
+
const lines = [
|
|
3861
|
+
`\u626B\u63CF ${path34.relative(repoRoot, root)} \u4E0B ${entryFiles.length} \u4E2A\u5165\u53E3\u3002`,
|
|
3862
|
+
`\u89C4\u5219\uFF1A${rules.join("\uFF1B")}\u3002`
|
|
3863
|
+
];
|
|
3864
|
+
const success = violations.length === 0;
|
|
3865
|
+
if (success) lines.push("\u672A\u53D1\u73B0\u7ED3\u6784\u8FDD\u89C4\u3002");
|
|
3866
|
+
else
|
|
3867
|
+
lines.push(
|
|
3868
|
+
`\u53D1\u73B0 ${violations.filter((line) => line.startsWith(" - ")).length} \u5904\u8FDD\u89C4\uFF1A`,
|
|
3869
|
+
...violations
|
|
3870
|
+
);
|
|
3871
|
+
return {
|
|
3872
|
+
name: ruleName,
|
|
3873
|
+
success,
|
|
3874
|
+
messages: lines.join("\n"),
|
|
3875
|
+
howToFix: success ? "" : `helper \u79FB\u51FA\u5165\u53E3\u6587\u4EF6\uFF1A\u88AB ${threshold} \u4E2A\u53CA\u4EE5\u4E0A\u5165\u53E3\u4F7F\u7528\u7684\u653E\u5230 ${sharedName}\uFF0C\u5176\u4F59\u653E\u5230 ${utilsName}/<\u5165\u53E3\u540D>\uFF1B${sharedName} \u4E0E ${utilsName} \u4E0D\u8981\u4E92\u76F8\u5F15\u7528\u3002`
|
|
3876
|
+
};
|
|
3877
|
+
}
|
|
3878
|
+
});
|
|
3879
|
+
function readFunctionName(node) {
|
|
3880
|
+
if (node.type === "FunctionDeclaration") return readName(node.id) ?? "\u533F\u540D\u51FD\u6570";
|
|
3881
|
+
if (node.type === "VariableDeclarator" && isFunctionLike(node.init)) {
|
|
3882
|
+
return readName(node.id) ?? "\u533F\u540D\u51FD\u6570";
|
|
3883
|
+
}
|
|
3884
|
+
return void 0;
|
|
3885
|
+
}
|
|
3886
|
+
function collectImports(source, prefix) {
|
|
3887
|
+
const imports = [];
|
|
3888
|
+
for (const node of source.program.body) {
|
|
3889
|
+
if (node.type !== "ImportDeclaration") continue;
|
|
3890
|
+
const specifier = readModuleSpecifier(node);
|
|
3891
|
+
if (!specifier?.startsWith(prefix)) continue;
|
|
3892
|
+
const importedNames = (node.specifiers ?? []).map(
|
|
3893
|
+
(item) => item.type === "ImportDefaultSpecifier" ? "default" : item.type === "ImportNamespaceSpecifier" ? "*" : readName(item.imported) ?? readName(item.local) ?? "anonymous"
|
|
3894
|
+
);
|
|
3895
|
+
imports.push({ specifier, importedNames, line: lineOf2(source, node) });
|
|
3896
|
+
}
|
|
3897
|
+
return imports;
|
|
3898
|
+
}
|
|
3899
|
+
async function collectFiles(root) {
|
|
3900
|
+
const files = [];
|
|
3901
|
+
const skipDirNames = new Set(DEFAULT_SKIP_DIR_NAMES);
|
|
3902
|
+
async function visit(dir) {
|
|
3903
|
+
const entries2 = await readDirIfExists2(dir);
|
|
3904
|
+
for (const entry of entries2 ?? []) {
|
|
3905
|
+
const full = path34.join(dir, entry.name);
|
|
3906
|
+
if (entry.isDirectory()) {
|
|
3907
|
+
if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
|
|
3908
|
+
await visit(full);
|
|
3909
|
+
continue;
|
|
3910
|
+
}
|
|
3911
|
+
if (entry.isFile() && [".ts", ".tsx"].some((extension) => full.endsWith(extension))) {
|
|
3912
|
+
files.push(full);
|
|
3913
|
+
}
|
|
3914
|
+
}
|
|
3915
|
+
}
|
|
3916
|
+
await visit(root);
|
|
3917
|
+
return files.sort((left, right) => left.localeCompare(right));
|
|
3918
|
+
}
|
|
3919
|
+
async function readDirIfExists2(dir) {
|
|
3920
|
+
try {
|
|
3921
|
+
return await fs3.readdir(dir, { withFileTypes: true });
|
|
3922
|
+
} catch (error) {
|
|
3923
|
+
if (error.code === "ENOENT") return void 0;
|
|
3924
|
+
throw error;
|
|
3925
|
+
}
|
|
3926
|
+
}
|
|
3927
|
+
function isInsidePath2(filePath, dir) {
|
|
3928
|
+
const relative = path34.relative(dir, filePath);
|
|
3929
|
+
return relative === "" || !relative.startsWith("..") && !path34.isAbsolute(relative);
|
|
3930
|
+
}
|
|
3931
|
+
function formatLocation(repoRoot, file, line) {
|
|
3932
|
+
return `${path34.relative(repoRoot, file)}:${line}`;
|
|
3933
|
+
}
|
|
3934
|
+
async function parseSourceFile3(file) {
|
|
3935
|
+
const code = await fs3.readFile(file, "utf8");
|
|
3936
|
+
const lineStarts = [0];
|
|
3937
|
+
for (let index = 0; index < code.length; index += 1) {
|
|
3938
|
+
if (code[index] === "\n") lineStarts.push(index + 1);
|
|
3939
|
+
}
|
|
3940
|
+
const parsed = parseSync3(file, code);
|
|
3941
|
+
if (parsed.errors.length)
|
|
3942
|
+
throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
|
|
3943
|
+
return { file, program: parsed.program, lineStarts };
|
|
3944
|
+
}
|
|
3945
|
+
function walk3(node, visit) {
|
|
3946
|
+
if (!node || typeof node !== "object") return;
|
|
3947
|
+
const current = node;
|
|
3948
|
+
if (typeof current.type === "string") visit(current);
|
|
3949
|
+
for (const key of Object.keys(current)) {
|
|
3950
|
+
if (SKIP_AST_KEYS3.has(key)) continue;
|
|
3951
|
+
const value = current[key];
|
|
3952
|
+
if (Array.isArray(value)) {
|
|
3953
|
+
for (const child of value) walk3(child, visit);
|
|
3954
|
+
} else if (value && typeof value === "object") {
|
|
3955
|
+
walk3(value, visit);
|
|
3956
|
+
}
|
|
3957
|
+
}
|
|
3958
|
+
}
|
|
3959
|
+
function lineOf2(source, node) {
|
|
3960
|
+
if (typeof node.start !== "number") return 0;
|
|
3961
|
+
let low = 0;
|
|
3962
|
+
let high = source.lineStarts.length - 1;
|
|
3963
|
+
while (low <= high) {
|
|
3964
|
+
const mid = Math.floor((low + high) / 2);
|
|
3965
|
+
if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
|
|
3966
|
+
else high = mid - 1;
|
|
3967
|
+
}
|
|
3968
|
+
return high + 1;
|
|
3969
|
+
}
|
|
3970
|
+
function readStringLiteral2(node) {
|
|
3971
|
+
if (!node) return void 0;
|
|
3972
|
+
if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") {
|
|
3973
|
+
return node.value;
|
|
3974
|
+
}
|
|
3975
|
+
return void 0;
|
|
3976
|
+
}
|
|
3977
|
+
function readName(node) {
|
|
3978
|
+
if (!node) return void 0;
|
|
3979
|
+
if (typeof node.name === "string") return node.name;
|
|
3980
|
+
if (typeof node.value === "string") return node.value;
|
|
3981
|
+
return void 0;
|
|
3982
|
+
}
|
|
3983
|
+
function isFunctionLike(node) {
|
|
3984
|
+
if (node && [
|
|
3985
|
+
"ParenthesizedExpression",
|
|
3986
|
+
"TSAsExpression",
|
|
3987
|
+
"TSSatisfiesExpression",
|
|
3988
|
+
"TSTypeAssertion",
|
|
3989
|
+
"TSNonNullExpression"
|
|
3990
|
+
].includes(node.type ?? "")) {
|
|
3991
|
+
return isFunctionLike(node.expression);
|
|
3992
|
+
}
|
|
3993
|
+
return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
|
|
3994
|
+
}
|
|
3995
|
+
function readModuleSpecifier(node) {
|
|
3996
|
+
if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
|
|
3997
|
+
return readStringLiteral2(node.source);
|
|
3998
|
+
}
|
|
3999
|
+
return void 0;
|
|
4000
|
+
}
|
|
4001
|
+
|
|
4002
|
+
// packages/conformance/rules/same-dir-import-only.ts
|
|
4003
|
+
import { promises as fs4 } from "node:fs";
|
|
4004
|
+
import path35 from "node:path";
|
|
4005
|
+
import { parseSync as parseSync4 } from "oxc-parser";
|
|
4006
|
+
import { z as z35 } from "zod";
|
|
4007
|
+
var optionsSchema6 = z35.object({
|
|
4008
|
+
scanRoot: z35.string().trim().min(1).describe("\u9012\u5F52\u626B\u63CF\u7684\u6E90\u7801\u76EE\u5F55\uFF0C\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9 projectRoot \u7684\u8DEF\u5F84\u3002"),
|
|
4009
|
+
excludeDirs: z35.array(z35.string()).readonly().default([]).describe("\u626B\u63CF\u65F6\u8DF3\u8FC7\u7684\u5B50\u76EE\u5F55\u53CA\u5176\u540E\u4EE3\uFF1B\u8DEF\u5F84\u76F8\u5BF9 projectRoot \u89E3\u6790\uFF0C\u4E5F\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u3002"),
|
|
4010
|
+
skipDirNames: z35.array(z35.string()).readonly().default(["node_modules", "dist", "coverage"]).describe("\u6309\u76EE\u5F55\u540D\u8DF3\u8FC7\uFF1B\u4F20\u5165\u65F6\u66FF\u6362\u9ED8\u8BA4\u5217\u8868\uFF0C\u9690\u85CF\u76EE\u5F55\u59CB\u7EC8\u8DF3\u8FC7\u3002"),
|
|
4011
|
+
marker: z35.string().trim().min(1).default("@import-scope same-dir").describe("\u6807\u8BB0\u5185\u90E8\u5B9E\u73B0\u7684\u6CE8\u91CA\u6587\u672C\uFF0C\u6CE8\u91CA\u53BB\u9664\u9996\u5C3E\u7A7A\u767D\u540E\u987B\u4E0E\u4E4B\u5B8C\u5168\u76F8\u540C\u3002"),
|
|
4012
|
+
aliases: z35.record(z35.string(), z35.string()).readonly().default({}).describe(
|
|
4013
|
+
'\u5BFC\u5165\u524D\u7F00\u5230\u76EE\u5F55\u7684\u6620\u5C04\uFF1B\u76EE\u5F55\u76F8\u5BF9 projectRoot \u89E3\u6790\uFF0C\u4E5F\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\uFF0C\u4F8B\u5982 `{ "@/": "src" }`\u3002'
|
|
4014
|
+
)
|
|
4015
|
+
});
|
|
4016
|
+
var SKIP_AST_KEYS4 = /* @__PURE__ */ new Set([
|
|
4017
|
+
"loc",
|
|
4018
|
+
"range",
|
|
4019
|
+
"start",
|
|
4020
|
+
"end",
|
|
4021
|
+
"parent",
|
|
4022
|
+
"leadingComments",
|
|
4023
|
+
"trailingComments"
|
|
4024
|
+
]);
|
|
4025
|
+
var SOURCE_EXTENSIONS = [".ts", ".tsx"];
|
|
4026
|
+
var ESM_SOURCE_EXTENSIONS = {
|
|
4027
|
+
".js": [".ts", ".tsx"],
|
|
4028
|
+
".jsx": [".tsx"]
|
|
4029
|
+
};
|
|
4030
|
+
var sameDirImportOnly = defineRule({
|
|
4031
|
+
id: "same-dir-import-only",
|
|
4032
|
+
displayName: "\u9650\u5236\u8DE8\u76EE\u5F55\u5F15\u7528",
|
|
4033
|
+
exportName: "sameDirImportOnly",
|
|
4034
|
+
summary: "\u4E3A\u5E26\u6307\u5B9A\u6CE8\u91CA\u7684\u5185\u90E8\u6587\u4EF6\u9650\u5236\u76F4\u63A5\u5F15\u7528\u8303\u56F4\uFF1A\u53EA\u6709\u540C\u4E00\u76EE\u5F55\u7684\u6587\u4EF6\u53EF\u4EE5\u5BFC\u5165\u6216\u8F6C\u5BFC\u51FA\u5B83\uFF0C\u5916\u90E8\u901A\u8FC7\u672A\u6807\u8BB0\u7684\u516C\u5F00\u5165\u53E3\u8BBF\u95EE\u3002",
|
|
4035
|
+
optionsSchema: optionsSchema6,
|
|
4036
|
+
examples: [{ options: { scanRoot: "src", aliases: { "@/": "src" } } }],
|
|
4037
|
+
notes: "\u68C0\u67E5 `.ts` / `.tsx` \u4E2D\u7684 `import`\u3001`export from` \u548C\u5B57\u7B26\u4E32\u5F62\u5F0F\u7684\u52A8\u6001 `import()`\uFF0C\u89E3\u6790\u76F8\u5BF9\u8DEF\u5F84\u3001\u5DF2\u914D\u7F6E\u524D\u7F00\u53CA\u76EE\u5F55 `index`\u3002\u626B\u63CF\u8303\u56F4\u4E4B\u5916\u7684\u76EE\u6807\u548C\u8BA1\u7B97\u8DEF\u5F84\u4E0D\u68C0\u67E5\u3002",
|
|
4038
|
+
async run(common, config) {
|
|
4039
|
+
const repoRoot = common.projectRoot;
|
|
4040
|
+
const aliases = Object.entries(config.aliases).sort(([a], [b]) => b.length - a.length).map(([prefix, target]) => [prefix, path35.resolve(repoRoot, target)]);
|
|
4041
|
+
const scanRoot = path35.resolve(repoRoot, config.scanRoot);
|
|
4042
|
+
const excludeDirs = config.excludeDirs.map((dir) => path35.resolve(repoRoot, dir));
|
|
4043
|
+
const files = await collectSourceFiles2(scanRoot, excludeDirs, config.skipDirNames);
|
|
4044
|
+
const sourceFiles = await Promise.all(files.map(parseSourceFile4));
|
|
4045
|
+
const sourceFileSet = new Set(sourceFiles.map((item) => item.file));
|
|
4046
|
+
const protectedFiles = new Set(
|
|
4047
|
+
sourceFiles.filter((file) => hasSameDirMarker(file, config.marker)).map((sourceFile) => sourceFile.file)
|
|
4048
|
+
);
|
|
4049
|
+
const violations = [];
|
|
4050
|
+
for (const sourceFile of sourceFiles) {
|
|
4051
|
+
for (const importEntry of collectImportEntries(sourceFile)) {
|
|
4052
|
+
const target = resolveImportTarget(
|
|
4053
|
+
importEntry.importer,
|
|
4054
|
+
importEntry.specifier,
|
|
4055
|
+
aliases,
|
|
4056
|
+
sourceFileSet
|
|
4057
|
+
);
|
|
4058
|
+
if (!target) continue;
|
|
4059
|
+
if (!protectedFiles.has(target)) continue;
|
|
4060
|
+
if (path35.dirname(importEntry.importer) === path35.dirname(target)) continue;
|
|
4061
|
+
violations.push({
|
|
4062
|
+
importer: importEntry.importer,
|
|
4063
|
+
target,
|
|
4064
|
+
specifier: importEntry.specifier,
|
|
4065
|
+
location: importEntry.location
|
|
4066
|
+
});
|
|
4067
|
+
}
|
|
4068
|
+
}
|
|
4069
|
+
const lines = [
|
|
4070
|
+
`Scanned ${files.length} file(s) for files marked with '${config.marker}'.`,
|
|
4071
|
+
`Protected files: ${protectedFiles.size}`
|
|
4072
|
+
];
|
|
4073
|
+
if (violations.length === 0) {
|
|
4074
|
+
lines.push("No cross-directory imports of protected files found.");
|
|
4075
|
+
return {
|
|
4076
|
+
name: "same-dir-import-only",
|
|
4077
|
+
success: true,
|
|
4078
|
+
messages: lines.join("\n"),
|
|
4079
|
+
howToFix: ""
|
|
4080
|
+
};
|
|
4081
|
+
}
|
|
4082
|
+
lines.push(`Found ${violations.length} cross-directory import(s) of protected files:`);
|
|
4083
|
+
for (const violation of violations) {
|
|
4084
|
+
lines.push(
|
|
4085
|
+
` - ${relativeLocation2(repoRoot, violation.location)} imports '${violation.specifier}'`
|
|
4086
|
+
);
|
|
4087
|
+
lines.push(` protected file: ${path35.relative(repoRoot, violation.target)}`);
|
|
4088
|
+
}
|
|
4089
|
+
return {
|
|
4090
|
+
name: "same-dir-import-only",
|
|
4091
|
+
success: false,
|
|
4092
|
+
messages: lines.join("\n"),
|
|
4093
|
+
howToFix: `Only import files marked with '${config.marker}' from files in the same directory, or move shared API into an unmarked file.`
|
|
4094
|
+
};
|
|
4095
|
+
}
|
|
4096
|
+
});
|
|
4097
|
+
async function collectSourceFiles2(root, excludeDirs, skipDirNames) {
|
|
4098
|
+
const out = [];
|
|
4099
|
+
const resolvedExcludeDirs = excludeDirs.map((item) => path35.resolve(item));
|
|
4100
|
+
async function visit(dir) {
|
|
4101
|
+
const entries2 = await fs4.readdir(dir, { withFileTypes: true });
|
|
4102
|
+
for (const entry of entries2) {
|
|
4103
|
+
const full = path35.join(dir, entry.name);
|
|
4104
|
+
if (entry.isDirectory()) {
|
|
4105
|
+
if (entry.name.startsWith(".")) continue;
|
|
4106
|
+
if (skipDirNames.includes(entry.name)) continue;
|
|
4107
|
+
if (isExcluded2(full, resolvedExcludeDirs)) continue;
|
|
4108
|
+
await visit(full);
|
|
4109
|
+
continue;
|
|
4110
|
+
}
|
|
4111
|
+
if (!entry.isFile()) continue;
|
|
4112
|
+
if (!SOURCE_EXTENSIONS.some((extension) => full.endsWith(extension))) continue;
|
|
4113
|
+
out.push(full);
|
|
4114
|
+
}
|
|
4115
|
+
}
|
|
4116
|
+
await visit(root);
|
|
4117
|
+
return out.sort();
|
|
4118
|
+
}
|
|
4119
|
+
async function parseSourceFile4(file) {
|
|
4120
|
+
const code = await fs4.readFile(file, "utf8");
|
|
4121
|
+
const ast = parseSync4(file, code);
|
|
4122
|
+
if (ast.errors.length)
|
|
4123
|
+
throw new Error(`${file}: ${ast.errors.map((error) => error.message).join("; ")}`);
|
|
4124
|
+
return {
|
|
4125
|
+
file,
|
|
4126
|
+
ast,
|
|
4127
|
+
lineStarts: collectLineStarts2(code)
|
|
4128
|
+
};
|
|
4129
|
+
}
|
|
4130
|
+
function hasSameDirMarker(sourceFile, marker) {
|
|
4131
|
+
return sourceFile.ast.comments.some((comment) => comment.value.trim() === marker);
|
|
4132
|
+
}
|
|
4133
|
+
function collectImportEntries(sourceFile) {
|
|
4134
|
+
const imports = [];
|
|
4135
|
+
walk4(sourceFile.ast.program, (node) => {
|
|
4136
|
+
const specifier = readImportSpecifier2(node);
|
|
4137
|
+
if (!specifier) return;
|
|
4138
|
+
imports.push({
|
|
4139
|
+
importer: sourceFile.file,
|
|
4140
|
+
specifier,
|
|
4141
|
+
location: locationFor2(sourceFile.file, node, sourceFile.lineStarts)
|
|
4142
|
+
});
|
|
4143
|
+
});
|
|
4144
|
+
return imports;
|
|
4145
|
+
}
|
|
4146
|
+
function readImportSpecifier2(node) {
|
|
4147
|
+
if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ImportExpression") {
|
|
4148
|
+
return readStringLiteral3(node.source);
|
|
4149
|
+
}
|
|
4150
|
+
return void 0;
|
|
4151
|
+
}
|
|
4152
|
+
function resolveImportTarget(importer, specifier, aliases, sourceFileSet) {
|
|
4153
|
+
const base = resolveImportBase(importer, specifier, aliases);
|
|
4154
|
+
if (!base) return void 0;
|
|
4155
|
+
const candidates = buildImportCandidates(base);
|
|
4156
|
+
return candidates.find((candidate) => sourceFileSet.has(candidate));
|
|
4157
|
+
}
|
|
4158
|
+
function resolveImportBase(importer, specifier, aliases) {
|
|
4159
|
+
if (specifier.startsWith("./") || specifier.startsWith("../")) {
|
|
4160
|
+
return path35.resolve(path35.dirname(importer), specifier);
|
|
4161
|
+
}
|
|
4162
|
+
for (const [prefix, root] of aliases) {
|
|
4163
|
+
if (specifier.startsWith(prefix)) return path35.resolve(root, specifier.slice(prefix.length));
|
|
4164
|
+
}
|
|
4165
|
+
return void 0;
|
|
4166
|
+
}
|
|
4167
|
+
function buildImportCandidates(base) {
|
|
4168
|
+
const extension = path35.extname(base);
|
|
4169
|
+
if (SOURCE_EXTENSIONS.includes(extension)) {
|
|
4170
|
+
return [base];
|
|
4171
|
+
}
|
|
4172
|
+
const candidates = (ESM_SOURCE_EXTENSIONS[extension] ?? []).map(
|
|
4173
|
+
(sourceExtension) => `${base.slice(0, -extension.length)}${sourceExtension}`
|
|
4174
|
+
);
|
|
4175
|
+
candidates.push(...SOURCE_EXTENSIONS.map((sourceExtension) => `${base}${sourceExtension}`));
|
|
4176
|
+
for (const sourceExtension of SOURCE_EXTENSIONS) {
|
|
4177
|
+
candidates.push(path35.join(base, `index${sourceExtension}`));
|
|
4178
|
+
}
|
|
4179
|
+
return candidates;
|
|
4180
|
+
}
|
|
4181
|
+
function walk4(node, visit) {
|
|
4182
|
+
if (!node || typeof node !== "object") return;
|
|
4183
|
+
const current = node;
|
|
4184
|
+
if (typeof current.type === "string") visit(current);
|
|
4185
|
+
for (const key of Object.keys(current)) {
|
|
4186
|
+
if (SKIP_AST_KEYS4.has(key)) continue;
|
|
4187
|
+
const value = current[key];
|
|
4188
|
+
if (Array.isArray(value)) {
|
|
4189
|
+
for (const child of value) walk4(child, visit);
|
|
4190
|
+
} else if (value && typeof value === "object") {
|
|
4191
|
+
walk4(value, visit);
|
|
4192
|
+
}
|
|
4193
|
+
}
|
|
4194
|
+
}
|
|
4195
|
+
function readStringLiteral3(node) {
|
|
4196
|
+
if (!node) return void 0;
|
|
4197
|
+
if (node.type === "Literal" && typeof node.value === "string") return node.value;
|
|
4198
|
+
if (node.type === "StringLiteral" && typeof node.value === "string") return node.value;
|
|
4199
|
+
return void 0;
|
|
4200
|
+
}
|
|
4201
|
+
function collectLineStarts2(code) {
|
|
4202
|
+
const starts = [0];
|
|
4203
|
+
for (let index = 0; index < code.length; index += 1) {
|
|
4204
|
+
if (code[index] === "\n") starts.push(index + 1);
|
|
4205
|
+
}
|
|
4206
|
+
return starts;
|
|
4207
|
+
}
|
|
4208
|
+
function locationFor2(file, node, lineStarts) {
|
|
4209
|
+
if (node.loc?.start.line) return `${file}:${node.loc.start.line}`;
|
|
4210
|
+
if (typeof node.start !== "number") return `${file}:0`;
|
|
4211
|
+
return `${file}:${lineForOffset(node.start, lineStarts)}`;
|
|
4212
|
+
}
|
|
4213
|
+
function lineForOffset(offset, lineStarts) {
|
|
4214
|
+
let low = 0;
|
|
4215
|
+
let high = lineStarts.length - 1;
|
|
4216
|
+
while (low <= high) {
|
|
4217
|
+
const mid = Math.floor((low + high) / 2);
|
|
4218
|
+
if (lineStarts[mid] <= offset) {
|
|
4219
|
+
low = mid + 1;
|
|
4220
|
+
} else {
|
|
4221
|
+
high = mid - 1;
|
|
4222
|
+
}
|
|
4223
|
+
}
|
|
4224
|
+
return high + 1;
|
|
4225
|
+
}
|
|
4226
|
+
function relativeLocation2(repoRoot, location) {
|
|
4227
|
+
const index = location.lastIndexOf(":");
|
|
4228
|
+
if (index === -1) return path35.relative(repoRoot, location);
|
|
4229
|
+
const file = location.slice(0, index);
|
|
4230
|
+
const line = location.slice(index + 1);
|
|
4231
|
+
return `${path35.relative(repoRoot, file)}:${line}`;
|
|
4232
|
+
}
|
|
4233
|
+
function isExcluded2(filePath, excludeDirs) {
|
|
4234
|
+
return excludeDirs.some((dir) => filePath === dir || filePath.startsWith(dir + path35.sep));
|
|
4235
|
+
}
|
|
4236
|
+
|
|
4237
|
+
// packages/conformance/rules/single-component-file.ts
|
|
4238
|
+
import { promises as fs5 } from "node:fs";
|
|
4239
|
+
import path36 from "node:path";
|
|
4240
|
+
import { parseSync as parseSync5 } from "oxc-parser";
|
|
4241
|
+
import { z as z36 } from "zod";
|
|
4242
|
+
var optionsSchema7 = z36.object({
|
|
4243
|
+
scanRoot: z36.string().trim().min(1).describe("\u9012\u5F52\u626B\u63CF\u7684\u6E90\u7801\u76EE\u5F55\uFF0C\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9 projectRoot \u7684\u8DEF\u5F84\u3002"),
|
|
4244
|
+
excludeDirs: z36.array(z36.string()).readonly().default([]).describe("\u626B\u63CF\u65F6\u8DF3\u8FC7\u7684\u5B50\u76EE\u5F55\u53CA\u5176\u540E\u4EE3\uFF1B\u8DEF\u5F84\u76F8\u5BF9 projectRoot \u89E3\u6790\uFF0C\u4E5F\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u3002"),
|
|
4245
|
+
skipDirNames: z36.array(z36.string()).readonly().default(["node_modules", "dist", "coverage"]).describe("\u6309\u76EE\u5F55\u540D\u8DF3\u8FC7\uFF1B\u4F20\u5165\u65F6\u66FF\u6362\u9ED8\u8BA4\u5217\u8868\uFF0C\u9690\u85CF\u76EE\u5F55\u59CB\u7EC8\u8DF3\u8FC7\u3002"),
|
|
4246
|
+
componentWrappers: z36.array(z36.string().trim().min(1)).readonly().default(["memo", "forwardRef"]).describe("\u8BC6\u522B\u7EC4\u4EF6\u65F6\u4F7F\u7528\u7684\u9AD8\u9636\u51FD\u6570\u540D\uFF1B\u4F20\u5165\u65F6\u66FF\u6362\u9ED8\u8BA4\u5217\u8868\uFF0C\u76F4\u63A5\u51FD\u6570\u548C\u7C7B\u7EC4\u4EF6\u4ECD\u4F1A\u68C0\u67E5\u3002")
|
|
4247
|
+
});
|
|
4248
|
+
var SKIP_AST_KEYS5 = /* @__PURE__ */ new Set([
|
|
4249
|
+
"loc",
|
|
4250
|
+
"range",
|
|
4251
|
+
"start",
|
|
4252
|
+
"end",
|
|
4253
|
+
"parent",
|
|
4254
|
+
"leadingComments",
|
|
4255
|
+
"trailingComments"
|
|
4256
|
+
]);
|
|
4257
|
+
var singleComponentFile = defineRule({
|
|
4258
|
+
id: "single-component-file",
|
|
4259
|
+
displayName: "\u5355\u6587\u4EF6\u5355\u7EC4\u4EF6",
|
|
4260
|
+
exportName: "singleComponentFile",
|
|
4261
|
+
summary: "\u6BCF\u4E2A TSX \u6587\u4EF6\u6700\u591A\u5B9A\u4E49\u4E00\u4E2A\u7EC4\u4EF6\uFF0C\u907F\u514D\u540C\u4E00\u6587\u4EF6\u9690\u85CF\u591A\u4E2A\u7EC4\u4EF6\u6216 JSX \u6E32\u67D3\u51FD\u6570\u3002",
|
|
4262
|
+
optionsSchema: optionsSchema7,
|
|
4263
|
+
examples: [{ options: { scanRoot: "src" } }],
|
|
4264
|
+
notes: "\u51FD\u6570\u3001\u7C7B\u3001\u533F\u540D\u9ED8\u8BA4\u5BFC\u51FA\u53CA\u9AD8\u9636\u51FD\u6570\u5185\u8FD4\u56DE JSX \u7684\u51FD\u6570\u8BA1\u4E3A\u7EC4\u4EF6\uFF0C\u540C\u540D\u5B9A\u4E49\u53EA\u8BA1\u4E00\u6B21\u3002",
|
|
4265
|
+
async run(context, options) {
|
|
4266
|
+
const wrappers = new Set(options.componentWrappers);
|
|
4267
|
+
const files = await collectFiles2(context.projectRoot, options, [".tsx"]);
|
|
4268
|
+
const findings = [];
|
|
4269
|
+
for (const file of files) {
|
|
4270
|
+
const source = await parseSourceFile5(file);
|
|
4271
|
+
const components = /* @__PURE__ */ new Map();
|
|
4272
|
+
walk5(source.program, (node) => {
|
|
4273
|
+
const name = readComponentName(node, wrappers);
|
|
4274
|
+
if (name && !components.has(name)) components.set(name, lineOf3(source, node));
|
|
4275
|
+
});
|
|
4276
|
+
if (components.size <= 1) continue;
|
|
4277
|
+
findings.push(` - ${path36.relative(context.projectRoot, file)}`);
|
|
4278
|
+
for (const [name, line] of components) {
|
|
4279
|
+
findings.push(` ${name} \u4F4D\u4E8E ${formatLocation2(context.projectRoot, file, line)}`);
|
|
4280
|
+
}
|
|
4281
|
+
}
|
|
4282
|
+
const lines = [`\u626B\u63CF ${files.length} \u4E2A TSX \u6587\u4EF6\u3002`];
|
|
4283
|
+
if (findings.length === 0) {
|
|
4284
|
+
lines.push("\u672A\u53D1\u73B0\u5305\u542B\u591A\u4E2A\u7EC4\u4EF6\u7684 TSX \u6587\u4EF6\u3002");
|
|
4285
|
+
return {
|
|
4286
|
+
name: "single-component-file",
|
|
4287
|
+
success: true,
|
|
4288
|
+
messages: lines.join("\n"),
|
|
4289
|
+
howToFix: ""
|
|
4290
|
+
};
|
|
4291
|
+
}
|
|
4292
|
+
lines.push("\u4EE5\u4E0B TSX \u6587\u4EF6\u5305\u542B\u591A\u4E2A\u7EC4\u4EF6\uFF1A", ...findings);
|
|
4293
|
+
return {
|
|
4294
|
+
name: "single-component-file",
|
|
4295
|
+
success: false,
|
|
4296
|
+
messages: lines.join("\n"),
|
|
4297
|
+
howToFix: "\u628A\u591A\u51FA\u7684\u7EC4\u4EF6\u79FB\u5230\u5404\u81EA\u7684 TSX \u6587\u4EF6\uFF0C\u6BCF\u4E2A\u6587\u4EF6\u53EA\u4FDD\u7559\u4E00\u4E2A\u7EC4\u4EF6\u3002"
|
|
4298
|
+
};
|
|
4299
|
+
}
|
|
4300
|
+
});
|
|
4301
|
+
function readComponentName(node, wrappers) {
|
|
4302
|
+
if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
|
|
4303
|
+
const name = readName2(node.id);
|
|
4304
|
+
return name && containsJsx(node.body) ? name : void 0;
|
|
4305
|
+
}
|
|
4306
|
+
if (node.type === "VariableDeclarator") {
|
|
4307
|
+
const name = readName2(node.id);
|
|
4308
|
+
return name && isComponentInitializer(node.init, wrappers) ? name : void 0;
|
|
4309
|
+
}
|
|
4310
|
+
if (node.type === "ExportDefaultDeclaration") {
|
|
4311
|
+
const declaration = node.declaration;
|
|
4312
|
+
if (!declaration || readName2(declaration.id)) return void 0;
|
|
4313
|
+
const isComponent = (isFunctionLike2(declaration) || declaration.type === "ClassDeclaration") && containsJsx(declaration) || isComponentInitializer(declaration, wrappers);
|
|
4314
|
+
return isComponent ? "default export" : void 0;
|
|
4315
|
+
}
|
|
4316
|
+
return void 0;
|
|
4317
|
+
}
|
|
4318
|
+
function isComponentInitializer(node, wrappers) {
|
|
4319
|
+
if (!node) return false;
|
|
4320
|
+
if (isFunctionLike2(node)) return containsJsx(node.body);
|
|
4321
|
+
if (node.type !== "CallExpression" && node.type !== "NewExpression") return false;
|
|
4322
|
+
const callee = node.callee;
|
|
4323
|
+
const calleeName = callee?.type === "Identifier" ? callee.name : readName2(callee?.property);
|
|
4324
|
+
if (!calleeName || !wrappers.has(calleeName)) return false;
|
|
4325
|
+
return (node.arguments ?? []).some(
|
|
4326
|
+
(argument) => isFunctionLike2(argument) && containsJsx(argument.body)
|
|
4327
|
+
);
|
|
4328
|
+
}
|
|
4329
|
+
async function collectFiles2(repoRoot, options, extensions) {
|
|
4330
|
+
const files = [];
|
|
4331
|
+
const excludeDirs = options.excludeDirs.map((dir) => path36.resolve(repoRoot, dir));
|
|
4332
|
+
const skipDirNames = new Set(options.skipDirNames);
|
|
4333
|
+
async function visit(dir) {
|
|
4334
|
+
const entries2 = await readDirIfExists3(dir);
|
|
4335
|
+
for (const entry of entries2 ?? []) {
|
|
4336
|
+
const full = path36.join(dir, entry.name);
|
|
4337
|
+
if (entry.isDirectory()) {
|
|
4338
|
+
if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
|
|
4339
|
+
if (excludeDirs.some((excluded) => isInsidePath3(full, excluded))) continue;
|
|
4340
|
+
await visit(full);
|
|
4341
|
+
continue;
|
|
4342
|
+
}
|
|
4343
|
+
if (entry.isFile() && extensions.some((extension) => full.endsWith(extension))) {
|
|
4344
|
+
files.push(full);
|
|
4345
|
+
}
|
|
4346
|
+
}
|
|
4347
|
+
}
|
|
4348
|
+
const scanRoot = path36.resolve(repoRoot, options.scanRoot);
|
|
4349
|
+
await fs5.access(scanRoot);
|
|
4350
|
+
await visit(scanRoot);
|
|
4351
|
+
return files.sort((left, right) => left.localeCompare(right));
|
|
4352
|
+
}
|
|
4353
|
+
async function readDirIfExists3(dir) {
|
|
4354
|
+
try {
|
|
4355
|
+
return await fs5.readdir(dir, { withFileTypes: true });
|
|
4356
|
+
} catch (error) {
|
|
4357
|
+
if (error.code === "ENOENT") return void 0;
|
|
4358
|
+
throw error;
|
|
4359
|
+
}
|
|
4360
|
+
}
|
|
4361
|
+
function isInsidePath3(filePath, dir) {
|
|
4362
|
+
const relative = path36.relative(dir, filePath);
|
|
4363
|
+
return relative === "" || !relative.startsWith("..") && !path36.isAbsolute(relative);
|
|
4364
|
+
}
|
|
4365
|
+
function formatLocation2(repoRoot, file, line) {
|
|
4366
|
+
return `${path36.relative(repoRoot, file)}:${line}`;
|
|
4367
|
+
}
|
|
4368
|
+
async function parseSourceFile5(file) {
|
|
4369
|
+
const code = await fs5.readFile(file, "utf8");
|
|
4370
|
+
const lineStarts = [0];
|
|
4371
|
+
for (let index = 0; index < code.length; index += 1) {
|
|
4372
|
+
if (code[index] === "\n") lineStarts.push(index + 1);
|
|
4373
|
+
}
|
|
4374
|
+
const parsed = parseSync5(file, code);
|
|
4375
|
+
if (parsed.errors.length)
|
|
4376
|
+
throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
|
|
4377
|
+
return { file, program: parsed.program, lineStarts };
|
|
4378
|
+
}
|
|
4379
|
+
function walk5(node, visit) {
|
|
4380
|
+
if (!node || typeof node !== "object") return;
|
|
4381
|
+
const current = node;
|
|
4382
|
+
if (typeof current.type === "string") visit(current);
|
|
4383
|
+
for (const key of Object.keys(current)) {
|
|
4384
|
+
if (SKIP_AST_KEYS5.has(key)) continue;
|
|
4385
|
+
const value = current[key];
|
|
4386
|
+
if (Array.isArray(value)) {
|
|
4387
|
+
for (const child of value) walk5(child, visit);
|
|
4388
|
+
} else if (value && typeof value === "object") {
|
|
4389
|
+
walk5(value, visit);
|
|
4390
|
+
}
|
|
4391
|
+
}
|
|
4392
|
+
}
|
|
4393
|
+
function lineOf3(source, node) {
|
|
4394
|
+
if (typeof node.start !== "number") return 0;
|
|
4395
|
+
let low = 0;
|
|
4396
|
+
let high = source.lineStarts.length - 1;
|
|
4397
|
+
while (low <= high) {
|
|
4398
|
+
const mid = Math.floor((low + high) / 2);
|
|
4399
|
+
if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
|
|
4400
|
+
else high = mid - 1;
|
|
4401
|
+
}
|
|
4402
|
+
return high + 1;
|
|
4403
|
+
}
|
|
4404
|
+
function readName2(node) {
|
|
4405
|
+
if (!node) return void 0;
|
|
4406
|
+
if (typeof node.name === "string") return node.name;
|
|
4407
|
+
if (typeof node.value === "string") return node.value;
|
|
4408
|
+
return void 0;
|
|
4409
|
+
}
|
|
4410
|
+
function isFunctionLike2(node) {
|
|
4411
|
+
return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
|
|
4412
|
+
}
|
|
4413
|
+
function containsJsx(node) {
|
|
4414
|
+
let found = false;
|
|
4415
|
+
walk5(node, (current) => {
|
|
4416
|
+
if (current.type === "JSXElement" || current.type === "JSXFragment") found = true;
|
|
4417
|
+
});
|
|
4418
|
+
return found;
|
|
4419
|
+
}
|
|
4420
|
+
|
|
4421
|
+
// packages/conformance/rules/source-locale-defaults.ts
|
|
4422
|
+
import { promises as fs6 } from "node:fs";
|
|
4423
|
+
import path37 from "node:path";
|
|
4424
|
+
import { parseSync as parseSync6 } from "oxc-parser";
|
|
4425
|
+
import { z as z37 } from "zod";
|
|
4426
|
+
var localizationCallSchema = z37.object({
|
|
4427
|
+
name: z37.string().trim().min(1).describe("\u51FD\u6570\u540D\uFF0C\u4F8B\u5982 localize\u3002"),
|
|
4428
|
+
valueArgument: z37.number().int().nonnegative().describe("\u9ED8\u8BA4\u6587\u6848\u6240\u5728\u7684\u53C2\u6570\u4F4D\u7F6E\uFF0C\u4ECE 0 \u5F00\u59CB\u3002"),
|
|
4429
|
+
member: z37.boolean().default(false).describe("\u662F\u5426\u540C\u65F6\u5339\u914D\u6210\u5458\u8C03\u7528\uFF0C\u4F8B\u5982 nls.format()\uFF1B\u9ED8\u8BA4\u53EA\u5339\u914D\u76F4\u63A5\u8C03\u7528\u3002")
|
|
4430
|
+
}).meta({ tsType: "LocalizationCall" });
|
|
4431
|
+
var optionsSchema8 = z37.object({
|
|
4432
|
+
scanRoot: z37.string().trim().min(1).describe("\u9012\u5F52\u626B\u63CF\u7684\u6E90\u7801\u76EE\u5F55\uFF0C\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9 projectRoot \u7684\u8DEF\u5F84\u3002"),
|
|
4433
|
+
excludeDirs: z37.array(z37.string()).readonly().default([]).describe("\u626B\u63CF\u65F6\u8DF3\u8FC7\u7684\u5B50\u76EE\u5F55\u53CA\u5176\u540E\u4EE3\uFF1B\u8DEF\u5F84\u76F8\u5BF9 projectRoot \u89E3\u6790\uFF0C\u4E5F\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u3002"),
|
|
4434
|
+
skipDirNames: z37.array(z37.string()).readonly().default(["node_modules", "dist", "coverage"]).describe("\u6309\u76EE\u5F55\u540D\u8DF3\u8FC7\uFF1B\u4F20\u5165\u65F6\u66FF\u6362\u9ED8\u8BA4\u5217\u8868\uFF0C\u9690\u85CF\u76EE\u5F55\u59CB\u7EC8\u8DF3\u8FC7\u3002"),
|
|
4435
|
+
calls: z37.array(localizationCallSchema).readonly().describe(
|
|
4436
|
+
"\u9700\u8981\u68C0\u67E5\u7684\u672C\u5730\u5316\u8C03\u7528\u5217\u8868\uFF1B\u53EA\u68C0\u67E5\u6307\u5B9A\u53C2\u6570\u4E2D\u7684\u5B57\u7B26\u4E32\u5B57\u9762\u91CF\uFF0C\u7A7A\u6570\u7EC4\u8868\u793A\u4E0D\u5339\u914D\u4EFB\u4F55\u8C03\u7528\u3002"
|
|
4437
|
+
),
|
|
4438
|
+
pattern: z37.instanceof(RegExp).meta({ tsType: "RegExp" }).describe(
|
|
4439
|
+
"\u5339\u914D\u5373\u5224\u4E3A\u8FDD\u89C4\u7684\u6B63\u5219\u8868\u8FBE\u5F0F\uFF0C\u4F8B\u5982 CJK_PATTERN\uFF1B\u6BCF\u6B21\u5339\u914D\u72EC\u7ACB\u6267\u884C\uFF0C\u4E0D\u6539\u53D8\u4F20\u5165\u6B63\u5219\u7684\u72B6\u6001\u3002"
|
|
4440
|
+
)
|
|
4441
|
+
});
|
|
4442
|
+
var SKIP_AST_KEYS6 = /* @__PURE__ */ new Set([
|
|
4443
|
+
"loc",
|
|
4444
|
+
"range",
|
|
4445
|
+
"start",
|
|
4446
|
+
"end",
|
|
4447
|
+
"parent",
|
|
4448
|
+
"leadingComments",
|
|
4449
|
+
"trailingComments"
|
|
4450
|
+
]);
|
|
4451
|
+
var sourceLocaleDefaults = defineRule({
|
|
4452
|
+
id: "source-locale-defaults",
|
|
4453
|
+
displayName: "\u68C0\u67E5\u6E90\u8BED\u8A00\u9ED8\u8BA4\u6587\u6848",
|
|
4454
|
+
exportName: "sourceLocaleDefaults",
|
|
4455
|
+
summary: "\u68C0\u67E5\u672C\u5730\u5316\u9ED8\u8BA4\u6587\u6848\u662F\u5426\u5305\u542B\u6307\u5B9A\u7981\u6B62\u5B57\u7B26\uFF0C\u4FBF\u4E8E\u8981\u6C42\u6E90\u7801\u4F7F\u7528\u6E90\u8BED\u8A00\u3001\u7FFB\u8BD1\u5B58\u653E\u5728\u8BED\u8A00\u6587\u4EF6\u4E2D\u3002",
|
|
4456
|
+
optionsSchema: optionsSchema8,
|
|
4457
|
+
examples: [
|
|
4458
|
+
{
|
|
4459
|
+
options: {
|
|
4460
|
+
scanRoot: "src",
|
|
4461
|
+
calls: [{ name: "localize", valueArgument: 1 }],
|
|
4462
|
+
pattern: /[\u4e00-\u9fff]/
|
|
4463
|
+
}
|
|
4464
|
+
}
|
|
4465
|
+
],
|
|
4466
|
+
notes: "`CJK_PATTERN` \u5339\u914D\u6C49\u5B57\u3001CJK \u6807\u70B9\u53CA\u5168\u89D2\u5B57\u7B26\uFF0C\u4E0D\u662F\u5B8C\u6574\u7684\u4E2D\u65E5\u97E9\u6587\u5B57\u68C0\u6D4B\u3002",
|
|
4467
|
+
async run(context, options) {
|
|
4468
|
+
const files = await collectFiles3(context.projectRoot, options, [".ts", ".tsx"]);
|
|
4469
|
+
const findings = [];
|
|
4470
|
+
for (const file of files) {
|
|
4471
|
+
const source = await parseSourceFile6(file);
|
|
4472
|
+
walk6(source.program, (node) => {
|
|
4473
|
+
if (node.type !== "CallExpression") return;
|
|
4474
|
+
const call = matchCall(options.calls, node.callee);
|
|
4475
|
+
if (!call) return;
|
|
4476
|
+
const value = readStringLiteral4(node.arguments?.[call.valueArgument]);
|
|
4477
|
+
if (value === void 0 || !new RegExp(options.pattern.source, options.pattern.flags).test(value))
|
|
4478
|
+
return;
|
|
4479
|
+
findings.push(
|
|
4480
|
+
` - ${call.name}() \u6587\u6848 '${value}' \u4F4D\u4E8E ${formatLocation3(context.projectRoot, file, lineOf4(source, node))}`
|
|
4481
|
+
);
|
|
4482
|
+
});
|
|
4483
|
+
}
|
|
4484
|
+
const names = options.calls.map((call) => `${call.name}()`).join("\u3001");
|
|
4485
|
+
const lines = [`\u626B\u63CF ${files.length} \u4E2A\u6587\u4EF6\u4E2D ${names} \u7684\u9ED8\u8BA4\u6587\u6848\u3002`];
|
|
4486
|
+
if (findings.length === 0) {
|
|
4487
|
+
lines.push("\u672A\u53D1\u73B0\u8FDD\u89C4\u6587\u6848\u3002");
|
|
4488
|
+
return {
|
|
4489
|
+
name: "source-locale-defaults",
|
|
4490
|
+
success: true,
|
|
4491
|
+
messages: lines.join("\n"),
|
|
4492
|
+
howToFix: ""
|
|
4493
|
+
};
|
|
4494
|
+
}
|
|
4495
|
+
lines.push(`\u53D1\u73B0 ${findings.length} \u5904\u8FDD\u89C4\u6587\u6848\uFF1A`, ...findings);
|
|
4496
|
+
return {
|
|
4497
|
+
name: "source-locale-defaults",
|
|
4498
|
+
success: false,
|
|
4499
|
+
messages: lines.join("\n"),
|
|
4500
|
+
howToFix: "\u9ED8\u8BA4\u6587\u6848\u6539\u7528\u6E90\u8BED\u8A00\uFF0C\u5176\u4ED6\u8BED\u8A00\u7684\u7FFB\u8BD1\u5199\u5165\u8BED\u8A00\u6587\u4EF6\u3002"
|
|
4501
|
+
};
|
|
4502
|
+
}
|
|
4503
|
+
});
|
|
4504
|
+
function matchCall(calls, callee) {
|
|
4505
|
+
if (!callee) return void 0;
|
|
4506
|
+
if (callee.type === "Identifier") return calls.find((call) => call.name === callee.name);
|
|
4507
|
+
if (callee.type === "MemberExpression" || callee.type === "StaticMemberExpression") {
|
|
4508
|
+
const name = readName3(callee.property);
|
|
4509
|
+
return calls.find((call) => call.member && call.name === name);
|
|
4510
|
+
}
|
|
4511
|
+
return void 0;
|
|
4512
|
+
}
|
|
4513
|
+
async function collectFiles3(repoRoot, options, extensions) {
|
|
4514
|
+
const files = [];
|
|
4515
|
+
const excludeDirs = options.excludeDirs.map((dir) => path37.resolve(repoRoot, dir));
|
|
4516
|
+
const skipDirNames = new Set(options.skipDirNames);
|
|
4517
|
+
async function visit(dir) {
|
|
4518
|
+
const entries2 = await readDirIfExists4(dir);
|
|
4519
|
+
for (const entry of entries2 ?? []) {
|
|
4520
|
+
const full = path37.join(dir, entry.name);
|
|
4521
|
+
if (entry.isDirectory()) {
|
|
4522
|
+
if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
|
|
4523
|
+
if (excludeDirs.some((excluded) => isInsidePath4(full, excluded))) continue;
|
|
4524
|
+
await visit(full);
|
|
4525
|
+
continue;
|
|
4526
|
+
}
|
|
4527
|
+
if (entry.isFile() && extensions.some((extension) => full.endsWith(extension))) {
|
|
4528
|
+
files.push(full);
|
|
4529
|
+
}
|
|
4530
|
+
}
|
|
4531
|
+
}
|
|
4532
|
+
const scanRoot = path37.resolve(repoRoot, options.scanRoot);
|
|
4533
|
+
await fs6.access(scanRoot);
|
|
4534
|
+
await visit(scanRoot);
|
|
4535
|
+
return files.sort((left, right) => left.localeCompare(right));
|
|
4536
|
+
}
|
|
4537
|
+
async function readDirIfExists4(dir) {
|
|
4538
|
+
try {
|
|
4539
|
+
return await fs6.readdir(dir, { withFileTypes: true });
|
|
4540
|
+
} catch (error) {
|
|
4541
|
+
if (error.code === "ENOENT") return void 0;
|
|
4542
|
+
throw error;
|
|
4543
|
+
}
|
|
4544
|
+
}
|
|
4545
|
+
function isInsidePath4(filePath, dir) {
|
|
4546
|
+
const relative = path37.relative(dir, filePath);
|
|
4547
|
+
return relative === "" || !relative.startsWith("..") && !path37.isAbsolute(relative);
|
|
4548
|
+
}
|
|
4549
|
+
function formatLocation3(repoRoot, file, line) {
|
|
4550
|
+
return `${path37.relative(repoRoot, file)}:${line}`;
|
|
4551
|
+
}
|
|
4552
|
+
async function parseSourceFile6(file) {
|
|
4553
|
+
const code = await fs6.readFile(file, "utf8");
|
|
4554
|
+
const lineStarts = [0];
|
|
4555
|
+
for (let index = 0; index < code.length; index += 1) {
|
|
4556
|
+
if (code[index] === "\n") lineStarts.push(index + 1);
|
|
4557
|
+
}
|
|
4558
|
+
const parsed = parseSync6(file, code);
|
|
4559
|
+
if (parsed.errors.length)
|
|
4560
|
+
throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
|
|
4561
|
+
return { file, program: parsed.program, lineStarts };
|
|
4562
|
+
}
|
|
4563
|
+
function walk6(node, visit) {
|
|
4564
|
+
if (!node || typeof node !== "object") return;
|
|
4565
|
+
const current = node;
|
|
4566
|
+
if (typeof current.type === "string") visit(current);
|
|
4567
|
+
for (const key of Object.keys(current)) {
|
|
4568
|
+
if (SKIP_AST_KEYS6.has(key)) continue;
|
|
4569
|
+
const value = current[key];
|
|
4570
|
+
if (Array.isArray(value)) {
|
|
4571
|
+
for (const child of value) walk6(child, visit);
|
|
4572
|
+
} else if (value && typeof value === "object") {
|
|
4573
|
+
walk6(value, visit);
|
|
4574
|
+
}
|
|
4575
|
+
}
|
|
4576
|
+
}
|
|
4577
|
+
function lineOf4(source, node) {
|
|
4578
|
+
if (typeof node.start !== "number") return 0;
|
|
4579
|
+
let low = 0;
|
|
4580
|
+
let high = source.lineStarts.length - 1;
|
|
4581
|
+
while (low <= high) {
|
|
4582
|
+
const mid = Math.floor((low + high) / 2);
|
|
4583
|
+
if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
|
|
4584
|
+
else high = mid - 1;
|
|
4585
|
+
}
|
|
4586
|
+
return high + 1;
|
|
4587
|
+
}
|
|
4588
|
+
function readStringLiteral4(node) {
|
|
4589
|
+
if (!node) return void 0;
|
|
4590
|
+
if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") {
|
|
4591
|
+
return node.value;
|
|
4592
|
+
}
|
|
4593
|
+
return void 0;
|
|
4594
|
+
}
|
|
4595
|
+
function readName3(node) {
|
|
4596
|
+
if (!node) return void 0;
|
|
4597
|
+
if (typeof node.name === "string") return node.name;
|
|
4598
|
+
if (typeof node.value === "string") return node.value;
|
|
4599
|
+
return void 0;
|
|
4600
|
+
}
|
|
4601
|
+
|
|
4602
|
+
// packages/conformance/rules/sync-locales.ts
|
|
4603
|
+
import { promises as fs7 } from "node:fs";
|
|
4604
|
+
import path38 from "node:path";
|
|
4605
|
+
import { parseSync as parseSync7 } from "oxc-parser";
|
|
4606
|
+
import { z as z38 } from "zod";
|
|
4607
|
+
var optionsSchema9 = z38.object({
|
|
4608
|
+
scanRoot: z38.string().trim().min(1).describe("\u9012\u5F52\u626B\u63CF\u7684\u6E90\u7801\u76EE\u5F55\uFF0C\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9 projectRoot \u7684\u8DEF\u5F84\u3002"),
|
|
4609
|
+
excludeDirs: z38.array(z38.string()).readonly().default([]).describe("\u626B\u63CF\u65F6\u8DF3\u8FC7\u7684\u5B50\u76EE\u5F55\u53CA\u5176\u540E\u4EE3\uFF1B\u8DEF\u5F84\u76F8\u5BF9 projectRoot \u89E3\u6790\uFF0C\u4E5F\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u3002"),
|
|
4610
|
+
skipDirNames: z38.array(z38.string()).readonly().default(["node_modules", "dist", "coverage"]).describe("\u6309\u76EE\u5F55\u540D\u8DF3\u8FC7\uFF1B\u4F20\u5165\u65F6\u66FF\u6362\u9ED8\u8BA4\u5217\u8868\uFF0C\u9690\u85CF\u76EE\u5F55\u59CB\u7EC8\u8DF3\u8FC7\u3002"),
|
|
4611
|
+
callName: z38.string().trim().min(1).default("localize").describe("\u672C\u5730\u5316\u51FD\u6570\u540D\uFF1B\u4EC5\u5339\u914D\u76F4\u63A5\u8C03\u7528\uFF0C\u4E0D\u5339\u914D\u5BF9\u8C61\u6210\u5458\u8C03\u7528\u3002"),
|
|
4612
|
+
keyArgument: z38.number().int().nonnegative().default(0).describe("key \u6240\u5728\u7684\u53C2\u6570\u4E0B\u6807\uFF0C\u4ECE 0 \u5F00\u59CB\uFF1B\u975E\u5B57\u7B26\u4E32\u5B57\u9762\u91CF\u4F1A\u88AB\u8DF3\u8FC7\u3002"),
|
|
4613
|
+
valueArgument: z38.number().int().nonnegative().default(1).describe("\u9ED8\u8BA4\u6587\u6848\u6240\u5728\u7684\u53C2\u6570\u4E0B\u6807\uFF0C\u4ECE 0 \u5F00\u59CB\u3002"),
|
|
4614
|
+
localesDir: z38.string().trim().min(1).describe("\u8BED\u8A00\u6587\u4EF6\u76EE\u5F55\uFF0C\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9 projectRoot \u7684\u8DEF\u5F84\uFF1B\u7F3A\u5931\u65F6\u81EA\u52A8\u521B\u5EFA\u3002"),
|
|
4615
|
+
defaultLocale: z38.string().trim().min(1).describe("\u6E90\u8BED\u8A00\u6807\u8BC6\uFF0C\u4F8B\u5982 en-US\uFF0C\u5BF9\u5E94 localesDir \u4E0B\u7684 en-US.json\u3002"),
|
|
4616
|
+
otherLocales: z38.array(z38.string().trim().min(1)).readonly().describe("\u9700\u8981\u540C\u6B65\u5E76\u68C0\u67E5\u7FFB\u8BD1\u7684\u5176\u4ED6\u8BED\u8A00\u6807\u8BC6\uFF1B\u4E0D\u5305\u542B defaultLocale\uFF0C\u7A7A\u6570\u7EC4\u8868\u793A\u4EC5\u540C\u6B65\u6E90\u8BED\u8A00\u3002"),
|
|
4617
|
+
metadataKey: z38.string().trim().min(1).optional().describe(
|
|
4618
|
+
"\u751F\u6210\u5668\u5143\u6570\u636E\u952E\uFF0C\u9ED8\u8BA4\u4E0D\u5199\u5165\uFF1B\u517C\u5BB9 i18n-ease \u65F6\u8BBE\u4E3A __i18n_ease__\uFF0C\u5DF2\u6709\u6587\u4EF6\u5FC5\u987B\u5305\u542B\u6B64\u952E\u3002"
|
|
4619
|
+
)
|
|
4620
|
+
});
|
|
4621
|
+
var SKIP_AST_KEYS7 = /* @__PURE__ */ new Set([
|
|
4622
|
+
"loc",
|
|
4623
|
+
"range",
|
|
4624
|
+
"start",
|
|
4625
|
+
"end",
|
|
4626
|
+
"parent",
|
|
4627
|
+
"leadingComments",
|
|
4628
|
+
"trailingComments"
|
|
4629
|
+
]);
|
|
4630
|
+
var syncLocales = defineRule({
|
|
4631
|
+
id: "sync-locales",
|
|
4632
|
+
displayName: "\u540C\u6B65\u672C\u5730\u5316\u6587\u4EF6",
|
|
4633
|
+
exportName: "syncLocales",
|
|
4634
|
+
summary: "\u4ECE\u6E90\u7801\u672C\u5730\u5316\u8C03\u7528\u540C\u6B65 JSON \u8BED\u8A00\u6587\u4EF6\u5E76\u68C0\u67E5\u672A\u7FFB\u8BD1\u6761\u76EE\u3002\u6B64\u89C4\u7EA6\u4F1A\u5199\u6587\u4EF6\uFF0C\u53D1\u751F\u66F4\u65B0\u65F6\u672C\u6B21\u68C0\u67E5\u5931\u8D25\uFF0C\u63D0\u9192\u5BA1\u67E5\u5E76\u63D0\u4EA4\u53D8\u5316\u3002",
|
|
4635
|
+
optionsSchema: optionsSchema9,
|
|
4636
|
+
examples: [
|
|
4637
|
+
{
|
|
4638
|
+
options: {
|
|
4639
|
+
scanRoot: "src",
|
|
4640
|
+
localesDir: "locales",
|
|
4641
|
+
defaultLocale: "en",
|
|
4642
|
+
otherLocales: ["zh"]
|
|
4643
|
+
}
|
|
4644
|
+
}
|
|
4645
|
+
],
|
|
4646
|
+
notes: "\u4F1A\u5199\u5165 `localesDir` \u4E2D\u914D\u7F6E\u7684\u8BED\u8A00\u6587\u4EF6\uFF0C\u540E\u7EED\u4EFB\u52A1\u53EF\u8BFB\u53D6\u8FD9\u4E9B\u53D8\u5316\u3002\u8BED\u8A00\u6587\u4EF6\u4E3A key \u5230\u5B57\u7B26\u4E32\u6216 `{ defaultMessage, content }` \u7684\u6620\u5C04\uFF1B\u540C\u6B65\u540E\u7EDF\u4E00\u751F\u6210\u5BF9\u8C61\u5F62\u5F0F\uFF0C\u79FB\u9664\u4E0D\u518D\u4F7F\u7528\u7684 key\uFF0C\u6E90\u6587\u6848\u6539\u53D8\u65F6\u6E05\u7A7A\u5BF9\u5E94\u8BD1\u6587\u3002",
|
|
4647
|
+
async run(common, config) {
|
|
4648
|
+
const repoRoot = common.projectRoot;
|
|
4649
|
+
const scanRoot = path38.resolve(repoRoot, config.scanRoot);
|
|
4650
|
+
const excludeDirs = config.excludeDirs.map((dir) => path38.resolve(repoRoot, dir));
|
|
4651
|
+
const localesDir = path38.resolve(repoRoot, config.localesDir);
|
|
4652
|
+
const files = await collectSourceFiles3(scanRoot, excludeDirs, config.skipDirNames);
|
|
4653
|
+
const sourceLocale = /* @__PURE__ */ new Map();
|
|
4654
|
+
for (const file of files) {
|
|
4655
|
+
const ast = await parseSourceFile7(file);
|
|
4656
|
+
walk7(ast.program, (node) => {
|
|
4657
|
+
if (!isLocalizeCall2(node, config.callName)) return;
|
|
4658
|
+
const key = readStringLiteral5(node.arguments[config.keyArgument]);
|
|
4659
|
+
if (key === void 0) return;
|
|
4660
|
+
const value = readStringLiteral5(node.arguments[config.valueArgument]);
|
|
4661
|
+
const existing = sourceLocale.get(key);
|
|
4662
|
+
if (existing === void 0 || !existing && value) {
|
|
4663
|
+
sourceLocale.set(key, value ?? "");
|
|
4664
|
+
}
|
|
4665
|
+
});
|
|
4666
|
+
}
|
|
4667
|
+
const defaultPath = path38.join(localesDir, `${config.defaultLocale}.json`);
|
|
4668
|
+
const defaultExisting = await readLocaleFile(defaultPath, config.metadataKey);
|
|
4669
|
+
const defaultMerged = mergeDefaultLocale(defaultExisting, sourceLocale, config.metadataKey);
|
|
4670
|
+
const changedFiles = [];
|
|
4671
|
+
if (await writeIfChanged(defaultPath, defaultMerged)) {
|
|
4672
|
+
changedFiles.push(defaultPath);
|
|
4673
|
+
}
|
|
4674
|
+
const untranslatedByLocale = /* @__PURE__ */ new Map();
|
|
4675
|
+
for (const locale of config.otherLocales) {
|
|
4676
|
+
const localePath = path38.join(localesDir, `${locale}.json`);
|
|
4677
|
+
const existing = await readLocaleFile(localePath, config.metadataKey);
|
|
4678
|
+
const merged = mergeOtherLocale(existing, defaultMerged, config.metadataKey);
|
|
4679
|
+
if (await writeIfChanged(localePath, merged)) {
|
|
4680
|
+
changedFiles.push(localePath);
|
|
4681
|
+
}
|
|
4682
|
+
const untranslated = [];
|
|
4683
|
+
for (const [key, value] of Object.entries(merged)) {
|
|
4684
|
+
if (key === config.metadataKey) continue;
|
|
4685
|
+
if (typeof value === "object" && !value.content) {
|
|
4686
|
+
untranslated.push({ key, defaultMessage: value.defaultMessage });
|
|
4687
|
+
} else if (typeof value === "string" && !value) {
|
|
4688
|
+
untranslated.push({ key, defaultMessage: "" });
|
|
4689
|
+
}
|
|
4690
|
+
}
|
|
4691
|
+
if (untranslated.length > 0) {
|
|
4692
|
+
untranslatedByLocale.set(locale, untranslated);
|
|
4693
|
+
}
|
|
4694
|
+
}
|
|
4695
|
+
const lines = [
|
|
4696
|
+
`Localization sync: scanned ${files.length} file(s), ${sourceLocale.size} key(s) in source.`
|
|
4697
|
+
];
|
|
4698
|
+
const hasOutOfSyncFiles = changedFiles.length > 0;
|
|
4699
|
+
const hasUntranslatedKeys = untranslatedByLocale.size > 0;
|
|
4700
|
+
const howToFix = [];
|
|
4701
|
+
const success = !hasOutOfSyncFiles && !hasUntranslatedKeys;
|
|
4702
|
+
if (hasOutOfSyncFiles) {
|
|
4703
|
+
lines.push(
|
|
4704
|
+
`Locale files are out of sync with source. Updated ${changedFiles.length} file(s):`
|
|
4705
|
+
);
|
|
4706
|
+
for (const file of changedFiles) {
|
|
4707
|
+
lines.push(` - ${path38.relative(repoRoot, file)}`);
|
|
4708
|
+
}
|
|
4709
|
+
howToFix.push("Locale files have been regenerated - commit them, then run the check again.");
|
|
4710
|
+
} else {
|
|
4711
|
+
lines.push("Locale files are in sync with source.");
|
|
4712
|
+
}
|
|
4713
|
+
for (const [locale, entries2] of untranslatedByLocale) {
|
|
4714
|
+
lines.push(`Found ${entries2.length} untranslated key(s) in ${locale}:`);
|
|
4715
|
+
for (const entry of entries2) {
|
|
4716
|
+
lines.push(` - '${entry.key}' (default: '${entry.defaultMessage}')`);
|
|
4717
|
+
}
|
|
4718
|
+
}
|
|
4719
|
+
if (hasUntranslatedKeys) {
|
|
4720
|
+
howToFix.push(
|
|
4721
|
+
"Translate the listed key(s) in non-default locale files, then run the check again."
|
|
4722
|
+
);
|
|
4723
|
+
}
|
|
4724
|
+
return {
|
|
4725
|
+
name: "sync-locales",
|
|
4726
|
+
success,
|
|
4727
|
+
messages: lines.join("\n"),
|
|
4728
|
+
howToFix: howToFix.join(" ")
|
|
4729
|
+
};
|
|
4730
|
+
}
|
|
4731
|
+
});
|
|
4732
|
+
function mergeDefaultLocale(oldConfig, newLocale, metadataKey) {
|
|
4733
|
+
const result = {};
|
|
4734
|
+
for (const [key, value] of newLocale) {
|
|
4735
|
+
const existing = oldConfig[key];
|
|
4736
|
+
if (!value && existing) {
|
|
4737
|
+
result[key] = existing;
|
|
4738
|
+
} else {
|
|
4739
|
+
result[key] = { defaultMessage: value, content: value };
|
|
4740
|
+
}
|
|
4741
|
+
}
|
|
4742
|
+
return sortObject(result, metadataKey);
|
|
4743
|
+
}
|
|
4744
|
+
function mergeOtherLocale(oldConfig, defaultConfig, metadataKey) {
|
|
4745
|
+
const result = {};
|
|
4746
|
+
for (const [key, defaultValue] of Object.entries(defaultConfig)) {
|
|
4747
|
+
if (key === metadataKey) continue;
|
|
4748
|
+
const defaultMessage = typeof defaultValue === "string" ? defaultValue : defaultValue.defaultMessage;
|
|
4749
|
+
const current = oldConfig[key];
|
|
4750
|
+
if (!current) {
|
|
4751
|
+
result[key] = { defaultMessage, content: "" };
|
|
4752
|
+
} else if (typeof current === "string") {
|
|
4753
|
+
result[key] = { defaultMessage, content: current };
|
|
4754
|
+
} else if (current.defaultMessage !== defaultMessage) {
|
|
4755
|
+
result[key] = { defaultMessage, content: "" };
|
|
4756
|
+
} else {
|
|
4757
|
+
result[key] = current;
|
|
4758
|
+
}
|
|
4759
|
+
}
|
|
4760
|
+
return sortObject(result, metadataKey);
|
|
4761
|
+
}
|
|
4762
|
+
function sortObject(obj, metadataKey) {
|
|
4763
|
+
const sorted = metadataKey ? { [metadataKey]: "true" } : {};
|
|
4764
|
+
const keys = Object.keys(obj).filter((key) => key !== metadataKey).sort((a, b) => a.localeCompare(b));
|
|
4765
|
+
for (const key of keys) {
|
|
4766
|
+
sorted[key] = obj[key];
|
|
4767
|
+
}
|
|
4768
|
+
return sorted;
|
|
4769
|
+
}
|
|
4770
|
+
async function readLocaleFile(filePath, metadataKey) {
|
|
4771
|
+
let content;
|
|
4772
|
+
try {
|
|
4773
|
+
content = await fs7.readFile(filePath, "utf8");
|
|
4774
|
+
} catch (error) {
|
|
4775
|
+
if (hasCode(error, "ENOENT")) return metadataKey ? { [metadataKey]: "true" } : {};
|
|
4776
|
+
throw error;
|
|
4777
|
+
}
|
|
4778
|
+
const json = JSON.parse(content);
|
|
4779
|
+
if (metadataKey && !json[metadataKey]) {
|
|
4780
|
+
throw new Error(`${filePath} is missing metadata ${metadataKey}.`);
|
|
4781
|
+
}
|
|
4782
|
+
return json;
|
|
4783
|
+
}
|
|
4784
|
+
async function writeIfChanged(filePath, value) {
|
|
4785
|
+
const next = `${JSON.stringify(value, null, 2)}
|
|
4786
|
+
`;
|
|
4787
|
+
let prev = "";
|
|
4788
|
+
try {
|
|
4789
|
+
prev = await fs7.readFile(filePath, "utf8");
|
|
4790
|
+
} catch (error) {
|
|
4791
|
+
if (!hasCode(error, "ENOENT")) throw error;
|
|
4792
|
+
}
|
|
4793
|
+
if (prev === next) return false;
|
|
4794
|
+
await fs7.mkdir(path38.dirname(filePath), { recursive: true });
|
|
4795
|
+
await fs7.writeFile(filePath, next);
|
|
4796
|
+
return true;
|
|
4797
|
+
}
|
|
4798
|
+
async function collectSourceFiles3(root, excludeDirs, skipDirNames) {
|
|
4799
|
+
const out = [];
|
|
4800
|
+
const resolvedExcludeDirs = excludeDirs.map((item) => path38.resolve(item));
|
|
4801
|
+
async function visit(dir) {
|
|
4802
|
+
const entries2 = await fs7.readdir(dir, { withFileTypes: true });
|
|
4803
|
+
for (const entry of entries2) {
|
|
4804
|
+
const full = path38.join(dir, entry.name);
|
|
4805
|
+
if (entry.isDirectory()) {
|
|
4806
|
+
if (entry.name.startsWith(".")) continue;
|
|
4807
|
+
if (skipDirNames.includes(entry.name)) continue;
|
|
4808
|
+
if (isExcluded3(full, resolvedExcludeDirs)) continue;
|
|
4809
|
+
await visit(full);
|
|
4810
|
+
continue;
|
|
4811
|
+
}
|
|
4812
|
+
if (!entry.isFile()) continue;
|
|
4813
|
+
if (!full.endsWith(".ts") && !full.endsWith(".tsx")) continue;
|
|
4814
|
+
out.push(full);
|
|
4815
|
+
}
|
|
4816
|
+
}
|
|
4817
|
+
await visit(root);
|
|
4818
|
+
return out.sort();
|
|
4819
|
+
}
|
|
4820
|
+
async function parseSourceFile7(file) {
|
|
4821
|
+
const code = await fs7.readFile(file, "utf8");
|
|
4822
|
+
const ast = parseSync7(file, code);
|
|
4823
|
+
if (ast.errors.length)
|
|
4824
|
+
throw new Error(`${file}: ${ast.errors.map((error) => error.message).join("; ")}`);
|
|
4825
|
+
return ast;
|
|
4826
|
+
}
|
|
4827
|
+
function walk7(node, visit) {
|
|
4828
|
+
if (!node || typeof node !== "object") return;
|
|
4829
|
+
const current = node;
|
|
4830
|
+
if (typeof current.type === "string") visit(current);
|
|
4831
|
+
for (const key of Object.keys(current)) {
|
|
4832
|
+
if (SKIP_AST_KEYS7.has(key)) continue;
|
|
4833
|
+
const value = current[key];
|
|
4834
|
+
if (Array.isArray(value)) {
|
|
4835
|
+
for (const child of value) walk7(child, visit);
|
|
4836
|
+
} else if (value && typeof value === "object") {
|
|
4837
|
+
walk7(value, visit);
|
|
4838
|
+
}
|
|
4839
|
+
}
|
|
4840
|
+
}
|
|
4841
|
+
function isLocalizeCall2(node, name) {
|
|
4842
|
+
return node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === name;
|
|
4843
|
+
}
|
|
4844
|
+
function readStringLiteral5(node) {
|
|
4845
|
+
if (!node) return void 0;
|
|
4846
|
+
if (node.type === "Literal" && typeof node.value === "string") return node.value;
|
|
4847
|
+
if (node.type === "StringLiteral" && typeof node.value === "string") return node.value;
|
|
4848
|
+
return void 0;
|
|
4849
|
+
}
|
|
4850
|
+
function isExcluded3(filePath, excludeDirs) {
|
|
4851
|
+
return excludeDirs.some((dir) => filePath === dir || filePath.startsWith(dir + path38.sep));
|
|
4852
|
+
}
|
|
4853
|
+
function hasCode(error, code) {
|
|
4854
|
+
return Boolean(error && typeof error === "object" && "code" in error && error.code === code);
|
|
4855
|
+
}
|
|
4856
|
+
|
|
4857
|
+
// packages/conformance/rules/ui-scenarios-structure.ts
|
|
4858
|
+
import { promises as fs8 } from "node:fs";
|
|
4859
|
+
import path39 from "node:path";
|
|
4860
|
+
import { parseSync as parseSync8 } from "oxc-parser";
|
|
4861
|
+
import { z as z39 } from "zod";
|
|
4862
|
+
var optionsSchema10 = z39.object({
|
|
4863
|
+
root: z39.string().trim().min(1).describe(
|
|
4864
|
+
"\u573A\u666F\u6839\u76EE\u5F55\uFF0C\u652F\u6301\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9 projectRoot \u7684\u8DEF\u5F84\uFF1B\u4EC5\u68C0\u67E5\u6B64\u76EE\u5F55\u76F4\u63A5\u5305\u542B\u7684\u5165\u53E3\u6587\u4EF6\u3002"
|
|
4865
|
+
),
|
|
4866
|
+
name: z39.string().trim().min(1).optional().describe(
|
|
4867
|
+
"\u7ED3\u679C\u540D\u4E0E\u5C55\u793A\u540D\uFF0C\u540C\u4E00\u4ED3\u5E93\u68C0\u67E5\u591A\u4E2A\u6D4B\u8BD5\u6839\u76EE\u5F55\u65F6\u7528\u4E8E\u533A\u5206\uFF0C\u9ED8\u8BA4 ui-scenarios-structure\u3002"
|
|
4868
|
+
),
|
|
4869
|
+
entrySuffix: z39.string().min(1).default(".ts").describe("\u5165\u53E3\u6587\u4EF6\u540E\u7F00\u3002"),
|
|
4870
|
+
sharedDir: z39.string().trim().min(1).default("shared").describe("\u591A\u4E2A\u5165\u53E3\u5171\u7528 helper \u7684\u76EE\u5F55\u540D\uFF0C\u76F8\u5BF9 root\u3002"),
|
|
4871
|
+
utilsDir: z39.string().trim().min(1).default("utils").describe("\u5404\u5165\u53E3\u4E13\u5C5E helper \u7684\u76EE\u5F55\u540D\uFF0C\u76F8\u5BF9 root\uFF1B\u5165\u53E3\u53EA\u80FD\u5BFC\u5165\u81EA\u8EAB\u540C\u540D\u5B50\u76EE\u5F55\u3002"),
|
|
4872
|
+
exportName: z39.string().trim().min(1).default("lint").describe(
|
|
4873
|
+
"\u6BCF\u4E2A\u5165\u53E3\u5FC5\u987B\u63D0\u4F9B\u7684\u5177\u540D\u5BFC\u51FA\uFF1B\u53EF\u5BFC\u51FA\u51FD\u6570\u6216\u6570\u636E\uFF0C\u53EA\u6709\u8BE5\u5BFC\u51FA\u5BF9\u5E94\u7684\u9876\u5C42\u51FD\u6570\u5141\u8BB8\u5728\u5165\u53E3\u4E2D\u5B9A\u4E49\u3002"
|
|
4874
|
+
),
|
|
4875
|
+
strictRoot: z39.boolean().default(true).describe("\u662F\u5426\u8981\u6C42 root \u53EA\u5305\u542B\u5165\u53E3\u6587\u4EF6\u548C\u914D\u7F6E\u7684\u4E24\u7C7B helper \u76EE\u5F55\uFF1B\u9690\u85CF\u6761\u76EE\u59CB\u7EC8\u8DF3\u8FC7\u3002"),
|
|
4876
|
+
sharedThreshold: z39.number().int().min(1).default(3).describe("helper \u88AB\u591A\u5C11\u4E2A\u5165\u53E3\u4F7F\u7528\u65F6\u5EFA\u8BAE\u79FB\u5230\u5171\u7528\u76EE\u5F55\uFF1B\u4EC5\u5F71\u54CD\u8FDD\u89C4\u65F6\u7684\u4FEE\u590D\u5EFA\u8BAE\u3002")
|
|
4877
|
+
});
|
|
4878
|
+
var SKIP_AST_KEYS8 = /* @__PURE__ */ new Set([
|
|
4879
|
+
"loc",
|
|
4880
|
+
"range",
|
|
4881
|
+
"start",
|
|
4882
|
+
"end",
|
|
4883
|
+
"parent",
|
|
4884
|
+
"leadingComments",
|
|
4885
|
+
"trailingComments"
|
|
4886
|
+
]);
|
|
4887
|
+
var DEFAULT_SKIP_DIR_NAMES2 = ["node_modules", "dist", "coverage"];
|
|
4888
|
+
var uiScenariosStructure = defineRule({
|
|
4889
|
+
id: "ui-scenarios-structure",
|
|
4890
|
+
displayName: "\u68C0\u67E5\u754C\u9762\u573A\u666F\u7ED3\u6784",
|
|
4891
|
+
exportName: "uiScenariosStructure",
|
|
4892
|
+
summary: "\u68C0\u67E5\u622A\u56FE\u573A\u666F\u7684\u76EE\u5F55\u548C\u5F15\u7528\u8FB9\u754C\uFF0C\u5E76\u8981\u6C42\u6BCF\u4E2A\u5165\u53E3\u63D0\u4F9B\u6307\u5B9A\u7684\u5177\u540D\u5BFC\u51FA\u3002\u5141\u8BB8\u8BE5\u5BFC\u51FA\u5BF9\u5E94\u7684\u9876\u5C42\u51FD\u6570\uFF0C\u7981\u6B62\u5176\u4ED6\u51FD\u6570\u58F0\u660E\u6216\u7ED1\u5B9A\u5230\u53D8\u91CF\u7684\u8F85\u52A9\u51FD\u6570\u3002",
|
|
4893
|
+
optionsSchema: optionsSchema10,
|
|
4894
|
+
examples: [{ options: { root: "tests/screenshots", exportName: "scenarios" } }],
|
|
4895
|
+
notes: "`exportName` \u9ED8\u8BA4 `lint`\u3002\u4F8B\u5982 `export function scenarios() {}`\u3001`export const scenarios = () => []`\u3001`const build = () => []; export { build as scenarios }` \u90FD\u53EF\u4EE5\u4F5C\u4E3A\u5165\u53E3\uFF0C\u4E5F\u53EF\u4EE5\u5BFC\u51FA\u6570\u636E\u5BF9\u8C61\u6216\u6570\u7EC4\u3002\u4EC5\u8C41\u514D\u5BF9\u5E94\u7684\u9876\u5C42\u51FD\u6570\uFF0C\u5165\u53E3\u5185\u90E8\u5B9A\u4E49\u7684\u5177\u540D helper \u4ECD\u4F1A\u62A5\u9519\uFF1B\u7C7B\u578B\u5BFC\u51FA\u4E0D\u7B97\u8FD0\u884C\u65F6\u5165\u53E3\u3002\n\n\u76F4\u63A5\u4F20\u7ED9\u6D4B\u8BD5\u8C03\u7528\u6216\u622A\u56FE\u6B65\u9AA4\u7684\u5185\u8054\u56DE\u8C03\u5141\u8BB8\u4FDD\u7559\u3002\u5165\u53E3\u53EA\u5141\u8BB8\u5F15\u7528\u81EA\u8EAB\u540C\u540D\u7684 utils \u5B50\u76EE\u5F55\uFF1Bshared \u548C utils \u4E0D\u80FD\u4E92\u76F8 import/export\uFF0C\u4E24\u7C7B helper \u76EE\u5F55\u540D\u53EF\u914D\u7F6E\u3002\u53EA\u68C0\u67E5 root \u76F4\u63A5\u5305\u542B\u7684\u5165\u53E3\u6587\u4EF6\uFF0C\u9012\u5F52\u68C0\u67E5 helper \u76EE\u5F55\u3002",
|
|
4896
|
+
resolveDisplayName: (options) => options.name ?? "\u68C0\u67E5\u754C\u9762\u573A\u666F\u7ED3\u6784",
|
|
4897
|
+
async run(context, options) {
|
|
4898
|
+
const ruleName = options.name ?? "ui-scenarios-structure";
|
|
4899
|
+
const repoRoot = context.projectRoot;
|
|
4900
|
+
const entrySuffix = options.entrySuffix;
|
|
4901
|
+
const strictRoot = options.strictRoot;
|
|
4902
|
+
const exportName = options.exportName;
|
|
4903
|
+
const root = path39.resolve(repoRoot, options.root);
|
|
4904
|
+
const sharedName = options.sharedDir;
|
|
4905
|
+
const utilsName = options.utilsDir;
|
|
4906
|
+
const threshold = options.sharedThreshold;
|
|
4907
|
+
const sharedRoot = path39.join(root, sharedName);
|
|
4908
|
+
const utilsRoot = path39.join(root, utilsName);
|
|
4909
|
+
const utilsPrefix = `./${utilsName}/`;
|
|
4910
|
+
const at = (file, line) => formatLocation4(repoRoot, file, line);
|
|
4911
|
+
const violations = [];
|
|
4912
|
+
const entries2 = await readDirIfExists5(root);
|
|
4913
|
+
if (!entries2) {
|
|
4914
|
+
return {
|
|
4915
|
+
name: ruleName,
|
|
4916
|
+
success: false,
|
|
4917
|
+
messages: `\u573A\u666F\u6839\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${path39.relative(repoRoot, root)}`,
|
|
4918
|
+
howToFix: "\u786E\u8BA4\u4F20\u5165\u7684\u573A\u666F\u6839\u76EE\u5F55\u8DEF\u5F84\u3002"
|
|
4919
|
+
};
|
|
4920
|
+
}
|
|
4921
|
+
const entryFiles = [];
|
|
4922
|
+
for (const entry of entries2) {
|
|
4923
|
+
if (entry.name.startsWith(".")) continue;
|
|
4924
|
+
const full = path39.join(root, entry.name);
|
|
4925
|
+
if (entry.name === sharedName || entry.name === utilsName) {
|
|
4926
|
+
if (!entry.isDirectory()) violations.push(` - ${at(full, 1)} ${entry.name} \u5FC5\u987B\u662F\u76EE\u5F55`);
|
|
4927
|
+
continue;
|
|
4928
|
+
}
|
|
4929
|
+
if (entry.isFile() && entry.name.endsWith(entrySuffix)) {
|
|
4930
|
+
entryFiles.push(full);
|
|
4931
|
+
continue;
|
|
4932
|
+
}
|
|
4933
|
+
if (strictRoot) {
|
|
4934
|
+
violations.push(
|
|
4935
|
+
` - ${at(full, 1)} \u6839\u76EE\u5F55\u53EA\u5141\u8BB8 *${entrySuffix} \u5165\u53E3\u4E0E ${sharedName}/${utilsName} \u76EE\u5F55`
|
|
4936
|
+
);
|
|
4937
|
+
}
|
|
4938
|
+
}
|
|
4939
|
+
entryFiles.sort((left, right) => left.localeCompare(right));
|
|
4940
|
+
const usages = /* @__PURE__ */ new Map();
|
|
4941
|
+
const importViolations = [];
|
|
4942
|
+
for (const file of entryFiles) {
|
|
4943
|
+
const source = await parseSourceFile8(file);
|
|
4944
|
+
const entryName = path39.basename(file, entrySuffix);
|
|
4945
|
+
const entryFunctions = collectEntryFunctions(source, exportName);
|
|
4946
|
+
walk8(source.program, (node) => {
|
|
4947
|
+
const functionName = readFunctionName2(node);
|
|
4948
|
+
if (functionName && !entryFunctions.has(node)) {
|
|
4949
|
+
violations.push(
|
|
4950
|
+
` - ${at(file, lineOf5(source, node))} \u5165\u53E3\u5185\u5B9A\u4E49\u8F85\u52A9\u51FD\u6570 ${functionName}`
|
|
4951
|
+
);
|
|
4952
|
+
}
|
|
4953
|
+
});
|
|
4954
|
+
if (!hasNamedExport(source, exportName)) {
|
|
4955
|
+
violations.push(` - ${at(file, 1)} \u5165\u53E3\u5FC5\u987B\u5BFC\u51FA ${exportName}`);
|
|
4956
|
+
}
|
|
4957
|
+
const expected = `${utilsPrefix}${entryName}`;
|
|
4958
|
+
for (const entry of collectImports2(source, utilsPrefix)) {
|
|
4959
|
+
for (const importedName of entry.importedNames) {
|
|
4960
|
+
const key = `${entry.specifier}#${importedName}`;
|
|
4961
|
+
usages.set(key, (usages.get(key) ?? /* @__PURE__ */ new Set()).add(file));
|
|
4962
|
+
}
|
|
4963
|
+
if (entry.specifier === expected || entry.specifier.startsWith(`${expected}/`)) continue;
|
|
4964
|
+
importViolations.push({ file, entry, expected });
|
|
4965
|
+
}
|
|
4966
|
+
}
|
|
4967
|
+
for (const { file, entry, expected } of importViolations) {
|
|
4968
|
+
violations.push(
|
|
4969
|
+
` - ${at(file, entry.line)} \u5BFC\u5165 '${entry.specifier}'\uFF0C\u5165\u53E3\u53EA\u80FD\u5BFC\u5165 ${expected}/... \u6216 ./${sharedName}/...`
|
|
4970
|
+
);
|
|
4971
|
+
for (const importedName of entry.importedNames) {
|
|
4972
|
+
const count = usages.get(`${entry.specifier}#${importedName}`)?.size ?? 0;
|
|
4973
|
+
violations.push(
|
|
4974
|
+
count >= threshold ? ` ${importedName} \u5DF2\u88AB ${count} \u4E2A\u5165\u53E3\u4F7F\u7528\uFF0C\u5EFA\u8BAE\u79FB\u5230 ${sharedName}\u3002` : ` ${importedName} \u88AB ${count} \u4E2A\u5165\u53E3\u4F7F\u7528\uFF0C\u5EFA\u8BAE\u5728\u5404\u5165\u53E3\u7684 ${utilsName} \u76EE\u5F55\u5206\u522B\u5B9E\u73B0\u3002`
|
|
4975
|
+
);
|
|
4976
|
+
}
|
|
4977
|
+
}
|
|
4978
|
+
const helperFiles = [...await collectFiles4(sharedRoot), ...await collectFiles4(utilsRoot)];
|
|
4979
|
+
for (const file of helperFiles) {
|
|
4980
|
+
const fromArea = isInsidePath5(file, sharedRoot) ? sharedName : utilsName;
|
|
4981
|
+
const source = await parseSourceFile8(file);
|
|
4982
|
+
for (const node of source.program.body) {
|
|
4983
|
+
const specifier = readModuleSpecifier2(node);
|
|
4984
|
+
if (!specifier?.startsWith(".")) continue;
|
|
4985
|
+
const target = path39.resolve(path39.dirname(file), specifier);
|
|
4986
|
+
const toArea = isInsidePath5(target, sharedRoot) ? sharedName : isInsidePath5(target, utilsRoot) ? utilsName : void 0;
|
|
4987
|
+
if (!toArea || toArea === fromArea) continue;
|
|
4988
|
+
violations.push(
|
|
4989
|
+
` - ${at(file, lineOf5(source, node))} ${fromArea} \u4E0D\u80FD\u5F15\u7528 ${toArea} '${specifier}'`
|
|
4990
|
+
);
|
|
4991
|
+
}
|
|
4992
|
+
}
|
|
4993
|
+
const rules = [
|
|
4994
|
+
`\u5165\u53E3\u5FC5\u987B\u5BFC\u51FA ${exportName}\uFF0C\u53EA\u5141\u8BB8\u8BE5\u5BFC\u51FA\u5BF9\u5E94\u7684\u9876\u5C42\u51FD\u6570`,
|
|
4995
|
+
`\u5165\u53E3\u53EA\u80FD\u5BFC\u5165 ${utilsPrefix}<\u5165\u53E3\u540D> \u6216 ./${sharedName}`,
|
|
4996
|
+
`${sharedName} \u4E0E ${utilsName} \u4E92\u4E0D\u5F15\u7528`,
|
|
4997
|
+
strictRoot ? `\u6839\u76EE\u5F55\u53EA\u653E\u5165\u53E3\u4E0E ${sharedName}/${utilsName}` : void 0
|
|
4998
|
+
].filter(Boolean);
|
|
4999
|
+
const lines = [
|
|
5000
|
+
`\u626B\u63CF ${path39.relative(repoRoot, root)} \u4E0B ${entryFiles.length} \u4E2A\u5165\u53E3\u3002`,
|
|
5001
|
+
`\u89C4\u5219\uFF1A${rules.join("\uFF1B")}\u3002`
|
|
5002
|
+
];
|
|
5003
|
+
const success = violations.length === 0;
|
|
5004
|
+
if (success) lines.push("\u672A\u53D1\u73B0\u7ED3\u6784\u8FDD\u89C4\u3002");
|
|
5005
|
+
else
|
|
5006
|
+
lines.push(
|
|
5007
|
+
`\u53D1\u73B0 ${violations.filter((line) => line.startsWith(" - ")).length} \u5904\u8FDD\u89C4\uFF1A`,
|
|
5008
|
+
...violations
|
|
5009
|
+
);
|
|
5010
|
+
return {
|
|
5011
|
+
name: ruleName,
|
|
5012
|
+
success,
|
|
5013
|
+
messages: lines.join("\n"),
|
|
5014
|
+
howToFix: success ? "" : `helper \u79FB\u51FA\u5165\u53E3\u6587\u4EF6\uFF1A\u88AB ${threshold} \u4E2A\u53CA\u4EE5\u4E0A\u5165\u53E3\u4F7F\u7528\u7684\u653E\u5230 ${sharedName}\uFF0C\u5176\u4F59\u653E\u5230 ${utilsName}/<\u5165\u53E3\u540D>\uFF1B${sharedName} \u4E0E ${utilsName} \u4E0D\u8981\u4E92\u76F8\u5F15\u7528\u3002`
|
|
5015
|
+
};
|
|
5016
|
+
}
|
|
5017
|
+
});
|
|
5018
|
+
function readFunctionName2(node) {
|
|
5019
|
+
if (node.type === "FunctionDeclaration") return readName4(node.id) ?? "\u533F\u540D\u51FD\u6570";
|
|
5020
|
+
if (node.type === "VariableDeclarator" && isFunctionLike3(node.init)) {
|
|
5021
|
+
return readName4(node.id) ?? "\u533F\u540D\u51FD\u6570";
|
|
5022
|
+
}
|
|
5023
|
+
return void 0;
|
|
5024
|
+
}
|
|
5025
|
+
function collectEntryFunctions(source, exportName) {
|
|
5026
|
+
const localNames = /* @__PURE__ */ new Set();
|
|
5027
|
+
for (const node of source.program.body) {
|
|
5028
|
+
if (node.type !== "ExportNamedDeclaration" || node.source || node.exportKind === "type")
|
|
5029
|
+
continue;
|
|
5030
|
+
const declaration = node.declaration;
|
|
5031
|
+
if (declaration?.type === "FunctionDeclaration" && readName4(declaration.id) === exportName) {
|
|
5032
|
+
localNames.add(exportName);
|
|
5033
|
+
}
|
|
5034
|
+
if (declaration?.type === "VariableDeclaration") {
|
|
5035
|
+
for (const item of declaration.declarations ?? []) {
|
|
5036
|
+
if (readName4(item.id) === exportName) localNames.add(exportName);
|
|
5037
|
+
}
|
|
5038
|
+
}
|
|
5039
|
+
for (const specifier of node.specifiers ?? []) {
|
|
5040
|
+
if (specifier.exportKind === "type") continue;
|
|
5041
|
+
if (readName4(specifier.exported) === exportName) {
|
|
5042
|
+
const local = readName4(specifier.local);
|
|
5043
|
+
if (local) localNames.add(local);
|
|
5044
|
+
}
|
|
5045
|
+
}
|
|
5046
|
+
}
|
|
5047
|
+
const allowed = /* @__PURE__ */ new Set();
|
|
5048
|
+
for (const node of source.program.body) {
|
|
5049
|
+
const declaration = node.type === "ExportNamedDeclaration" ? node.declaration : node;
|
|
5050
|
+
if (declaration?.type === "FunctionDeclaration" && localNames.has(readName4(declaration.id) ?? "")) {
|
|
5051
|
+
allowed.add(declaration);
|
|
5052
|
+
}
|
|
5053
|
+
if (declaration?.type === "VariableDeclaration") {
|
|
5054
|
+
for (const item of declaration.declarations ?? []) {
|
|
5055
|
+
if (localNames.has(readName4(item.id) ?? "") && isFunctionLike3(item.init)) allowed.add(item);
|
|
5056
|
+
}
|
|
5057
|
+
}
|
|
5058
|
+
}
|
|
5059
|
+
return allowed;
|
|
5060
|
+
}
|
|
5061
|
+
function hasNamedExport(source, exportName) {
|
|
5062
|
+
for (const node of source.program.body) {
|
|
5063
|
+
if (node.type !== "ExportNamedDeclaration" || node.exportKind === "type") continue;
|
|
5064
|
+
const declaration = node.declaration;
|
|
5065
|
+
if (!declaration?.declare && (declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration")) {
|
|
5066
|
+
if (readName4(declaration.id) === exportName) return true;
|
|
5067
|
+
}
|
|
5068
|
+
if (declaration?.type === "VariableDeclaration" && !declaration.declare) {
|
|
5069
|
+
const declarations = declaration.declarations ?? [];
|
|
5070
|
+
if (declarations.some((item) => readName4(item.id) === exportName)) return true;
|
|
5071
|
+
}
|
|
5072
|
+
for (const specifier of node.specifiers ?? []) {
|
|
5073
|
+
if (specifier.exportKind === "type") continue;
|
|
5074
|
+
if ((readName4(specifier.exported) ?? readName4(specifier.local)) === exportName) return true;
|
|
5075
|
+
}
|
|
5076
|
+
}
|
|
5077
|
+
return false;
|
|
5078
|
+
}
|
|
5079
|
+
function collectImports2(source, prefix) {
|
|
5080
|
+
const imports = [];
|
|
5081
|
+
for (const node of source.program.body) {
|
|
5082
|
+
if (node.type !== "ImportDeclaration") continue;
|
|
5083
|
+
const specifier = readModuleSpecifier2(node);
|
|
5084
|
+
if (!specifier?.startsWith(prefix)) continue;
|
|
5085
|
+
const importedNames = (node.specifiers ?? []).map(
|
|
5086
|
+
(item) => item.type === "ImportDefaultSpecifier" ? "default" : item.type === "ImportNamespaceSpecifier" ? "*" : readName4(item.imported) ?? readName4(item.local) ?? "anonymous"
|
|
5087
|
+
);
|
|
5088
|
+
imports.push({ specifier, importedNames, line: lineOf5(source, node) });
|
|
5089
|
+
}
|
|
5090
|
+
return imports;
|
|
5091
|
+
}
|
|
5092
|
+
async function collectFiles4(root) {
|
|
5093
|
+
const files = [];
|
|
5094
|
+
const skipDirNames = new Set(DEFAULT_SKIP_DIR_NAMES2);
|
|
5095
|
+
async function visit(dir) {
|
|
5096
|
+
const entries2 = await readDirIfExists5(dir);
|
|
5097
|
+
for (const entry of entries2 ?? []) {
|
|
5098
|
+
const full = path39.join(dir, entry.name);
|
|
5099
|
+
if (entry.isDirectory()) {
|
|
5100
|
+
if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
|
|
5101
|
+
await visit(full);
|
|
5102
|
+
continue;
|
|
5103
|
+
}
|
|
5104
|
+
if (entry.isFile() && [".ts", ".tsx"].some((extension) => full.endsWith(extension))) {
|
|
5105
|
+
files.push(full);
|
|
5106
|
+
}
|
|
5107
|
+
}
|
|
5108
|
+
}
|
|
5109
|
+
await visit(root);
|
|
5110
|
+
return files.sort((left, right) => left.localeCompare(right));
|
|
5111
|
+
}
|
|
5112
|
+
async function readDirIfExists5(dir) {
|
|
5113
|
+
try {
|
|
5114
|
+
return await fs8.readdir(dir, { withFileTypes: true });
|
|
5115
|
+
} catch (error) {
|
|
5116
|
+
if (error.code === "ENOENT") return void 0;
|
|
5117
|
+
throw error;
|
|
5118
|
+
}
|
|
5119
|
+
}
|
|
5120
|
+
function isInsidePath5(filePath, dir) {
|
|
5121
|
+
const relative = path39.relative(dir, filePath);
|
|
5122
|
+
return relative === "" || !relative.startsWith("..") && !path39.isAbsolute(relative);
|
|
5123
|
+
}
|
|
5124
|
+
function formatLocation4(repoRoot, file, line) {
|
|
5125
|
+
return `${path39.relative(repoRoot, file)}:${line}`;
|
|
5126
|
+
}
|
|
5127
|
+
async function parseSourceFile8(file) {
|
|
5128
|
+
const code = await fs8.readFile(file, "utf8");
|
|
5129
|
+
const lineStarts = [0];
|
|
5130
|
+
for (let index = 0; index < code.length; index += 1) {
|
|
5131
|
+
if (code[index] === "\n") lineStarts.push(index + 1);
|
|
5132
|
+
}
|
|
5133
|
+
const parsed = parseSync8(file, code);
|
|
5134
|
+
if (parsed.errors.length)
|
|
5135
|
+
throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
|
|
5136
|
+
return { file, program: parsed.program, lineStarts };
|
|
5137
|
+
}
|
|
5138
|
+
function walk8(node, visit) {
|
|
5139
|
+
if (!node || typeof node !== "object") return;
|
|
5140
|
+
const current = node;
|
|
5141
|
+
if (typeof current.type === "string") visit(current);
|
|
5142
|
+
for (const key of Object.keys(current)) {
|
|
5143
|
+
if (SKIP_AST_KEYS8.has(key)) continue;
|
|
5144
|
+
const value = current[key];
|
|
5145
|
+
if (Array.isArray(value)) {
|
|
5146
|
+
for (const child of value) walk8(child, visit);
|
|
5147
|
+
} else if (value && typeof value === "object") {
|
|
5148
|
+
walk8(value, visit);
|
|
5149
|
+
}
|
|
5150
|
+
}
|
|
5151
|
+
}
|
|
5152
|
+
function lineOf5(source, node) {
|
|
5153
|
+
if (typeof node.start !== "number") return 0;
|
|
5154
|
+
let low = 0;
|
|
5155
|
+
let high = source.lineStarts.length - 1;
|
|
5156
|
+
while (low <= high) {
|
|
5157
|
+
const mid = Math.floor((low + high) / 2);
|
|
5158
|
+
if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
|
|
5159
|
+
else high = mid - 1;
|
|
5160
|
+
}
|
|
5161
|
+
return high + 1;
|
|
5162
|
+
}
|
|
5163
|
+
function readStringLiteral6(node) {
|
|
5164
|
+
if (!node) return void 0;
|
|
5165
|
+
if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") {
|
|
5166
|
+
return node.value;
|
|
5167
|
+
}
|
|
5168
|
+
return void 0;
|
|
5169
|
+
}
|
|
5170
|
+
function readName4(node) {
|
|
5171
|
+
if (!node) return void 0;
|
|
5172
|
+
if (typeof node.name === "string") return node.name;
|
|
5173
|
+
if (typeof node.value === "string") return node.value;
|
|
5174
|
+
return void 0;
|
|
5175
|
+
}
|
|
5176
|
+
function isFunctionLike3(node) {
|
|
5177
|
+
if (node && [
|
|
5178
|
+
"ParenthesizedExpression",
|
|
5179
|
+
"TSAsExpression",
|
|
5180
|
+
"TSSatisfiesExpression",
|
|
5181
|
+
"TSTypeAssertion",
|
|
5182
|
+
"TSNonNullExpression"
|
|
5183
|
+
].includes(node.type ?? "")) {
|
|
5184
|
+
return isFunctionLike3(node.expression);
|
|
5185
|
+
}
|
|
5186
|
+
return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
|
|
5187
|
+
}
|
|
5188
|
+
function readModuleSpecifier2(node) {
|
|
5189
|
+
if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
|
|
5190
|
+
return readStringLiteral6(node.source);
|
|
5191
|
+
}
|
|
5192
|
+
return void 0;
|
|
5193
|
+
}
|
|
5194
|
+
|
|
5195
|
+
// packages/conformance/rules.ts
|
|
5196
|
+
var builtinRules = [
|
|
5197
|
+
baselineMaxDiffPixels,
|
|
5198
|
+
commitMessage,
|
|
5199
|
+
conformanceRuleFormat,
|
|
5200
|
+
duplicateLocalization,
|
|
5201
|
+
e2eScenariosStructure,
|
|
5202
|
+
sameDirImportOnly,
|
|
5203
|
+
singleComponentFile,
|
|
5204
|
+
sourceLocaleDefaults,
|
|
5205
|
+
syncLocales,
|
|
5206
|
+
uiScenariosStructure
|
|
5207
|
+
];
|
|
5208
|
+
|
|
5209
|
+
// packages/conformance/runner/load.ts
|
|
5210
|
+
import { access as access2 } from "node:fs/promises";
|
|
5211
|
+
import path40 from "node:path";
|
|
5212
|
+
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
5213
|
+
import { tsImport as tsImport2 } from "tsx/esm/api";
|
|
5214
|
+
async function loadConformanceConfig(directory) {
|
|
5215
|
+
const file = path40.resolve(directory, "evidra.conformance.ts");
|
|
5216
|
+
try {
|
|
5217
|
+
await access2(file);
|
|
5218
|
+
} catch (error) {
|
|
5219
|
+
if (error.code === "ENOENT") return null;
|
|
5220
|
+
throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u914D\u7F6E\u6587\u4EF6\uFF1A${file}`, { cause: error });
|
|
5221
|
+
}
|
|
5222
|
+
let config;
|
|
5223
|
+
try {
|
|
5224
|
+
const loaded = (await tsImport2(pathToFileURL2(file).href, import.meta.url)).default;
|
|
5225
|
+
config = loaded?.__esModule ? loaded.default : loaded;
|
|
5226
|
+
} catch (error) {
|
|
5227
|
+
throw new Error(
|
|
5228
|
+
`\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25 ${file}\uFF1A${error instanceof Error ? error.message : String(error)}`
|
|
5229
|
+
);
|
|
5230
|
+
}
|
|
5231
|
+
if (!config || !Array.isArray(config.rules) || config.rules.some((task) => typeof task !== "function") || config.projectRoot !== void 0 && typeof config.projectRoot !== "string") {
|
|
5232
|
+
throw new Error(`${file} \u5FC5\u987B\u9ED8\u8BA4\u5BFC\u51FA { projectRoot?: string, rules: RuleTask[] }`);
|
|
5233
|
+
}
|
|
5234
|
+
const projectRoot = path40.resolve(path40.dirname(file), config.projectRoot ?? ".");
|
|
5235
|
+
return { projectRoot, rules: config.rules };
|
|
5236
|
+
}
|
|
5237
|
+
|
|
5238
|
+
// packages/service/src/conformance.ts
|
|
5239
|
+
var catalog = builtinRules.map((rule) => rule.meta);
|
|
5240
|
+
async function listRules(root) {
|
|
5241
|
+
const config = await loadConformanceConfig(root);
|
|
5242
|
+
const entries2 = /* @__PURE__ */ new Map();
|
|
5243
|
+
for (const [index, task] of (config?.rules ?? []).entries()) {
|
|
5244
|
+
const id = task.id?.trim() || task.doc?.id || task.name || `rule-${index + 1}`;
|
|
5245
|
+
if (entries2.has(id)) continue;
|
|
5246
|
+
const bundled = catalog.find((rule) => rule.id === id);
|
|
5247
|
+
entries2.set(id, {
|
|
5248
|
+
id,
|
|
5249
|
+
displayName: task.displayName?.trim() || task.doc?.displayName || bundled?.displayName || task.name || `\u81EA\u5B9A\u4E49\u89C4\u7EA6 ${index + 1}`,
|
|
5250
|
+
enabled: true,
|
|
5251
|
+
readme: typeof task.readme === "string" ? task.readme : void 0,
|
|
5252
|
+
doc: task.doc ?? bundled
|
|
5253
|
+
});
|
|
5254
|
+
}
|
|
5255
|
+
const rules = config ? Array.from(entries2.values(), (entry) => entry.displayName) : null;
|
|
5256
|
+
for (const rule of catalog) {
|
|
5257
|
+
if (!entries2.has(rule.id)) {
|
|
5258
|
+
entries2.set(rule.id, {
|
|
5259
|
+
id: rule.id,
|
|
5260
|
+
displayName: rule.displayName,
|
|
5261
|
+
enabled: false,
|
|
5262
|
+
doc: rule
|
|
5263
|
+
});
|
|
5264
|
+
}
|
|
5265
|
+
}
|
|
5266
|
+
return { rules, entries: entries2 };
|
|
5267
|
+
}
|
|
5268
|
+
function isWithin(directory, file) {
|
|
5269
|
+
const relative = path41.relative(directory, file);
|
|
5270
|
+
return relative !== ".." && !relative.startsWith(`..${path41.sep}`) && !path41.isAbsolute(relative);
|
|
5271
|
+
}
|
|
5272
|
+
async function resolveMarkdown(directory, file) {
|
|
5273
|
+
if (path41.isAbsolute(file) || path41.extname(file).toLowerCase() !== ".md") return null;
|
|
5274
|
+
const candidate = path41.resolve(directory, file);
|
|
5275
|
+
if (!isWithin(directory, candidate)) return null;
|
|
5276
|
+
try {
|
|
5277
|
+
const resolved = await realpath4(candidate);
|
|
5278
|
+
if (!isWithin(await realpath4(directory), resolved) || !(await stat3(resolved)).isFile())
|
|
5279
|
+
return null;
|
|
5280
|
+
return resolved;
|
|
5281
|
+
} catch (error) {
|
|
5282
|
+
if (["ENOENT", "ENOTDIR"].includes(error.code ?? "")) return null;
|
|
5283
|
+
throw error;
|
|
5284
|
+
}
|
|
5285
|
+
}
|
|
5286
|
+
async function hasReadme(root, entry) {
|
|
5287
|
+
if (entry.readme !== void 0) return !!await resolveMarkdown(root, entry.readme);
|
|
5288
|
+
return !!entry.doc;
|
|
5289
|
+
}
|
|
5290
|
+
async function readReadme(root, entry) {
|
|
5291
|
+
if (entry.readme !== void 0) {
|
|
5292
|
+
const file = await resolveMarkdown(root, entry.readme);
|
|
5293
|
+
return file ? readFile13(file, "utf8") : null;
|
|
5294
|
+
}
|
|
5295
|
+
return entry.doc ? renderRuleDoc(entry.doc) : null;
|
|
5296
|
+
}
|
|
5297
|
+
function createConformanceRoutes(root) {
|
|
5298
|
+
const app = new Hono();
|
|
5299
|
+
app.get("/", async (context) => {
|
|
5300
|
+
const { rules, entries: entries2 } = await listRules(root);
|
|
5301
|
+
return context.json({
|
|
5302
|
+
rules,
|
|
5303
|
+
entries: await Promise.all(
|
|
5304
|
+
Array.from(entries2.values(), async (item) => ({
|
|
5305
|
+
id: item.id,
|
|
5306
|
+
displayName: item.displayName,
|
|
5307
|
+
enabled: item.enabled,
|
|
5308
|
+
hasReadme: await hasReadme(root, item)
|
|
5309
|
+
}))
|
|
5310
|
+
)
|
|
5311
|
+
});
|
|
5312
|
+
});
|
|
5313
|
+
app.get("/readme", async (context) => {
|
|
5314
|
+
const id = context.req.query("rule");
|
|
5315
|
+
const { entries: entries2 } = await listRules(root);
|
|
5316
|
+
const rule = id ? entries2.get(id) : void 0;
|
|
5317
|
+
if (!rule) return context.json({ error: "\u627E\u4E0D\u5230\u6307\u5B9A\u89C4\u7EA6" }, 404);
|
|
5318
|
+
const markdown = await readReadme(root, rule);
|
|
5319
|
+
return context.json({ markdown });
|
|
5320
|
+
});
|
|
5321
|
+
return app;
|
|
5322
|
+
}
|
|
5323
|
+
|
|
5324
|
+
// packages/service/src/reportSession.ts
|
|
5325
|
+
import { createHash as createHash4, randomBytes, timingSafeEqual } from "node:crypto";
|
|
5326
|
+
import { getCookie, setCookie } from "hono/cookie";
|
|
5327
|
+
|
|
5328
|
+
// packages/client-sdk/src/error.ts
|
|
5329
|
+
var REPORT_PASSWORD_REQUIRED = "REPORT_PASSWORD_REQUIRED";
|
|
5330
|
+
var REPORT_PASSWORD_INVALID = "REPORT_PASSWORD_INVALID";
|
|
5331
|
+
|
|
5332
|
+
// packages/service/src/reportSession.ts
|
|
5333
|
+
function createReportSession(password) {
|
|
5334
|
+
const passwordHash = createHash4("sha256").update(password).digest();
|
|
5335
|
+
const token = randomBytes(32).toString("base64url");
|
|
5336
|
+
const cookieName = (context) => `evidra_session_${new URL(context.req.url).port || "default"}`;
|
|
5337
|
+
const requireSession = async (context, next) => {
|
|
5338
|
+
if (getCookie(context, cookieName(context)) !== token) {
|
|
5339
|
+
context.header("Cache-Control", "no-store");
|
|
5340
|
+
return context.json({ code: REPORT_PASSWORD_REQUIRED, error: "\u8BF7\u8F93\u5165\u62A5\u544A\u5BC6\u7801" }, 401);
|
|
5341
|
+
}
|
|
5342
|
+
await next();
|
|
5343
|
+
};
|
|
5344
|
+
async function login(context) {
|
|
5345
|
+
if (context.req.header("Content-Type")?.split(";")[0]?.trim().toLowerCase() !== "application/json")
|
|
5346
|
+
return context.json({ error: "\u8BF7\u4F7F\u7528 JSON \u63D0\u4EA4\u5BC6\u7801" }, 415);
|
|
5347
|
+
const body = await context.req.json().catch(() => null);
|
|
5348
|
+
if (typeof body?.password !== "string" || !timingSafeEqual(createHash4("sha256").update(body.password).digest(), passwordHash)) {
|
|
5349
|
+
return context.json({ code: REPORT_PASSWORD_INVALID, error: "\u5BC6\u7801\u9519\u8BEF\uFF0C\u8BF7\u91CD\u65B0\u8F93\u5165\u3002" }, 401);
|
|
5350
|
+
}
|
|
5351
|
+
setCookie(context, cookieName(context), token, {
|
|
5352
|
+
httpOnly: true,
|
|
5353
|
+
sameSite: "Strict",
|
|
5354
|
+
secure: new URL(context.req.url).protocol === "https:",
|
|
5355
|
+
path: "/"
|
|
5356
|
+
});
|
|
5357
|
+
return context.body(null, 204);
|
|
5358
|
+
}
|
|
5359
|
+
return { login, requireSession };
|
|
5360
|
+
}
|
|
5361
|
+
|
|
5362
|
+
// packages/service/src/server.ts
|
|
5363
|
+
function defaultWebDist() {
|
|
5364
|
+
const fromSource = path42.resolve(import.meta.dirname, "../../../dist/web");
|
|
5365
|
+
const fromBundle = path42.resolve(import.meta.dirname, "../../dist/web");
|
|
5366
|
+
return [fromSource, fromBundle].find((directory) => existsSync(path42.join(directory, "index.html"))) ?? fromSource;
|
|
5367
|
+
}
|
|
5368
|
+
async function startServer(options) {
|
|
5369
|
+
const root = path42.resolve(options.repoRoot);
|
|
5370
|
+
await loadConfig({ repoRoot: root });
|
|
5371
|
+
const webDist = options.webDist ?? defaultWebDist();
|
|
5372
|
+
if (options.password === "") throw new Error("\u62A5\u544A\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A");
|
|
5373
|
+
const app = createApp(root, webDist, options.password);
|
|
5374
|
+
let server;
|
|
5375
|
+
const address = await new Promise((resolve, reject) => {
|
|
5376
|
+
server = serve(
|
|
5377
|
+
{
|
|
5378
|
+
fetch: app.fetch,
|
|
5379
|
+
port: options.port ?? 4175,
|
|
5380
|
+
hostname: options.host ?? "127.0.0.1"
|
|
5381
|
+
},
|
|
5382
|
+
resolve
|
|
5383
|
+
);
|
|
5384
|
+
server.once("error", reject);
|
|
5385
|
+
});
|
|
5386
|
+
const url = `http://${options.host ?? "127.0.0.1"}:${address.port}`;
|
|
5387
|
+
return {
|
|
5388
|
+
url,
|
|
5389
|
+
port: address.port,
|
|
5390
|
+
async close() {
|
|
5391
|
+
await new Promise((resolve, reject) => {
|
|
5392
|
+
server.close((error) => error ? reject(error) : resolve());
|
|
5393
|
+
server.closeAllConnections?.();
|
|
5394
|
+
});
|
|
5395
|
+
}
|
|
5396
|
+
};
|
|
5397
|
+
}
|
|
5398
|
+
function projectFileError(error) {
|
|
5399
|
+
if (!(error instanceof Error) || !("code" in error)) throw error;
|
|
5400
|
+
switch (error.code) {
|
|
5401
|
+
case "ENOENT":
|
|
5402
|
+
case "ENOTDIR":
|
|
5403
|
+
throw Object.assign(new Error("\u6587\u4EF6\u6216\u76EE\u5F55\u4E0D\u5B58\u5728\uFF0C\u53EF\u80FD\u5DF2\u88AB\u5220\u9664\u3002"), { statusCode: 404 });
|
|
5404
|
+
case "EPERM":
|
|
5405
|
+
case "EACCES":
|
|
5406
|
+
throw Object.assign(new Error("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u8FD9\u4E2A\u6587\u4EF6\u6216\u76EE\u5F55\u3002"), { statusCode: 403 });
|
|
5407
|
+
default:
|
|
5408
|
+
throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55\u3002");
|
|
5409
|
+
}
|
|
5410
|
+
}
|
|
5411
|
+
function createApp(root, webDist, password) {
|
|
5412
|
+
const app = new Hono2();
|
|
5413
|
+
app.onError((error, context) => {
|
|
5414
|
+
if (error instanceof HTTPException) return context.json({ error: error.message }, error.status);
|
|
5415
|
+
const status = error instanceof z40.ZodError ? 400 : error.statusCode ?? 500;
|
|
5416
|
+
return context.json({ error: String(error.message ?? error) }, status);
|
|
5417
|
+
});
|
|
5418
|
+
app.use("/api/*", async (context, next) => {
|
|
5419
|
+
context.header("Cache-Control", "no-store");
|
|
5420
|
+
await next();
|
|
5421
|
+
});
|
|
5422
|
+
if (password !== void 0) {
|
|
5423
|
+
const session = createReportSession(password);
|
|
5424
|
+
app.post("/api/session", session.login);
|
|
5425
|
+
app.use("/api/*", session.requireSession);
|
|
5426
|
+
app.use("/api/*", csrf());
|
|
5427
|
+
app.use("/report-static/*", session.requireSession);
|
|
5428
|
+
}
|
|
5429
|
+
app.get("/api/project", async (context) => {
|
|
5430
|
+
const [project, config] = await Promise.all([
|
|
5431
|
+
readProjectInfo({ repoRoot: root }),
|
|
5432
|
+
loadConfig({ repoRoot: root })
|
|
5433
|
+
]);
|
|
5434
|
+
return context.json({ ...project, reportDir: config.reportDir.split(path42.sep).join("/") });
|
|
5435
|
+
});
|
|
5436
|
+
app.route("/api/conformance", createConformanceRoutes(root));
|
|
5437
|
+
app.get(
|
|
5438
|
+
"/api/files",
|
|
5439
|
+
async (context) => context.json(
|
|
5440
|
+
await listProjectFiles({
|
|
5441
|
+
repoRoot: root,
|
|
5442
|
+
directory: context.req.query("directory") ?? ""
|
|
5443
|
+
}).catch(projectFileError)
|
|
5444
|
+
)
|
|
5445
|
+
);
|
|
5446
|
+
app.get(
|
|
5447
|
+
"/api/files/content",
|
|
5448
|
+
async (context) => context.json(
|
|
5449
|
+
await readProjectFile({
|
|
5450
|
+
repoRoot: root,
|
|
5451
|
+
file: context.req.query("path") ?? "",
|
|
5452
|
+
offset: Number(context.req.query("offset") ?? 0)
|
|
5453
|
+
}).catch(projectFileError)
|
|
5454
|
+
)
|
|
5455
|
+
);
|
|
5456
|
+
app.get(
|
|
5457
|
+
"/api/changelog",
|
|
5458
|
+
async (context) => context.json(await listChangelogCommits({ repoRoot: root }))
|
|
5459
|
+
);
|
|
5460
|
+
app.get(
|
|
5461
|
+
"/api/changelog/:commitId/files",
|
|
3041
5462
|
async (context) => context.json(
|
|
3042
5463
|
await getChangelogFiles({
|
|
3043
5464
|
repoRoot: root,
|
|
@@ -3140,12 +5561,12 @@ function createApp(root, webDist, password) {
|
|
|
3140
5561
|
await next();
|
|
3141
5562
|
const filePath = context.get("staticFile");
|
|
3142
5563
|
if (!filePath) return;
|
|
3143
|
-
const stats = await
|
|
5564
|
+
const stats = await stat4(filePath);
|
|
3144
5565
|
context.header(
|
|
3145
5566
|
"ETag",
|
|
3146
5567
|
`W/"${stats.size.toString(16)}-${stats.mtimeMs.toString(16)}-${stats.ctimeMs.toString(16)}"`
|
|
3147
5568
|
);
|
|
3148
|
-
const relativePath =
|
|
5569
|
+
const relativePath = path42.relative(webDist, filePath).split(path42.sep).join("/");
|
|
3149
5570
|
const reportFile = context.req.path.startsWith("/report-static/");
|
|
3150
5571
|
if (reportFile && password !== void 0) {
|
|
3151
5572
|
context.header("Cache-Control", "private, no-cache");
|
|
@@ -3193,7 +5614,7 @@ function createApp(root, webDist, password) {
|
|
|
3193
5614
|
await next();
|
|
3194
5615
|
});
|
|
3195
5616
|
app.get("*", serveStatic({ root: webDist, ...staticOptions }));
|
|
3196
|
-
app.get("*", (context, next) =>
|
|
5617
|
+
app.get("*", (context, next) => path42.extname(context.req.path) ? context.notFound() : next());
|
|
3197
5618
|
app.get("*", serveStatic({ root: webDist, path: "index.html", ...staticOptions }));
|
|
3198
5619
|
app.get("*", (context) => context.text("\u62A5\u544A UI \u5C1A\u672A\u6784\u5EFA\uFF1A\u8BF7\u5148\u8FD0\u884C pnpm build", 404));
|
|
3199
5620
|
return app;
|
|
@@ -3222,13 +5643,13 @@ async function startWorkbench(options) {
|
|
|
3222
5643
|
}
|
|
3223
5644
|
|
|
3224
5645
|
// packages/service/src/init.ts
|
|
3225
|
-
import { existsSync as
|
|
5646
|
+
import { existsSync as existsSync2, statSync } from "node:fs";
|
|
3226
5647
|
import { cp, readdir as readdir6, rm as rm6, writeFile as writeFile3 } from "node:fs/promises";
|
|
3227
|
-
import
|
|
5648
|
+
import path43 from "node:path";
|
|
3228
5649
|
var skillsDirectory = [
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
].find((directory) =>
|
|
5650
|
+
path43.resolve(import.meta.dirname, "../../../skills"),
|
|
5651
|
+
path43.resolve(import.meta.dirname, "../../skills")
|
|
5652
|
+
].find((directory) => existsSync2(directory));
|
|
3232
5653
|
var warning = `# \u8BF7\u52FF\u4FEE\u6539\u6B64\u76EE\u5F55
|
|
3233
5654
|
|
|
3234
5655
|
\u6B64\u76EE\u5F55\u7531 \`evidra init\` \u751F\u6210\u3002\u6BCF\u6B21\u8FD0\u884C \`evidra init\` \u90FD\u4F1A\u5220\u9664\u5E76\u91CD\u65B0\u5199\u5165\u6574\u4E2A\u76EE\u5F55\uFF0C\u5728\u8FD9\u91CC\u505A\u7684\u4FEE\u6539\u4F1A\u4E22\u5931\u3002
|
|
@@ -3236,31 +5657,31 @@ var warning = `# \u8BF7\u52FF\u4FEE\u6539\u6B64\u76EE\u5F55
|
|
|
3236
5657
|
\u5982\u9700\u81EA\u5B9A\u4E49\uFF0C\u8BF7\u628A\u76EE\u5F55\u590D\u5236\u4E3A\u5176\u4ED6\u540D\u5B57\uFF0C\u5E76\u4FEE\u6539\u5176\u4E2D SKILL.md \u7684 \`name\`\u3002
|
|
3237
5658
|
`;
|
|
3238
5659
|
async function initProject(directory) {
|
|
3239
|
-
const root =
|
|
5660
|
+
const root = path43.resolve(directory);
|
|
3240
5661
|
if (!skillsDirectory) throw new Error("\u672A\u627E\u5230\u968F\u5305\u63D0\u4F9B\u7684 skills \u76EE\u5F55");
|
|
3241
5662
|
const skills = (await readdir6(skillsDirectory, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name);
|
|
3242
5663
|
const messages = [];
|
|
3243
5664
|
const agents = [".claude", ".codex"];
|
|
3244
|
-
if (statSync(
|
|
5665
|
+
if (statSync(path43.join(root, ".agents"), { throwIfNoEntry: false })?.isDirectory()) {
|
|
3245
5666
|
agents.push(".agents");
|
|
3246
5667
|
}
|
|
3247
5668
|
for (const agent of agents) {
|
|
3248
5669
|
for (const skill of skills) {
|
|
3249
|
-
const target =
|
|
5670
|
+
const target = path43.join(root, agent, "skills", skill);
|
|
3250
5671
|
await rm6(target, { recursive: true, force: true });
|
|
3251
|
-
await cp(
|
|
5672
|
+
await cp(path43.join(skillsDirectory, skill), target, {
|
|
3252
5673
|
recursive: true,
|
|
3253
|
-
filter: (source) => !
|
|
5674
|
+
filter: (source) => !path43.basename(source).startsWith(".")
|
|
3254
5675
|
});
|
|
3255
|
-
await writeFile3(
|
|
3256
|
-
messages.push(`\u5DF2\u5199\u5165 ${
|
|
5676
|
+
await writeFile3(path43.join(target, "DO_NOT_EDIT.md"), warning);
|
|
5677
|
+
messages.push(`\u5DF2\u5199\u5165 ${path43.relative(root, target)}`);
|
|
3257
5678
|
}
|
|
3258
5679
|
}
|
|
3259
5680
|
return messages;
|
|
3260
5681
|
}
|
|
3261
5682
|
|
|
3262
5683
|
// packages/conformance/runner/cli.ts
|
|
3263
|
-
import
|
|
5684
|
+
import path44 from "node:path";
|
|
3264
5685
|
|
|
3265
5686
|
// packages/conformance/runner/run.ts
|
|
3266
5687
|
async function runner(common, tasks) {
|
|
@@ -3299,7 +5720,7 @@ function printResults(results) {
|
|
|
3299
5720
|
async function runConformance(directory) {
|
|
3300
5721
|
const config = await loadConformanceConfig(directory);
|
|
3301
5722
|
if (!config)
|
|
3302
|
-
throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u914D\u7F6E\u6587\u4EF6\uFF1A${
|
|
5723
|
+
throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u914D\u7F6E\u6587\u4EF6\uFF1A${path44.resolve(directory, "evidra.conformance.ts")}`);
|
|
3303
5724
|
return printResults(await runner({ projectRoot: config.projectRoot }, config.rules));
|
|
3304
5725
|
}
|
|
3305
5726
|
|
|
@@ -3328,7 +5749,7 @@ function startPassword() {
|
|
|
3328
5749
|
return password;
|
|
3329
5750
|
}
|
|
3330
5751
|
cli.command("init [path]", "\u590D\u5236 skill \u5230 .claude\u3001.codex \u548C\u5DF2\u5B58\u5728\u7684 .agents\uFF0C\u9ED8\u8BA4\u5F53\u524D\u76EE\u5F55").action(async (target) => {
|
|
3331
|
-
const root =
|
|
5752
|
+
const root = path45.resolve(target ?? process.cwd());
|
|
3332
5753
|
console.log(`\u521D\u59CB\u5316 Evidra\uFF1A${root}`);
|
|
3333
5754
|
for (const message of await initProject(root)) console.log(message);
|
|
3334
5755
|
});
|
|
@@ -3337,7 +5758,7 @@ cli.command("start", "\u542F\u52A8\u5DE5\u4F5C\u53F0\uFF0C\u670D\u52A1\u5728\u52
|
|
|
3337
5758
|
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
3338
5759
|
throw new Error("\u7AEF\u53E3\u5FC5\u987B\u662F 1\u201365535 \u7684\u6574\u6570");
|
|
3339
5760
|
await startWorkbench({
|
|
3340
|
-
repoRoot:
|
|
5761
|
+
repoRoot: path45.resolve(options.repo ?? process.env.TEST_REPORT_REPO ?? process.cwd()),
|
|
3341
5762
|
port,
|
|
3342
5763
|
password: startPassword()
|
|
3343
5764
|
});
|
|
@@ -3345,7 +5766,7 @@ cli.command("start", "\u542F\u52A8\u5DE5\u4F5C\u53F0\uFF0C\u670D\u52A1\u5728\u52
|
|
|
3345
5766
|
cli.command("compare", "\u8C03\u7528 core \u6BD4\u8F83\u4EFB\u52A1\u548C\u57FA\u7EBF\uFF0C\u8F93\u51FA summary").option("--repo <path>", "\u4ED3\u5E93\u8DEF\u5F84\uFF0C\u9ED8\u8BA4\u5F53\u524D\u76EE\u5F55").option("--task-id <id>", "\u4EFB\u52A1 ID").option("--full", "\u8F93\u51FA\u5B8C\u6574\u6BD4\u8F83\u7ED3\u679C").action(async (options) => {
|
|
3346
5767
|
if (!options.taskId) throw new Error("\u8BF7\u63D0\u4F9B --task-id");
|
|
3347
5768
|
const result = await compareTask({
|
|
3348
|
-
repoRoot:
|
|
5769
|
+
repoRoot: path45.resolve(options.repo ?? process.cwd()),
|
|
3349
5770
|
taskId: options.taskId
|
|
3350
5771
|
});
|
|
3351
5772
|
console.log(JSON.stringify(options.full ? result : result.summary, null, 2));
|
|
@@ -3355,7 +5776,7 @@ cli.command("compare-tasks", "\u6BD4\u8F83\u4E24\u4E2A\u4EFB\u52A1\u7684\u7528\u
|
|
|
3355
5776
|
if (!options.baseTaskId) throw new Error("\u8BF7\u63D0\u4F9B --base-task-id");
|
|
3356
5777
|
if (!options.taskId) throw new Error("\u8BF7\u63D0\u4F9B --task-id");
|
|
3357
5778
|
const result = await compareTasks({
|
|
3358
|
-
repoRoot:
|
|
5779
|
+
repoRoot: path45.resolve(options.repo ?? process.cwd()),
|
|
3359
5780
|
baseTaskId: options.baseTaskId,
|
|
3360
5781
|
taskId: options.taskId
|
|
3361
5782
|
});
|