@raintree-technology/hig-doctor-core 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,156 +0,0 @@
1
- import { describe, test, expect } from "bun:test";
2
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { parseConfig, loadConfig, applyConfig } from "./config";
6
- import type { PatternMatch } from "./patterns";
7
- import { audit } from "./audit";
8
-
9
- const match = (over: Partial<PatternMatch>): PatternMatch => ({
10
- ruleId: "swift/hardcoded-color",
11
- engine: "regex",
12
- category: "foundations",
13
- subcategory: "color",
14
- type: "concern",
15
- pattern: "hardcodedColor",
16
- line: 1,
17
- lineContent: ".foregroundColor(.red)",
18
- file: "A.swift",
19
- severity: "moderate",
20
- ...over,
21
- });
22
-
23
- describe("parseConfig", () => {
24
- test("accepts rules, ignore, and overrides", () => {
25
- const { config, warnings } = parseConfig(
26
- JSON.stringify({
27
- rules: { "swift/hardcoded-color": "off", "web/*": "serious" },
28
- ignore: ["legacy/**"],
29
- overrides: [{ files: ["marketing/**"], rules: { "css/outline-none": "off" } }],
30
- }),
31
- "cfg",
32
- );
33
- expect(config.rules?.["swift/hardcoded-color"]).toBe("off");
34
- expect(config.ignore).toEqual(["legacy/**"]);
35
- expect(config.overrides?.length).toBe(1);
36
- expect(warnings).toEqual([]);
37
- });
38
-
39
- test("warns on unknown exact rule IDs but not on globs", () => {
40
- const { warnings } = parseConfig(
41
- JSON.stringify({ rules: { "swift/does-not-exist": "off", "nope/*": "off" } }),
42
- "cfg",
43
- );
44
- expect(warnings.length).toBe(1);
45
- expect(warnings[0]).toContain("swift/does-not-exist");
46
- });
47
-
48
- test("rejects invalid settings, shapes, and JSON", () => {
49
- expect(() => parseConfig(JSON.stringify({ rules: { "swift/hardcoded-color": "loud" } }), "cfg")).toThrow("invalid setting");
50
- expect(() => parseConfig(JSON.stringify({ ignore: "legacy/**" }), "cfg")).toThrow('"ignore" must be an array');
51
- expect(() => parseConfig(JSON.stringify({ overrides: [{ rules: {} }] }), "cfg")).toThrow('"files" must be a non-empty array');
52
- expect(() => parseConfig("{nope", "cfg")).toThrow("not valid JSON");
53
- });
54
- });
55
-
56
- describe("applyConfig — path separators", () => {
57
- // match.file carries the platform separator; the globs are POSIX. Without
58
- // normalizing, every per-path override silently no-ops on Windows.
59
- test("per-path overrides match regardless of separator", () => {
60
- const config = {
61
- overrides: [{ files: ["marketing/**"], rules: { "css/outline-none": "off" as const } }],
62
- };
63
- for (const file of ["marketing/promo.css", "marketing\\promo.css"]) {
64
- const match = {
65
- ruleId: "css/outline-none",
66
- engine: "regex" as const,
67
- category: "foundations",
68
- subcategory: "accessibility",
69
- type: "concern" as const,
70
- pattern: "outline none",
71
- line: 1,
72
- lineContent: "outline: none;",
73
- file,
74
- severity: "serious" as const,
75
- };
76
- expect(applyConfig([match], config)).toEqual([]);
77
- }
78
- });
79
- });
80
-
81
- describe("applyConfig", () => {
82
- test("off drops matches; severities remap concerns only", () => {
83
- const matches = [
84
- match({}),
85
- match({ ruleId: "swift/navigation-view-deprecated", pattern: "NavigationView (deprecated)" }),
86
- match({ ruleId: "swift/semantic-color", type: "positive", severity: undefined }),
87
- ];
88
- const out = applyConfig(matches, {
89
- rules: {
90
- "swift/hardcoded-color": "off",
91
- "swift/navigation-view-deprecated": "critical",
92
- "swift/semantic-color": "serious",
93
- },
94
- });
95
- expect(out.length).toBe(2);
96
- expect(out[0].severity).toBe("critical");
97
- expect(out[1].severity).toBeUndefined(); // positives never gain a severity
98
- });
99
-
100
- test("prefix globs apply with longest-prefix precedence", () => {
101
- const out = applyConfig([match({})], {
102
- rules: { "swift/*": "off", "swift/hardcoded-*": "critical" },
103
- });
104
- expect(out.length).toBe(1);
105
- expect(out[0].severity).toBe("critical");
106
- });
107
-
108
- test("per-path overrides beat global rules, last override wins", () => {
109
- const matches = [match({ file: "marketing/Hero.swift" }), match({ file: "app/Main.swift" })];
110
- const out = applyConfig(matches, {
111
- rules: { "swift/hardcoded-color": "critical" },
112
- overrides: [
113
- { files: ["marketing/**"], rules: { "swift/hardcoded-color": "off" } },
114
- ],
115
- });
116
- expect(out.length).toBe(1);
117
- expect(out[0].file).toBe("app/Main.swift");
118
- expect(out[0].severity).toBe("critical");
119
- });
120
- });
121
-
122
- describe("audit config integration", () => {
123
- test("discovers hig-doctor.config.json: ignore globs and rule offs apply", async () => {
124
- const dir = await mkdtemp(join(tmpdir(), "hig-config-"));
125
- try {
126
- await writeFile(join(dir, "View.swift"), ".foregroundColor(.red)\n");
127
- await writeFile(join(dir, "Legacy.swift"), ".foregroundColor(.blue)\n");
128
- await writeFile(
129
- join(dir, "hig-doctor.config.json"),
130
- JSON.stringify({ ignore: ["Legacy.swift"], rules: { "swift/hardcoded-color": "off" } }),
131
- );
132
- const result = await audit(dir);
133
- expect(result.configPath).toContain("hig-doctor.config.json");
134
- expect(result.scanResult.codeFiles.map(f => f.relativePath)).toEqual(["View.swift"]);
135
- expect(result.allMatches.filter(m => m.ruleId === "swift/hardcoded-color")).toEqual([]);
136
- } finally {
137
- await rm(dir, { recursive: true });
138
- }
139
- });
140
-
141
- test("noConfig skips discovery", async () => {
142
- const dir = await mkdtemp(join(tmpdir(), "hig-config-"));
143
- try {
144
- await writeFile(join(dir, "View.swift"), ".foregroundColor(.red)\n");
145
- await writeFile(
146
- join(dir, "hig-doctor.config.json"),
147
- JSON.stringify({ rules: { "swift/hardcoded-color": "off" } }),
148
- );
149
- const result = await audit(dir, undefined, { noConfig: true });
150
- expect(result.configPath).toBeNull();
151
- expect(result.allMatches.some(m => m.ruleId === "swift/hardcoded-color")).toBe(true);
152
- } finally {
153
- await rm(dir, { recursive: true });
154
- }
155
- });
156
- });
@@ -1,121 +0,0 @@
1
- import { describe, test, expect } from "bun:test";
2
- import { analyzeTsx, astTsxAvailable, isUsableTs, AST_TSX_RULES } from "./ast-tsx";
3
- import { analyzeFile } from "../analyze";
4
-
5
- // Under Bun a missing optional `typescript` resolves to a stub object rather
6
- // than throwing, so a bare null check let the engine run and crash on the first
7
- // property access instead of falling back to regex.
8
- describe("typescript capability probe", () => {
9
- test("rejects stubs and non-modules, accepts the real compiler", () => {
10
- expect(isUsableTs(null)).toBe(false);
11
- expect(isUsableTs(undefined)).toBe(false);
12
- expect(isUsableTs({})).toBe(false);
13
- expect(isUsableTs({ default: {}, __esModule: true })).toBe(false);
14
- // Present but missing the JSX predicates the engine calls.
15
- expect(isUsableTs({ createSourceFile: () => {}, ScriptTarget: {}, ScriptKind: {} })).toBe(false);
16
- expect(isUsableTs(require("typescript"))).toBe(true);
17
- });
18
- });
19
-
20
- // These tests assume the optional `typescript` dependency is installed (it is in
21
- // this repo's toolchain). They assert the AST tier's precision over regex.
22
- describe.if(astTsxAvailable())("ast-tsx engine", () => {
23
- test("only runs on .tsx/.jsx files", () => {
24
- expect(analyzeTsx("<img src='x'/>", "a.ts")).toBeNull();
25
- expect(analyzeTsx("<img src='x'/>", "a.js")).toBeNull();
26
- expect(Array.isArray(analyzeTsx("const x = <img src='x'/>;", "a.tsx"))).toBe(true);
27
- });
28
-
29
- test("abstains on spread props (regex would false-positive)", () => {
30
- const out = analyzeFile("export const I = (p) => <img {...p} />;", "A.tsx");
31
- expect(out.filter(m => m.ruleId === "web/missing-alt")).toEqual([]);
32
- });
33
-
34
- test("flags a genuinely missing alt and tags it ast-tsx", () => {
35
- const out = analyzeFile('export const I = () => <img src="/x.png" />;', "B.tsx");
36
- const hit = out.find(m => m.ruleId === "web/missing-alt");
37
- expect(hit?.engine).toBe("ast-tsx");
38
- });
39
-
40
- test("does not flag img with alt or decorative empty alt", () => {
41
- const out = analyzeFile('const I = () => <img src="/x" alt="A cat" />;\nconst J = () => <img src="/y" alt="" />;', "C.tsx");
42
- expect(out.filter(m => m.ruleId === "web/missing-alt")).toEqual([]);
43
- });
44
-
45
- test("handles multi-line div onClick with nested > in the handler", () => {
46
- const code = "export const R = () => (\n <div\n onClick={() => setX(a > b)}\n >\n Open\n </div>\n);";
47
- const out = analyzeFile(code, "D.tsx");
48
- const hit = out.find(m => m.ruleId === "web/div-with-on-click-no-role");
49
- expect(hit?.engine).toBe("ast-tsx");
50
- });
51
-
52
- test("does not flag a clickable div that already has role/tabIndex/keydown", () => {
53
- const out = analyzeFile('const R = () => <div role="button" tabIndex={0} onKeyDown={k} onClick={go}>Go</div>;', "E.tsx");
54
- expect(out.filter(m => m.ruleId === "web/div-with-on-click-no-role")).toEqual([]);
55
- });
56
-
57
- test("detects positive tabIndex but not 0 or -1", () => {
58
- expect(analyzeFile("const A = () => <div tabIndex={3} />;", "F.tsx").some(m => m.ruleId === "web/positive-tabindex")).toBe(true);
59
- expect(analyzeFile("const A = () => <div tabIndex={0} />;", "G.tsx").some(m => m.ruleId === "web/positive-tabindex")).toBe(false);
60
- expect(analyzeFile("const A = () => <div tabIndex={-1} />;", "H.tsx").some(m => m.ruleId === "web/positive-tabindex")).toBe(false);
61
- });
62
-
63
- // Self-closing elements have no JsxElement wrapper, so reporting the node's
64
- // parent pointed at the enclosing element instead — which also silently broke
65
- // line-keyed `hig-disable-next-line` suppression for these rules.
66
- test("reports the element's own line, not the enclosing element's", () => {
67
- const code = [
68
- "export const A = () => (",
69
- " <section>",
70
- " <p>one</p>",
71
- ' <img src="/x.png" />',
72
- " <span tabIndex={4} />",
73
- " <div onClick={go}>hi</div>",
74
- " </section>",
75
- ");",
76
- ].join("\n");
77
- const out = analyzeTsx(code, "L.tsx") ?? [];
78
- const lineOf = (ruleId: string) => out.find(m => m.ruleId === ruleId)?.line;
79
- expect(lineOf("web/missing-alt")).toBe(4);
80
- expect(lineOf("web/positive-tabindex")).toBe(5);
81
- expect(lineOf("web/div-with-on-click-no-role")).toBe(6);
82
- });
83
-
84
- // The AST tier builds findings outside detectPatterns, so it has to apply
85
- // inline suppressions itself or `hig-disable-*` silently does nothing here.
86
- test("honours inline suppressions for AST-owned rules", () => {
87
- const nextLine = [
88
- "export const S = () => (",
89
- " <section>",
90
- " {/* hig-disable-next-line web/missing-alt -- decorative */}",
91
- ' <img src="/spacer.png" />',
92
- " </section>",
93
- ");",
94
- ].join("\n");
95
- expect(analyzeFile(nextLine, "S.tsx").filter(m => m.ruleId === "web/missing-alt")).toEqual([]);
96
-
97
- const fileWide = [
98
- "// hig-disable-file web/missing-alt",
99
- 'export const T = () => <img src="/a.png" />;',
100
- ].join("\n");
101
- expect(analyzeFile(fileWide, "T.tsx").filter(m => m.ruleId === "web/missing-alt")).toEqual([]);
102
-
103
- // A suppression for a different rule must not swallow the finding.
104
- const otherRule = [
105
- "export const U = () => (",
106
- " <section>",
107
- " {/* hig-disable-next-line web/positive-tabindex */}",
108
- ' <img src="/b.png" />',
109
- " </section>",
110
- ");",
111
- ].join("\n");
112
- expect(analyzeFile(otherRule, "U.tsx").some(m => m.ruleId === "web/missing-alt")).toBe(true);
113
- });
114
-
115
- test("replaces regex verdicts for AST-owned rules (no duplicate findings)", () => {
116
- const out = analyzeFile('const I = () => <img src="/x.png" />;', "I.tsx");
117
- const alts = out.filter(m => m.ruleId === "web/missing-alt");
118
- expect(alts.length).toBe(1);
119
- expect([...AST_TSX_RULES]).toContain("web/missing-alt");
120
- });
121
- });
@@ -1,39 +0,0 @@
1
- import { describe, test, expect } from "bun:test";
2
- import { refineSwift } from "./swift-structural";
3
- import { analyzeFile } from "../analyze";
4
- import { detectPatterns } from "../patterns";
5
-
6
- describe("swift-structural engine", () => {
7
- test("drops Image findings when an accessibility modifier is chained (even across lines)", () => {
8
- const code = `Image(systemName: "star")\n .resizable()\n .accessibilityLabel("Favorite")`;
9
- expect(analyzeFile(code, "V.swift").filter(m => m.ruleId === "swift/image-without-a11y")).toEqual([]);
10
- });
11
-
12
- test("keeps Image findings without any a11y modifier and tags them swift-structural", () => {
13
- const code = `Image(systemName: "star").frame(width: 20, height: 20)`;
14
- const hit = analyzeFile(code, "V.swift").find(m => m.ruleId === "swift/image-without-a11y");
15
- expect(hit?.engine).toBe("swift-structural");
16
- });
17
-
18
- test("drops onTapGesture findings when the chain carries a trait/label", () => {
19
- const code = `Text("Go")\n .onTapGesture { go() }\n .accessibilityAddTraits(.isButton)`;
20
- expect(analyzeFile(code, "V.swift").filter(m => m.ruleId === "swift/on-tap-gesture-without-traits")).toEqual([]);
21
- });
22
-
23
- test("keeps a bare onTapGesture and tags it swift-structural", () => {
24
- const code = `Text("Go").onTapGesture { go() }`;
25
- const hit = analyzeFile(code, "V.swift").find(m => m.ruleId === "swift/on-tap-gesture-without-traits");
26
- expect(hit?.engine).toBe("swift-structural");
27
- });
28
-
29
- test("is not fooled by an accessibilityLabel inside a comment or string", () => {
30
- const code = `Image(systemName: "star") // .accessibilityLabel("nope")\n .frame(width: 20)`;
31
- const hit = analyzeFile(code, "V.swift").find(m => m.ruleId === "swift/image-without-a11y");
32
- expect(hit?.engine).toBe("swift-structural");
33
- });
34
-
35
- test("passes non-Swift matches through untouched", () => {
36
- const matches = detectPatterns('<img src="x">', "a.html");
37
- expect(refineSwift(matches, "")).toEqual(matches);
38
- });
39
- });
package/src/fixes.test.ts DELETED
@@ -1,152 +0,0 @@
1
- import { describe, test, expect } from "bun:test";
2
- import { suggestFix, suggestFixInContent, applyFixes, isFixable } from "./fixes";
3
- import type { PatternMatch } from "./patterns";
4
-
5
- const m = (over: Partial<PatternMatch>): PatternMatch => ({
6
- ruleId: "css/physical-text-align",
7
- engine: "regex",
8
- category: "foundations",
9
- subcategory: "i18n",
10
- type: "concern",
11
- pattern: "physical text-align",
12
- line: 1,
13
- lineContent: "text-align: left;",
14
- file: "a.css",
15
- severity: "moderate",
16
- ...over,
17
- });
18
-
19
- // A "safe" fix must be behavior-preserving. Rewriting a quoted value changes
20
- // what the page renders, and rewriting a comment silently rewords the author's
21
- // note about the very declaration being changed.
22
- describe("suggestFix — leaves strings and comments alone", () => {
23
- test("fixes the declaration but not an identical string value", () => {
24
- const line = '.a::before { content: "text-align: left"; text-align: left; }';
25
- const fix = suggestFix(m({}), line);
26
- expect(fix?.after).toBe('.a::before { content: "text-align: left"; text-align: start; }');
27
- });
28
-
29
- test("fixes the declaration but not a trailing comment", () => {
30
- const line = ".b { text-align: left; } /* keep text-align: left for legacy */";
31
- const fix = suggestFix(m({}), line);
32
- expect(fix?.after).toBe(".b { text-align: start; } /* keep text-align: left for legacy */");
33
- });
34
-
35
- test("handles single quotes and an interior comment", () => {
36
- expect(suggestFix(m({}), ".g::after { content: 'text-align: right'; }")).toBeNull();
37
- const line = ".f { text-align: left; /* was right */ text-align: right; }";
38
- expect(suggestFix(m({}), line)?.after).toBe(
39
- ".f { text-align: start; /* was right */ text-align: end; }",
40
- );
41
- });
42
-
43
- test("preserves a CRLF line ending", () => {
44
- expect(suggestFix(m({}), ".c { text-align: left; }\r")?.after).toBe(".c { text-align: start; }\r");
45
- });
46
-
47
- test("uses file context to preserve a multi-line comment before a declaration", () => {
48
- const content = `.d { /* Keep this note:
49
- text-align: left is required for the legacy view. */ text-align: left;
50
- }`;
51
- const fix = suggestFixInContent(m({ line: 2 }), content);
52
- expect(fix?.after).toBe(
53
- " text-align: left is required for the legacy view. */ text-align: start;",
54
- );
55
- });
56
-
57
- test("uses file context to preserve an escaped multi-line string", () => {
58
- const content = `.f::before { content: "Keep \\
59
- text-align: left"; text-align: left; }`;
60
- const fix = suggestFixInContent(m({ line: 2 }), content);
61
- expect(fix?.after).toBe('text-align: left"; text-align: start; }');
62
- });
63
- });
64
-
65
- describe("suggestFix", () => {
66
- test("safe: physical → logical text-align", () => {
67
- const fix = suggestFix(m({}), " text-align: left;");
68
- expect(fix?.safe).toBe(true);
69
- expect(fix?.after).toBe(" text-align: start;");
70
- });
71
-
72
- test("safe: strips user-scalable=no from a viewport meta, preserving the rest", () => {
73
- const fix = suggestFix(
74
- m({ ruleId: "web/user-scalable-no", file: "i.html" }),
75
- `<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">`,
76
- );
77
- expect(fix?.safe).toBe(true);
78
- expect(fix?.after).toBe(`<meta name="viewport" content="width=device-width, initial-scale=1">`);
79
- });
80
-
81
- test("safe: strips maximum-scale=1", () => {
82
- const fix = suggestFix(
83
- m({ ruleId: "web/maximum-scale-1", file: "i.html" }),
84
- `<meta name="viewport" content="width=device-width, maximum-scale=1.0">`,
85
- );
86
- expect(fix?.after).toContain("width=device-width");
87
- expect(fix?.after).not.toContain("maximum-scale");
88
- });
89
-
90
- test("unsafe: NavigationView → NavigationStack is a suggestion, not safe", () => {
91
- const fix = suggestFix(m({ ruleId: "swift/navigation-view-deprecated", file: "V.swift" }), " NavigationView {");
92
- expect(fix?.safe).toBe(false);
93
- expect(fix?.after).toBe(" NavigationStack {");
94
- });
95
-
96
- test("unsafe: positive tabIndex → 0", () => {
97
- expect(suggestFix(m({ ruleId: "web/positive-tabindex", file: "F.tsx" }), "<div tabIndex={3} />")?.after).toBe("<div tabIndex={0} />");
98
- expect(suggestFix(m({ ruleId: "web/positive-tabindex", file: "F.tsx" }), `<div tabindex="5" />`)?.after).toBe(`<div tabindex="0" />`);
99
- });
100
-
101
- test("returns null for rules without a fixer or when nothing changes", () => {
102
- expect(suggestFix(m({ ruleId: "web/missing-alt" }), "<img>")).toBeNull();
103
- expect(suggestFix(m({}), "text-align: center;")).toBeNull();
104
- expect(isFixable("css/physical-text-align")).toBe(true);
105
- expect(isFixable("web/missing-alt")).toBe(false);
106
- });
107
- });
108
-
109
- describe("applyFixes", () => {
110
- test("applies safe fixes to content, collects unsafe as suggestions", () => {
111
- const content = `.a { text-align: left; }\n.b { text-align: right; }\nNavigationView {`;
112
- const matches = [
113
- m({ ruleId: "css/physical-text-align", line: 1 }),
114
- m({ ruleId: "css/physical-text-align", line: 2, lineContent: "text-align: right;" }),
115
- m({ ruleId: "swift/navigation-view-deprecated", line: 3, lineContent: "NavigationView {" }),
116
- ];
117
- const out = applyFixes(content, matches);
118
- expect(out.applied.length).toBe(2);
119
- expect(out.suggestions.length).toBe(1);
120
- expect(out.content).toContain("text-align: start;");
121
- expect(out.content).toContain("text-align: end;");
122
- // Unsafe fix is NOT written into content.
123
- expect(out.content).toContain("NavigationView {");
124
- });
125
-
126
- test("applies at most one fixer per (line, rule) and ignores out-of-range lines", () => {
127
- const content = `text-align: left;`;
128
- const matches = [m({ line: 1 }), m({ line: 1 }), m({ line: 99 })];
129
- const out = applyFixes(content, matches);
130
- expect(out.applied.length).toBe(1);
131
- expect(out.content).toBe("text-align: start;");
132
- });
133
-
134
- test("does not rewrite text inside a multi-line comment on a matched line", () => {
135
- const content = `.e { /* Keep this note:
136
- text-align: right is intentional. */ text-align: right;
137
- }`;
138
- const out = applyFixes(content, [m({ line: 2 })]);
139
- expect(out.content).toBe(`.e { /* Keep this note:
140
- text-align: right is intentional. */ text-align: end;
141
- }`);
142
- expect(out.applied).toHaveLength(1);
143
- });
144
-
145
- test("does not rewrite text inside an escaped multi-line string on a matched line", () => {
146
- const content = `.g::before { content: "Keep \\
147
- text-align: right"; text-align: right; }`;
148
- const out = applyFixes(content, [m({ line: 2 })]);
149
- expect(out.content).toBe(`.g::before { content: "Keep \\
150
- text-align: right"; text-align: end; }`);
151
- });
152
- });