@raintree-technology/hig-doctor-core 0.1.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.
@@ -0,0 +1,131 @@
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", () => {
57
+ test("off drops matches; severities remap concerns only", () => {
58
+ const matches = [
59
+ match({}),
60
+ match({ ruleId: "swift/navigation-view-deprecated", pattern: "NavigationView (deprecated)" }),
61
+ match({ ruleId: "swift/semantic-color", type: "positive", severity: undefined }),
62
+ ];
63
+ const out = applyConfig(matches, {
64
+ rules: {
65
+ "swift/hardcoded-color": "off",
66
+ "swift/navigation-view-deprecated": "critical",
67
+ "swift/semantic-color": "serious",
68
+ },
69
+ });
70
+ expect(out.length).toBe(2);
71
+ expect(out[0].severity).toBe("critical");
72
+ expect(out[1].severity).toBeUndefined(); // positives never gain a severity
73
+ });
74
+
75
+ test("prefix globs apply with longest-prefix precedence", () => {
76
+ const out = applyConfig([match({})], {
77
+ rules: { "swift/*": "off", "swift/hardcoded-*": "critical" },
78
+ });
79
+ expect(out.length).toBe(1);
80
+ expect(out[0].severity).toBe("critical");
81
+ });
82
+
83
+ test("per-path overrides beat global rules, last override wins", () => {
84
+ const matches = [match({ file: "marketing/Hero.swift" }), match({ file: "app/Main.swift" })];
85
+ const out = applyConfig(matches, {
86
+ rules: { "swift/hardcoded-color": "critical" },
87
+ overrides: [
88
+ { files: ["marketing/**"], rules: { "swift/hardcoded-color": "off" } },
89
+ ],
90
+ });
91
+ expect(out.length).toBe(1);
92
+ expect(out[0].file).toBe("app/Main.swift");
93
+ expect(out[0].severity).toBe("critical");
94
+ });
95
+ });
96
+
97
+ describe("audit config integration", () => {
98
+ test("discovers hig-doctor.config.json: ignore globs and rule offs apply", async () => {
99
+ const dir = await mkdtemp(join(tmpdir(), "hig-config-"));
100
+ try {
101
+ await writeFile(join(dir, "View.swift"), ".foregroundColor(.red)\n");
102
+ await writeFile(join(dir, "Legacy.swift"), ".foregroundColor(.blue)\n");
103
+ await writeFile(
104
+ join(dir, "hig-doctor.config.json"),
105
+ JSON.stringify({ ignore: ["Legacy.swift"], rules: { "swift/hardcoded-color": "off" } }),
106
+ );
107
+ const result = await audit(dir);
108
+ expect(result.configPath).toContain("hig-doctor.config.json");
109
+ expect(result.scanResult.codeFiles.map(f => f.relativePath)).toEqual(["View.swift"]);
110
+ expect(result.allMatches.filter(m => m.ruleId === "swift/hardcoded-color")).toEqual([]);
111
+ } finally {
112
+ await rm(dir, { recursive: true });
113
+ }
114
+ });
115
+
116
+ test("noConfig skips discovery", async () => {
117
+ const dir = await mkdtemp(join(tmpdir(), "hig-config-"));
118
+ try {
119
+ await writeFile(join(dir, "View.swift"), ".foregroundColor(.red)\n");
120
+ await writeFile(
121
+ join(dir, "hig-doctor.config.json"),
122
+ JSON.stringify({ rules: { "swift/hardcoded-color": "off" } }),
123
+ );
124
+ const result = await audit(dir, undefined, { noConfig: true });
125
+ expect(result.configPath).toBeNull();
126
+ expect(result.allMatches.some(m => m.ruleId === "swift/hardcoded-color")).toBe(true);
127
+ } finally {
128
+ await rm(dir, { recursive: true });
129
+ }
130
+ });
131
+ });
package/src/config.ts ADDED
@@ -0,0 +1,174 @@
1
+ // config.ts — hig-doctor.config.json discovery, validation, and application.
2
+ //
3
+ // The config file lives at the root of the audited project:
4
+ // {
5
+ // "rules": { "swift/hardcoded-color": "off", "web/*": "serious" },
6
+ // "ignore": ["legacy/**", "vendor/**"],
7
+ // "overrides": [
8
+ // { "files": ["marketing/**"], "rules": { "css/outline-none": "off" } }
9
+ // ]
10
+ // }
11
+ // Rule keys are stable rule IDs (see docs/rules.md) or prefix globs ending in
12
+ // "*". Values: "off" drops the rule, a severity remaps concern severity, "on"
13
+ // keeps the default. Overrides apply per file glob; the last matching override
14
+ // wins over the global rules map.
15
+ import { readFile } from "node:fs/promises";
16
+ import { isAbsolute, join, resolve } from "node:path";
17
+ import type { PatternMatch, Severity } from "./patterns";
18
+ import { getRuleById } from "./patterns";
19
+ import { globToRegExp } from "./scanner";
20
+
21
+ export type RuleSetting = "off" | "on" | Severity;
22
+
23
+ export interface ConfigOverride {
24
+ files: string[];
25
+ rules: Record<string, RuleSetting>;
26
+ }
27
+
28
+ export interface HigDoctorConfig {
29
+ rules?: Record<string, RuleSetting>;
30
+ ignore?: string[];
31
+ overrides?: ConfigOverride[];
32
+ }
33
+
34
+ export interface LoadedConfig {
35
+ /** Absolute path of the loaded file, or null when no config exists. */
36
+ path: string | null;
37
+ config: HigDoctorConfig;
38
+ /** Non-fatal problems (e.g. unknown rule IDs) surfaced to the caller. */
39
+ warnings: string[];
40
+ }
41
+
42
+ export const CONFIG_FILENAME = "hig-doctor.config.json";
43
+
44
+ const VALID_SETTINGS = new Set(["off", "on", "critical", "serious", "moderate"]);
45
+
46
+ function validateRules(
47
+ rules: unknown,
48
+ where: string,
49
+ warnings: string[],
50
+ ): Record<string, RuleSetting> {
51
+ if (rules == null) return {};
52
+ if (typeof rules !== "object" || Array.isArray(rules)) {
53
+ throw new Error(`${where}: "rules" must be an object mapping rule IDs to settings`);
54
+ }
55
+ const out: Record<string, RuleSetting> = {};
56
+ for (const [id, setting] of Object.entries(rules)) {
57
+ if (typeof setting !== "string" || !VALID_SETTINGS.has(setting)) {
58
+ throw new Error(
59
+ `${where}: invalid setting ${JSON.stringify(setting)} for rule "${id}" — expected "off", "on", "critical", "serious", or "moderate"`,
60
+ );
61
+ }
62
+ if (!id.includes("*") && !getRuleById(id)) {
63
+ warnings.push(`${where}: unknown rule ID "${id}" (see docs/rules.md)`);
64
+ }
65
+ out[id] = setting as RuleSetting;
66
+ }
67
+ return out;
68
+ }
69
+
70
+ export function parseConfig(raw: string, sourcePath: string): { config: HigDoctorConfig; warnings: string[] } {
71
+ let json: unknown;
72
+ try {
73
+ json = JSON.parse(raw);
74
+ } catch (err) {
75
+ throw new Error(`${sourcePath} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
76
+ }
77
+ if (json == null || typeof json !== "object" || Array.isArray(json)) {
78
+ throw new Error(`${sourcePath}: config must be a JSON object`);
79
+ }
80
+ const obj = json as Record<string, unknown>;
81
+ const warnings: string[] = [];
82
+ const config: HigDoctorConfig = {};
83
+
84
+ config.rules = validateRules(obj.rules, sourcePath, warnings);
85
+
86
+ if (obj.ignore != null) {
87
+ if (!Array.isArray(obj.ignore) || obj.ignore.some(g => typeof g !== "string")) {
88
+ throw new Error(`${sourcePath}: "ignore" must be an array of glob strings`);
89
+ }
90
+ config.ignore = obj.ignore as string[];
91
+ }
92
+
93
+ if (obj.overrides != null) {
94
+ if (!Array.isArray(obj.overrides)) {
95
+ throw new Error(`${sourcePath}: "overrides" must be an array`);
96
+ }
97
+ config.overrides = (obj.overrides as unknown[]).map((entry, i) => {
98
+ const where = `${sourcePath} overrides[${i}]`;
99
+ if (entry == null || typeof entry !== "object" || Array.isArray(entry)) {
100
+ throw new Error(`${where}: must be an object with "files" and "rules"`);
101
+ }
102
+ const o = entry as Record<string, unknown>;
103
+ if (!Array.isArray(o.files) || o.files.length === 0 || o.files.some(g => typeof g !== "string")) {
104
+ throw new Error(`${where}: "files" must be a non-empty array of glob strings`);
105
+ }
106
+ return { files: o.files as string[], rules: validateRules(o.rules, where, warnings) };
107
+ });
108
+ }
109
+
110
+ return { config, warnings };
111
+ }
112
+
113
+ export async function loadConfig(directory: string, explicitPath?: string): Promise<LoadedConfig> {
114
+ const path = explicitPath
115
+ ? (isAbsolute(explicitPath) ? explicitPath : resolve(explicitPath))
116
+ : join(resolve(directory), CONFIG_FILENAME);
117
+ let raw: string;
118
+ try {
119
+ raw = await readFile(path, "utf-8");
120
+ } catch {
121
+ if (explicitPath) throw new Error(`Config file not found: ${path}`);
122
+ return { path: null, config: {}, warnings: [] };
123
+ }
124
+ const { config, warnings } = parseConfig(raw, path);
125
+ return { path, config, warnings };
126
+ }
127
+
128
+ interface CompiledOverride {
129
+ files: RegExp[];
130
+ rules: Record<string, RuleSetting>;
131
+ }
132
+
133
+ function settingFor(ruleId: string, rules: Record<string, RuleSetting> | undefined): RuleSetting | null {
134
+ if (!rules) return null;
135
+ if (ruleId in rules) return rules[ruleId];
136
+ // Prefix globs: most specific (longest prefix) wins.
137
+ let best: { len: number; setting: RuleSetting } | null = null;
138
+ for (const [key, setting] of Object.entries(rules)) {
139
+ if (!key.endsWith("*")) continue;
140
+ const prefix = key.slice(0, -1);
141
+ if (ruleId.startsWith(prefix) && (!best || prefix.length > best.len)) {
142
+ best = { len: prefix.length, setting };
143
+ }
144
+ }
145
+ return best?.setting ?? null;
146
+ }
147
+
148
+ /** Apply rule settings (global + per-path overrides) to detected matches. */
149
+ export function applyConfig(matches: PatternMatch[], config: HigDoctorConfig): PatternMatch[] {
150
+ const hasRules = config.rules && Object.keys(config.rules).length > 0;
151
+ const overrides: CompiledOverride[] = (config.overrides ?? []).map(o => ({
152
+ files: o.files.map(globToRegExp),
153
+ rules: o.rules,
154
+ }));
155
+ if (!hasRules && overrides.length === 0) return matches;
156
+
157
+ const out: PatternMatch[] = [];
158
+ for (const match of matches) {
159
+ let setting = settingFor(match.ruleId, config.rules);
160
+ for (const override of overrides) {
161
+ if (override.files.some(re => re.test(match.file))) {
162
+ const s = settingFor(match.ruleId, override.rules);
163
+ if (s !== null) setting = s;
164
+ }
165
+ }
166
+ if (setting === "off") continue;
167
+ if (setting && setting !== "on" && match.type === "concern") {
168
+ out.push({ ...match, severity: setting });
169
+ } else {
170
+ out.push(match);
171
+ }
172
+ }
173
+ return out;
174
+ }
@@ -0,0 +1,54 @@
1
+ import { describe, test, expect } from "bun:test";
2
+ import { analyzeTsx, astTsxAvailable, AST_TSX_RULES } from "./ast-tsx";
3
+ import { analyzeFile } from "../analyze";
4
+
5
+ // These tests assume the optional `typescript` dependency is installed (it is in
6
+ // this repo's toolchain). They assert the AST tier's precision over regex.
7
+ describe.if(astTsxAvailable())("ast-tsx engine", () => {
8
+ test("only runs on .tsx/.jsx files", () => {
9
+ expect(analyzeTsx("<img src='x'/>", "a.ts")).toBeNull();
10
+ expect(analyzeTsx("<img src='x'/>", "a.js")).toBeNull();
11
+ expect(Array.isArray(analyzeTsx("const x = <img src='x'/>;", "a.tsx"))).toBe(true);
12
+ });
13
+
14
+ test("abstains on spread props (regex would false-positive)", () => {
15
+ const out = analyzeFile("export const I = (p) => <img {...p} />;", "A.tsx");
16
+ expect(out.filter(m => m.ruleId === "web/missing-alt")).toEqual([]);
17
+ });
18
+
19
+ test("flags a genuinely missing alt and tags it ast-tsx", () => {
20
+ const out = analyzeFile('export const I = () => <img src="/x.png" />;', "B.tsx");
21
+ const hit = out.find(m => m.ruleId === "web/missing-alt");
22
+ expect(hit?.engine).toBe("ast-tsx");
23
+ });
24
+
25
+ test("does not flag img with alt or decorative empty alt", () => {
26
+ const out = analyzeFile('const I = () => <img src="/x" alt="A cat" />;\nconst J = () => <img src="/y" alt="" />;', "C.tsx");
27
+ expect(out.filter(m => m.ruleId === "web/missing-alt")).toEqual([]);
28
+ });
29
+
30
+ test("handles multi-line div onClick with nested > in the handler", () => {
31
+ const code = "export const R = () => (\n <div\n onClick={() => setX(a > b)}\n >\n Open\n </div>\n);";
32
+ const out = analyzeFile(code, "D.tsx");
33
+ const hit = out.find(m => m.ruleId === "web/div-with-on-click-no-role");
34
+ expect(hit?.engine).toBe("ast-tsx");
35
+ });
36
+
37
+ test("does not flag a clickable div that already has role/tabIndex/keydown", () => {
38
+ const out = analyzeFile('const R = () => <div role="button" tabIndex={0} onKeyDown={k} onClick={go}>Go</div>;', "E.tsx");
39
+ expect(out.filter(m => m.ruleId === "web/div-with-on-click-no-role")).toEqual([]);
40
+ });
41
+
42
+ test("detects positive tabIndex but not 0 or -1", () => {
43
+ expect(analyzeFile("const A = () => <div tabIndex={3} />;", "F.tsx").some(m => m.ruleId === "web/positive-tabindex")).toBe(true);
44
+ expect(analyzeFile("const A = () => <div tabIndex={0} />;", "G.tsx").some(m => m.ruleId === "web/positive-tabindex")).toBe(false);
45
+ expect(analyzeFile("const A = () => <div tabIndex={-1} />;", "H.tsx").some(m => m.ruleId === "web/positive-tabindex")).toBe(false);
46
+ });
47
+
48
+ test("replaces regex verdicts for AST-owned rules (no duplicate findings)", () => {
49
+ const out = analyzeFile('const I = () => <img src="/x.png" />;', "I.tsx");
50
+ const alts = out.filter(m => m.ruleId === "web/missing-alt");
51
+ expect(alts.length).toBe(1);
52
+ expect([...AST_TSX_RULES]).toContain("web/missing-alt");
53
+ });
54
+ });
@@ -0,0 +1,167 @@
1
+ // ast-tsx.ts — TypeScript-compiler-backed JSX analysis.
2
+ //
3
+ // The regex tier judges JSX attributes with document-scope regexes that break
4
+ // on nested `>` inside expressions, multi-line elements, and spread props. This
5
+ // engine parses the file with the real TypeScript compiler and inspects the JSX
6
+ // AST, so it both removes those false positives and honestly abstains when a
7
+ // spread attribute makes the answer unknowable.
8
+ //
9
+ // typescript is an OPTIONAL dependency: when it can't be resolved the engine
10
+ // reports itself unavailable and the regex tier stands as the fallback, exactly
11
+ // as the rule catalog's engine tags advertise.
12
+ import { createRequire } from "node:module";
13
+ import type { PatternMatch, Severity } from "../patterns";
14
+ import { getRuleById } from "../patterns";
15
+
16
+ // Rule IDs this engine authoritatively decides for .tsx/.jsx files. When the
17
+ // engine runs, regex findings for these IDs are discarded and replaced with the
18
+ // engine's verdict.
19
+ export const AST_TSX_RULES = new Set([
20
+ "web/missing-alt",
21
+ "web/image-without-alt",
22
+ "web/div-with-on-click-no-role",
23
+ "web/span-with-on-click-no-role",
24
+ "web/positive-tabindex",
25
+ ]);
26
+
27
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
28
+ type TS = any;
29
+ let tsModule: TS | null | undefined;
30
+
31
+ function loadTs(): TS | null {
32
+ if (tsModule !== undefined) return tsModule;
33
+ try {
34
+ // createRequire keeps this a runtime resolution (not bundled by esbuild,
35
+ // which marks typescript external) so a missing optional dep is survivable.
36
+ tsModule = createRequire(import.meta.url)("typescript");
37
+ } catch {
38
+ tsModule = null;
39
+ }
40
+ return tsModule;
41
+ }
42
+
43
+ export function astTsxAvailable(): boolean {
44
+ return loadTs() != null;
45
+ }
46
+
47
+ function isTsxFile(file: string): boolean {
48
+ return /\.(tsx|jsx)$/.test(file);
49
+ }
50
+
51
+ interface Finding {
52
+ ruleId: string;
53
+ line: number;
54
+ lineContent: string;
55
+ }
56
+
57
+ function push(findings: Finding[], ruleId: string, ts: TS, node: TS, source: TS): void {
58
+ const { line } = source.getLineAndCharacterOfPosition(node.getStart(source));
59
+ const text = source.text.split("\n")[line] ?? "";
60
+ findings.push({ ruleId, line: line + 1, lineContent: text.trim() });
61
+ }
62
+
63
+ /**
64
+ * Analyze a JSX/TSX file. Returns null when typescript is unavailable or the
65
+ * file isn't JSX — the caller then keeps the regex findings unchanged.
66
+ */
67
+ export function analyzeTsx(code: string, file: string): PatternMatch[] | null {
68
+ if (!isTsxFile(file)) return null;
69
+ const ts = loadTs();
70
+ if (!ts) return null;
71
+
72
+ const source = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
73
+ const findings: Finding[] = [];
74
+
75
+ const attrs = (opening: TS): { names: Set<string>; hasSpread: boolean; byName: Map<string, TS> } => {
76
+ const names = new Set<string>();
77
+ const byName = new Map<string, TS>();
78
+ let hasSpread = false;
79
+ for (const prop of opening.attributes.properties) {
80
+ if (ts.isJsxSpreadAttribute(prop)) { hasSpread = true; continue; }
81
+ if (ts.isJsxAttribute(prop) && prop.name) {
82
+ const name = prop.name.getText(source);
83
+ names.add(name);
84
+ byName.set(name, prop);
85
+ }
86
+ }
87
+ return { names, hasSpread, byName };
88
+ };
89
+
90
+ const tagNameOf = (opening: TS): string => opening.tagName.getText(source);
91
+
92
+ const attrIsTruthy = (attr: TS): boolean => {
93
+ // <x aria-hidden />, aria-hidden="true", aria-hidden={true}
94
+ if (!attr.initializer) return true;
95
+ if (ts.isStringLiteral(attr.initializer)) return attr.initializer.text === "true";
96
+ if (ts.isJsxExpression(attr.initializer) && attr.initializer.expression) {
97
+ return attr.initializer.expression.kind === ts.SyntaxKind.TrueKeyword;
98
+ }
99
+ return false;
100
+ };
101
+
102
+ const positiveTabIndex = (attr: TS): boolean => {
103
+ if (!attr.initializer) return false;
104
+ let raw: string | null = null;
105
+ if (ts.isStringLiteral(attr.initializer)) raw = attr.initializer.text;
106
+ else if (ts.isJsxExpression(attr.initializer) && attr.initializer.expression) {
107
+ const e = attr.initializer.expression;
108
+ if (ts.isNumericLiteral(e)) raw = e.text;
109
+ else if (ts.isPrefixUnaryExpression?.(e) && e.operator === ts.SyntaxKind.MinusToken) raw = "-1";
110
+ }
111
+ if (raw == null) return false;
112
+ const n = Number(raw);
113
+ return Number.isFinite(n) && n > 0;
114
+ };
115
+
116
+ const visitOpening = (opening: TS) => {
117
+ const tag = tagNameOf(opening);
118
+ const { names, hasSpread, byName } = attrs(opening);
119
+
120
+ // <img> / <Image> without alt. Spread props may carry alt → abstain.
121
+ if ((tag === "img" || tag === "Image") && !hasSpread && !names.has("alt")) {
122
+ push(findings, "web/missing-alt", ts, opening.parent ?? opening, source);
123
+ }
124
+
125
+ // Lowercase host <div>/<span> with onClick and no role/interactive semantics.
126
+ if ((tag === "div" || tag === "span") && names.has("onClick") && !hasSpread) {
127
+ const interactive = names.has("role") || names.has("tabIndex") ||
128
+ names.has("onKeyDown") || names.has("onKeyPress") || names.has("onKeyUp");
129
+ if (!interactive) {
130
+ const ruleId = tag === "div" ? "web/div-with-on-click-no-role" : "web/span-with-on-click-no-role";
131
+ push(findings, ruleId, ts, opening.parent ?? opening, source);
132
+ }
133
+ }
134
+
135
+ // Positive tabIndex on any element.
136
+ const tabIndexAttr = byName.get("tabIndex");
137
+ if (tabIndexAttr && positiveTabIndex(tabIndexAttr)) {
138
+ push(findings, "web/positive-tabindex", ts, opening.parent ?? opening, source);
139
+ }
140
+
141
+ void attrIsTruthy; // reserved for future aria-hidden-on-focusable AST rule
142
+ };
143
+
144
+ const walk = (node: TS) => {
145
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
146
+ visitOpening(node);
147
+ }
148
+ ts.forEachChild(node, walk);
149
+ };
150
+ walk(source);
151
+
152
+ return findings.map(f => {
153
+ const meta = getRuleById(f.ruleId);
154
+ return {
155
+ ruleId: f.ruleId,
156
+ engine: "ast-tsx" as const,
157
+ category: meta?.category ?? "foundations",
158
+ subcategory: meta?.subcategory ?? "accessibility",
159
+ type: "concern" as const,
160
+ pattern: meta?.label ?? f.ruleId,
161
+ line: f.line,
162
+ lineContent: f.lineContent,
163
+ file,
164
+ severity: (meta?.severity ?? "moderate") as Severity,
165
+ };
166
+ });
167
+ }
@@ -0,0 +1,39 @@
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
+ });