@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.
package/dist/index.js ADDED
@@ -0,0 +1,2780 @@
1
+ // src/scanner.ts
2
+ import { readdir, readFile, stat } from "node:fs/promises";
3
+ import { join, relative, extname, sep } from "node:path";
4
+ var IGNORED_DIRS = /* @__PURE__ */ new Set([
5
+ ".build",
6
+ ".git",
7
+ "node_modules",
8
+ "Pods",
9
+ "DerivedData",
10
+ ".swiftpm",
11
+ "Carthage",
12
+ "Build",
13
+ ".next",
14
+ ".nuxt",
15
+ ".output",
16
+ "dist",
17
+ "build",
18
+ ".cache",
19
+ ".turbo",
20
+ "coverage",
21
+ "__pycache__",
22
+ ".dart_tool",
23
+ ".pub-cache",
24
+ "android",
25
+ "ios",
26
+ "macos",
27
+ "linux",
28
+ "windows"
29
+ ]);
30
+ var MAX_FILE_BYTES = 15e5;
31
+ var MAX_DEPTH = 25;
32
+ var GENERATED_FILE = /\.(min|bundle|chunk)\.(js|css|mjs|cjs)$/i;
33
+ var CODE_EXTENSIONS = /* @__PURE__ */ new Set([
34
+ ".swift",
35
+ ".tsx",
36
+ ".jsx",
37
+ ".ts",
38
+ ".js",
39
+ ".vue",
40
+ ".svelte",
41
+ ".dart",
42
+ ".kt",
43
+ ".java"
44
+ ]);
45
+ var STYLE_EXTENSIONS = /* @__PURE__ */ new Set([
46
+ ".css",
47
+ ".scss",
48
+ ".sass",
49
+ ".less",
50
+ ".styl"
51
+ ]);
52
+ var MARKUP_EXTENSIONS = /* @__PURE__ */ new Set([
53
+ ".html",
54
+ ".htm",
55
+ ".xml",
56
+ ".storyboard",
57
+ ".xib"
58
+ ]);
59
+ var CONFIG_FILES = /* @__PURE__ */ new Set([
60
+ "tailwind.config.ts",
61
+ "tailwind.config.js",
62
+ "tailwind.config.mjs",
63
+ "next.config.ts",
64
+ "next.config.js",
65
+ "next.config.mjs",
66
+ "nuxt.config.ts",
67
+ "nuxt.config.js",
68
+ "svelte.config.js",
69
+ "svelte.config.ts",
70
+ "angular.json",
71
+ "package.json",
72
+ "tsconfig.json",
73
+ "Info.plist",
74
+ "Package.swift",
75
+ "pubspec.yaml",
76
+ "app.json",
77
+ "expo.json",
78
+ "eas.json",
79
+ "components.json",
80
+ "build.gradle",
81
+ "build.gradle.kts",
82
+ "AndroidManifest.xml"
83
+ ]);
84
+ var IGNORE_FILE = ".higauditignore";
85
+ function globToRegExp(glob) {
86
+ const g = glob.replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
87
+ let re = "";
88
+ for (let i = 0; i < g.length; i++) {
89
+ const ch = g[i];
90
+ if (ch === "*") {
91
+ if (g[i + 1] === "*") {
92
+ if (g[i + 2] === "/") {
93
+ re += "(?:.*/)?";
94
+ i += 2;
95
+ } else {
96
+ re += ".*";
97
+ i += 1;
98
+ }
99
+ } else {
100
+ re += "[^/]*";
101
+ }
102
+ } else if (ch === "?") {
103
+ re += "[^/]";
104
+ } else if ("\\^$.|+()[]{}".includes(ch)) {
105
+ re += "\\" + ch;
106
+ } else {
107
+ re += ch;
108
+ }
109
+ }
110
+ return new RegExp("^" + re + "$");
111
+ }
112
+ async function loadIgnorePatterns(directory) {
113
+ try {
114
+ const content = await readFile(join(directory, IGNORE_FILE), "utf-8");
115
+ return content.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
116
+ } catch {
117
+ return [];
118
+ }
119
+ }
120
+ function buildIgnoreMatcher(patterns) {
121
+ const regexps = patterns.map(globToRegExp);
122
+ if (regexps.length === 0) return () => false;
123
+ return (relPath) => {
124
+ const posix = relPath.split(sep).join("/");
125
+ return regexps.some((re) => re.test(posix));
126
+ };
127
+ }
128
+ async function readText(path) {
129
+ try {
130
+ const info = await stat(path);
131
+ if (info.size > MAX_FILE_BYTES) return null;
132
+ return await readFile(path, "utf-8");
133
+ } catch {
134
+ return null;
135
+ }
136
+ }
137
+ async function walkDir(dir, rootDir, result, isIgnored, depth = 0) {
138
+ if (depth > MAX_DEPTH) return;
139
+ let entries;
140
+ try {
141
+ entries = await readdir(dir, { withFileTypes: true });
142
+ } catch {
143
+ return;
144
+ }
145
+ for (const entry of entries) {
146
+ const fullPath = join(dir, entry.name);
147
+ const relPath = relative(rootDir, fullPath);
148
+ if (entry.isSymbolicLink()) continue;
149
+ if (entry.isDirectory()) {
150
+ if (IGNORED_DIRS.has(entry.name)) continue;
151
+ if (isIgnored(relPath)) continue;
152
+ if (entry.name.endsWith(".xcassets")) {
153
+ result.assetCatalogs.push(relPath);
154
+ continue;
155
+ }
156
+ if (entry.name.endsWith(".xcodeproj") || entry.name.endsWith(".xcworkspace")) {
157
+ result.xcodeProjects.push(relPath);
158
+ continue;
159
+ }
160
+ await walkDir(fullPath, rootDir, result, isIgnored, depth + 1);
161
+ } else if (entry.isFile()) {
162
+ const ext = extname(entry.name);
163
+ if (/\.(test|spec)\.[^.]+$/.test(entry.name)) continue;
164
+ if (GENERATED_FILE.test(entry.name)) continue;
165
+ if (isIgnored(relPath)) continue;
166
+ const isConfig = CONFIG_FILES.has(entry.name);
167
+ const wantCode = CODE_EXTENSIONS.has(ext);
168
+ const wantStyle = STYLE_EXTENSIONS.has(ext);
169
+ const wantMarkup = MARKUP_EXTENSIONS.has(ext);
170
+ if (!isConfig && !wantCode && !wantStyle && !wantMarkup) continue;
171
+ const content = await readText(fullPath);
172
+ if (content === null) continue;
173
+ const file = { relativePath: relPath, absolutePath: fullPath, content };
174
+ if (isConfig) {
175
+ result.configFiles.push(file);
176
+ if (entry.name === "Info.plist") result.infoPlistPaths.push(relPath);
177
+ if (entry.name === "Package.swift") result.packageSwift = file;
178
+ if (wantCode) {
179
+ result.codeFiles.push(file);
180
+ if (ext === ".swift") result.swiftFiles.push(file);
181
+ }
182
+ } else if (wantCode) {
183
+ result.codeFiles.push(file);
184
+ if (ext === ".swift") result.swiftFiles.push(file);
185
+ } else if (wantStyle) {
186
+ result.styleFiles.push(file);
187
+ } else if (wantMarkup) {
188
+ result.markupFiles.push(file);
189
+ if (ext === ".storyboard" || ext === ".xib") result.storyboards.push(file);
190
+ }
191
+ }
192
+ }
193
+ }
194
+ function detectFrameworks(result) {
195
+ const frameworks = [];
196
+ const hasExt = (ext) => result.codeFiles.some((f) => f.relativePath.endsWith(ext));
197
+ const hasConfig = (name) => result.configFiles.some((f) => f.relativePath.endsWith(name));
198
+ const configContains = (name, text) => {
199
+ const file = result.configFiles.find((f) => f.relativePath.endsWith(name));
200
+ return file?.content.includes(text) ?? false;
201
+ };
202
+ if (hasExt(".swift")) {
203
+ const hasSwiftUI = result.codeFiles.some((f) => f.content.includes("import SwiftUI"));
204
+ const hasUIKit = result.codeFiles.some((f) => f.content.includes("import UIKit"));
205
+ if (hasSwiftUI) frameworks.push("swiftui");
206
+ if (hasUIKit) frameworks.push("uikit");
207
+ if (!hasSwiftUI && !hasUIKit) frameworks.push("swiftui");
208
+ }
209
+ if (hasConfig("next.config.ts") || hasConfig("next.config.js") || hasConfig("next.config.mjs")) {
210
+ frameworks.push("nextjs");
211
+ } else if ((hasExt(".tsx") || hasExt(".jsx")) && configContains("package.json", '"react"')) {
212
+ if (configContains("package.json", '"react-native"') || hasConfig("app.json")) {
213
+ frameworks.push("react-native");
214
+ } else {
215
+ frameworks.push("react");
216
+ }
217
+ }
218
+ if (hasExt(".vue")) {
219
+ if (hasConfig("nuxt.config.ts") || hasConfig("nuxt.config.js")) {
220
+ frameworks.push("nuxt");
221
+ } else {
222
+ frameworks.push("vue");
223
+ }
224
+ }
225
+ if (hasExt(".svelte")) {
226
+ if (hasConfig("svelte.config.js") || hasConfig("svelte.config.ts")) {
227
+ frameworks.push("sveltekit");
228
+ } else {
229
+ frameworks.push("svelte");
230
+ }
231
+ }
232
+ if (hasConfig("angular.json") || configContains("package.json", '"@angular/core"')) {
233
+ frameworks.push("angular");
234
+ }
235
+ if (hasExt(".dart") || hasConfig("pubspec.yaml")) {
236
+ frameworks.push("flutter");
237
+ }
238
+ if (hasExt(".kt")) {
239
+ const hasCompose = result.codeFiles.some((f) => f.content.includes("androidx.compose"));
240
+ if (hasCompose) {
241
+ frameworks.push("compose");
242
+ } else {
243
+ frameworks.push("android");
244
+ }
245
+ } else if (result.markupFiles.some((f) => f.relativePath.endsWith(".xml") && f.content.includes("android:"))) {
246
+ frameworks.push("android");
247
+ }
248
+ if (frameworks.length === 0 && result.markupFiles.some((f) => f.relativePath.endsWith(".html"))) {
249
+ frameworks.push("html");
250
+ }
251
+ if (frameworks.length === 0) frameworks.push("unknown");
252
+ return frameworks;
253
+ }
254
+ async function scanProject(directory, options = {}) {
255
+ const result = {
256
+ directory,
257
+ frameworks: [],
258
+ codeFiles: [],
259
+ styleFiles: [],
260
+ configFiles: [],
261
+ markupFiles: [],
262
+ swiftFiles: [],
263
+ infoPlistPaths: [],
264
+ assetCatalogs: [],
265
+ storyboards: [],
266
+ xcodeProjects: [],
267
+ packageSwift: null
268
+ };
269
+ const patterns = [...await loadIgnorePatterns(directory), ...options.exclude ?? []];
270
+ const isIgnored = buildIgnoreMatcher(patterns);
271
+ await walkDir(directory, directory, result, isIgnored);
272
+ result.frameworks = detectFrameworks(result);
273
+ return result;
274
+ }
275
+
276
+ // src/patterns.ts
277
+ var HIG_SNAPSHOT_DATE = "2025-02-02";
278
+ var CRITICAL_CONCERNS = /* @__PURE__ */ new Set([
279
+ "missing alt",
280
+ "Image without alt",
281
+ "svg without a11y",
282
+ "empty heading",
283
+ "empty button",
284
+ "missing html lang",
285
+ "video without track",
286
+ "blink element",
287
+ "marquee element",
288
+ "user-scalable=no",
289
+ "maximum-scale=1",
290
+ "ImageView without contentDescription"
291
+ ]);
292
+ var SERIOUS_CONCERNS = /* @__PURE__ */ new Set([
293
+ // "onTapGesture without traits", "Image without a11y", and "hover without
294
+ // focus" are deliberately NOT here: they fire heuristically on common,
295
+ // frequently-fine code, so they default to moderate instead of tripping a
296
+ // `--fail-on serious` CI gate.
297
+ "isAccessibilityElement false on interactive",
298
+ "div with onClick no role",
299
+ "span with onClick no role",
300
+ "ambiguous link text",
301
+ "positive tabindex",
302
+ "aria-hidden on focusable",
303
+ "onMouseOver without onFocus",
304
+ "onMouseOut without onBlur",
305
+ "div as button",
306
+ "div as nav/header class",
307
+ "autoplay media",
308
+ "outline none",
309
+ "v-on:click without keyboard",
310
+ "on:click without on:keydown",
311
+ "(click) without (keydown)",
312
+ "clickable without Role",
313
+ "nested touchables"
314
+ ]);
315
+ function severityFor(pattern) {
316
+ if (CRITICAL_CONCERNS.has(pattern)) return "critical";
317
+ if (SERIOUS_CONCERNS.has(pattern)) return "serious";
318
+ return "moderate";
319
+ }
320
+ var SWIFT = /\.swift$/;
321
+ var WEB = /\.(tsx|jsx|html?)$/;
322
+ var TSX_JSX = /\.(tsx|jsx)$/;
323
+ var TS_JS = /\.(tsx|jsx|ts|js)$/;
324
+ var VUE = /\.vue$/;
325
+ var SVELTE = /\.svelte$/;
326
+ var ANGULAR = /\.(ts|html)$/;
327
+ var DART = /\.dart$/;
328
+ var KOTLIN = /\.kt$/;
329
+ var ANDROID_XML = /\.xml$/;
330
+ var WEB_ALL = /\.(tsx|jsx|html?|vue|svelte)$/;
331
+ var STYLE_ALL = /\.(css|scss|sass|less)$/;
332
+ var swiftRules = [
333
+ // Layout & Navigation
334
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "TabView", regex: /\bTabView\b/, fileFilter: SWIFT },
335
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "NavigationStack", regex: /\bNavigationStack\b/, fileFilter: SWIFT },
336
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "NavigationSplitView", regex: /\bNavigationSplitView\b/, fileFilter: SWIFT },
337
+ { category: "components-layout", subcategory: "navigation", type: "concern", pattern: "NavigationView (deprecated)", regex: /\bNavigationView\b/, fileFilter: SWIFT },
338
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "NavigationLink", regex: /\bNavigationLink\b/, fileFilter: SWIFT },
339
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "List", regex: /\bList\s*\{/, fileFilter: SWIFT },
340
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "ScrollView", regex: /\bScrollView\b/, fileFilter: SWIFT },
341
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "LazyVGrid", regex: /\bLazyVGrid\b/, fileFilter: SWIFT },
342
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "LazyHGrid", regex: /\bLazyHGrid\b/, fileFilter: SWIFT },
343
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "GeometryReader", regex: /\bGeometryReader\b/, fileFilter: SWIFT },
344
+ { category: "components-layout", subcategory: "layout", type: "positive", pattern: "adaptiveLayout", regex: /\.adaptive\(minimum:/, fileFilter: SWIFT },
345
+ // Color
346
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcodedColor", regex: /\.foregroundColor\(\.(red|blue|green|yellow|orange|purple|pink|white|black)\)/, fileFilter: SWIFT },
347
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcodedRGBColor", regex: /Color\(\s*red:/, fileFilter: SWIFT },
348
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcodedUIColor", regex: /UIColor\(\s*red:/, fileFilter: SWIFT },
349
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcoded Color(uiColor:)", regex: /Color\(\s*uiColor:\s*UIColor\(\s*red:/, fileFilter: SWIFT },
350
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "semanticColor", regex: /\.(primary|secondary|accentColor)\b/, fileFilter: SWIFT },
351
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "foregroundStyle", regex: /\.foregroundStyle\(\.(primary|secondary|tertiary|quaternary)\)/, fileFilter: SWIFT },
352
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "assetCatalogColor", regex: /Color\(\s*"[^"]+"\s*\)/, fileFilter: SWIFT },
353
+ // Typography
354
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "dynamicTypeStyle", regex: /\.font\(\.(largeTitle|title|title2|title3|headline|subheadline|body|callout|footnote|caption|caption2)\)/, fileFilter: SWIFT },
355
+ { category: "foundations", subcategory: "typography", type: "concern", pattern: "hardcodedFontSize", regex: /\.font\(\.system\(size:/, fileFilter: SWIFT },
356
+ { category: "foundations", subcategory: "typography", type: "concern", pattern: "hardcodedUIFont", regex: /UIFont\.\s*systemFont\(ofSize:/, fileFilter: SWIFT },
357
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "scaledMetric", regex: /@ScaledMetric/, fileFilter: SWIFT },
358
+ // Accessibility
359
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "accessibilityLabel", regex: /\.accessibilityLabel\(/, fileFilter: SWIFT },
360
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "accessibilityHint", regex: /\.accessibilityHint\(/, fileFilter: SWIFT },
361
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "accessibilityHidden", regex: /\.accessibilityHidden\(/, fileFilter: SWIFT },
362
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "accessibilityAddTraits", regex: /\.accessibilityAddTraits\(/, fileFilter: SWIFT },
363
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "accessibilityValue", regex: /\.accessibilityValue\(/, fileFilter: SWIFT },
364
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "accessibilityAction", regex: /\.accessibilityAction\(/, fileFilter: SWIFT },
365
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "reduceMotion", regex: /accessibilityReduceMotion/, fileFilter: SWIFT },
366
+ // Swift accessibility concerns
367
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "onTapGesture without traits", regex: /\.onTapGesture\s*\{/, fileFilter: SWIFT },
368
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "Image without a11y", regex: /\bImage\(\s*systemName:/, fileFilter: SWIFT },
369
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "isAccessibilityElement false on interactive", regex: /\.isAccessibilityElement\s*=\s*false/, fileFilter: SWIFT },
370
+ // Dark mode
371
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "colorScheme", regex: /@Environment\(\\\.colorScheme\)/, fileFilter: SWIFT },
372
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "preferredColorScheme", regex: /\.preferredColorScheme\(/, fileFilter: SWIFT },
373
+ // Controls
374
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "Button", regex: /\bButton\s*[{(]/, fileFilter: SWIFT },
375
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "Toggle", regex: /\bToggle\s*[{(]/, fileFilter: SWIFT },
376
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "Picker", regex: /\bPicker\s*[{(]/, fileFilter: SWIFT },
377
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "Slider", regex: /\bSlider\s*[{(]/, fileFilter: SWIFT },
378
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "Stepper", regex: /\bStepper\s*[{(]/, fileFilter: SWIFT },
379
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "DatePicker", regex: /\bDatePicker\s*[{(]/, fileFilter: SWIFT },
380
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "ColorPicker", regex: /\bColorPicker\s*[{(]/, fileFilter: SWIFT },
381
+ // Dialogs
382
+ { category: "components-dialogs", subcategory: "modals", type: "pattern", pattern: "sheet", regex: /\.sheet\(/, fileFilter: SWIFT },
383
+ { category: "components-dialogs", subcategory: "alerts", type: "pattern", pattern: "alert", regex: /\.alert\(/, fileFilter: SWIFT },
384
+ { category: "components-dialogs", subcategory: "alerts", type: "pattern", pattern: "confirmationDialog", regex: /\.confirmationDialog\(/, fileFilter: SWIFT },
385
+ { category: "components-dialogs", subcategory: "popover", type: "pattern", pattern: "popover", regex: /\.popover\(/, fileFilter: SWIFT },
386
+ // Search
387
+ { category: "components-search", subcategory: "search", type: "pattern", pattern: "searchable", regex: /\.searchable\(/, fileFilter: SWIFT },
388
+ // Status
389
+ { category: "components-status", subcategory: "progress", type: "pattern", pattern: "ProgressView", regex: /\bProgressView\b/, fileFilter: SWIFT },
390
+ // Menus
391
+ { category: "components-menus", subcategory: "menus", type: "pattern", pattern: "contextMenu", regex: /\.contextMenu\s*\{/, fileFilter: SWIFT },
392
+ { category: "components-menus", subcategory: "menus", type: "pattern", pattern: "Menu", regex: /\bMenu\s*\{/, fileFilter: SWIFT },
393
+ { category: "components-menus", subcategory: "toolbar", type: "pattern", pattern: "toolbar", regex: /\.toolbar\s*\{/, fileFilter: SWIFT },
394
+ // Patterns
395
+ { category: "patterns", subcategory: "animation", type: "pattern", pattern: "withAnimation", regex: /\bwithAnimation\b/, fileFilter: SWIFT },
396
+ { category: "patterns", subcategory: "haptics", type: "pattern", pattern: "sensoryFeedback", regex: /\.sensoryFeedback\(/, fileFilter: SWIFT },
397
+ { category: "patterns", subcategory: "dragDrop", type: "pattern", pattern: "onDrag", regex: /\.onDrag\b/, fileFilter: SWIFT },
398
+ { category: "patterns", subcategory: "refresh", type: "pattern", pattern: "refreshable", regex: /\.refreshable\b/, fileFilter: SWIFT },
399
+ { category: "patterns", subcategory: "swipeActions", type: "pattern", pattern: "swipeActions", regex: /\.swipeActions\b/, fileFilter: SWIFT },
400
+ // Inputs
401
+ { category: "inputs", subcategory: "gestures", type: "pattern", pattern: "TapGesture", regex: /\.onTapGesture\b/, fileFilter: SWIFT },
402
+ { category: "inputs", subcategory: "keyboard", type: "pattern", pattern: "keyboardShortcut", regex: /\.keyboardShortcut\(/, fileFilter: SWIFT },
403
+ { category: "inputs", subcategory: "focus", type: "pattern", pattern: "focusState", regex: /@FocusState\b/, fileFilter: SWIFT },
404
+ // Technologies
405
+ { category: "technologies", subcategory: "appIntents", type: "pattern", pattern: "AppIntent", regex: /\bAppIntent\b/, fileFilter: SWIFT },
406
+ { category: "technologies", subcategory: "swiftData", type: "pattern", pattern: "SwiftData", regex: /import\s+SwiftData/, fileFilter: SWIFT },
407
+ { category: "technologies", subcategory: "widgets", type: "pattern", pattern: "WidgetKit", regex: /import\s+WidgetKit/, fileFilter: SWIFT },
408
+ { category: "technologies", subcategory: "activityKit", type: "pattern", pattern: "ActivityKit", regex: /import\s+ActivityKit/, fileFilter: SWIFT },
409
+ { category: "technologies", subcategory: "healthKit", type: "pattern", pattern: "HealthKit", regex: /import\s+HealthKit/, fileFilter: SWIFT },
410
+ { category: "technologies", subcategory: "arKit", type: "pattern", pattern: "ARKit", regex: /import\s+ARKit/, fileFilter: SWIFT },
411
+ { category: "technologies", subcategory: "applePay", type: "pattern", pattern: "PassKit/ApplePay", regex: /import\s+PassKit|PKPaymentButton/, fileFilter: SWIFT },
412
+ { category: "technologies", subcategory: "signInApple", type: "pattern", pattern: "SignInWithApple", regex: /ASAuthorizationAppleIDButton|SignInWithAppleButton/, fileFilter: SWIFT },
413
+ // Platforms
414
+ { category: "platforms", subcategory: "multiplatform", type: "positive", pattern: "conditionalPlatform", regex: /#if\s+(os\(iOS\)|os\(macOS\)|os\(watchOS\)|os\(tvOS\)|os\(visionOS\))/, fileFilter: SWIFT },
415
+ // UIKit concerns
416
+ { category: "foundations", subcategory: "layout", type: "concern", pattern: "hardcoded CGRect", regex: /CGRect\(\s*x:\s*\d/, fileFilter: SWIFT },
417
+ { category: "foundations", subcategory: "layout", type: "concern", pattern: "ignoresSafeArea", regex: /\.ignoresSafeArea\(/, fileFilter: SWIFT },
418
+ { category: "patterns", subcategory: "state", type: "concern", pattern: "non-private @State", regex: /@State\b(?!\s+private\b)\s+(?:var|let)\b/, fileFilter: SWIFT }
419
+ ];
420
+ var webCodeRules = [
421
+ // ── Accessibility: Positives ────────────────────────────────
422
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "aria-label", regex: /aria-label\s*=/, fileFilter: WEB },
423
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "aria-describedby", regex: /aria-describedby/, fileFilter: WEB },
424
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "aria-live", regex: /aria-live/, fileFilter: WEB },
425
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "aria-expanded", regex: /aria-expanded/, fileFilter: WEB },
426
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "aria-hidden", regex: /aria-hidden/, fileFilter: WEB },
427
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "aria-current", regex: /aria-current/, fileFilter: WEB },
428
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "aria-invalid", regex: /aria-invalid/, fileFilter: WEB },
429
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "aria-errormessage", regex: /aria-errormessage/, fileFilter: WEB },
430
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "aria-required", regex: /aria-required/, fileFilter: WEB },
431
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "role attribute", regex: /role=["']/, fileFilter: WEB },
432
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "sr-only", regex: /sr-only|visually-hidden|screen-reader/i, fileFilter: /\.(tsx|jsx|html?|css|vue|svelte)$/ },
433
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "alt text", regex: /\balt=["'][^"']+["']/, fileFilter: WEB_ALL },
434
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "tabIndex", regex: /tabIndex=\{0\}|tabindex="0"/, fileFilter: WEB_ALL },
435
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "focus management", regex: /onFocus|onBlur|useRef.*focus/, fileFilter: TS_JS },
436
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "keyboard handler", regex: /onKeyDown|onKeyUp|onKeyPress/, fileFilter: TSX_JSX },
437
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "skip link", regex: /skip.*nav|skip.*content|skiplink/i, fileFilter: /\.(tsx|jsx|html?|css|vue|svelte)$/ },
438
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "htmlFor/for attribute", regex: /htmlFor=|for=["']/, fileFilter: WEB_ALL },
439
+ // ── Accessibility: Concerns ─────────────────────────────────
440
+ // Negative-attribute checks use a "tempered greedy token" — (?:(?!X)[^>])* —
441
+ // which walks the tag body asserting attribute X never appears before the
442
+ // closing >. A plain lookbehind/lookahead backtracks and matches tags that DO
443
+ // have the attribute (the original bug flagged <img alt="..."> as missing alt).
444
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "missing alt", regex: /<img\b(?:(?!\balt\s*=)[^>])*>/i, fileFilter: WEB_ALL, scope: "document" },
445
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "Image without alt", regex: /<Image\b(?:(?!\balt\s*=)[^>])*>/, fileFilter: TSX_JSX, scope: "document" },
446
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "svg without a11y", regex: /<svg\b(?:(?!aria-label|aria-hidden|\brole\s*=)[^>])*>/, fileFilter: WEB_ALL, scope: "document" },
447
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "div with onClick no role", regex: /<div\b(?:(?!\brole\s*=)[^>])*\bonClick\b(?:(?!\brole\s*=)[^>])*>/, fileFilter: TSX_JSX, scope: "document" },
448
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "span with onClick no role", regex: /<span\b(?:(?!\brole\s*=)[^>])*\bonClick\b(?:(?!\brole\s*=)[^>])*>/, fileFilter: TSX_JSX, scope: "document" },
449
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "ambiguous link text", regex: />\s*(click here|read more|learn more|here|more)\s*</i, fileFilter: WEB_ALL },
450
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "positive tabindex", regex: /tabIndex=\{[1-9]|tabindex="[1-9]/, fileFilter: WEB_ALL },
451
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "aria-hidden on focusable", regex: /aria-hidden=["']true["'][^>]*(?:<button|<a\s|<input|tabIndex)/, fileFilter: WEB_ALL },
452
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "onMouseOver without onFocus", regex: /onMouseOver=(?![^>]*onFocus)/, fileFilter: TSX_JSX },
453
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "onMouseOut without onBlur", regex: /onMouseOut=(?![^>]*onBlur)/, fileFilter: TSX_JSX },
454
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "autoFocus", regex: /autoFocus\b|autofocus\b/, fileFilter: WEB_ALL },
455
+ // ── Heading & Structure ─────────────────────────────────────
456
+ { category: "foundations", subcategory: "structure", type: "concern", pattern: "empty heading", regex: /<h[1-6][^>]*>\s*<\/h[1-6]>/, fileFilter: WEB_ALL, scope: "document" },
457
+ { category: "foundations", subcategory: "structure", type: "concern", pattern: "empty button", regex: /<button[^>]*>\s*<\/button>/, fileFilter: WEB_ALL, scope: "document" },
458
+ { category: "foundations", subcategory: "structure", type: "concern", pattern: "div as button", regex: /<div[^>]*role=["']button["']/, fileFilter: WEB_ALL, scope: "document" },
459
+ { category: "foundations", subcategory: "structure", type: "concern", pattern: "div as nav/header class", regex: /<div[^>]*class(?:Name)?=["'][^"']*\b(nav|header|footer|sidebar)\b/i, fileFilter: WEB_ALL, scope: "document" },
460
+ { category: "foundations", subcategory: "structure", type: "concern", pattern: "missing html lang", regex: /<html(?!\s[^>]*lang=)/, fileFilter: /\.html?$/, scope: "document" },
461
+ { category: "foundations", subcategory: "structure", type: "positive", pattern: "html lang attribute", regex: /<html\s[^>]*lang=["'][a-z]/, fileFilter: /\.html?$/ },
462
+ { category: "foundations", subcategory: "structure", type: "positive", pattern: "landmark main", regex: /<main\b|role=["']main["']/, fileFilter: WEB_ALL },
463
+ { category: "foundations", subcategory: "structure", type: "positive", pattern: "landmark nav", regex: /<nav\b|role=["']navigation["']/, fileFilter: WEB_ALL },
464
+ { category: "foundations", subcategory: "structure", type: "positive", pattern: "landmark banner", regex: /role=["']banner["']/, fileFilter: WEB_ALL },
465
+ { category: "foundations", subcategory: "structure", type: "positive", pattern: "landmark contentinfo", regex: /role=["']contentinfo["']/, fileFilter: WEB_ALL },
466
+ { category: "foundations", subcategory: "structure", type: "positive", pattern: "heading h1", regex: /<h1\b/, fileFilter: WEB_ALL },
467
+ { category: "foundations", subcategory: "structure", type: "pattern", pattern: "heading h2", regex: /<h2\b/, fileFilter: WEB_ALL },
468
+ { category: "foundations", subcategory: "structure", type: "pattern", pattern: "heading h3", regex: /<h3\b/, fileFilter: WEB_ALL },
469
+ // ── Color system ────────────────────────────────────────────
470
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "CSS variable color", regex: /var\(--[a-z]/, fileFilter: /\.(tsx|jsx|css|scss|html?|vue|svelte)$/ },
471
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "semantic text color", regex: /text-(foreground|muted-foreground|primary|secondary|destructive|accent-foreground)/, fileFilter: TSX_JSX },
472
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "semantic bg color", regex: /bg-(background|muted|accent|card|popover|primary|secondary|destructive)/, fileFilter: TSX_JSX },
473
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "semantic border color", regex: /border-(border|input|ring)/, fileFilter: TSX_JSX },
474
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "inline color style", regex: /style=\{?\{[^}]*color:\s*['"]#/, fileFilter: TSX_JSX },
475
+ // ── Typography ──────────────────────────────────────────────
476
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "design token font size", regex: /text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)\b/, fileFilter: TSX_JSX },
477
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "font-weight token", regex: /font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)\b/, fileFilter: TSX_JSX },
478
+ { category: "foundations", subcategory: "typography", type: "concern", pattern: "hardcoded font-size px", regex: /font-size:\s*\d+px/, fileFilter: /\.(css|scss|tsx|jsx)$/ },
479
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "rem/em font size", regex: /font-size:\s*[\d.]+r?em/, fileFilter: STYLE_ALL },
480
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "system font stack", regex: /font-family:.*(-apple-system|BlinkMacSystemFont|system-ui|SF Pro)/i, fileFilter: STYLE_ALL },
481
+ // ── Dark mode ───────────────────────────────────────────────
482
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "dark mode class", regex: /\bdark:/, fileFilter: TSX_JSX },
483
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "prefers-color-scheme", regex: /prefers-color-scheme/, fileFilter: /\.(css|scss|tsx|jsx|ts|js|vue|svelte)$/ },
484
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "color-scheme property", regex: /color-scheme:\s*(light\s+dark|dark\s+light)/, fileFilter: STYLE_ALL },
485
+ // ── Responsive / Layout ─────────────────────────────────────
486
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "responsive breakpoint", regex: /\b(sm:|md:|lg:|xl:|2xl:)/, fileFilter: TSX_JSX },
487
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "media query", regex: /@media\s*\(/, fileFilter: STYLE_ALL },
488
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "safe area inset", regex: /safe-area-inset|env\(safe-area/, fileFilter: /\.(css|scss|tsx|jsx)$/ },
489
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "container query", regex: /@container\b/, fileFilter: STYLE_ALL },
490
+ // ── Motion ──────────────────────────────────────────────────
491
+ { category: "foundations", subcategory: "motion", type: "positive", pattern: "prefers-reduced-motion", regex: /prefers-reduced-motion/, fileFilter: /\.(css|scss|tsx|jsx|ts|js|vue|svelte)$/ },
492
+ { category: "foundations", subcategory: "motion", type: "pattern", pattern: "CSS animation", regex: /@keyframes/, fileFilter: STYLE_ALL },
493
+ { category: "foundations", subcategory: "motion", type: "pattern", pattern: "CSS transition", regex: /transition:/, fileFilter: STYLE_ALL },
494
+ // ── Touch targets ───────────────────────────────────────────
495
+ { category: "foundations", subcategory: "touchTargets", type: "positive", pattern: "min touch target 44px", regex: /min-(width|height):\s*4[4-8]px|min-(w|h)-1[1-2]\b/, fileFilter: /\.(css|scss|tsx|jsx)$/ },
496
+ // ── Navigation (components-layout) ──────────────────────────
497
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "nav element", regex: /<nav\b/, fileFilter: WEB_ALL },
498
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "Link component", regex: /<Link\b/, fileFilter: TSX_JSX },
499
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "useRouter", regex: /useRouter\b/, fileFilter: TS_JS },
500
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "usePathname", regex: /usePathname\b/, fileFilter: TS_JS },
501
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "header element", regex: /<header\b/, fileFilter: WEB_ALL },
502
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "main element", regex: /<main\b/, fileFilter: WEB_ALL },
503
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "footer element", regex: /<footer\b/, fileFilter: WEB_ALL },
504
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "section element", regex: /<section\b/, fileFilter: WEB_ALL },
505
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "aside element", regex: /<aside\b/, fileFilter: WEB_ALL },
506
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "article element", regex: /<article\b/, fileFilter: WEB_ALL },
507
+ { category: "components-layout", subcategory: "layout", type: "positive", pattern: "grid layout", regex: /grid-cols|grid-template/, fileFilter: /\.(tsx|jsx|css|scss)$/ },
508
+ // ── Controls (components-controls) ──────────────────────────
509
+ { category: "components-controls", subcategory: "buttons", type: "pattern", pattern: "button element", regex: /<button\b|<Button\b/, fileFilter: WEB_ALL },
510
+ { category: "components-controls", subcategory: "inputs", type: "pattern", pattern: "input element", regex: /<input\b|<Input\b/, fileFilter: WEB_ALL },
511
+ { category: "components-controls", subcategory: "inputs", type: "pattern", pattern: "select element", regex: /<select\b|<Select\b/, fileFilter: WEB_ALL },
512
+ { category: "components-controls", subcategory: "inputs", type: "pattern", pattern: "textarea element", regex: /<textarea\b|<Textarea\b/, fileFilter: WEB_ALL },
513
+ { category: "components-controls", subcategory: "inputs", type: "pattern", pattern: "checkbox/radio", regex: /type=["'](checkbox|radio)["']/, fileFilter: WEB_ALL },
514
+ { category: "components-controls", subcategory: "inputs", type: "positive", pattern: "label element", regex: /<label\b|<Label\b/, fileFilter: WEB_ALL },
515
+ { category: "components-controls", subcategory: "toggle", type: "pattern", pattern: "switch/toggle", regex: /<Switch\b|role=["']switch["']/, fileFilter: TSX_JSX },
516
+ // ── Forms (inputs) ──────────────────────────────────────────
517
+ { category: "inputs", subcategory: "forms", type: "pattern", pattern: "form element", regex: /<form\b|<Form\b/, fileFilter: WEB_ALL },
518
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "form validation", regex: /\brequired\b|pattern=|minLength|maxLength/, fileFilter: WEB_ALL },
519
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "input type email", regex: /type=["']email["']/, fileFilter: WEB_ALL },
520
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "input type tel", regex: /type=["']tel["']/, fileFilter: WEB_ALL },
521
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "input type url", regex: /type=["']url["']/, fileFilter: WEB_ALL },
522
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "input type number", regex: /type=["']number["']/, fileFilter: WEB_ALL },
523
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "autocomplete attribute", regex: /autocomplete=["']/, fileFilter: WEB_ALL },
524
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "fieldset element", regex: /<fieldset\b/, fileFilter: WEB_ALL },
525
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "legend element", regex: /<legend\b/, fileFilter: WEB_ALL },
526
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "placeholder text", regex: /placeholder=["']/, fileFilter: WEB_ALL },
527
+ // ── Dialogs (components-dialogs) ────────────────────────────
528
+ { category: "components-dialogs", subcategory: "modals", type: "pattern", pattern: "dialog element", regex: /<dialog\b|<Dialog\b/, fileFilter: WEB_ALL },
529
+ { category: "components-dialogs", subcategory: "modals", type: "pattern", pattern: "modal/sheet", regex: /<Modal\b|<Sheet\b|<Drawer\b/, fileFilter: TSX_JSX },
530
+ { category: "components-dialogs", subcategory: "alerts", type: "pattern", pattern: "alert dialog", regex: /<AlertDialog\b|role=["']alertdialog["']/, fileFilter: TSX_JSX },
531
+ { category: "components-dialogs", subcategory: "popover", type: "pattern", pattern: "popover", regex: /<Popover\b/, fileFilter: TSX_JSX },
532
+ { category: "components-dialogs", subcategory: "toast", type: "pattern", pattern: "toast/notification", regex: /<Toast\b|toast\(|<Toaster\b|<Sonner\b/, fileFilter: TSX_JSX },
533
+ { category: "components-dialogs", subcategory: "tooltip", type: "pattern", pattern: "tooltip", regex: /<Tooltip\b|role=["']tooltip["']/, fileFilter: WEB_ALL },
534
+ // ── Search (components-search) ──────────────────────────────
535
+ { category: "components-search", subcategory: "search", type: "pattern", pattern: "search input", regex: /type=["']search["']/, fileFilter: WEB_ALL },
536
+ { category: "components-search", subcategory: "search", type: "pattern", pattern: "search role", regex: /role=["']search["']/, fileFilter: WEB_ALL },
537
+ // ── Menus (components-menus) ────────────────────────────────
538
+ { category: "components-menus", subcategory: "menus", type: "pattern", pattern: "dropdown menu", regex: /<DropdownMenu\b/, fileFilter: TSX_JSX },
539
+ { category: "components-menus", subcategory: "menus", type: "pattern", pattern: "context menu", regex: /<ContextMenu\b|onContextMenu/, fileFilter: TSX_JSX },
540
+ { category: "components-menus", subcategory: "menus", type: "pattern", pattern: "menu role", regex: /role=["']menu["']|role=["']menubar["']/, fileFilter: WEB_ALL },
541
+ { category: "components-menus", subcategory: "menus", type: "pattern", pattern: "menuitem role", regex: /role=["']menuitem["']/, fileFilter: WEB_ALL },
542
+ // ── Status (components-status) ──────────────────────────────
543
+ { category: "components-status", subcategory: "progress", type: "pattern", pattern: "progress bar", regex: /<progress\b|<Progress\b|role=["']progressbar["']/, fileFilter: WEB_ALL },
544
+ { category: "components-status", subcategory: "loading", type: "pattern", pattern: "loading state", regex: /isLoading|loading\s*[=:]|<Skeleton\b|<Spinner\b/, fileFilter: TS_JS },
545
+ { category: "components-status", subcategory: "loading", type: "pattern", pattern: "aria-busy", regex: /aria-busy/, fileFilter: WEB_ALL },
546
+ // ── Content (components-content) ────────────────────────────
547
+ { category: "components-content", subcategory: "images", type: "pattern", pattern: "Next Image", regex: /<Image\b.*\bsrc=/, fileFilter: TSX_JSX },
548
+ { category: "components-content", subcategory: "tables", type: "pattern", pattern: "table element", regex: /<table\b|<Table\b/, fileFilter: WEB_ALL },
549
+ { category: "components-content", subcategory: "accordion", type: "pattern", pattern: "accordion", regex: /<Accordion\b/, fileFilter: TSX_JSX },
550
+ { category: "components-content", subcategory: "cards", type: "pattern", pattern: "card component", regex: /<Card\b/, fileFilter: TSX_JSX },
551
+ { category: "components-content", subcategory: "lists", type: "pattern", pattern: "list elements", regex: /<ul\b|<ol\b|<dl\b/, fileFilter: WEB_ALL },
552
+ { category: "components-content", subcategory: "details", type: "pattern", pattern: "details/summary", regex: /<details\b|<summary\b/, fileFilter: WEB_ALL },
553
+ // ── Patterns ────────────────────────────────────────────────
554
+ { category: "patterns", subcategory: "animation", type: "pattern", pattern: "framer motion", regex: /framer-motion|motion\.[a-z]/, fileFilter: TS_JS },
555
+ { category: "patterns", subcategory: "seo", type: "positive", pattern: "metadata/head", regex: /export.*metadata|<Head\b|<title\b/, fileFilter: TS_JS },
556
+ { category: "patterns", subcategory: "errorHandling", type: "positive", pattern: "error boundary", regex: /ErrorBoundary|error\.tsx/, fileFilter: TS_JS },
557
+ { category: "patterns", subcategory: "i18n", type: "positive", pattern: "i18n/l10n", regex: /useTranslation|i18n|intl|formatMessage|<FormattedMessage/, fileFilter: TS_JS },
558
+ // ── Technologies ────────────────────────────────────────────
559
+ { category: "technologies", subcategory: "analytics", type: "pattern", pattern: "analytics", regex: /@vercel\/analytics|gtag|GoogleAnalytics/, fileFilter: TS_JS },
560
+ // ── Media accessibility ─────────────────────────────────────
561
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "video without track", regex: /<video\b(?:(?!<\/video>|<track\b)[\s\S])*?<\/video>/i, fileFilter: WEB_ALL, scope: "document" },
562
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "autoplay media", regex: /\bauto[Pp]lay\b(?!\s*=\s*\{?\s*['"]?false)/, fileFilter: WEB_ALL },
563
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "blink element", regex: /<blink\b/, fileFilter: WEB_ALL },
564
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "marquee element", regex: /<marquee\b/, fileFilter: WEB_ALL },
565
+ // ── Viewport concerns ───────────────────────────────────────
566
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "user-scalable=no", regex: /user-scalable\s*=\s*no/, fileFilter: WEB_ALL },
567
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "maximum-scale=1", regex: /maximum-scale\s*=\s*1\b/, fileFilter: WEB_ALL }
568
+ ];
569
+ var cssRules = [
570
+ // Color
571
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "CSS custom property def", regex: /--[a-z][\w-]*:\s*/, fileFilter: STYLE_ALL },
572
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcoded hex in CSS", regex: /(?:^|[\s;{])(?:color|background(?:-color)?|border(?:-color)?):\s*#[0-9a-fA-F]{3,8}\b/, fileFilter: STYLE_ALL },
573
+ // Typography
574
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "clamp font size", regex: /font-size:\s*clamp\(/, fileFilter: STYLE_ALL },
575
+ { category: "foundations", subcategory: "typography", type: "concern", pattern: "font-size below 12px", regex: /font-size:\s*(1[01]|[0-9])px\b/, fileFilter: STYLE_ALL },
576
+ { category: "foundations", subcategory: "typography", type: "concern", pattern: "text-align justify", regex: /text-align:\s*justify/, fileFilter: STYLE_ALL },
577
+ { category: "foundations", subcategory: "typography", type: "concern", pattern: "line-height below 1.2", regex: /line-height:\s*(0\.\d+|1\.[01]\d*)\s*[;}]/, fileFilter: STYLE_ALL },
578
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "max-width on text", regex: /max-width:.*ch\b/, fileFilter: STYLE_ALL },
579
+ // Accessibility
580
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "focus-visible", regex: /:focus-visible/, fileFilter: STYLE_ALL },
581
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "focus ring styles", regex: /outline.*focus|ring-/, fileFilter: STYLE_ALL },
582
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "high contrast", regex: /forced-colors|high-contrast|prefers-contrast/, fileFilter: STYLE_ALL },
583
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "outline none", regex: /outline:\s*(none|0)\b/, fileFilter: STYLE_ALL, skipInBlock: /(:focus:not\(:focus-visible\))|(@media\s+print)/ },
584
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "hover without focus", regex: /:hover\b/, fileFilter: STYLE_ALL, scope: "document", requireAbsent: /:focus/ },
585
+ // Layout
586
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "print styles", regex: /@media\s+print/, fileFilter: STYLE_ALL },
587
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "logical properties", regex: /margin-inline|padding-inline|border-inline|inset-inline/, fileFilter: STYLE_ALL },
588
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "flexbox gap", regex: /\bgap:\s*/, fileFilter: STYLE_ALL },
589
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "aspect-ratio", regex: /aspect-ratio:/, fileFilter: STYLE_ALL },
590
+ { category: "foundations", subcategory: "layout", type: "concern", pattern: "overflow hidden on body", regex: /body\s*\{[^}]*overflow:\s*hidden/, fileFilter: STYLE_ALL },
591
+ // Touch targets
592
+ { category: "foundations", subcategory: "touchTargets", type: "positive", pattern: "touch target sizing", regex: /min-(width|height):\s*4[4-8]px/, fileFilter: STYLE_ALL },
593
+ // z-index
594
+ { category: "foundations", subcategory: "layout", type: "concern", pattern: "extreme z-index", regex: /z-index:\s*[1-9]\d{3,}/, fileFilter: STYLE_ALL },
595
+ // !important
596
+ { category: "foundations", subcategory: "layout", type: "concern", pattern: "!important usage", regex: /!important/, fileFilter: STYLE_ALL, skipInBlock: /@media\s+print|prefers-reduced-motion/ },
597
+ // Scrollbar
598
+ { category: "foundations", subcategory: "layout", type: "pattern", pattern: "custom scrollbar", regex: /-webkit-scrollbar|scrollbar-width/, fileFilter: STYLE_ALL },
599
+ // i18n / RTL
600
+ { category: "foundations", subcategory: "i18n", type: "positive", pattern: "RTL direction", regex: /direction:\s*rtl|\[dir=["']rtl["']\]/, fileFilter: STYLE_ALL },
601
+ { category: "foundations", subcategory: "i18n", type: "positive", pattern: "logical text-align", regex: /text-align:\s*(start|end)\b/, fileFilter: STYLE_ALL },
602
+ { category: "foundations", subcategory: "i18n", type: "positive", pattern: "logical margin/padding", regex: /margin-inline-start|margin-inline-end|padding-inline-start|padding-inline-end/, fileFilter: STYLE_ALL },
603
+ { category: "foundations", subcategory: "i18n", type: "concern", pattern: "physical text-align", regex: /text-align:\s*(left|right)\b/, fileFilter: STYLE_ALL }
604
+ ];
605
+ var vueRules = [
606
+ // Accessibility positives
607
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "v-bind aria-label", regex: /:?aria-label=|v-bind:aria-label/, fileFilter: VUE },
608
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "v-bind aria-describedby", regex: /:?aria-describedby=|v-bind:aria-describedby/, fileFilter: VUE },
609
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "v-bind aria-expanded", regex: /:?aria-expanded=|v-bind:aria-expanded/, fileFilter: VUE },
610
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "v-bind role", regex: /:?role=|v-bind:role/, fileFilter: VUE },
611
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "v-bind alt", regex: /:?alt=|v-bind:alt/, fileFilter: VUE },
612
+ // Accessibility concerns
613
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "v-on:click without keyboard", regex: /v-on:click=|@click=(?![^>]*(?:@keydown|@keyup|v-on:keydown|v-on:keyup))/, fileFilter: VUE },
614
+ // Navigation
615
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "router-link", regex: /<router-link\b/, fileFilter: VUE },
616
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "NuxtLink", regex: /<NuxtLink\b/, fileFilter: VUE },
617
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "useRouter (Vue)", regex: /useRouter\(\)/, fileFilter: VUE },
618
+ // Semantic elements
619
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "nav in template", regex: /<nav\b/, fileFilter: VUE },
620
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "header in template", regex: /<header\b/, fileFilter: VUE },
621
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "main in template", regex: /<main\b/, fileFilter: VUE },
622
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "footer in template", regex: /<footer\b/, fileFilter: VUE },
623
+ // Dark mode
624
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "Vue dark class", regex: /class="[^"]*dark:|:class="[^"]*dark/, fileFilter: VUE },
625
+ // Controls
626
+ { category: "components-controls", subcategory: "inputs", type: "pattern", pattern: "v-model", regex: /v-model=/, fileFilter: VUE },
627
+ // Forms
628
+ { category: "inputs", subcategory: "forms", type: "pattern", pattern: "Vue form", regex: /<form\b/, fileFilter: VUE },
629
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "Vue form validation", regex: /required\b|v-validate|@submit\.prevent/, fileFilter: VUE },
630
+ // Transitions
631
+ { category: "patterns", subcategory: "animation", type: "pattern", pattern: "Vue transition", regex: /<transition\b|<Transition\b/, fileFilter: VUE },
632
+ // i18n
633
+ { category: "patterns", subcategory: "i18n", type: "positive", pattern: "Vue i18n", regex: /\$t\(|useI18n|vue-i18n/, fileFilter: VUE }
634
+ ];
635
+ var svelteRules = [
636
+ // Accessibility
637
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "aria-label (Svelte)", regex: /aria-label=/, fileFilter: SVELTE },
638
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "aria-describedby (Svelte)", regex: /aria-describedby=/, fileFilter: SVELTE },
639
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "role (Svelte)", regex: /role=["']/, fileFilter: SVELTE },
640
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "on:click without on:keydown", regex: /on:click=(?![^>]*on:key(down|up)=)/, fileFilter: SVELTE },
641
+ // Navigation
642
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "SvelteKit link", regex: /<a\s[^>]*href=["']\//, fileFilter: SVELTE },
643
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "nav (Svelte)", regex: /<nav\b/, fileFilter: SVELTE },
644
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "header (Svelte)", regex: /<header\b/, fileFilter: SVELTE },
645
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "main (Svelte)", regex: /<main\b/, fileFilter: SVELTE },
646
+ // Dark mode
647
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "Svelte dark class", regex: /class:dark|class="[^"]*dark:/, fileFilter: SVELTE },
648
+ // Motion
649
+ { category: "foundations", subcategory: "motion", type: "positive", pattern: "Svelte reduced motion", regex: /prefersReducedMotion|prefers-reduced-motion/, fileFilter: SVELTE },
650
+ { category: "patterns", subcategory: "animation", type: "pattern", pattern: "Svelte transition", regex: /transition:|in:|out:/, fileFilter: SVELTE },
651
+ // Forms
652
+ { category: "inputs", subcategory: "forms", type: "pattern", pattern: "Svelte form", regex: /<form\b/, fileFilter: SVELTE },
653
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "Svelte bind:value", regex: /bind:value=/, fileFilter: SVELTE },
654
+ // i18n
655
+ { category: "patterns", subcategory: "i18n", type: "positive", pattern: "Svelte i18n", regex: /svelte-i18n|\$_\(|i18n/, fileFilter: SVELTE }
656
+ ];
657
+ var angularRules = [
658
+ // Accessibility
659
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "[attr.aria-label]", regex: /\[attr\.aria-label\]=/, fileFilter: ANGULAR },
660
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "[attr.aria-describedby]", regex: /\[attr\.aria-describedby\]=/, fileFilter: ANGULAR },
661
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "[attr.role]", regex: /\[attr\.role\]=/, fileFilter: ANGULAR },
662
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "Angular CDK a11y", regex: /cdkTrapFocus|cdkFocusInitial|cdkMonitorSubtreeFocus|A11yModule/, fileFilter: ANGULAR },
663
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "(click) without (keydown)", regex: /\(click\)=(?![^>]*\(keydown\)=)/, fileFilter: ANGULAR },
664
+ // Navigation
665
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "routerLink", regex: /routerLink=/, fileFilter: ANGULAR },
666
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "router-outlet", regex: /<router-outlet/, fileFilter: ANGULAR },
667
+ // Angular Material
668
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "mat-button", regex: /mat-button|matButton/, fileFilter: ANGULAR },
669
+ { category: "components-controls", subcategory: "inputs", type: "pattern", pattern: "mat-form-field", regex: /mat-form-field|matFormField/, fileFilter: ANGULAR },
670
+ { category: "components-controls", subcategory: "inputs", type: "pattern", pattern: "mat-input", regex: /matInput/, fileFilter: ANGULAR },
671
+ { category: "components-controls", subcategory: "toggle", type: "pattern", pattern: "mat-slide-toggle", regex: /mat-slide-toggle/, fileFilter: ANGULAR },
672
+ { category: "components-dialogs", subcategory: "modals", type: "pattern", pattern: "mat-dialog", regex: /MatDialog|mat-dialog/, fileFilter: ANGULAR },
673
+ { category: "components-content", subcategory: "tables", type: "pattern", pattern: "mat-table", regex: /mat-table|matTable/, fileFilter: ANGULAR },
674
+ // Forms
675
+ { category: "inputs", subcategory: "forms", type: "pattern", pattern: "Angular form", regex: /\[formGroup\]=|formControlName=|ngModel/, fileFilter: ANGULAR },
676
+ { category: "inputs", subcategory: "forms", type: "positive", pattern: "Angular validation", regex: /Validators\.|required|minlength|maxlength/, fileFilter: ANGULAR },
677
+ // i18n
678
+ { category: "patterns", subcategory: "i18n", type: "positive", pattern: "Angular i18n", regex: /i18n\b|@angular\/localize|translate/, fileFilter: ANGULAR },
679
+ // Dark mode
680
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "Angular dark theme", regex: /dark-theme|\.dark\b/, fileFilter: ANGULAR }
681
+ ];
682
+ var kotlinRules = [
683
+ // Accessibility
684
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "contentDescription", regex: /contentDescription\s*=/, fileFilter: KOTLIN },
685
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "semantics modifier", regex: /Modifier\.semantics/, fileFilter: KOTLIN },
686
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "clearAndSetSemantics", regex: /clearAndSetSemantics/, fileFilter: KOTLIN },
687
+ // Catches both the trailing-lambda form `Modifier.clickable { }` (which has no
688
+ // way to pass a role and is therefore always a concern) and the parenthesized
689
+ // `Modifier.clickable(...)` form when no role argument is present.
690
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "clickable without Role", regex: /Modifier\.clickable\s*(\{|\((?![^)]*role\s*=))/, fileFilter: KOTLIN },
691
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "testTag", regex: /testTag\s*=/, fileFilter: KOTLIN },
692
+ // Color
693
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "MaterialTheme colorScheme", regex: /MaterialTheme\.colorScheme/, fileFilter: KOTLIN },
694
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcoded Color(0x)", regex: /Color\(0x[0-9a-fA-F]+\)/, fileFilter: KOTLIN },
695
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcoded Color.Red/Blue", regex: /Color\.(Red|Blue|Green|Yellow|White|Black|Gray|Cyan|Magenta)\b/, fileFilter: KOTLIN },
696
+ // Typography
697
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "MaterialTheme typography", regex: /MaterialTheme\.typography/, fileFilter: KOTLIN },
698
+ { category: "foundations", subcategory: "typography", type: "concern", pattern: "hardcoded fontSize", regex: /fontSize\s*=\s*\d+\.sp/, fileFilter: KOTLIN },
699
+ // Dark mode
700
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "isSystemInDarkTheme", regex: /isSystemInDarkTheme\(\)/, fileFilter: KOTLIN },
701
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "darkColorScheme", regex: /darkColorScheme\b/, fileFilter: KOTLIN },
702
+ // Layout
703
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "NavigationBar", regex: /\bNavigationBar\b/, fileFilter: KOTLIN },
704
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "NavHost", regex: /\bNavHost\b/, fileFilter: KOTLIN },
705
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "BottomNavigation", regex: /\bBottomNavigation\b/, fileFilter: KOTLIN },
706
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "Scaffold", regex: /\bScaffold\s*\(/, fileFilter: KOTLIN },
707
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "LazyColumn", regex: /\bLazyColumn\b/, fileFilter: KOTLIN },
708
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "LazyRow", regex: /\bLazyRow\b/, fileFilter: KOTLIN },
709
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "LazyVerticalGrid", regex: /\bLazyVerticalGrid\b/, fileFilter: KOTLIN },
710
+ // Controls
711
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "Compose Button", regex: /\bButton\s*\(/, fileFilter: KOTLIN },
712
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "TextField", regex: /\bTextField\s*\(|OutlinedTextField\s*\(/, fileFilter: KOTLIN },
713
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "Compose Switch", regex: /\bSwitch\s*\(/, fileFilter: KOTLIN },
714
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "Compose Checkbox", regex: /\bCheckbox\s*\(/, fileFilter: KOTLIN },
715
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "Compose Slider", regex: /\bSlider\s*\(/, fileFilter: KOTLIN },
716
+ // Dialogs
717
+ { category: "components-dialogs", subcategory: "modals", type: "pattern", pattern: "AlertDialog (Compose)", regex: /\bAlertDialog\s*\(/, fileFilter: KOTLIN },
718
+ { category: "components-dialogs", subcategory: "modals", type: "pattern", pattern: "BottomSheet", regex: /BottomSheet|ModalBottomSheet/, fileFilter: KOTLIN },
719
+ // Search
720
+ { category: "components-search", subcategory: "search", type: "pattern", pattern: "SearchBar (Compose)", regex: /\bSearchBar\s*\(/, fileFilter: KOTLIN },
721
+ // Status
722
+ { category: "components-status", subcategory: "progress", type: "pattern", pattern: "CircularProgress", regex: /CircularProgressIndicator|LinearProgressIndicator/, fileFilter: KOTLIN }
723
+ ];
724
+ var androidXmlRules = [
725
+ // Accessibility
726
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "android:contentDescription", regex: /android:contentDescription=/, fileFilter: ANDROID_XML },
727
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "ImageView without contentDescription", regex: /<ImageView(?![^>]*contentDescription=)/, fileFilter: ANDROID_XML },
728
+ { category: "foundations", subcategory: "accessibility", type: "pattern", pattern: "importantForAccessibility", regex: /android:importantForAccessibility/, fileFilter: ANDROID_XML },
729
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "android:labelFor", regex: /android:labelFor=/, fileFilter: ANDROID_XML },
730
+ // Color / resources
731
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "@color/ resource", regex: /@color\//, fileFilter: ANDROID_XML },
732
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcoded color in XML", regex: /android:(?:text|background)Color=["']#/, fileFilter: ANDROID_XML },
733
+ // Typography
734
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "sp text size", regex: /android:textSize=["']\d+sp/, fileFilter: ANDROID_XML },
735
+ { category: "foundations", subcategory: "typography", type: "concern", pattern: "dp text size", regex: /android:textSize=["']\d+dp/, fileFilter: ANDROID_XML },
736
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "@style/ usage", regex: /@style\//, fileFilter: ANDROID_XML },
737
+ // Layout
738
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "dp units", regex: /\d+dp\b/, fileFilter: ANDROID_XML },
739
+ { category: "foundations", subcategory: "layout", type: "concern", pattern: "px units in XML", regex: /\d+px\b/, fileFilter: ANDROID_XML },
740
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "@dimen/ resource", regex: /@dimen\//, fileFilter: ANDROID_XML },
741
+ // Components
742
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "ConstraintLayout", regex: /ConstraintLayout/, fileFilter: ANDROID_XML },
743
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "RecyclerView", regex: /RecyclerView/, fileFilter: ANDROID_XML },
744
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "BottomNavigationView", regex: /BottomNavigationView/, fileFilter: ANDROID_XML },
745
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "NavigationView", regex: /NavigationView/, fileFilter: ANDROID_XML },
746
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "MaterialButton", regex: /MaterialButton/, fileFilter: ANDROID_XML },
747
+ // Touch targets
748
+ { category: "foundations", subcategory: "touchTargets", type: "positive", pattern: "minHeight 48dp", regex: /android:minHeight=["']4[4-8]dp/, fileFilter: ANDROID_XML }
749
+ ];
750
+ var reactNativeRules = [
751
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "accessibilityLabel", regex: /accessibilityLabel=/, fileFilter: TSX_JSX },
752
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "accessibilityRole", regex: /accessibilityRole=/, fileFilter: TSX_JSX },
753
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "accessibilityHint", regex: /accessibilityHint=/, fileFilter: TSX_JSX },
754
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "accessibilityState", regex: /accessibilityState=/, fileFilter: TSX_JSX },
755
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "accessible={true}", regex: /accessible=\{true\}/, fileFilter: TSX_JSX },
756
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "useColorScheme", regex: /useColorScheme\b/, fileFilter: TS_JS },
757
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "useWindowDimensions", regex: /useWindowDimensions\b/, fileFilter: TS_JS },
758
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "React Navigation", regex: /createNativeStackNavigator|createBottomTabNavigator|NavigationContainer/, fileFilter: TS_JS },
759
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "FlatList", regex: /\bFlatList\b/, fileFilter: TSX_JSX },
760
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "SectionList", regex: /\bSectionList\b/, fileFilter: TSX_JSX },
761
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "SafeAreaView", regex: /\bSafeAreaView\b/, fileFilter: TSX_JSX },
762
+ { category: "inputs", subcategory: "gestures", type: "pattern", pattern: "Gesture handler", regex: /PanGestureHandler|TapGestureHandler|GestureDetector/, fileFilter: TSX_JSX },
763
+ { category: "patterns", subcategory: "haptics", type: "pattern", pattern: "Haptics", regex: /Haptics\.|expo-haptics/, fileFilter: TS_JS },
764
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "nested touchables", regex: /accessible=\{true\}[\s\S]*?<Touchable/, fileFilter: TSX_JSX }
765
+ ];
766
+ var flutterRules = [
767
+ // Accessibility
768
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "Semantics widget", regex: /\bSemantics\(/, fileFilter: DART },
769
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "ExcludeSemantics", regex: /\bExcludeSemantics\(/, fileFilter: DART },
770
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "MergeSemantics", regex: /\bMergeSemantics\(/, fileFilter: DART },
771
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "semanticLabel", regex: /semanticLabel:/, fileFilter: DART },
772
+ // Color
773
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "Theme color", regex: /Theme\.of\(context\)\.colorScheme/, fileFilter: DART },
774
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcoded Color", regex: /Color\(0x[0-9a-fA-F]+\)/, fileFilter: DART },
775
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "Colors.red/blue", regex: /Colors\.(red|blue|green|yellow|orange|purple|pink|white|black|grey)\b/, fileFilter: DART },
776
+ // Typography
777
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "Theme text style", regex: /Theme\.of\(context\)\.textTheme/, fileFilter: DART },
778
+ { category: "foundations", subcategory: "typography", type: "concern", pattern: "hardcoded fontSize", regex: /fontSize:\s*\d+/, fileFilter: DART },
779
+ // Dark mode
780
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "brightness detection", regex: /MediaQuery\.of\(context\)\.platformBrightness/, fileFilter: DART },
781
+ { category: "foundations", subcategory: "darkMode", type: "positive", pattern: "darkTheme", regex: /darkTheme:/, fileFilter: DART },
782
+ // Layout
783
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "MediaQuery responsive", regex: /MediaQuery\.of\(context\)\.size/, fileFilter: DART },
784
+ { category: "foundations", subcategory: "layout", type: "positive", pattern: "LayoutBuilder", regex: /\bLayoutBuilder\b/, fileFilter: DART },
785
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "Navigator", regex: /\bNavigator\b/, fileFilter: DART },
786
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "CupertinoTabBar", regex: /\bCupertinoTabBar\b/, fileFilter: DART },
787
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "GoRouter", regex: /\bGoRouter\b/, fileFilter: DART },
788
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "ListView", regex: /\bListView\b/, fileFilter: DART },
789
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "GridView", regex: /\bGridView\b/, fileFilter: DART },
790
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "CupertinoButton", regex: /\bCupertinoButton\b/, fileFilter: DART },
791
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "ElevatedButton", regex: /\bElevatedButton\b/, fileFilter: DART },
792
+ // i18n
793
+ { category: "patterns", subcategory: "i18n", type: "positive", pattern: "Flutter l10n", regex: /AppLocalizations|flutter_localizations|intl/, fileFilter: DART }
794
+ ];
795
+ var uikitRules = [
796
+ // Navigation & structure
797
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "UINavigationController", regex: /\bUINavigationController\b/, fileFilter: SWIFT },
798
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "UITabBarController", regex: /\bUITabBarController\b/, fileFilter: SWIFT },
799
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "UISplitViewController", regex: /\bUISplitViewController\b/, fileFilter: SWIFT },
800
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "UIPageViewController", regex: /\bUIPageViewController\b/, fileFilter: SWIFT },
801
+ { category: "components-layout", subcategory: "lists", type: "pattern", pattern: "UICollectionView", regex: /\bUICollectionView\b/, fileFilter: SWIFT },
802
+ { category: "components-layout", subcategory: "lists", type: "pattern", pattern: "UITableView", regex: /\bUITableView\b/, fileFilter: SWIFT },
803
+ { category: "components-layout", subcategory: "layout", type: "pattern", pattern: "UIStackView", regex: /\bUIStackView\b/, fileFilter: SWIFT },
804
+ { category: "components-search", subcategory: "search", type: "pattern", pattern: "UISearchController", regex: /\bUISearchController\b/, fileFilter: SWIFT },
805
+ { category: "components-menus", subcategory: "menus", type: "pattern", pattern: "UIMenu", regex: /\bUIMenu\b/, fileFilter: SWIFT },
806
+ { category: "components-menus", subcategory: "menus", type: "pattern", pattern: "UIContextMenuConfiguration", regex: /\bUIContextMenuConfiguration\b/, fileFilter: SWIFT },
807
+ { category: "components-status", subcategory: "modals", type: "pattern", pattern: "UIAlertController", regex: /\bUIAlertController\b/, fileFilter: SWIFT },
808
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "UISegmentedControl", regex: /\bUISegmentedControl\b/, fileFilter: SWIFT },
809
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "UISwitch", regex: /\bUISwitch\b/, fileFilter: SWIFT },
810
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "UIStepper", regex: /\bUIStepper\b/, fileFilter: SWIFT },
811
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "UIToolbar", regex: /\bUIToolbar\b/, fileFilter: SWIFT },
812
+ // Typography — Dynamic Type
813
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "UIKit preferredFont", regex: /preferredFont\(forTextStyle:/, fileFilter: SWIFT },
814
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "adjustsFontForContentSizeCategory", regex: /adjustsFontForContentSizeCategory\s*=\s*true/, fileFilter: SWIFT },
815
+ { category: "foundations", subcategory: "typography", type: "concern", pattern: "hardcoded UIFont(name:)", regex: /UIFont\(name:[^)]*,\s*size:\s*\d/, fileFilter: SWIFT },
816
+ // Color — semantic vs hardcoded
817
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "UIKit semantic color", regex: /UIColor\.(label|secondaryLabel|tertiaryLabel|systemBackground|secondarySystemBackground|tintColor|systemFill|separator|link)\b/, fileFilter: SWIFT },
818
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcoded UIColor constant", regex: /UIColor\.(white|black|gray|lightGray|darkGray|red|blue|green|yellow|orange|purple|brown|cyan|magenta)\b/, fileFilter: SWIFT },
819
+ // Accessibility
820
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "UIKit accessibilityLabel", regex: /\.accessibilityLabel\s*=/, fileFilter: SWIFT },
821
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "UIKit isAccessibilityElement", regex: /\.isAccessibilityElement\s*=\s*true/, fileFilter: SWIFT },
822
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "UIKit accessibilityTraits", regex: /\.accessibilityTraits\s*=/, fileFilter: SWIFT },
823
+ { category: "foundations", subcategory: "accessibility", type: "concern", pattern: "viewWithTag lookup", regex: /\.viewWithTag\(/, fileFilter: SWIFT },
824
+ // SF Symbols
825
+ { category: "foundations", subcategory: "sf-symbols", type: "positive", pattern: "UIImage(systemName:)", regex: /UIImage\(systemName:/, fileFilter: SWIFT },
826
+ // Layout — Auto Layout & safe area
827
+ { category: "components-layout", subcategory: "layout", type: "positive", pattern: "Auto Layout constraints", regex: /NSLayoutConstraint|\.constraint\(equalTo:/, fileFilter: SWIFT },
828
+ { category: "components-layout", subcategory: "layout", type: "positive", pattern: "safeAreaLayoutGuide", regex: /safeAreaLayoutGuide/, fileFilter: SWIFT },
829
+ { category: "components-layout", subcategory: "layout", type: "concern", pattern: "UIScreen.main.bounds for layout", regex: /UIScreen\.main\.bounds/, fileFilter: SWIFT },
830
+ // Haptics
831
+ { category: "patterns", subcategory: "haptics", type: "positive", pattern: "UIFeedbackGenerator", regex: /UI(Impact|Notification|Selection)FeedbackGenerator/, fileFilter: SWIFT },
832
+ // Dark mode
833
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "userInterfaceStyle", regex: /traitCollection\.userInterfaceStyle|overrideUserInterfaceStyle/, fileFilter: SWIFT },
834
+ // Deprecated APIs
835
+ { category: "components-status", subcategory: "modals", type: "concern", pattern: "UIAlertView (deprecated)", regex: /\bUIAlertView\b/, fileFilter: SWIFT },
836
+ { category: "components-status", subcategory: "modals", type: "concern", pattern: "UIActionSheet (deprecated)", regex: /\bUIActionSheet\b/, fileFilter: SWIFT },
837
+ { category: "technologies", subcategory: "structure", type: "concern", pattern: "UIWebView (deprecated)", regex: /\bUIWebView\b/, fileFilter: SWIFT },
838
+ { category: "components-search", subcategory: "search", type: "concern", pattern: "UISearchDisplayController (deprecated)", regex: /\bUISearchDisplayController\b/, fileFilter: SWIFT },
839
+ { category: "foundations", subcategory: "structure", type: "concern", pattern: "setStatusBarStyle (deprecated)", regex: /setStatusBarStyle|statusBarStyle\s*=/, fileFilter: SWIFT }
840
+ ];
841
+ var appkitRules = [
842
+ // Structure
843
+ { category: "components-layout", subcategory: "windows", type: "pattern", pattern: "NSWindow", regex: /\bNSWindow\b/, fileFilter: SWIFT },
844
+ { category: "components-layout", subcategory: "windows", type: "pattern", pattern: "NSWindowController", regex: /\bNSWindowController\b/, fileFilter: SWIFT },
845
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "NSSplitViewController", regex: /\bNSSplitViewController\b/, fileFilter: SWIFT },
846
+ { category: "components-layout", subcategory: "sidebars", type: "pattern", pattern: "NSOutlineView", regex: /\bNSOutlineView\b/, fileFilter: SWIFT },
847
+ { category: "components-layout", subcategory: "lists", type: "pattern", pattern: "NSTableView", regex: /\bNSTableView\b/, fileFilter: SWIFT },
848
+ { category: "components-layout", subcategory: "lists", type: "pattern", pattern: "NSCollectionView", regex: /\bNSCollectionView\b/, fileFilter: SWIFT },
849
+ { category: "components-layout", subcategory: "toolbar", type: "pattern", pattern: "NSToolbar", regex: /\bNSToolbar\b/, fileFilter: SWIFT },
850
+ { category: "components-menus", subcategory: "menu-bar", type: "pattern", pattern: "NSMenu", regex: /\bNSMenu\b/, fileFilter: SWIFT },
851
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "NSButton", regex: /\bNSButton\b/, fileFilter: SWIFT },
852
+ { category: "components-controls", subcategory: "controls", type: "pattern", pattern: "NSSegmentedControl", regex: /\bNSSegmentedControl\b/, fileFilter: SWIFT },
853
+ { category: "components-status", subcategory: "modals", type: "pattern", pattern: "NSAlert", regex: /\bNSAlert\b/, fileFilter: SWIFT },
854
+ { category: "components-controls", subcategory: "inputs", type: "pattern", pattern: "NSComboBox", regex: /\bNSComboBox\b/, fileFilter: SWIFT },
855
+ { category: "components-controls", subcategory: "inputs", type: "pattern", pattern: "NSPopUpButton", regex: /\bNSPopUpButton\b/, fileFilter: SWIFT },
856
+ // Materials & vibrancy (macOS)
857
+ { category: "foundations", subcategory: "materials", type: "pattern", pattern: "NSVisualEffectView", regex: /\bNSVisualEffectView\b/, fileFilter: SWIFT },
858
+ { category: "foundations", subcategory: "materials", type: "positive", pattern: "NSVisualEffect material", regex: /\.material\s*=\s*\.(sidebar|menu|popover|headerView|contentBackground|windowBackground|hudWindow|underWindowBackground)/, fileFilter: SWIFT },
859
+ // Color — semantic vs hardcoded
860
+ { category: "foundations", subcategory: "color", type: "positive", pattern: "NSColor semantic", regex: /NSColor\.(labelColor|secondaryLabelColor|controlAccentColor|windowBackgroundColor|textColor|controlColor|separatorColor|linkColor)\b/, fileFilter: SWIFT },
861
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcoded NSColor(red:)", regex: /NSColor\(\s*(calibratedRed|deviceRed|red):/, fileFilter: SWIFT },
862
+ { category: "foundations", subcategory: "color", type: "concern", pattern: "hardcoded NSColor constant", regex: /NSColor\.(white|black|gray|red|blue|green|yellow|orange|purple)\b/, fileFilter: SWIFT },
863
+ // Typography
864
+ { category: "foundations", subcategory: "typography", type: "positive", pattern: "NSFont.preferredFont", regex: /NSFont\.preferredFont\(forTextStyle:/, fileFilter: SWIFT },
865
+ { category: "foundations", subcategory: "typography", type: "concern", pattern: "hardcoded NSFont size", regex: /NSFont\.systemFont\(ofSize:\s*\d/, fileFilter: SWIFT },
866
+ // Accessibility
867
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "setAccessibilityLabel", regex: /setAccessibilityLabel\(|\.accessibilityLabel\s*=/, fileFilter: SWIFT },
868
+ { category: "foundations", subcategory: "accessibility", type: "positive", pattern: "NSAccessibility protocol", regex: /NSAccessibilityElement|isAccessibilityElement\(\)/, fileFilter: SWIFT },
869
+ // Layout
870
+ { category: "components-layout", subcategory: "layout", type: "positive", pattern: "AppKit Auto Layout", regex: /translatesAutoresizingMaskIntoConstraints\s*=\s*false/, fileFilter: SWIFT },
871
+ // Pointer
872
+ { category: "inputs", subcategory: "keyboard", type: "positive", pattern: "NSCursor", regex: /\bNSCursor\b/, fileFilter: SWIFT },
873
+ // Deprecated
874
+ { category: "components-menus", subcategory: "menu-bar", type: "concern", pattern: "NSMenuItem setSubmenu (deprecated)", regex: /setSubmenu:forItem:/, fileFilter: SWIFT }
875
+ ];
876
+ var watchosRules = [
877
+ // WatchKit structure
878
+ { category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "WKInterfaceController", regex: /\bWKInterfaceController\b/, fileFilter: SWIFT },
879
+ { category: "platforms", subcategory: "navigation", type: "pattern", pattern: "WKHostingController", regex: /\bWKHostingController\b/, fileFilter: SWIFT },
880
+ // Digital Crown
881
+ { category: "inputs", subcategory: "digital-crown", type: "positive", pattern: "digitalCrownRotation", regex: /\.digitalCrownRotation\(/, fileFilter: SWIFT },
882
+ { category: "inputs", subcategory: "digital-crown", type: "pattern", pattern: "WKCrownSequencer", regex: /\bWKCrownSequencer\b|crownSequencer/, fileFilter: SWIFT },
883
+ { category: "inputs", subcategory: "digital-crown", type: "positive", pattern: "focusable for crown", regex: /\.focusable\(/, fileFilter: SWIFT },
884
+ // Complications
885
+ { category: "platforms", subcategory: "complications", type: "pattern", pattern: "CLKComplication", regex: /\bCLKComplication/, fileFilter: SWIFT },
886
+ { category: "platforms", subcategory: "complications", type: "pattern", pattern: "WidgetKit complication", regex: /CLKComplicationWidgetMigrator|\.accessoryCircular|\.accessoryCorner/, fileFilter: SWIFT },
887
+ // Always-On / luminance
888
+ { category: "platforms", subcategory: "always-on", type: "positive", pattern: "isLuminanceReduced", regex: /isLuminanceReduced/, fileFilter: SWIFT },
889
+ { category: "platforms", subcategory: "always-on", type: "positive", pattern: "privacySensitive", regex: /\.privacySensitive\(/, fileFilter: SWIFT },
890
+ // Watch faces / workouts
891
+ { category: "platforms", subcategory: "workouts", type: "pattern", pattern: "HKWorkoutSession", regex: /\bHKWorkoutSession\b/, fileFilter: SWIFT },
892
+ { category: "platforms", subcategory: "workouts", type: "positive", pattern: "WKExtendedRuntimeSession", regex: /\bWKExtendedRuntimeSession\b/, fileFilter: SWIFT },
893
+ // Haptics (watch)
894
+ { category: "patterns", subcategory: "haptics", type: "positive", pattern: "WKInterfaceDevice haptic", regex: /WKInterfaceDevice\.current\(\)\.play\(/, fileFilter: SWIFT },
895
+ // Notifications
896
+ { category: "patterns", subcategory: "state", type: "pattern", pattern: "WKUserNotificationInterfaceController", regex: /\bWKUserNotificationInterfaceController\b/, fileFilter: SWIFT }
897
+ ];
898
+ var visionosRules = [
899
+ // Windows, volumes, immersive spaces
900
+ { category: "components-layout", subcategory: "windows", type: "pattern", pattern: "visionOS volumetric window", regex: /\.windowStyle\(\.volumetric\)/, fileFilter: SWIFT },
901
+ { category: "platforms", subcategory: "immersive", type: "pattern", pattern: "ImmersiveSpace", regex: /\bImmersiveSpace\b/, fileFilter: SWIFT },
902
+ { category: "platforms", subcategory: "immersive", type: "positive", pattern: "immersionStyle mixed", regex: /\.immersionStyle\(/, fileFilter: SWIFT },
903
+ { category: "platforms", subcategory: "spatial", type: "pattern", pattern: "RealityView", regex: /\bRealityView\b/, fileFilter: SWIFT },
904
+ // Ornaments
905
+ { category: "components-layout", subcategory: "ornaments", type: "positive", pattern: "ornament", regex: /\.ornament\(/, fileFilter: SWIFT },
906
+ // Glass materials
907
+ { category: "foundations", subcategory: "materials", type: "positive", pattern: "glassBackgroundEffect", regex: /\.glassBackgroundEffect\(/, fileFilter: SWIFT },
908
+ // Hover / gaze interaction
909
+ { category: "inputs", subcategory: "spatial", type: "positive", pattern: "hoverEffect", regex: /\.hoverEffect\(/, fileFilter: SWIFT },
910
+ { category: "inputs", subcategory: "spatial", type: "positive", pattern: "visionOS spatial gesture", regex: /SpatialTapGesture|\.targetedToAnyEntity\(/, fileFilter: SWIFT },
911
+ // Depth / 3D layout
912
+ { category: "components-layout", subcategory: "spatial", type: "pattern", pattern: "Model3D", regex: /\bModel3D\b/, fileFilter: SWIFT },
913
+ { category: "components-layout", subcategory: "spatial", type: "positive", pattern: "depth alignment", regex: /\.offset\(z:|alignment3D/, fileFilter: SWIFT }
914
+ ];
915
+ function slugify(label) {
916
+ return label.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
917
+ }
918
+ var SECTIONS = [
919
+ ["swift", swiftRules],
920
+ ["uikit", uikitRules],
921
+ ["appkit", appkitRules],
922
+ ["watchos", watchosRules],
923
+ ["visionos", visionosRules],
924
+ ["web", webCodeRules],
925
+ ["css", cssRules],
926
+ ["vue", vueRules],
927
+ ["svelte", svelteRules],
928
+ ["angular", angularRules],
929
+ ["compose", kotlinRules],
930
+ ["android-xml", androidXmlRules],
931
+ ["react-native", reactNativeRules],
932
+ ["flutter", flutterRules]
933
+ ];
934
+ var allRules = [];
935
+ var ENGINE_BY_RULE_ID = {
936
+ "swift/image-without-a11y": "swift-structural",
937
+ "swift/on-tap-gesture-without-traits": "swift-structural",
938
+ "web/missing-alt": "ast-tsx",
939
+ "web/image-without-alt": "ast-tsx",
940
+ "web/div-with-on-click-no-role": "ast-tsx",
941
+ "web/span-with-on-click-no-role": "ast-tsx",
942
+ "web/positive-tabindex": "ast-tsx"
943
+ };
944
+ {
945
+ const used = /* @__PURE__ */ new Set();
946
+ for (const [framework, rules] of SECTIONS) {
947
+ for (const rule of rules) {
948
+ const base = `${framework}/${slugify(rule.pattern)}`;
949
+ let id = base;
950
+ for (let n = 2; used.has(id); n++) id = `${base}-${n}`;
951
+ used.add(id);
952
+ allRules.push({ ...rule, id, framework, engine: ENGINE_BY_RULE_ID[id] ?? "regex" });
953
+ }
954
+ }
955
+ }
956
+ var HIG_BASE = "https://developer.apple.com/design/human-interface-guidelines/";
957
+ var SUBCATEGORY_HIG = {
958
+ accessibility: "accessibility",
959
+ accordion: "disclosure-controls",
960
+ alerts: "alerts",
961
+ analytics: "privacy",
962
+ animation: "motion",
963
+ buttons: "buttons",
964
+ cards: "layout",
965
+ color: "color",
966
+ controls: "controls",
967
+ details: "disclosure-controls",
968
+ focus: "focus-and-selection",
969
+ forms: "entering-data",
970
+ gestures: "gestures",
971
+ haptics: "playing-haptics",
972
+ images: "images",
973
+ inputs: "text-fields",
974
+ keyboard: "keyboards",
975
+ layout: "layout",
976
+ lists: "lists-and-tables",
977
+ loading: "loading",
978
+ menus: "menus",
979
+ modals: "modality",
980
+ motion: "motion",
981
+ multiplatform: "",
982
+ navigation: "",
983
+ popover: "popovers",
984
+ progress: "progress-indicators",
985
+ refresh: "loading",
986
+ search: "searching",
987
+ seo: "",
988
+ state: "feedback",
989
+ structure: "layout",
990
+ tables: "lists-and-tables",
991
+ toast: "feedback",
992
+ toggle: "toggles",
993
+ toolbar: "toolbars",
994
+ tooltip: "offering-help",
995
+ typography: "typography",
996
+ widgets: "widgets",
997
+ // Apple-platform subcategories
998
+ windows: "windows",
999
+ sidebars: "sidebars",
1000
+ "split-views": "split-views",
1001
+ "menu-bar": "the-menu-bar",
1002
+ materials: "materials",
1003
+ "sf-symbols": "sf-symbols",
1004
+ "digital-crown": "digital-crown",
1005
+ complications: "complications",
1006
+ "always-on": "always-on",
1007
+ workouts: "workouts",
1008
+ immersive: "immersive-experiences",
1009
+ spatial: "spatial-layout",
1010
+ ornaments: "ornaments"
1011
+ };
1012
+ function higCitation(rule) {
1013
+ if (rule.hig) return rule.hig;
1014
+ const slug = SUBCATEGORY_HIG[rule.subcategory] ?? "";
1015
+ return HIG_BASE + slug;
1016
+ }
1017
+ var FIX_GUIDANCE = {
1018
+ // Critical
1019
+ "missing alt": 'Add descriptive alt text, or alt="" when the image is purely decorative.',
1020
+ "Image without alt": 'Add descriptive alt text, or alt="" when the image is purely decorative.',
1021
+ "svg without a11y": 'Give inline SVG role="img" plus a <title> or aria-label, or aria-hidden="true" if decorative.',
1022
+ "empty heading": "Add text content to the heading or remove it; screen readers announce empty headings as unlabeled.",
1023
+ "empty button": "Give the button visible text or an aria-label.",
1024
+ "missing html lang": 'Add lang="\u2026" to the <html> element so assistive tech picks the right voice.',
1025
+ "video without track": 'Add a <track kind="captions"> file to the video.',
1026
+ "blink element": "Remove <blink>; if emphasis is needed, use CSS animation that honors prefers-reduced-motion.",
1027
+ "marquee element": "Remove <marquee>; use static layout or an accessible animation that honors prefers-reduced-motion.",
1028
+ "user-scalable=no": "Remove user-scalable=no from the viewport meta so pinch-zoom keeps working.",
1029
+ "maximum-scale=1": "Remove maximum-scale=1 from the viewport meta so users can zoom.",
1030
+ "ImageView without contentDescription": 'Add android:contentDescription, or importantForAccessibility="no" if decorative.',
1031
+ // Serious
1032
+ "isAccessibilityElement false on interactive": "Keep interactive elements exposed to accessibility; give them a label instead of hiding them.",
1033
+ "div with onClick no role": 'Use a native <button>, or add role="button", tabIndex={0}, and Enter/Space key handling.',
1034
+ "span with onClick no role": 'Use a native <button>, or add role="button", tabIndex={0}, and Enter/Space key handling.',
1035
+ "ambiguous link text": 'Write link text that names the destination; avoid "click here"/"read more".',
1036
+ "positive tabindex": 'Use tabindex="0" (or -1); positive values override the natural focus order.',
1037
+ "aria-hidden on focusable": "Remove aria-hidden from focusable elements, or take them out of the tab order too.",
1038
+ "onMouseOver without onFocus": "Pair onMouseOver with onFocus so keyboard users get the same affordance.",
1039
+ "onMouseOut without onBlur": "Pair onMouseOut with onBlur so keyboard users get the same affordance.",
1040
+ "div as button": "Replace the div with a native <button>; it brings focus, key handling, and semantics for free.",
1041
+ "div as nav/header class": "Use the semantic <nav>/<header> element instead of a classed div so landmarks exist.",
1042
+ "autoplay media": "Avoid autoplay; if unavoidable, autoplay muted with visible controls.",
1043
+ "outline none": "Keep a visible focus indicator \u2014 style :focus-visible instead of removing the outline.",
1044
+ "v-on:click without keyboard": "Add @keydown.enter/@keydown.space handling, or use a <button>.",
1045
+ "on:click without on:keydown": "Add on:keydown handling, or use a <button>.",
1046
+ "(click) without (keydown)": "Add a (keydown) handler, or use a <button>.",
1047
+ "clickable without Role": "Pass role = Role.Button (or use Modifier.semantics) so TalkBack announces the control.",
1048
+ "nested touchables": "Flatten nested touchables; keep one interactive wrapper per control.",
1049
+ // Common moderates
1050
+ "hardcodedColor": "Use semantic colors (.primary, .secondary, or an asset-catalog color) that adapt to dark mode.",
1051
+ "hardcodedRGBColor": "Move the color into an asset catalog with light/dark variants.",
1052
+ "hardcodedUIColor": "Use a semantic UIColor (label, systemBackground) or an asset-catalog color.",
1053
+ "NavigationView (deprecated)": "Migrate to NavigationStack (single column) or NavigationSplitView (sidebar layouts).",
1054
+ "onTapGesture without traits": "Prefer Button, or add .accessibilityAddTraits(.isButton) so VoiceOver announces it.",
1055
+ // UIKit
1056
+ "hardcoded UIColor constant": "Use a semantic UIColor (.label, .systemBackground, .tintColor) that adapts to appearance.",
1057
+ "hardcoded UIFont(name:)": "Scale custom fonts with UIFontMetrics, or use preferredFont(forTextStyle:).",
1058
+ "viewWithTag lookup": "Reference views by outlet or property; tag-based lookup is fragile and breaks with view reordering.",
1059
+ "UIScreen.main.bounds for layout": "Lay out against the view's bounds or safeAreaLayoutGuide; UIScreen.main ignores Split View and Slide Over.",
1060
+ "UIAlertView (deprecated)": "Use UIAlertController with a .alert style.",
1061
+ "UIActionSheet (deprecated)": "Use UIAlertController with an .actionSheet style.",
1062
+ "UIWebView (deprecated)": "Use WKWebView.",
1063
+ "UISearchDisplayController (deprecated)": "Use UISearchController.",
1064
+ "setStatusBarStyle (deprecated)": "Override preferredStatusBarStyle on the view controller instead.",
1065
+ // AppKit
1066
+ "hardcoded NSColor(red:)": "Use a semantic NSColor (.labelColor, .controlAccentColor) or a Color Set asset with light/dark variants.",
1067
+ "hardcoded NSColor constant": "Use a semantic NSColor (.labelColor, .windowBackgroundColor) that adapts to appearance and accent color.",
1068
+ "hardcoded NSFont size": "Use NSFont.preferredFont(forTextStyle:) so text respects the user's size settings.",
1069
+ "NSMenuItem setSubmenu (deprecated)": "Set the item's submenu property directly."
1070
+ };
1071
+ function fixGuidance(rule) {
1072
+ return rule.fix ?? FIX_GUIDANCE[rule.pattern] ?? null;
1073
+ }
1074
+ function toMeta(rule) {
1075
+ return {
1076
+ id: rule.id,
1077
+ framework: rule.framework,
1078
+ category: rule.category,
1079
+ subcategory: rule.subcategory,
1080
+ type: rule.type,
1081
+ label: rule.pattern,
1082
+ severity: rule.type === "concern" ? severityFor(rule.pattern) : null,
1083
+ engine: rule.engine,
1084
+ hig: higCitation(rule),
1085
+ fix: fixGuidance(rule)
1086
+ };
1087
+ }
1088
+ function ruleCatalog() {
1089
+ return allRules.map(toMeta);
1090
+ }
1091
+ function getRuleById(id) {
1092
+ const rule = allRules.find((r) => r.id === id);
1093
+ return rule ? toMeta(rule) : void 0;
1094
+ }
1095
+ function stripComments(line, state, lineComments) {
1096
+ let out = "";
1097
+ let str = null;
1098
+ const n = line.length;
1099
+ let i = 0;
1100
+ while (i < n) {
1101
+ const c = line[i];
1102
+ const c2 = i + 1 < n ? line[i + 1] : "";
1103
+ if (state.inBlock) {
1104
+ if (c === "*" && c2 === "/") {
1105
+ state.inBlock = false;
1106
+ i += 2;
1107
+ } else {
1108
+ i++;
1109
+ }
1110
+ continue;
1111
+ }
1112
+ if (state.inHtml) {
1113
+ if (c === "-" && c2 === "-" && line[i + 2] === ">") {
1114
+ state.inHtml = false;
1115
+ i += 3;
1116
+ } else {
1117
+ i++;
1118
+ }
1119
+ continue;
1120
+ }
1121
+ if (str !== null) {
1122
+ out += c;
1123
+ if (c === "\\" && i + 1 < n) {
1124
+ out += c2;
1125
+ i += 2;
1126
+ continue;
1127
+ }
1128
+ if (c === str) str = null;
1129
+ i++;
1130
+ continue;
1131
+ }
1132
+ if (c === '"' || c === "'" || c === "`") {
1133
+ str = c;
1134
+ out += c;
1135
+ i++;
1136
+ continue;
1137
+ }
1138
+ if (c === "/" && c2 === "*") {
1139
+ state.inBlock = true;
1140
+ i += 2;
1141
+ continue;
1142
+ }
1143
+ if (lineComments && c === "/" && c2 === "/") break;
1144
+ if (c === "<" && c2 === "!" && line[i + 2] === "-" && line[i + 3] === "-") {
1145
+ state.inHtml = true;
1146
+ i += 4;
1147
+ continue;
1148
+ }
1149
+ out += c;
1150
+ i++;
1151
+ }
1152
+ return out;
1153
+ }
1154
+ function parseSuppression(line) {
1155
+ const m = line.match(/hig-disable-(next-line|file)\b(.*)$/);
1156
+ if (!m) return null;
1157
+ const ids = [];
1158
+ for (const token of (m[2] ?? "").trim().split(/\s+/)) {
1159
+ if (token === "" || token === "--") break;
1160
+ if (!/^[a-z0-9/*-]+$/.test(token) || !token.includes("/")) break;
1161
+ ids.push(token);
1162
+ }
1163
+ return { kind: m[1], ids: ids.length > 0 ? ids : "all" };
1164
+ }
1165
+ function suppressionCovers(ids, ruleId) {
1166
+ if (ids === "all") return true;
1167
+ return ids.some(
1168
+ (id) => id.endsWith("*") ? ruleId.startsWith(id.slice(0, -1)) : ruleId === id
1169
+ );
1170
+ }
1171
+ function detectPatterns(code, file) {
1172
+ const matches = [];
1173
+ const rawLines = code.split("\n");
1174
+ let fileSuppression = null;
1175
+ const lineSuppressions = /* @__PURE__ */ new Map();
1176
+ for (let i = 0; i < rawLines.length; i++) {
1177
+ if (!rawLines[i].includes("hig-disable-")) continue;
1178
+ const sup = parseSuppression(rawLines[i]);
1179
+ if (!sup) continue;
1180
+ if (sup.kind === "file") {
1181
+ fileSuppression = fileSuppression === "all" || sup.ids === "all" ? "all" : [...fileSuppression ?? [], ...sup.ids];
1182
+ } else {
1183
+ const existing = lineSuppressions.get(i + 2);
1184
+ lineSuppressions.set(
1185
+ i + 2,
1186
+ existing === "all" || sup.ids === "all" ? "all" : [...existing ?? [], ...sup.ids]
1187
+ );
1188
+ }
1189
+ }
1190
+ const isSuppressed = (ruleId, line) => {
1191
+ if (fileSuppression && suppressionCovers(fileSuppression, ruleId)) return true;
1192
+ const forLine = lineSuppressions.get(line);
1193
+ return forLine !== void 0 && suppressionCovers(forLine, ruleId);
1194
+ };
1195
+ const isStyleFile = /\.(css|scss|sass|less)$/.test(file);
1196
+ const allowLineComments = !/\.(css|html?|xml|storyboard|xib)$/i.test(file);
1197
+ const commentState = { inBlock: false, inHtml: false };
1198
+ const lines = rawLines.map((l) => stripComments(l, commentState, allowLineComments));
1199
+ const applicable = allRules.filter((r) => !r.fileFilter || r.fileFilter.test(file));
1200
+ const lineRules = applicable.filter((r) => r.scope !== "document");
1201
+ const docRules = applicable.filter((r) => r.scope === "document");
1202
+ const blockContext = [];
1203
+ let braceDepth = 0;
1204
+ const blockStartDepth = [];
1205
+ for (let i = 0; i < lines.length; i++) {
1206
+ const scanLine = lines[i];
1207
+ if (isStyleFile) {
1208
+ const opensBlock = scanLine.includes("{");
1209
+ const closesBlock = scanLine.includes("}");
1210
+ if (opensBlock) {
1211
+ let contextLines = scanLine;
1212
+ for (let j = Math.max(0, i - 3); j < i; j++) {
1213
+ if (!lines[j].includes("}") && !lines[j].includes("{")) {
1214
+ contextLines = `${lines[j]} ${contextLines}`;
1215
+ }
1216
+ }
1217
+ blockContext.push(contextLines);
1218
+ blockStartDepth.push(braceDepth);
1219
+ braceDepth++;
1220
+ }
1221
+ if (closesBlock) {
1222
+ braceDepth = Math.max(0, braceDepth - 1);
1223
+ while (blockStartDepth.length > 0 && blockStartDepth[blockStartDepth.length - 1] >= braceDepth) {
1224
+ blockStartDepth.pop();
1225
+ blockContext.pop();
1226
+ }
1227
+ }
1228
+ }
1229
+ for (const rule of lineRules) {
1230
+ if (rule.regex.test(scanLine)) {
1231
+ const skipInBlock = rule.skipInBlock;
1232
+ if (skipInBlock && isStyleFile) {
1233
+ const inSkippedBlock = blockContext.some((ctx) => skipInBlock.test(ctx));
1234
+ if (inSkippedBlock) continue;
1235
+ }
1236
+ if (isSuppressed(rule.id, i + 1)) continue;
1237
+ matches.push({
1238
+ ruleId: rule.id,
1239
+ engine: "regex",
1240
+ category: rule.category,
1241
+ subcategory: rule.subcategory,
1242
+ type: rule.type,
1243
+ pattern: rule.pattern,
1244
+ line: i + 1,
1245
+ lineContent: rawLines[i].trim(),
1246
+ file,
1247
+ severity: rule.type === "concern" ? severityFor(rule.pattern) : void 0
1248
+ });
1249
+ }
1250
+ }
1251
+ }
1252
+ if (docRules.length > 0) {
1253
+ const stripped = lines.join("\n");
1254
+ const lineStarts = [0];
1255
+ for (let k = 0; k < stripped.length; k++) {
1256
+ if (stripped[k] === "\n") lineStarts.push(k + 1);
1257
+ }
1258
+ const lineNumberAt = (index) => {
1259
+ let lo = 0;
1260
+ let hi = lineStarts.length - 1;
1261
+ while (lo < hi) {
1262
+ const mid = lo + hi + 1 >> 1;
1263
+ if (lineStarts[mid] <= index) lo = mid;
1264
+ else hi = mid - 1;
1265
+ }
1266
+ return lo + 1;
1267
+ };
1268
+ for (const rule of docRules) {
1269
+ if (rule.requireAbsent && rule.requireAbsent.test(stripped)) continue;
1270
+ const flags = rule.regex.flags.includes("g") ? rule.regex.flags : rule.regex.flags + "g";
1271
+ const re = new RegExp(rule.regex.source, flags);
1272
+ let m;
1273
+ while ((m = re.exec(stripped)) !== null) {
1274
+ const lineNo = lineNumberAt(m.index);
1275
+ if (isSuppressed(rule.id, lineNo)) {
1276
+ if (rule.requireAbsent) break;
1277
+ if (m.index === re.lastIndex) re.lastIndex++;
1278
+ continue;
1279
+ }
1280
+ matches.push({
1281
+ ruleId: rule.id,
1282
+ engine: "regex",
1283
+ category: rule.category,
1284
+ subcategory: rule.subcategory,
1285
+ type: rule.type,
1286
+ pattern: rule.pattern,
1287
+ line: lineNo,
1288
+ lineContent: (rawLines[lineNo - 1] ?? "").trim(),
1289
+ file,
1290
+ severity: rule.type === "concern" ? severityFor(rule.pattern) : void 0
1291
+ });
1292
+ if (rule.requireAbsent) break;
1293
+ if (m.index === re.lastIndex) re.lastIndex++;
1294
+ }
1295
+ }
1296
+ matches.sort((a, b) => a.line - b.line);
1297
+ }
1298
+ return matches;
1299
+ }
1300
+ var RULE_COUNT = allRules.length;
1301
+
1302
+ // src/engines/swift-structural.ts
1303
+ var A11Y_MODIFIERS = [
1304
+ "accessibilityLabel",
1305
+ "accessibilityHidden",
1306
+ "accessibilityHint",
1307
+ "accessibilityValue",
1308
+ "accessibilityElement",
1309
+ "accessibilityRepresentation",
1310
+ "accessibilityAddTraits",
1311
+ "accessibilityLabeledPair"
1312
+ ];
1313
+ function stripSwift(code) {
1314
+ let out = "";
1315
+ let i = 0;
1316
+ const n = code.length;
1317
+ let inBlock = false;
1318
+ let inString = false;
1319
+ while (i < n) {
1320
+ const c = code[i];
1321
+ const c2 = i + 1 < n ? code[i + 1] : "";
1322
+ if (inBlock) {
1323
+ if (c === "*" && c2 === "/") {
1324
+ inBlock = false;
1325
+ i += 2;
1326
+ } else {
1327
+ i++;
1328
+ }
1329
+ continue;
1330
+ }
1331
+ if (inString) {
1332
+ if (c === "\\") {
1333
+ i += 2;
1334
+ continue;
1335
+ }
1336
+ if (c === '"') {
1337
+ inString = false;
1338
+ out += '"';
1339
+ i++;
1340
+ continue;
1341
+ }
1342
+ i++;
1343
+ continue;
1344
+ }
1345
+ if (c === "/" && c2 === "*") {
1346
+ inBlock = true;
1347
+ i += 2;
1348
+ continue;
1349
+ }
1350
+ if (c === "/" && c2 === "/") {
1351
+ while (i < n && code[i] !== "\n") i++;
1352
+ continue;
1353
+ }
1354
+ if (c === '"') {
1355
+ inString = true;
1356
+ out += '"';
1357
+ i++;
1358
+ continue;
1359
+ }
1360
+ out += c;
1361
+ i++;
1362
+ }
1363
+ return out;
1364
+ }
1365
+ function chainedModifiers(stripped, from) {
1366
+ const mods = [];
1367
+ let i = from;
1368
+ const n = stripped.length;
1369
+ const skipWs = () => {
1370
+ while (i < n && /\s/.test(stripped[i])) i++;
1371
+ };
1372
+ const skipGroup = (open, close) => {
1373
+ let depth = 0;
1374
+ for (; i < n; i++) {
1375
+ const ch = stripped[i];
1376
+ if (ch === open) depth++;
1377
+ else if (ch === close) {
1378
+ depth--;
1379
+ if (depth === 0) {
1380
+ i++;
1381
+ return;
1382
+ }
1383
+ }
1384
+ }
1385
+ };
1386
+ skipWs();
1387
+ if (stripped[i] === "(") skipGroup("(", ")");
1388
+ while (true) {
1389
+ skipWs();
1390
+ if (stripped[i] !== ".") break;
1391
+ i++;
1392
+ skipWs();
1393
+ let id = "";
1394
+ while (i < n && /[A-Za-z0-9_]/.test(stripped[i])) {
1395
+ id += stripped[i];
1396
+ i++;
1397
+ }
1398
+ if (id === "") break;
1399
+ mods.push(id);
1400
+ skipWs();
1401
+ if (stripped[i] === "(") skipGroup("(", ")");
1402
+ skipWs();
1403
+ if (stripped[i] === "{") skipGroup("{", "}");
1404
+ }
1405
+ return mods;
1406
+ }
1407
+ function lineAt(stripped, index) {
1408
+ let line = 1;
1409
+ for (let i = 0; i < index && i < stripped.length; i++) {
1410
+ if (stripped[i] === "\n") line++;
1411
+ }
1412
+ return line;
1413
+ }
1414
+ function refineSwift(matches, code) {
1415
+ const swiftRefined = /* @__PURE__ */ new Set(["Image without a11y", "onTapGesture without traits"]);
1416
+ if (!matches.some((m) => swiftRefined.has(m.pattern))) return matches;
1417
+ const stripped = stripSwift(code);
1418
+ const handledImageLines = /* @__PURE__ */ new Set();
1419
+ const handledTapLines = /* @__PURE__ */ new Set();
1420
+ for (const m of stripped.matchAll(/\bImage\s*\(\s*systemName:/g)) {
1421
+ const idx = m.index ?? 0;
1422
+ const parenIdx = stripped.indexOf("(", idx);
1423
+ const mods = chainedModifiers(stripped, parenIdx);
1424
+ if (mods.some((mod) => A11Y_MODIFIERS.includes(mod))) {
1425
+ handledImageLines.add(lineAt(stripped, idx));
1426
+ }
1427
+ }
1428
+ for (const m of stripped.matchAll(/\.onTapGesture\s*\{/g)) {
1429
+ const idx = m.index ?? 0;
1430
+ const braceIdx = stripped.indexOf("{", idx);
1431
+ let j = braceIdx;
1432
+ let depth = 0;
1433
+ for (; j < stripped.length; j++) {
1434
+ if (stripped[j] === "{") depth++;
1435
+ else if (stripped[j] === "}") {
1436
+ depth--;
1437
+ if (depth === 0) {
1438
+ j++;
1439
+ break;
1440
+ }
1441
+ }
1442
+ }
1443
+ const after = chainedModifiers(stripped, j);
1444
+ if (after.some((mod) => A11Y_MODIFIERS.includes(mod))) {
1445
+ handledTapLines.add(lineAt(stripped, idx));
1446
+ }
1447
+ }
1448
+ const out = [];
1449
+ for (const match of matches) {
1450
+ if (match.pattern === "Image without a11y") {
1451
+ if (handledImageLines.has(match.line)) continue;
1452
+ out.push({ ...match, engine: "swift-structural" });
1453
+ } else if (match.pattern === "onTapGesture without traits") {
1454
+ if (handledTapLines.has(match.line)) continue;
1455
+ out.push({ ...match, engine: "swift-structural" });
1456
+ } else {
1457
+ out.push(match);
1458
+ }
1459
+ }
1460
+ return out;
1461
+ }
1462
+
1463
+ // src/engines/ast-tsx.ts
1464
+ import { createRequire } from "node:module";
1465
+ var AST_TSX_RULES = /* @__PURE__ */ new Set([
1466
+ "web/missing-alt",
1467
+ "web/image-without-alt",
1468
+ "web/div-with-on-click-no-role",
1469
+ "web/span-with-on-click-no-role",
1470
+ "web/positive-tabindex"
1471
+ ]);
1472
+ var tsModule;
1473
+ function loadTs() {
1474
+ if (tsModule !== void 0) return tsModule;
1475
+ try {
1476
+ tsModule = createRequire(import.meta.url)("typescript");
1477
+ } catch {
1478
+ tsModule = null;
1479
+ }
1480
+ return tsModule;
1481
+ }
1482
+ function astTsxAvailable() {
1483
+ return loadTs() != null;
1484
+ }
1485
+ function isTsxFile(file) {
1486
+ return /\.(tsx|jsx)$/.test(file);
1487
+ }
1488
+ function push(findings, ruleId, ts, node, source) {
1489
+ const { line } = source.getLineAndCharacterOfPosition(node.getStart(source));
1490
+ const text = source.text.split("\n")[line] ?? "";
1491
+ findings.push({ ruleId, line: line + 1, lineContent: text.trim() });
1492
+ }
1493
+ function analyzeTsx(code, file) {
1494
+ if (!isTsxFile(file)) return null;
1495
+ const ts = loadTs();
1496
+ if (!ts) return null;
1497
+ const source = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
1498
+ const findings = [];
1499
+ const attrs = (opening) => {
1500
+ const names = /* @__PURE__ */ new Set();
1501
+ const byName = /* @__PURE__ */ new Map();
1502
+ let hasSpread = false;
1503
+ for (const prop of opening.attributes.properties) {
1504
+ if (ts.isJsxSpreadAttribute(prop)) {
1505
+ hasSpread = true;
1506
+ continue;
1507
+ }
1508
+ if (ts.isJsxAttribute(prop) && prop.name) {
1509
+ const name = prop.name.getText(source);
1510
+ names.add(name);
1511
+ byName.set(name, prop);
1512
+ }
1513
+ }
1514
+ return { names, hasSpread, byName };
1515
+ };
1516
+ const tagNameOf = (opening) => opening.tagName.getText(source);
1517
+ const attrIsTruthy = (attr) => {
1518
+ if (!attr.initializer) return true;
1519
+ if (ts.isStringLiteral(attr.initializer)) return attr.initializer.text === "true";
1520
+ if (ts.isJsxExpression(attr.initializer) && attr.initializer.expression) {
1521
+ return attr.initializer.expression.kind === ts.SyntaxKind.TrueKeyword;
1522
+ }
1523
+ return false;
1524
+ };
1525
+ const positiveTabIndex = (attr) => {
1526
+ if (!attr.initializer) return false;
1527
+ let raw = null;
1528
+ if (ts.isStringLiteral(attr.initializer)) raw = attr.initializer.text;
1529
+ else if (ts.isJsxExpression(attr.initializer) && attr.initializer.expression) {
1530
+ const e = attr.initializer.expression;
1531
+ if (ts.isNumericLiteral(e)) raw = e.text;
1532
+ else if (ts.isPrefixUnaryExpression?.(e) && e.operator === ts.SyntaxKind.MinusToken) raw = "-1";
1533
+ }
1534
+ if (raw == null) return false;
1535
+ const n = Number(raw);
1536
+ return Number.isFinite(n) && n > 0;
1537
+ };
1538
+ const visitOpening = (opening) => {
1539
+ const tag = tagNameOf(opening);
1540
+ const { names, hasSpread, byName } = attrs(opening);
1541
+ if ((tag === "img" || tag === "Image") && !hasSpread && !names.has("alt")) {
1542
+ push(findings, "web/missing-alt", ts, opening.parent ?? opening, source);
1543
+ }
1544
+ if ((tag === "div" || tag === "span") && names.has("onClick") && !hasSpread) {
1545
+ const interactive = names.has("role") || names.has("tabIndex") || names.has("onKeyDown") || names.has("onKeyPress") || names.has("onKeyUp");
1546
+ if (!interactive) {
1547
+ const ruleId = tag === "div" ? "web/div-with-on-click-no-role" : "web/span-with-on-click-no-role";
1548
+ push(findings, ruleId, ts, opening.parent ?? opening, source);
1549
+ }
1550
+ }
1551
+ const tabIndexAttr = byName.get("tabIndex");
1552
+ if (tabIndexAttr && positiveTabIndex(tabIndexAttr)) {
1553
+ push(findings, "web/positive-tabindex", ts, opening.parent ?? opening, source);
1554
+ }
1555
+ void attrIsTruthy;
1556
+ };
1557
+ const walk = (node) => {
1558
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
1559
+ visitOpening(node);
1560
+ }
1561
+ ts.forEachChild(node, walk);
1562
+ };
1563
+ walk(source);
1564
+ return findings.map((f) => {
1565
+ const meta = getRuleById(f.ruleId);
1566
+ return {
1567
+ ruleId: f.ruleId,
1568
+ engine: "ast-tsx",
1569
+ category: meta?.category ?? "foundations",
1570
+ subcategory: meta?.subcategory ?? "accessibility",
1571
+ type: "concern",
1572
+ pattern: meta?.label ?? f.ruleId,
1573
+ line: f.line,
1574
+ lineContent: f.lineContent,
1575
+ file,
1576
+ severity: meta?.severity ?? "moderate"
1577
+ };
1578
+ });
1579
+ }
1580
+
1581
+ // src/analyze.ts
1582
+ function analyzeFile(code, file) {
1583
+ let matches = detectPatterns(code, file);
1584
+ if (/\.swift$/.test(file)) {
1585
+ matches = refineSwift(matches, code);
1586
+ }
1587
+ const ast = analyzeTsx(code, file);
1588
+ if (ast !== null) {
1589
+ matches = matches.filter((m) => !AST_TSX_RULES.has(m.ruleId));
1590
+ matches.push(...ast);
1591
+ matches.sort((a, b) => a.line - b.line);
1592
+ }
1593
+ return matches;
1594
+ }
1595
+
1596
+ // src/categorizer.ts
1597
+ var CATEGORY_TO_SKILL = {
1598
+ "foundations": "hig-foundations",
1599
+ "components-layout": "hig-components-layout",
1600
+ "components-selection": "hig-components-selection",
1601
+ "components-actions": "hig-components-actions",
1602
+ "components-presentation": "hig-components-presentation",
1603
+ "components-textinput": "hig-components-textinput",
1604
+ "components-media": "hig-components-media",
1605
+ "components-controls": "hig-components-controls",
1606
+ "components-menus": "hig-components-menus",
1607
+ "components-dialogs": "hig-components-dialogs",
1608
+ "components-search": "hig-components-search",
1609
+ "components-status": "hig-components-status",
1610
+ "components-content": "hig-components-content",
1611
+ "components-system": "hig-components-system",
1612
+ "patterns": "hig-patterns",
1613
+ "platforms": "hig-platforms",
1614
+ "technologies": "hig-technologies",
1615
+ "inputs": "hig-inputs"
1616
+ };
1617
+ var CATEGORY_LABELS = {
1618
+ "hig-foundations": "Foundations",
1619
+ "hig-components-layout": "Layout & Navigation",
1620
+ "hig-components-selection": "Selection Controls",
1621
+ "hig-components-actions": "Actions",
1622
+ "hig-components-presentation": "Presentation",
1623
+ "hig-components-textinput": "Text Input",
1624
+ "hig-components-media": "Media",
1625
+ "hig-components-controls": "Controls",
1626
+ "hig-components-menus": "Menus & Actions",
1627
+ "hig-components-dialogs": "Dialogs & Presentations",
1628
+ "hig-components-search": "Search & Navigation",
1629
+ "hig-components-status": "Status & Progress",
1630
+ "hig-components-content": "Content Display",
1631
+ "hig-components-system": "System Integration",
1632
+ "hig-patterns": "Interaction Patterns",
1633
+ "hig-inputs": "Input Methods",
1634
+ "hig-technologies": "Apple Technologies",
1635
+ "hig-platforms": "Platform Adaptation"
1636
+ };
1637
+ function categorizeMatches(matches) {
1638
+ if (matches.length === 0) return [];
1639
+ const grouped = /* @__PURE__ */ new Map();
1640
+ for (const match of matches) {
1641
+ const skillName = CATEGORY_TO_SKILL[match.category] || `hig-${match.category}`;
1642
+ if (!grouped.has(skillName)) {
1643
+ grouped.set(skillName, []);
1644
+ }
1645
+ grouped.get(skillName).push(match);
1646
+ }
1647
+ const categories = [];
1648
+ for (const [skillName, skillMatches] of grouped) {
1649
+ const files = [...new Set(skillMatches.map((m) => m.file))];
1650
+ const concerns = skillMatches.filter((m) => m.type === "concern");
1651
+ categories.push({
1652
+ skillName,
1653
+ category: skillMatches[0].category,
1654
+ label: CATEGORY_LABELS[skillName] ?? skillName,
1655
+ matches: skillMatches,
1656
+ concerns: concerns.length,
1657
+ positives: skillMatches.filter((m) => m.type === "positive").length,
1658
+ patterns: skillMatches.filter((m) => m.type === "pattern").length,
1659
+ critical: concerns.filter((m) => m.severity === "critical").length,
1660
+ serious: concerns.filter((m) => m.severity === "serious").length,
1661
+ moderate: concerns.filter((m) => m.severity === "moderate").length,
1662
+ fileCount: files.length,
1663
+ files
1664
+ });
1665
+ }
1666
+ categories.sort((a, b) => b.matches.length - a.matches.length);
1667
+ return categories;
1668
+ }
1669
+
1670
+ // src/audit-generator.ts
1671
+ import { readFile as readFile2 } from "node:fs/promises";
1672
+ import { join as join2 } from "node:path";
1673
+ function formatDate() {
1674
+ return (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1675
+ }
1676
+ function langForFile(file) {
1677
+ if (file.endsWith(".swift")) return "swift";
1678
+ if (file.endsWith(".tsx") || file.endsWith(".jsx")) return "tsx";
1679
+ if (file.endsWith(".ts") || file.endsWith(".js")) return "typescript";
1680
+ if (file.endsWith(".css") || file.endsWith(".scss")) return "css";
1681
+ if (file.endsWith(".html") || file.endsWith(".htm")) return "html";
1682
+ if (file.endsWith(".dart")) return "dart";
1683
+ if (file.endsWith(".kt")) return "kotlin";
1684
+ return "";
1685
+ }
1686
+ function commentPrefix(file) {
1687
+ if (file.endsWith(".css") || file.endsWith(".scss")) return "/* ";
1688
+ return "// ";
1689
+ }
1690
+ function commentSuffix(file) {
1691
+ if (file.endsWith(".css") || file.endsWith(".scss")) return " */";
1692
+ return "";
1693
+ }
1694
+ function escapeMarkdownText(value) {
1695
+ return value.replace(/[\r\n\t]+/g, " ").replace(/\\/g, "\\\\").replace(/([`*_{}\[\]()#+.!|-])/g, "\\$1");
1696
+ }
1697
+ function longestRun(value, char) {
1698
+ let longest = 0;
1699
+ let current = 0;
1700
+ for (const c of value) {
1701
+ if (c === char) {
1702
+ current++;
1703
+ longest = Math.max(longest, current);
1704
+ } else {
1705
+ current = 0;
1706
+ }
1707
+ }
1708
+ return longest;
1709
+ }
1710
+ function fenceFor(matches) {
1711
+ const longestTildeRun = matches.reduce(
1712
+ (max, match) => Math.max(max, longestRun(match.lineContent, "~")),
1713
+ 0
1714
+ );
1715
+ return "~".repeat(Math.max(3, longestTildeRun + 1));
1716
+ }
1717
+ function sanitizeExcerptLine(value) {
1718
+ return value.replace(/[\r\n\t]+/g, " ");
1719
+ }
1720
+ function renderExcerpts(category) {
1721
+ const lines = [];
1722
+ const byFile = /* @__PURE__ */ new Map();
1723
+ for (const m of category.matches) {
1724
+ if (!byFile.has(m.file)) byFile.set(m.file, []);
1725
+ byFile.get(m.file).push(m);
1726
+ }
1727
+ for (const [file, matches] of byFile) {
1728
+ const lang = langForFile(file);
1729
+ const cp = commentPrefix(file);
1730
+ const cs = commentSuffix(file);
1731
+ const fence = fenceFor(matches);
1732
+ lines.push(`**${escapeMarkdownText(file)}**`);
1733
+ lines.push(`${fence}${lang}`);
1734
+ for (const m of matches.slice(0, 15)) {
1735
+ const tag = m.type === "concern" ? ` ${cp}\u26A0 concern${cs}` : m.type === "positive" ? ` ${cp}\u2713 good${cs}` : "";
1736
+ lines.push(`L${m.line}: ${sanitizeExcerptLine(m.lineContent)}${tag}`);
1737
+ }
1738
+ if (matches.length > 15) {
1739
+ lines.push(`${cp}... and ${matches.length - 15} more matches${cs}`);
1740
+ }
1741
+ lines.push(fence);
1742
+ lines.push("");
1743
+ }
1744
+ return lines.join("\n");
1745
+ }
1746
+ async function loadSkillContent(skillsDir, skillName) {
1747
+ try {
1748
+ const skillPath = join2(skillsDir, skillName, "SKILL.md");
1749
+ const content = await readFile2(skillPath, "utf-8");
1750
+ const stripped = content.replace(/^---\s*\r?\n[\s\S]*?\r?\n---\s*(?:\r?\n|$)/, "");
1751
+ const principlesMatch = stripped.match(/## Key Principles\n([\s\S]*?)(?=\n## |$)/);
1752
+ return principlesMatch ? principlesMatch[1].trim() : stripped.slice(0, 2e3);
1753
+ } catch {
1754
+ return null;
1755
+ }
1756
+ }
1757
+ function generateAuditMarkdown(scanResult, categories, skillsDir, skillContents) {
1758
+ const lines = [];
1759
+ const appName = scanResult.directory.split("/").pop() || "App";
1760
+ lines.push(`# HIG Audit: ${appName}`);
1761
+ lines.push("");
1762
+ lines.push(`**Generated**: ${formatDate()}`);
1763
+ lines.push(`**Project**: ${scanResult.directory}`);
1764
+ lines.push(`**Frameworks detected**: ${scanResult.frameworks.join(", ")}`);
1765
+ const fileCounts = [
1766
+ `${scanResult.codeFiles.length} code`,
1767
+ `${scanResult.styleFiles.length} style`,
1768
+ `${scanResult.configFiles.length} config`
1769
+ ].join(", ");
1770
+ lines.push(`**Files scanned**: ${fileCounts}`);
1771
+ lines.push("");
1772
+ const totalConcerns = categories.reduce((s, c) => s + c.concerns, 0);
1773
+ const totalPositives = categories.reduce((s, c) => s + c.positives, 0);
1774
+ const totalPatterns = categories.reduce((s, c) => s + c.patterns, 0);
1775
+ lines.push(`**Quick stats**: ${totalConcerns} potential concerns, ${totalPositives} positive patterns, ${totalPatterns} component usages detected across ${categories.length} HIG categories`);
1776
+ lines.push("");
1777
+ lines.push("## Instructions for AI Evaluator");
1778
+ lines.push("");
1779
+ lines.push("You are reviewing a project for Apple Human Interface Guidelines compliance.");
1780
+ lines.push("The HIG principles (accessibility, color systems, typography, responsive layout, motion) apply to all surfaces \u2014 native, web, and cross-platform.");
1781
+ lines.push("For each category below, evaluate the code excerpts against the HIG reference material.");
1782
+ lines.push("");
1783
+ lines.push("**Scoring**: Rate each category 1-10:");
1784
+ lines.push("- **9-10**: Excellent HIG compliance, follows best practices");
1785
+ lines.push("- **7-8**: Good compliance with minor improvements possible");
1786
+ lines.push("- **5-6**: Partial compliance, several areas need attention");
1787
+ lines.push("- **3-4**: Significant HIG violations");
1788
+ lines.push("- **1-2**: Major violations or missing fundamental practices");
1789
+ lines.push("");
1790
+ lines.push("**Output**: For each category, provide:");
1791
+ lines.push("1. Score (1-10)");
1792
+ lines.push("2. What's done well (cite specific code)");
1793
+ lines.push("3. What needs improvement (cite specific file:line)");
1794
+ lines.push("4. Specific fix recommendations");
1795
+ lines.push("");
1796
+ for (const category of categories) {
1797
+ lines.push(`## Category: ${category.label}`);
1798
+ lines.push("");
1799
+ lines.push(`*${category.matches.length} detections across ${category.fileCount} file(s) \u2014 ${category.concerns} concern(s), ${category.positives} positive(s)*`);
1800
+ lines.push("");
1801
+ lines.push("### Code Excerpts");
1802
+ lines.push("");
1803
+ if (category.matches.length > 0) {
1804
+ lines.push(renderExcerpts(category));
1805
+ } else {
1806
+ lines.push("*No patterns detected for this category.*");
1807
+ lines.push("");
1808
+ }
1809
+ lines.push("### HIG Reference");
1810
+ lines.push("");
1811
+ const content = skillContents?.get(category.skillName);
1812
+ if (content) {
1813
+ lines.push(content);
1814
+ } else {
1815
+ lines.push(`*Load reference from skill: ${category.skillName}*`);
1816
+ }
1817
+ lines.push("");
1818
+ lines.push("### Evaluate");
1819
+ lines.push("");
1820
+ const checks = getEvaluationChecklist(category.skillName);
1821
+ for (const check of checks) {
1822
+ lines.push(`- ${check}`);
1823
+ }
1824
+ lines.push("");
1825
+ }
1826
+ lines.push("## Scoring Summary");
1827
+ lines.push("");
1828
+ lines.push("| Category | Score (1-10) | Key Findings |");
1829
+ lines.push("|----------|-------------|-------------|");
1830
+ for (const category of categories) {
1831
+ lines.push(`| ${category.label} | | |`);
1832
+ }
1833
+ lines.push("| **Overall** | **/10** | |");
1834
+ lines.push("");
1835
+ return lines.join("\n");
1836
+ }
1837
+ function getEvaluationChecklist(skillName) {
1838
+ const checklists = {
1839
+ "hig-foundations": [
1840
+ "Color usage: system semantic colors vs hardcoded values",
1841
+ "Typography: Dynamic Type text styles vs fixed font sizes",
1842
+ "Accessibility: labels, hints, traits on interactive elements",
1843
+ "Dark mode: proper color adaptation, no hardcoded light/dark values",
1844
+ "Motion: Reduce Motion support for animations"
1845
+ ],
1846
+ "hig-components-layout": [
1847
+ "Navigation pattern matches app structure (tabs for flat, sidebar for deep)",
1848
+ "Adaptive layout: responds to size classes, multitasking",
1849
+ "Standard navigation components (NavigationSplitView, not deprecated NavigationView)",
1850
+ "Consistent back navigation and spatial hierarchy"
1851
+ ],
1852
+ "hig-components-controls": [
1853
+ "Standard control usage (Button, Toggle, Picker, etc.)",
1854
+ "Proper button styles and roles",
1855
+ "Clear action labels and consistent interaction patterns"
1856
+ ],
1857
+ "hig-components-selection": [
1858
+ "Appropriate picker and selection controls",
1859
+ "Clear selection state feedback"
1860
+ ],
1861
+ "hig-components-actions": [
1862
+ "Button hierarchy and prominence",
1863
+ "Destructive actions clearly marked",
1864
+ "Swipe actions follow HIG conventions"
1865
+ ],
1866
+ "hig-components-presentation": [
1867
+ "Sheets for focused tasks, popovers for contextual info",
1868
+ "Alerts used sparingly for important decisions",
1869
+ "Confirmation dialogs for destructive actions"
1870
+ ],
1871
+ "hig-components-textinput": [
1872
+ "Text fields use appropriate keyboard types",
1873
+ "Search functionality uses .searchable where appropriate"
1874
+ ],
1875
+ "hig-components-media": [
1876
+ "Image handling with proper async loading",
1877
+ "Media playback uses system controls"
1878
+ ],
1879
+ "hig-components-menus": [
1880
+ "Context menus provide relevant actions",
1881
+ "Menu organization follows HIG grouping conventions"
1882
+ ],
1883
+ "hig-components-dialogs": [
1884
+ "Alerts used sparingly for important decisions",
1885
+ "Sheets for focused tasks, popovers for contextual info",
1886
+ "Confirmation dialogs for destructive actions"
1887
+ ],
1888
+ "hig-components-search": [
1889
+ "Searchable modifier used for filterable content",
1890
+ "Search suggestions and scopes where appropriate"
1891
+ ],
1892
+ "hig-components-status": [
1893
+ "Progress indicators for long operations",
1894
+ "Appropriate use of determinate vs indeterminate progress"
1895
+ ],
1896
+ "hig-components-content": [
1897
+ "Content display uses appropriate containers",
1898
+ "Image handling with proper async loading"
1899
+ ],
1900
+ "hig-components-system": [
1901
+ "System integration uses standard APIs (ShareLink, PhotosPicker)",
1902
+ "Deep link handling, widget support where relevant"
1903
+ ],
1904
+ "hig-patterns": [
1905
+ "Drag and drop support where appropriate",
1906
+ "Pull-to-refresh for refreshable content",
1907
+ "Swipe actions follow HIG conventions",
1908
+ "Undo support for destructive actions"
1909
+ ],
1910
+ "hig-inputs": [
1911
+ "Text input uses appropriate field types",
1912
+ "Keyboard shortcuts for power users (macOS/iPad)",
1913
+ "Gesture usage follows platform conventions"
1914
+ ],
1915
+ "hig-technologies": [
1916
+ "Apple framework integration follows HIG for that technology",
1917
+ "Proper permission handling and progressive disclosure"
1918
+ ],
1919
+ "hig-platforms": [
1920
+ "UI adapts appropriately across target platforms",
1921
+ "Platform idioms respected (iPhone vs iPad vs Mac)"
1922
+ ]
1923
+ };
1924
+ return checklists[skillName] ?? ["Evaluate against Apple HIG best practices for this category"];
1925
+ }
1926
+
1927
+ // src/config.ts
1928
+ import { readFile as readFile3 } from "node:fs/promises";
1929
+ import { isAbsolute, join as join3, resolve } from "node:path";
1930
+ var CONFIG_FILENAME = "hig-doctor.config.json";
1931
+ var VALID_SETTINGS = /* @__PURE__ */ new Set(["off", "on", "critical", "serious", "moderate"]);
1932
+ function validateRules(rules, where, warnings) {
1933
+ if (rules == null) return {};
1934
+ if (typeof rules !== "object" || Array.isArray(rules)) {
1935
+ throw new Error(`${where}: "rules" must be an object mapping rule IDs to settings`);
1936
+ }
1937
+ const out = {};
1938
+ for (const [id, setting] of Object.entries(rules)) {
1939
+ if (typeof setting !== "string" || !VALID_SETTINGS.has(setting)) {
1940
+ throw new Error(
1941
+ `${where}: invalid setting ${JSON.stringify(setting)} for rule "${id}" \u2014 expected "off", "on", "critical", "serious", or "moderate"`
1942
+ );
1943
+ }
1944
+ if (!id.includes("*") && !getRuleById(id)) {
1945
+ warnings.push(`${where}: unknown rule ID "${id}" (see docs/rules.md)`);
1946
+ }
1947
+ out[id] = setting;
1948
+ }
1949
+ return out;
1950
+ }
1951
+ function parseConfig(raw, sourcePath) {
1952
+ let json;
1953
+ try {
1954
+ json = JSON.parse(raw);
1955
+ } catch (err) {
1956
+ throw new Error(`${sourcePath} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
1957
+ }
1958
+ if (json == null || typeof json !== "object" || Array.isArray(json)) {
1959
+ throw new Error(`${sourcePath}: config must be a JSON object`);
1960
+ }
1961
+ const obj = json;
1962
+ const warnings = [];
1963
+ const config = {};
1964
+ config.rules = validateRules(obj.rules, sourcePath, warnings);
1965
+ if (obj.ignore != null) {
1966
+ if (!Array.isArray(obj.ignore) || obj.ignore.some((g) => typeof g !== "string")) {
1967
+ throw new Error(`${sourcePath}: "ignore" must be an array of glob strings`);
1968
+ }
1969
+ config.ignore = obj.ignore;
1970
+ }
1971
+ if (obj.overrides != null) {
1972
+ if (!Array.isArray(obj.overrides)) {
1973
+ throw new Error(`${sourcePath}: "overrides" must be an array`);
1974
+ }
1975
+ config.overrides = obj.overrides.map((entry, i) => {
1976
+ const where = `${sourcePath} overrides[${i}]`;
1977
+ if (entry == null || typeof entry !== "object" || Array.isArray(entry)) {
1978
+ throw new Error(`${where}: must be an object with "files" and "rules"`);
1979
+ }
1980
+ const o = entry;
1981
+ if (!Array.isArray(o.files) || o.files.length === 0 || o.files.some((g) => typeof g !== "string")) {
1982
+ throw new Error(`${where}: "files" must be a non-empty array of glob strings`);
1983
+ }
1984
+ return { files: o.files, rules: validateRules(o.rules, where, warnings) };
1985
+ });
1986
+ }
1987
+ return { config, warnings };
1988
+ }
1989
+ async function loadConfig(directory, explicitPath) {
1990
+ const path = explicitPath ? isAbsolute(explicitPath) ? explicitPath : resolve(explicitPath) : join3(resolve(directory), CONFIG_FILENAME);
1991
+ let raw;
1992
+ try {
1993
+ raw = await readFile3(path, "utf-8");
1994
+ } catch {
1995
+ if (explicitPath) throw new Error(`Config file not found: ${path}`);
1996
+ return { path: null, config: {}, warnings: [] };
1997
+ }
1998
+ const { config, warnings } = parseConfig(raw, path);
1999
+ return { path, config, warnings };
2000
+ }
2001
+ function settingFor(ruleId, rules) {
2002
+ if (!rules) return null;
2003
+ if (ruleId in rules) return rules[ruleId];
2004
+ let best = null;
2005
+ for (const [key, setting] of Object.entries(rules)) {
2006
+ if (!key.endsWith("*")) continue;
2007
+ const prefix = key.slice(0, -1);
2008
+ if (ruleId.startsWith(prefix) && (!best || prefix.length > best.len)) {
2009
+ best = { len: prefix.length, setting };
2010
+ }
2011
+ }
2012
+ return best?.setting ?? null;
2013
+ }
2014
+ function applyConfig(matches, config) {
2015
+ const hasRules = config.rules && Object.keys(config.rules).length > 0;
2016
+ const overrides = (config.overrides ?? []).map((o) => ({
2017
+ files: o.files.map(globToRegExp),
2018
+ rules: o.rules
2019
+ }));
2020
+ if (!hasRules && overrides.length === 0) return matches;
2021
+ const out = [];
2022
+ for (const match of matches) {
2023
+ let setting = settingFor(match.ruleId, config.rules);
2024
+ for (const override of overrides) {
2025
+ if (override.files.some((re) => re.test(match.file))) {
2026
+ const s = settingFor(match.ruleId, override.rules);
2027
+ if (s !== null) setting = s;
2028
+ }
2029
+ }
2030
+ if (setting === "off") continue;
2031
+ if (setting && setting !== "on" && match.type === "concern") {
2032
+ out.push({ ...match, severity: setting });
2033
+ } else {
2034
+ out.push(match);
2035
+ }
2036
+ }
2037
+ return out;
2038
+ }
2039
+
2040
+ // src/baseline.ts
2041
+ import { readFile as readFile4, writeFile } from "node:fs/promises";
2042
+ import { isAbsolute as isAbsolute2, join as join4, resolve as resolve2 } from "node:path";
2043
+ var BASELINE_FILENAME = ".hig-baseline.json";
2044
+ function baselineKey(match) {
2045
+ const content = match.lineContent.replace(/\s+/g, " ").trim();
2046
+ return `${match.ruleId}\0${match.file}\0${content}`;
2047
+ }
2048
+ function createBaseline(matches, generated) {
2049
+ const findings = {};
2050
+ for (const match of matches) {
2051
+ if (match.type !== "concern") continue;
2052
+ const key = baselineKey(match);
2053
+ findings[key] = (findings[key] ?? 0) + 1;
2054
+ }
2055
+ return { version: 1, generated, findings };
2056
+ }
2057
+ function applyBaseline(matches, baseline) {
2058
+ const remaining = new Map(Object.entries(baseline.findings));
2059
+ const kept = [];
2060
+ let baselined = 0;
2061
+ for (const match of matches) {
2062
+ if (match.type === "concern") {
2063
+ const key = baselineKey(match);
2064
+ const left = remaining.get(key) ?? 0;
2065
+ if (left > 0) {
2066
+ remaining.set(key, left - 1);
2067
+ baselined++;
2068
+ continue;
2069
+ }
2070
+ }
2071
+ kept.push(match);
2072
+ }
2073
+ let stale = 0;
2074
+ for (const left of remaining.values()) stale += left;
2075
+ return { kept, baselined, stale };
2076
+ }
2077
+ function parseBaseline(raw, sourcePath) {
2078
+ let json;
2079
+ try {
2080
+ json = JSON.parse(raw);
2081
+ } catch (err) {
2082
+ throw new Error(`${sourcePath} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
2083
+ }
2084
+ const obj = json;
2085
+ if (obj == null || obj.version !== 1 || typeof obj.findings !== "object" || obj.findings == null) {
2086
+ throw new Error(`${sourcePath}: not a hig-doctor baseline (expected {version: 1, findings: {...}})`);
2087
+ }
2088
+ for (const [key, count] of Object.entries(obj.findings)) {
2089
+ if (typeof count !== "number" || count < 0 || !Number.isInteger(count)) {
2090
+ throw new Error(`${sourcePath}: invalid count for ${JSON.stringify(key)}`);
2091
+ }
2092
+ }
2093
+ return { version: 1, generated: typeof obj.generated === "string" ? obj.generated : "", findings: obj.findings };
2094
+ }
2095
+ async function loadBaseline(directory, explicitPath) {
2096
+ const path = explicitPath ? isAbsolute2(explicitPath) ? explicitPath : resolve2(explicitPath) : join4(resolve2(directory), BASELINE_FILENAME);
2097
+ let raw;
2098
+ try {
2099
+ raw = await readFile4(path, "utf-8");
2100
+ } catch {
2101
+ if (explicitPath) throw new Error(`Baseline file not found: ${path}`);
2102
+ return null;
2103
+ }
2104
+ return { path, baseline: parseBaseline(raw, path) };
2105
+ }
2106
+ async function writeBaseline(path, baseline) {
2107
+ await writeFile(path, JSON.stringify(baseline, null, 2) + "\n");
2108
+ }
2109
+
2110
+ // src/cache.ts
2111
+ import { createHash } from "node:crypto";
2112
+ import { readFile as readFile5, writeFile as writeFile2 } from "node:fs/promises";
2113
+ var CACHE_VERSION = 2;
2114
+ var CACHE_FILENAME = ".hig-cache.json";
2115
+ function namespace() {
2116
+ return `v${CACHE_VERSION}.rules${RULE_COUNT}`;
2117
+ }
2118
+ function keyFor(path, content) {
2119
+ return createHash("sha256").update(path).update("\0").update(content).digest("hex").slice(0, 24);
2120
+ }
2121
+ var ScanCache = class _ScanCache {
2122
+ entries;
2123
+ hits = 0;
2124
+ misses = 0;
2125
+ constructor(entries) {
2126
+ this.entries = entries;
2127
+ }
2128
+ static async load(path) {
2129
+ try {
2130
+ const raw = await readFile5(path, "utf-8");
2131
+ const parsed = JSON.parse(raw);
2132
+ if (parsed.namespace === namespace() && parsed.entries) {
2133
+ return new _ScanCache(new Map(Object.entries(parsed.entries)));
2134
+ }
2135
+ } catch {
2136
+ }
2137
+ return new _ScanCache(/* @__PURE__ */ new Map());
2138
+ }
2139
+ /** Return cached findings for this file, or null on a miss. */
2140
+ get(path, content) {
2141
+ const hit = this.entries.get(keyFor(path, content));
2142
+ if (hit) {
2143
+ this.hits++;
2144
+ return hit;
2145
+ }
2146
+ this.misses++;
2147
+ return null;
2148
+ }
2149
+ set(path, content, matches) {
2150
+ this.entries.set(keyFor(path, content), matches);
2151
+ }
2152
+ get stats() {
2153
+ return { hits: this.hits, misses: this.misses };
2154
+ }
2155
+ /** Persist only the keys touched this run, so deleted files don't accumulate. */
2156
+ async save(path, touched) {
2157
+ const entries = {};
2158
+ for (const [k, v] of this.entries) {
2159
+ if (touched.has(k)) entries[k] = v;
2160
+ }
2161
+ const file = { namespace: namespace(), entries };
2162
+ await writeFile2(path, JSON.stringify(file));
2163
+ }
2164
+ keyOf(path, content) {
2165
+ return keyFor(path, content);
2166
+ }
2167
+ };
2168
+
2169
+ // src/audit.ts
2170
+ import { resolve as resolve3, join as join5 } from "node:path";
2171
+ import { access } from "node:fs/promises";
2172
+ import { fileURLToPath } from "node:url";
2173
+ var moduleDir = fileURLToPath(new URL(".", import.meta.url));
2174
+ async function audit(directory, skillsDir, options = {}) {
2175
+ const resolvedDir = resolve3(directory);
2176
+ const loaded = options.noConfig ? { path: null, config: {}, warnings: [] } : await loadConfig(resolvedDir, options.configPath);
2177
+ const exclude = [...loaded.config.ignore ?? [], ...options.exclude ?? []];
2178
+ const scanResult = await scanProject(resolvedDir, { exclude });
2179
+ const detected = [];
2180
+ const allFiles = [...scanResult.codeFiles, ...scanResult.styleFiles, ...scanResult.markupFiles];
2181
+ const cachePath = join5(resolvedDir, CACHE_FILENAME);
2182
+ const cache = options.cache ? await ScanCache.load(cachePath) : null;
2183
+ const touched = /* @__PURE__ */ new Set();
2184
+ for (const file of allFiles) {
2185
+ let matches = cache?.get(file.relativePath, file.content) ?? null;
2186
+ if (matches === null) {
2187
+ matches = analyzeFile(file.content, file.relativePath);
2188
+ cache?.set(file.relativePath, file.content, matches);
2189
+ }
2190
+ if (cache) touched.add(cache.keyOf(file.relativePath, file.content));
2191
+ detected.push(...matches);
2192
+ }
2193
+ if (cache) await cache.save(cachePath, touched);
2194
+ const configured = applyConfig(detected, loaded.config);
2195
+ let allMatches = configured;
2196
+ let baselinePath = null;
2197
+ let baselined = 0;
2198
+ let baselineStale = 0;
2199
+ if (!options.noBaseline) {
2200
+ const found = await loadBaseline(resolvedDir, options.baselinePath);
2201
+ if (found) {
2202
+ const applied = applyBaseline(configured, found.baseline);
2203
+ allMatches = applied.kept;
2204
+ baselinePath = found.path;
2205
+ baselined = applied.baselined;
2206
+ baselineStale = applied.stale;
2207
+ }
2208
+ }
2209
+ const categories = categorizeMatches(allMatches);
2210
+ let resolvedSkillsDir = null;
2211
+ const skillContents = /* @__PURE__ */ new Map();
2212
+ if (skillsDir) {
2213
+ resolvedSkillsDir = resolve3(skillsDir);
2214
+ } else {
2215
+ const candidates = [
2216
+ join5(resolvedDir, "skills"),
2217
+ join5(resolvedDir, "..", "skills"),
2218
+ join5(resolvedDir, "..", "..", "skills"),
2219
+ // Relative to this package (for development: packages/core/src → repo root)
2220
+ join5(moduleDir, "..", "..", "..", "skills")
2221
+ ];
2222
+ for (const candidate of candidates) {
2223
+ try {
2224
+ await access(candidate);
2225
+ resolvedSkillsDir = candidate;
2226
+ break;
2227
+ } catch {
2228
+ }
2229
+ }
2230
+ }
2231
+ if (resolvedSkillsDir) {
2232
+ for (const category of categories) {
2233
+ const content = await loadSkillContent(resolvedSkillsDir, category.skillName);
2234
+ if (content) skillContents.set(category.skillName, content);
2235
+ }
2236
+ }
2237
+ const markdown = generateAuditMarkdown(scanResult, categories, resolvedSkillsDir, skillContents);
2238
+ return {
2239
+ scanResult,
2240
+ allMatches,
2241
+ categories,
2242
+ markdown,
2243
+ configPath: loaded.path,
2244
+ configWarnings: loaded.warnings,
2245
+ baselinePath,
2246
+ baselined,
2247
+ baselineStale,
2248
+ cacheStats: cache ? cache.stats : null
2249
+ };
2250
+ }
2251
+
2252
+ // src/sarif.ts
2253
+ var SARIF_LEVEL = {
2254
+ critical: "error",
2255
+ serious: "warning",
2256
+ moderate: "note"
2257
+ };
2258
+ function toSarif(matches, options) {
2259
+ const concerns = matches.filter((m) => m.type === "concern");
2260
+ const ruleIndex = /* @__PURE__ */ new Map();
2261
+ const rules = [];
2262
+ for (const match of concerns) {
2263
+ if (ruleIndex.has(match.ruleId)) continue;
2264
+ const meta = getRuleById(match.ruleId);
2265
+ ruleIndex.set(match.ruleId, rules.length);
2266
+ rules.push({
2267
+ id: match.ruleId,
2268
+ name: meta?.label ?? match.pattern,
2269
+ shortDescription: { text: meta?.label ?? match.pattern },
2270
+ ...meta?.fix ? { fullDescription: { text: meta.fix } } : {},
2271
+ helpUri: meta?.hig,
2272
+ properties: {
2273
+ engine: meta?.engine ?? match.engine,
2274
+ category: match.category,
2275
+ subcategory: match.subcategory
2276
+ },
2277
+ defaultConfiguration: {
2278
+ level: SARIF_LEVEL[meta?.severity ?? match.severity ?? "moderate"]
2279
+ }
2280
+ });
2281
+ }
2282
+ const results = concerns.map((match) => {
2283
+ const meta = getRuleById(match.ruleId);
2284
+ const fix = meta?.fix ? ` Fix: ${meta.fix}` : "";
2285
+ const uri = match.file.replace(/\\/g, "/");
2286
+ const suggested = options.getFix?.(match) ?? null;
2287
+ return {
2288
+ ruleId: match.ruleId,
2289
+ ruleIndex: ruleIndex.get(match.ruleId),
2290
+ level: SARIF_LEVEL[match.severity ?? "moderate"],
2291
+ message: { text: `${match.pattern} (${match.category}/${match.subcategory}).${fix}` },
2292
+ locations: [
2293
+ {
2294
+ physicalLocation: {
2295
+ artifactLocation: { uri, uriBaseId: "SRCROOT" },
2296
+ region: { startLine: match.line }
2297
+ }
2298
+ }
2299
+ ],
2300
+ partialFingerprints: {
2301
+ // Content-based, line-number-free — matches the baseline fingerprint so
2302
+ // code motion doesn't produce "new" alerts.
2303
+ higDoctorKey: `${match.ruleId} ${match.file} ${match.lineContent.replace(/\s+/g, " ").trim()}`
2304
+ },
2305
+ ...suggested ? {
2306
+ fixes: [
2307
+ {
2308
+ description: { text: `${suggested.description}${suggested.safe ? "" : " (review before applying)"}` },
2309
+ artifactChanges: [
2310
+ {
2311
+ artifactLocation: { uri, uriBaseId: "SRCROOT" },
2312
+ replacements: [
2313
+ {
2314
+ deletedRegion: { startLine: match.line, endLine: match.line },
2315
+ insertedContent: { text: suggested.after }
2316
+ }
2317
+ ]
2318
+ }
2319
+ ]
2320
+ }
2321
+ ]
2322
+ } : {}
2323
+ };
2324
+ });
2325
+ return {
2326
+ $schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
2327
+ version: "2.1.0",
2328
+ runs: [
2329
+ {
2330
+ tool: {
2331
+ driver: {
2332
+ name: "hig-doctor",
2333
+ informationUri: "https://github.com/raintree-technology/hig-doctor",
2334
+ version: options.toolVersion,
2335
+ ...options.snapshotDate ? { properties: { higSnapshot: options.snapshotDate } } : {},
2336
+ rules
2337
+ }
2338
+ },
2339
+ originalUriBaseIds: {
2340
+ SRCROOT: { description: { text: "Root of the audited project" } }
2341
+ },
2342
+ results
2343
+ }
2344
+ ]
2345
+ };
2346
+ }
2347
+
2348
+ // src/fixes.ts
2349
+ function stripViewportToken(line, token) {
2350
+ if (!token.test(line)) return null;
2351
+ let out = line.replace(new RegExp(`\\s*,\\s*${token.source}`, "i"), "").replace(new RegExp(`${token.source}\\s*,\\s*`, "i"), "").replace(new RegExp(`\\s*${token.source}`, "i"), "");
2352
+ out = out.replace(/,\s*,/g, ", ").replace(/,\s*(["'])/g, "$1").replace(/=\s*,/g, "=");
2353
+ return out === line ? null : out;
2354
+ }
2355
+ var FIXERS = {
2356
+ "css/physical-text-align": {
2357
+ safe: true,
2358
+ description: "Use logical text-align (start/end) so text follows writing direction.",
2359
+ apply: (line) => {
2360
+ const fixed = line.replace(/text-align:\s*left\b/g, "text-align: start").replace(/text-align:\s*right\b/g, "text-align: end");
2361
+ return fixed === line ? null : fixed;
2362
+ }
2363
+ },
2364
+ "web/user-scalable-no": {
2365
+ safe: true,
2366
+ description: "Remove user-scalable=no so pinch-zoom keeps working.",
2367
+ apply: (line) => stripViewportToken(line, /user-scalable\s*=\s*no/)
2368
+ },
2369
+ "web/maximum-scale-1": {
2370
+ safe: true,
2371
+ description: "Remove maximum-scale=1 so users can zoom.",
2372
+ apply: (line) => stripViewportToken(line, /maximum-scale\s*=\s*1(?:\.0)?/)
2373
+ },
2374
+ "swift/navigation-view-deprecated": {
2375
+ // Unsafe: a NavigationView with a sidebar should become NavigationSplitView,
2376
+ // which a line-level transform can't tell apart. Suggest the common case.
2377
+ safe: false,
2378
+ description: "Replace NavigationView with NavigationStack (or NavigationSplitView for sidebar layouts).",
2379
+ apply: (line) => {
2380
+ const fixed = line.replace(/\bNavigationView\b/g, "NavigationStack");
2381
+ return fixed === line ? null : fixed;
2382
+ }
2383
+ },
2384
+ "web/positive-tabindex": {
2385
+ // Unsafe: dropping to 0 changes focus order; the author must confirm intent.
2386
+ safe: false,
2387
+ description: "Use tabIndex 0 (or -1); positive values override the natural focus order.",
2388
+ apply: (line) => {
2389
+ const fixed = line.replace(/tabIndex=\{\s*[1-9]\d*\s*\}/g, "tabIndex={0}").replace(/tabindex=(["'])[1-9]\d*\1/g, "tabindex=$10$1");
2390
+ return fixed === line ? null : fixed;
2391
+ }
2392
+ }
2393
+ };
2394
+ function isFixable(ruleId) {
2395
+ return ruleId in FIXERS;
2396
+ }
2397
+ function suggestFix(match, rawLine) {
2398
+ const fixer = FIXERS[match.ruleId];
2399
+ if (!fixer) return null;
2400
+ const after = fixer.apply(rawLine);
2401
+ if (after === null || after === rawLine) return null;
2402
+ return { ruleId: match.ruleId, line: match.line, before: rawLine, after, safe: fixer.safe, description: fixer.description };
2403
+ }
2404
+ function applyFixes(content, matches) {
2405
+ const lines = content.split("\n");
2406
+ const applied = [];
2407
+ const suggestions = [];
2408
+ const seen = /* @__PURE__ */ new Set();
2409
+ for (const match of matches) {
2410
+ const fixer = FIXERS[match.ruleId];
2411
+ if (!fixer) continue;
2412
+ const idx = match.line - 1;
2413
+ if (idx < 0 || idx >= lines.length) continue;
2414
+ const key = `${match.line}:${match.ruleId}`;
2415
+ if (seen.has(key)) continue;
2416
+ seen.add(key);
2417
+ const rawLine = lines[idx];
2418
+ const after = fixer.apply(rawLine);
2419
+ if (after === null || after === rawLine) continue;
2420
+ const fix = { ruleId: match.ruleId, line: match.line, before: rawLine, after, safe: fixer.safe, description: fixer.description };
2421
+ if (fixer.safe) {
2422
+ lines[idx] = after;
2423
+ applied.push(fix);
2424
+ } else {
2425
+ suggestions.push(fix);
2426
+ }
2427
+ }
2428
+ return { content: lines.join("\n"), applied, suggestions };
2429
+ }
2430
+
2431
+ // src/benchmark.ts
2432
+ var BENCHMARK_CASES = [
2433
+ // ── Swift / SwiftUI ────────────────────────────────────────────
2434
+ {
2435
+ id: "swift-color-bad",
2436
+ framework: "swift",
2437
+ file: "BadColors.swift",
2438
+ kind: "bad",
2439
+ code: `struct V: View {
2440
+ var body: some View {
2441
+ Text("Hi").foregroundColor(.red)
2442
+ Rectangle().foregroundColor(.blue)
2443
+ }
2444
+ }`,
2445
+ expect: ["swift/hardcoded-color", "swift/hardcoded-color"]
2446
+ },
2447
+ {
2448
+ id: "swift-color-good",
2449
+ framework: "swift",
2450
+ file: "GoodColors.swift",
2451
+ kind: "good",
2452
+ code: `struct V: View {
2453
+ var body: some View {
2454
+ Text("Hi").foregroundStyle(.primary)
2455
+ Rectangle().foregroundColor(Color("BrandAccent"))
2456
+ }
2457
+ }`,
2458
+ expect: []
2459
+ },
2460
+ {
2461
+ id: "swift-nav-bad",
2462
+ framework: "swift",
2463
+ file: "BadNav.swift",
2464
+ kind: "bad",
2465
+ code: `struct Root: View {
2466
+ var body: some View {
2467
+ NavigationView {
2468
+ Text("Legacy")
2469
+ }
2470
+ }
2471
+ }`,
2472
+ expect: ["swift/navigation-view-deprecated"]
2473
+ },
2474
+ {
2475
+ id: "swift-nav-good",
2476
+ framework: "swift",
2477
+ file: "GoodNav.swift",
2478
+ kind: "good",
2479
+ code: `struct Root: View {
2480
+ var body: some View {
2481
+ NavigationStack {
2482
+ Text("Modern")
2483
+ }
2484
+ }
2485
+ }`,
2486
+ expect: []
2487
+ },
2488
+ {
2489
+ id: "swift-typography-bad",
2490
+ framework: "swift",
2491
+ file: "BadType.swift",
2492
+ kind: "bad",
2493
+ code: `Text("Title").font(.system(size: 24))`,
2494
+ expect: ["swift/hardcoded-font-size"]
2495
+ },
2496
+ {
2497
+ id: "swift-typography-good",
2498
+ framework: "swift",
2499
+ file: "GoodType.swift",
2500
+ kind: "good",
2501
+ code: `Text("Title").font(.title)`,
2502
+ expect: []
2503
+ },
2504
+ // ── Web / React ────────────────────────────────────────────────
2505
+ {
2506
+ id: "web-img-bad",
2507
+ framework: "web",
2508
+ file: "BadImg.tsx",
2509
+ kind: "bad",
2510
+ code: `export const Hero = () => <img src="/hero.png" />;`,
2511
+ expect: ["web/missing-alt"]
2512
+ },
2513
+ {
2514
+ id: "web-img-good",
2515
+ framework: "web",
2516
+ file: "GoodImg.tsx",
2517
+ kind: "good",
2518
+ code: `export const Hero = () => <img src="/hero.png" alt="Product hero shot" />;`,
2519
+ expect: []
2520
+ },
2521
+ {
2522
+ id: "web-clickable-bad",
2523
+ framework: "web",
2524
+ file: "BadClick.tsx",
2525
+ kind: "bad",
2526
+ code: `export const Row = () => <div onClick={() => open()}>Open</div>;`,
2527
+ expect: ["web/div-with-on-click-no-role"]
2528
+ },
2529
+ {
2530
+ id: "web-clickable-good",
2531
+ framework: "web",
2532
+ file: "GoodClick.tsx",
2533
+ kind: "good",
2534
+ code: `export const Row = () => <button onClick={() => open()}>Open</button>;`,
2535
+ expect: []
2536
+ },
2537
+ {
2538
+ id: "web-tabindex-bad",
2539
+ framework: "web",
2540
+ file: "BadTab.tsx",
2541
+ kind: "bad",
2542
+ code: `export const F = () => <input tabIndex={3} />;`,
2543
+ expect: ["web/positive-tabindex"]
2544
+ },
2545
+ {
2546
+ id: "web-link-good",
2547
+ framework: "web",
2548
+ file: "GoodLink.tsx",
2549
+ kind: "good",
2550
+ code: `export const L = () => <a href="/pricing">See pricing plans</a>;`,
2551
+ expect: []
2552
+ },
2553
+ // ── CSS ────────────────────────────────────────────────────────
2554
+ {
2555
+ id: "css-outline-bad",
2556
+ framework: "css",
2557
+ file: "bad.css",
2558
+ kind: "bad",
2559
+ code: `button:focus { outline: none; }`,
2560
+ expect: ["css/outline-none"]
2561
+ },
2562
+ {
2563
+ id: "css-outline-good",
2564
+ framework: "css",
2565
+ file: "good.css",
2566
+ kind: "good",
2567
+ code: `button:focus-visible { outline: 2px solid Highlight; }`,
2568
+ expect: []
2569
+ },
2570
+ {
2571
+ id: "css-important-bad",
2572
+ framework: "css",
2573
+ file: "important.css",
2574
+ kind: "bad",
2575
+ code: `.a { color: var(--fg) !important; }`,
2576
+ expect: ["css/important-usage"]
2577
+ },
2578
+ {
2579
+ id: "css-logical-good",
2580
+ framework: "css",
2581
+ file: "logical.css",
2582
+ kind: "good",
2583
+ code: `.a { text-align: start; margin-inline-start: 8px; }`,
2584
+ expect: []
2585
+ },
2586
+ // ── HTML ───────────────────────────────────────────────────────
2587
+ {
2588
+ id: "html-viewport-bad",
2589
+ framework: "web",
2590
+ file: "bad.html",
2591
+ kind: "bad",
2592
+ code: `<!doctype html><html lang="en"><head><meta name="viewport" content="width=device-width, user-scalable=no"></head><body><h1>Hi</h1></body></html>`,
2593
+ expect: ["web/user-scalable-no"]
2594
+ },
2595
+ {
2596
+ id: "html-good",
2597
+ framework: "web",
2598
+ file: "good.html",
2599
+ kind: "good",
2600
+ code: `<!doctype html><html lang="en"><head><meta name="viewport" content="width=device-width, initial-scale=1"></head><body><h1>Hi</h1></body></html>`,
2601
+ expect: []
2602
+ },
2603
+ // ── AST-tier precision cases (regex would misjudge these) ──────
2604
+ {
2605
+ id: "web-img-spread-good",
2606
+ framework: "web",
2607
+ file: "SpreadImg.tsx",
2608
+ kind: "good",
2609
+ code: `export const Avatar = (props) => <img {...props} />;`,
2610
+ expect: []
2611
+ // spread props may carry alt — the AST tier abstains
2612
+ },
2613
+ {
2614
+ id: "web-img-multiline-bad",
2615
+ framework: "web",
2616
+ file: "MultilineImg.tsx",
2617
+ kind: "bad",
2618
+ code: `export const Hero = () => (
2619
+ <img
2620
+ src="/hero.png"
2621
+ width={640}
2622
+ />
2623
+ );`,
2624
+ expect: ["web/missing-alt"]
2625
+ },
2626
+ {
2627
+ id: "web-div-nested-gt-bad",
2628
+ framework: "web",
2629
+ file: "NestedGt.tsx",
2630
+ kind: "bad",
2631
+ code: `export const Row = () => (
2632
+ <div onClick={() => select(a > b ? a : b)}>
2633
+ Pick
2634
+ </div>
2635
+ );`,
2636
+ expect: ["web/div-with-on-click-no-role"]
2637
+ },
2638
+ {
2639
+ id: "web-span-keyboard-good",
2640
+ framework: "web",
2641
+ file: "AccessibleSpan.tsx",
2642
+ kind: "good",
2643
+ code: `export const Row = () => (
2644
+ <span role="button" tabIndex={0} onKeyDown={onKey} onClick={onClick}>
2645
+ Pick
2646
+ </span>
2647
+ );`,
2648
+ expect: []
2649
+ // AST tier abstains: role + tabIndex + keydown make it operable
2650
+ },
2651
+ {
2652
+ id: "swift-image-labeled-good",
2653
+ framework: "swift",
2654
+ file: "LabeledImage.swift",
2655
+ kind: "good",
2656
+ code: `Image(systemName: "star")
2657
+ .resizable()
2658
+ .accessibilityLabel("Favorite")`,
2659
+ expect: []
2660
+ // structural analysis sees the chained label
2661
+ },
2662
+ {
2663
+ id: "swift-image-bare-bad",
2664
+ framework: "swift",
2665
+ file: "BareImage.swift",
2666
+ kind: "bad",
2667
+ code: `Image(systemName: "star").frame(width: 20, height: 20)`,
2668
+ expect: ["swift/image-without-a11y"]
2669
+ },
2670
+ // ── Cross-platform ─────────────────────────────────────────────
2671
+ {
2672
+ id: "compose-clickable-bad",
2673
+ framework: "compose",
2674
+ file: "Bad.kt",
2675
+ kind: "bad",
2676
+ code: `Box(Modifier.clickable { open() }) { Text("Open") }`,
2677
+ expect: ["compose/clickable-without-role"]
2678
+ },
2679
+ {
2680
+ id: "android-image-bad",
2681
+ framework: "android-xml",
2682
+ file: "bad.xml",
2683
+ kind: "bad",
2684
+ code: `<ImageView android:src="@drawable/logo" android:layout_width="48dp" android:layout_height="48dp" />`,
2685
+ expect: ["android-xml/image-view-without-content-description"]
2686
+ },
2687
+ {
2688
+ id: "flutter-color-bad",
2689
+ framework: "flutter",
2690
+ file: "bad.dart",
2691
+ kind: "bad",
2692
+ code: `Container(color: Color(0xFFFF0000));`,
2693
+ expect: ["flutter/hardcoded-color"]
2694
+ }
2695
+ ];
2696
+ function ratio(n, d) {
2697
+ return d === 0 ? 1 : Math.round(n / d * 1e3) / 1e3;
2698
+ }
2699
+ function runBenchmark(cases = BENCHMARK_CASES) {
2700
+ const tp = /* @__PURE__ */ new Map();
2701
+ const fp = /* @__PURE__ */ new Map();
2702
+ const fn = /* @__PURE__ */ new Map();
2703
+ const bump = (m, k) => m.set(k, (m.get(k) ?? 0) + 1);
2704
+ const falsePositives = [];
2705
+ const falseNegatives = [];
2706
+ for (const c of cases) {
2707
+ const concerns = analyzeFile(c.code, c.file).filter((m) => m.type === "concern");
2708
+ const expected = [...c.expect];
2709
+ for (const match of concerns) {
2710
+ const idx = expected.indexOf(match.ruleId);
2711
+ if (idx !== -1) {
2712
+ expected.splice(idx, 1);
2713
+ bump(tp, match.ruleId);
2714
+ } else {
2715
+ bump(fp, match.ruleId);
2716
+ falsePositives.push({ case: c.id, ruleId: match.ruleId, line: match.line });
2717
+ }
2718
+ }
2719
+ for (const missed of expected) {
2720
+ bump(fn, missed);
2721
+ falseNegatives.push({ case: c.id, ruleId: missed });
2722
+ }
2723
+ }
2724
+ const ruleIds = /* @__PURE__ */ new Set([...tp.keys(), ...fp.keys(), ...fn.keys()]);
2725
+ const perRule = [...ruleIds].sort().map((ruleId) => {
2726
+ const t = tp.get(ruleId) ?? 0;
2727
+ const f = fp.get(ruleId) ?? 0;
2728
+ const n = fn.get(ruleId) ?? 0;
2729
+ return { ruleId, tp: t, fp: f, fn: n, precision: ratio(t, t + f), recall: ratio(t, t + n) };
2730
+ });
2731
+ const sum = (m) => [...m.values()].reduce((a, b) => a + b, 0);
2732
+ const T = sum(tp);
2733
+ const F = sum(fp);
2734
+ const N = sum(fn);
2735
+ return {
2736
+ perRule,
2737
+ overall: { tp: T, fp: F, fn: N, precision: ratio(T, T + F), recall: ratio(T, T + N) },
2738
+ falsePositives,
2739
+ falseNegatives
2740
+ };
2741
+ }
2742
+ export {
2743
+ AST_TSX_RULES,
2744
+ BASELINE_FILENAME,
2745
+ BENCHMARK_CASES,
2746
+ CACHE_FILENAME,
2747
+ CONFIG_FILENAME,
2748
+ HIG_SNAPSHOT_DATE,
2749
+ RULE_COUNT,
2750
+ ScanCache,
2751
+ analyzeFile,
2752
+ applyBaseline,
2753
+ applyConfig,
2754
+ applyFixes,
2755
+ astTsxAvailable,
2756
+ audit,
2757
+ baselineKey,
2758
+ categorizeMatches,
2759
+ createBaseline,
2760
+ detectPatterns,
2761
+ fixGuidance,
2762
+ generateAuditMarkdown,
2763
+ getRuleById,
2764
+ globToRegExp,
2765
+ higCitation,
2766
+ isFixable,
2767
+ loadBaseline,
2768
+ loadConfig,
2769
+ loadSkillContent,
2770
+ parseBaseline,
2771
+ parseConfig,
2772
+ refineSwift,
2773
+ ruleCatalog,
2774
+ runBenchmark,
2775
+ scanProject,
2776
+ severityFor,
2777
+ suggestFix,
2778
+ toSarif,
2779
+ writeBaseline
2780
+ };