@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,171 @@
1
+ // swift-structural.ts — dependency-free structural refinement for Swift.
2
+ //
3
+ // The regex tier flags every `Image(systemName:)` and every `.onTapGesture {`
4
+ // as a possible accessibility concern. Most are fine: the image carries an
5
+ // accessibility modifier, or the tap target is already a Button. This analyzer
6
+ // walks the chained-modifier expression around each such match (comments and
7
+ // string literals stripped, newlines folded) and drops the finding when the
8
+ // structure proves it is handled. Survivors are re-tagged engine
9
+ // "swift-structural" so the engine that judged them is visible.
10
+ import type { PatternMatch } from "../patterns";
11
+
12
+ // Accessibility modifiers whose presence in an Image's modifier chain means the
13
+ // image is labeled or intentionally hidden — not a concern.
14
+ const A11Y_MODIFIERS = [
15
+ "accessibilityLabel",
16
+ "accessibilityHidden",
17
+ "accessibilityHint",
18
+ "accessibilityValue",
19
+ "accessibilityElement",
20
+ "accessibilityRepresentation",
21
+ "accessibilityAddTraits",
22
+ "accessibilityLabeledPair",
23
+ ];
24
+
25
+ // Strip // line comments, /* */ block comments, and "..." string contents so
26
+ // the structural scan never trips on commented code or string payloads. String
27
+ // delimiters are preserved as empty "" so token adjacency is unchanged.
28
+ function stripSwift(code: string): string {
29
+ let out = "";
30
+ let i = 0;
31
+ const n = code.length;
32
+ let inBlock = false;
33
+ let inString = false;
34
+ while (i < n) {
35
+ const c = code[i];
36
+ const c2 = i + 1 < n ? code[i + 1] : "";
37
+ if (inBlock) {
38
+ if (c === "*" && c2 === "/") { inBlock = false; i += 2; } else { i++; }
39
+ continue;
40
+ }
41
+ if (inString) {
42
+ if (c === "\\") { i += 2; continue; }
43
+ if (c === '"') { inString = false; out += '"'; i++; continue; }
44
+ i++;
45
+ continue;
46
+ }
47
+ if (c === "/" && c2 === "*") { inBlock = true; i += 2; continue; }
48
+ if (c === "/" && c2 === "/") {
49
+ while (i < n && code[i] !== "\n") i++;
50
+ continue;
51
+ }
52
+ if (c === '"') { inString = true; out += '"'; i++; continue; }
53
+ out += c;
54
+ i++;
55
+ }
56
+ return out;
57
+ }
58
+
59
+ // From an index just after a token, capture the run of chained modifiers:
60
+ // a sequence of `.identifier` / `.identifier(...)` / `.identifier { ... }`
61
+ // possibly spanning newlines and whitespace, stopping when the chain ends
62
+ // (a token that is not part of a member-access continuation). Returns the
63
+ // concatenated modifier identifiers seen in the chain.
64
+ function chainedModifiers(stripped: string, from: number): string[] {
65
+ const mods: string[] = [];
66
+ let i = from;
67
+ const n = stripped.length;
68
+ const skipWs = () => { while (i < n && /\s/.test(stripped[i])) i++; };
69
+
70
+ // Consume a balanced (...) or {...} group starting at i (which must be the open char).
71
+ const skipGroup = (open: string, close: string) => {
72
+ let depth = 0;
73
+ for (; i < n; i++) {
74
+ const ch = stripped[i];
75
+ if (ch === open) depth++;
76
+ else if (ch === close) { depth--; if (depth === 0) { i++; return; } }
77
+ }
78
+ };
79
+
80
+ // First, if the token itself is a call, skip its argument group.
81
+ skipWs();
82
+ if (stripped[i] === "(") skipGroup("(", ")");
83
+
84
+ while (true) {
85
+ skipWs();
86
+ if (stripped[i] !== ".") break;
87
+ i++; // consume the dot
88
+ skipWs();
89
+ let id = "";
90
+ while (i < n && /[A-Za-z0-9_]/.test(stripped[i])) { id += stripped[i]; i++; }
91
+ if (id === "") break;
92
+ mods.push(id);
93
+ skipWs();
94
+ if (stripped[i] === "(") skipGroup("(", ")");
95
+ skipWs();
96
+ if (stripped[i] === "{") skipGroup("{", "}");
97
+ }
98
+ return mods;
99
+ }
100
+
101
+ // Map a character index in the stripped source to a 1-based line number using
102
+ // the ORIGINAL source's newline positions. stripSwift preserves newlines, so
103
+ // indices align between stripped and original.
104
+ function lineAt(stripped: string, index: number): number {
105
+ let line = 1;
106
+ for (let i = 0; i < index && i < stripped.length; i++) {
107
+ if (stripped[i] === "\n") line++;
108
+ }
109
+ return line;
110
+ }
111
+
112
+ /**
113
+ * Refine Swift matches: drop `Image without a11y` and `onTapGesture without
114
+ * traits` findings that structural analysis proves are handled, and re-tag the
115
+ * survivors engine "swift-structural". Other matches pass through untouched.
116
+ */
117
+ export function refineSwift(matches: PatternMatch[], code: string): PatternMatch[] {
118
+ const swiftRefined = new Set(["Image without a11y", "onTapGesture without traits"]);
119
+ if (!matches.some(m => swiftRefined.has(m.pattern))) return matches;
120
+
121
+ const stripped = stripSwift(code);
122
+
123
+ // Precompute, per refined pattern, the set of lines where the structure shows
124
+ // the finding is handled (so it should be dropped).
125
+ const handledImageLines = new Set<number>();
126
+ const handledTapLines = new Set<number>();
127
+
128
+ // Images: for each Image(systemName: ...) occurrence, inspect its modifier chain.
129
+ for (const m of stripped.matchAll(/\bImage\s*\(\s*systemName:/g)) {
130
+ const idx = m.index ?? 0;
131
+ // Move to the "(" so chainedModifiers skips the Image(...) argument group.
132
+ const parenIdx = stripped.indexOf("(", idx);
133
+ const mods = chainedModifiers(stripped, parenIdx);
134
+ if (mods.some(mod => A11Y_MODIFIERS.includes(mod))) {
135
+ handledImageLines.add(lineAt(stripped, idx));
136
+ }
137
+ }
138
+
139
+ // onTapGesture: handled when the same chain carries an accessibility trait/
140
+ // label, i.e. the tappable view is exposed to assistive tech.
141
+ for (const m of stripped.matchAll(/\.onTapGesture\s*\{/g)) {
142
+ const idx = m.index ?? 0;
143
+ // Look at the modifier chain that continues AFTER the onTapGesture closure.
144
+ const braceIdx = stripped.indexOf("{", idx);
145
+ // Skip the closure body, then read subsequent modifiers.
146
+ let j = braceIdx;
147
+ let depth = 0;
148
+ for (; j < stripped.length; j++) {
149
+ if (stripped[j] === "{") depth++;
150
+ else if (stripped[j] === "}") { depth--; if (depth === 0) { j++; break; } }
151
+ }
152
+ const after = chainedModifiers(stripped, j);
153
+ if (after.some(mod => A11Y_MODIFIERS.includes(mod))) {
154
+ handledTapLines.add(lineAt(stripped, idx));
155
+ }
156
+ }
157
+
158
+ const out: PatternMatch[] = [];
159
+ for (const match of matches) {
160
+ if (match.pattern === "Image without a11y") {
161
+ if (handledImageLines.has(match.line)) continue; // structurally handled
162
+ out.push({ ...match, engine: "swift-structural" });
163
+ } else if (match.pattern === "onTapGesture without traits") {
164
+ if (handledTapLines.has(match.line)) continue;
165
+ out.push({ ...match, engine: "swift-structural" });
166
+ } else {
167
+ out.push(match);
168
+ }
169
+ }
170
+ return out;
171
+ }
@@ -0,0 +1,87 @@
1
+ import { describe, test, expect } from "bun:test";
2
+ import { suggestFix, 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
+ describe("suggestFix", () => {
20
+ test("safe: physical → logical text-align", () => {
21
+ const fix = suggestFix(m({}), " text-align: left;");
22
+ expect(fix?.safe).toBe(true);
23
+ expect(fix?.after).toBe(" text-align: start;");
24
+ });
25
+
26
+ test("safe: strips user-scalable=no from a viewport meta, preserving the rest", () => {
27
+ const fix = suggestFix(
28
+ m({ ruleId: "web/user-scalable-no", file: "i.html" }),
29
+ `<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">`,
30
+ );
31
+ expect(fix?.safe).toBe(true);
32
+ expect(fix?.after).toBe(`<meta name="viewport" content="width=device-width, initial-scale=1">`);
33
+ });
34
+
35
+ test("safe: strips maximum-scale=1", () => {
36
+ const fix = suggestFix(
37
+ m({ ruleId: "web/maximum-scale-1", file: "i.html" }),
38
+ `<meta name="viewport" content="width=device-width, maximum-scale=1.0">`,
39
+ );
40
+ expect(fix?.after).toContain("width=device-width");
41
+ expect(fix?.after).not.toContain("maximum-scale");
42
+ });
43
+
44
+ test("unsafe: NavigationView → NavigationStack is a suggestion, not safe", () => {
45
+ const fix = suggestFix(m({ ruleId: "swift/navigation-view-deprecated", file: "V.swift" }), " NavigationView {");
46
+ expect(fix?.safe).toBe(false);
47
+ expect(fix?.after).toBe(" NavigationStack {");
48
+ });
49
+
50
+ test("unsafe: positive tabIndex → 0", () => {
51
+ expect(suggestFix(m({ ruleId: "web/positive-tabindex", file: "F.tsx" }), "<div tabIndex={3} />")?.after).toBe("<div tabIndex={0} />");
52
+ expect(suggestFix(m({ ruleId: "web/positive-tabindex", file: "F.tsx" }), `<div tabindex="5" />`)?.after).toBe(`<div tabindex="0" />`);
53
+ });
54
+
55
+ test("returns null for rules without a fixer or when nothing changes", () => {
56
+ expect(suggestFix(m({ ruleId: "web/missing-alt" }), "<img>")).toBeNull();
57
+ expect(suggestFix(m({}), "text-align: center;")).toBeNull();
58
+ expect(isFixable("css/physical-text-align")).toBe(true);
59
+ expect(isFixable("web/missing-alt")).toBe(false);
60
+ });
61
+ });
62
+
63
+ describe("applyFixes", () => {
64
+ test("applies safe fixes to content, collects unsafe as suggestions", () => {
65
+ const content = `.a { text-align: left; }\n.b { text-align: right; }\nNavigationView {`;
66
+ const matches = [
67
+ m({ ruleId: "css/physical-text-align", line: 1 }),
68
+ m({ ruleId: "css/physical-text-align", line: 2, lineContent: "text-align: right;" }),
69
+ m({ ruleId: "swift/navigation-view-deprecated", line: 3, lineContent: "NavigationView {" }),
70
+ ];
71
+ const out = applyFixes(content, matches);
72
+ expect(out.applied.length).toBe(2);
73
+ expect(out.suggestions.length).toBe(1);
74
+ expect(out.content).toContain("text-align: start;");
75
+ expect(out.content).toContain("text-align: end;");
76
+ // Unsafe fix is NOT written into content.
77
+ expect(out.content).toContain("NavigationView {");
78
+ });
79
+
80
+ test("applies at most one fixer per (line, rule) and ignores out-of-range lines", () => {
81
+ const content = `text-align: left;`;
82
+ const matches = [m({ line: 1 }), m({ line: 1 }), m({ line: 99 })];
83
+ const out = applyFixes(content, matches);
84
+ expect(out.applied.length).toBe(1);
85
+ expect(out.content).toBe("text-align: start;");
86
+ });
87
+ });
package/src/fixes.ts ADDED
@@ -0,0 +1,136 @@
1
+ // fixes.ts — mechanical autofixes and machine-readable suggestions.
2
+ //
3
+ // A fixer maps a source line that triggered a rule to a corrected line. Fixers
4
+ // are marked `safe` when the transform is unambiguous and behavior-preserving
5
+ // (applied by `--fix`); `unsafe` fixers only ever surface as suggestions for a
6
+ // human or agent to review (in JSON output and SARIF `fixes`), never written to
7
+ // disk automatically. Fixers operate on a single line, so they compose with the
8
+ // line-oriented scanner and never need the whole AST.
9
+ import type { PatternMatch } from "./patterns";
10
+
11
+ export interface SuggestedFix {
12
+ ruleId: string;
13
+ line: number;
14
+ before: string;
15
+ after: string;
16
+ safe: boolean;
17
+ description: string;
18
+ }
19
+
20
+ interface Fixer {
21
+ safe: boolean;
22
+ description: string;
23
+ apply: (line: string) => string | null;
24
+ }
25
+
26
+ // Remove a comma-separated token (and a dangling separator) from a viewport
27
+ // content string, e.g. "width=device-width, user-scalable=no" → "width=device-width".
28
+ function stripViewportToken(line: string, token: RegExp): string | null {
29
+ if (!token.test(line)) return null;
30
+ let out = line
31
+ .replace(new RegExp(`\\s*,\\s*${token.source}`, "i"), "")
32
+ .replace(new RegExp(`${token.source}\\s*,\\s*`, "i"), "")
33
+ .replace(new RegExp(`\\s*${token.source}`, "i"), "");
34
+ // Tidy any doubled or trailing commas the removal left behind.
35
+ out = out.replace(/,\s*,/g, ", ").replace(/,\s*(["'])/g, "$1").replace(/=\s*,/g, "=");
36
+ return out === line ? null : out;
37
+ }
38
+
39
+ const FIXERS: Record<string, Fixer> = {
40
+ "css/physical-text-align": {
41
+ safe: true,
42
+ description: "Use logical text-align (start/end) so text follows writing direction.",
43
+ apply: (line) => {
44
+ const fixed = line
45
+ .replace(/text-align:\s*left\b/g, "text-align: start")
46
+ .replace(/text-align:\s*right\b/g, "text-align: end");
47
+ return fixed === line ? null : fixed;
48
+ },
49
+ },
50
+ "web/user-scalable-no": {
51
+ safe: true,
52
+ description: "Remove user-scalable=no so pinch-zoom keeps working.",
53
+ apply: (line) => stripViewportToken(line, /user-scalable\s*=\s*no/),
54
+ },
55
+ "web/maximum-scale-1": {
56
+ safe: true,
57
+ description: "Remove maximum-scale=1 so users can zoom.",
58
+ apply: (line) => stripViewportToken(line, /maximum-scale\s*=\s*1(?:\.0)?/),
59
+ },
60
+ "swift/navigation-view-deprecated": {
61
+ // Unsafe: a NavigationView with a sidebar should become NavigationSplitView,
62
+ // which a line-level transform can't tell apart. Suggest the common case.
63
+ safe: false,
64
+ description: "Replace NavigationView with NavigationStack (or NavigationSplitView for sidebar layouts).",
65
+ apply: (line) => {
66
+ const fixed = line.replace(/\bNavigationView\b/g, "NavigationStack");
67
+ return fixed === line ? null : fixed;
68
+ },
69
+ },
70
+ "web/positive-tabindex": {
71
+ // Unsafe: dropping to 0 changes focus order; the author must confirm intent.
72
+ safe: false,
73
+ description: "Use tabIndex 0 (or -1); positive values override the natural focus order.",
74
+ apply: (line) => {
75
+ const fixed = line
76
+ .replace(/tabIndex=\{\s*[1-9]\d*\s*\}/g, "tabIndex={0}")
77
+ .replace(/tabindex=(["'])[1-9]\d*\1/g, "tabindex=$10$1");
78
+ return fixed === line ? null : fixed;
79
+ },
80
+ },
81
+ };
82
+
83
+ export function isFixable(ruleId: string): boolean {
84
+ return ruleId in FIXERS;
85
+ }
86
+
87
+ /** Compute the suggested fix for a match given the raw (untrimmed) source line. */
88
+ export function suggestFix(match: Pick<PatternMatch, "ruleId" | "line">, rawLine: string): SuggestedFix | null {
89
+ const fixer = FIXERS[match.ruleId];
90
+ if (!fixer) return null;
91
+ const after = fixer.apply(rawLine);
92
+ if (after === null || after === rawLine) return null;
93
+ return { ruleId: match.ruleId, line: match.line, before: rawLine, after, safe: fixer.safe, description: fixer.description };
94
+ }
95
+
96
+ export interface FixApplication {
97
+ content: string;
98
+ applied: SuggestedFix[];
99
+ /** Unsafe fixes that were surfaced but not written. */
100
+ suggestions: SuggestedFix[];
101
+ }
102
+
103
+ /**
104
+ * Apply every SAFE fix for the given matches to a file's content and collect
105
+ * the unsafe ones as suggestions. Matches must belong to this file. At most one
106
+ * fixer runs per (line, rule); multiple rules on one line apply in sequence.
107
+ */
108
+ export function applyFixes(content: string, matches: PatternMatch[]): FixApplication {
109
+ const lines = content.split("\n");
110
+ const applied: SuggestedFix[] = [];
111
+ const suggestions: SuggestedFix[] = [];
112
+ const seen = new Set<string>();
113
+
114
+ for (const match of matches) {
115
+ const fixer = FIXERS[match.ruleId];
116
+ if (!fixer) continue;
117
+ const idx = match.line - 1;
118
+ if (idx < 0 || idx >= lines.length) continue;
119
+ const key = `${match.line}:${match.ruleId}`;
120
+ if (seen.has(key)) continue;
121
+ seen.add(key);
122
+
123
+ const rawLine = lines[idx];
124
+ const after = fixer.apply(rawLine);
125
+ if (after === null || after === rawLine) continue;
126
+ const fix: SuggestedFix = { ruleId: match.ruleId, line: match.line, before: rawLine, after, safe: fixer.safe, description: fixer.description };
127
+ if (fixer.safe) {
128
+ lines[idx] = after;
129
+ applied.push(fix);
130
+ } else {
131
+ suggestions.push(fix);
132
+ }
133
+ }
134
+
135
+ return { content: lines.join("\n"), applied, suggestions };
136
+ }
package/src/index.ts ADDED
@@ -0,0 +1,80 @@
1
+ // @raintree-technology/hig-doctor-core — public API surface.
2
+ // The CLI, MCP server, and website audit demo all consume the engine through
3
+ // this module; keep additions here deliberate since they become npm API.
4
+ export {
5
+ audit,
6
+ type AuditOptions,
7
+ type AuditResult,
8
+ } from "./audit";
9
+ export { analyzeFile } from "./analyze";
10
+ export { astTsxAvailable, AST_TSX_RULES } from "./engines/ast-tsx";
11
+ export { refineSwift } from "./engines/swift-structural";
12
+ export {
13
+ detectPatterns,
14
+ severityFor,
15
+ ruleCatalog,
16
+ getRuleById,
17
+ higCitation,
18
+ fixGuidance,
19
+ RULE_COUNT,
20
+ HIG_SNAPSHOT_DATE,
21
+ type PatternMatch,
22
+ type Severity,
23
+ type Engine,
24
+ type RuleMeta,
25
+ } from "./patterns";
26
+ export {
27
+ scanProject,
28
+ globToRegExp,
29
+ type Framework,
30
+ type ScanResult,
31
+ type ScannedFile,
32
+ } from "./scanner";
33
+ export {
34
+ loadConfig,
35
+ parseConfig,
36
+ applyConfig,
37
+ CONFIG_FILENAME,
38
+ type HigDoctorConfig,
39
+ type LoadedConfig,
40
+ type RuleSetting,
41
+ type ConfigOverride,
42
+ } from "./config";
43
+ export {
44
+ categorizeMatches,
45
+ type CategorySummary,
46
+ } from "./categorizer";
47
+ export {
48
+ generateAuditMarkdown,
49
+ loadSkillContent,
50
+ } from "./audit-generator";
51
+ export {
52
+ createBaseline,
53
+ applyBaseline,
54
+ loadBaseline,
55
+ parseBaseline,
56
+ writeBaseline,
57
+ baselineKey,
58
+ BASELINE_FILENAME,
59
+ type Baseline,
60
+ type BaselineApplication,
61
+ } from "./baseline";
62
+ export { ScanCache, CACHE_FILENAME } from "./cache";
63
+ export {
64
+ toSarif,
65
+ type SarifOptions,
66
+ } from "./sarif";
67
+ export {
68
+ suggestFix,
69
+ applyFixes,
70
+ isFixable,
71
+ type SuggestedFix,
72
+ type FixApplication,
73
+ } from "./fixes";
74
+ export {
75
+ runBenchmark,
76
+ BENCHMARK_CASES,
77
+ type BenchmarkCase,
78
+ type BenchmarkReport,
79
+ type RuleScore,
80
+ } from "./benchmark";