@raintree-technology/hig-doctor-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ import { describe, test, expect } from "bun:test";
2
+ import { toSarif } from "./sarif";
3
+ import { detectPatterns } from "./patterns";
4
+
5
+ describe("toSarif", () => {
6
+ const matches = detectPatterns(`.foregroundColor(.red)\nNavigationView {`, "Sources/App/View.swift");
7
+
8
+ test("emits a valid-shaped 2.1.0 log with concerns only", () => {
9
+ const sarif = toSarif(matches, { toolVersion: "9.9.9", snapshotDate: "2025-02-02" }) as any;
10
+ expect(sarif.version).toBe("2.1.0");
11
+ const run = sarif.runs[0];
12
+ expect(run.tool.driver.name).toBe("hig-doctor");
13
+ expect(run.tool.driver.version).toBe("9.9.9");
14
+ expect(run.tool.driver.properties.higSnapshot).toBe("2025-02-02");
15
+ // Only concerns become results; the fixture has ≥2 (hardcoded color + deprecated NavigationView).
16
+ expect(run.results.length).toBe(matches.filter((m: any) => m.type === "concern").length);
17
+ for (const result of run.results) {
18
+ expect(typeof result.ruleId).toBe("string");
19
+ expect(run.tool.driver.rules[result.ruleIndex].id).toBe(result.ruleId);
20
+ expect(result.locations[0].physicalLocation.artifactLocation.uri).toBe("Sources/App/View.swift");
21
+ expect(result.locations[0].physicalLocation.region.startLine).toBeGreaterThan(0);
22
+ expect(["error", "warning", "note"]).toContain(result.level);
23
+ expect(typeof result.partialFingerprints.higDoctorKey).toBe("string");
24
+ }
25
+ });
26
+
27
+ test("driver rules carry helpUri citations and fire-order indexes", () => {
28
+ const sarif = toSarif(matches, { toolVersion: "0.0.0" }) as any;
29
+ for (const rule of sarif.runs[0].tool.driver.rules) {
30
+ expect(rule.helpUri).toContain("developer.apple.com/design/human-interface-guidelines");
31
+ }
32
+ });
33
+
34
+ test("no concerns → empty results and rules", () => {
35
+ const sarif = toSarif([], { toolVersion: "0.0.0" }) as any;
36
+ expect(sarif.runs[0].results).toEqual([]);
37
+ expect(sarif.runs[0].tool.driver.rules).toEqual([]);
38
+ });
39
+ });
package/src/sarif.ts ADDED
@@ -0,0 +1,117 @@
1
+ // sarif.ts — SARIF 2.1.0 output for GitHub code scanning and other consumers.
2
+ // Only concern findings become SARIF results (positives/patterns are not
3
+ // defects). Severity maps critical→error, serious→warning, moderate→note.
4
+ import type { PatternMatch, Severity } from "./patterns";
5
+ import { getRuleById } from "./patterns";
6
+ import type { SuggestedFix } from "./fixes";
7
+
8
+ const SARIF_LEVEL: Record<Severity, "error" | "warning" | "note"> = {
9
+ critical: "error",
10
+ serious: "warning",
11
+ moderate: "note",
12
+ };
13
+
14
+ export interface SarifOptions {
15
+ /** Tool version reported in the SARIF driver. */
16
+ toolVersion: string;
17
+ /** HIG snapshot date the ruleset was authored against. */
18
+ snapshotDate?: string;
19
+ /** Optional resolver returning a suggested fix for a match (safe or unsafe). */
20
+ getFix?: (match: PatternMatch) => SuggestedFix | null;
21
+ }
22
+
23
+ export function toSarif(matches: PatternMatch[], options: SarifOptions): object {
24
+ const concerns = matches.filter(m => m.type === "concern");
25
+
26
+ // Driver rules: only those that actually fired, in first-seen order.
27
+ const ruleIndex = new Map<string, number>();
28
+ const rules: object[] = [];
29
+ for (const match of concerns) {
30
+ if (ruleIndex.has(match.ruleId)) continue;
31
+ const meta = getRuleById(match.ruleId);
32
+ ruleIndex.set(match.ruleId, rules.length);
33
+ rules.push({
34
+ id: match.ruleId,
35
+ name: meta?.label ?? match.pattern,
36
+ shortDescription: { text: meta?.label ?? match.pattern },
37
+ ...(meta?.fix ? { fullDescription: { text: meta.fix } } : {}),
38
+ helpUri: meta?.hig,
39
+ properties: {
40
+ engine: meta?.engine ?? match.engine,
41
+ category: match.category,
42
+ subcategory: match.subcategory,
43
+ },
44
+ defaultConfiguration: {
45
+ level: SARIF_LEVEL[(meta?.severity ?? match.severity ?? "moderate") as Severity],
46
+ },
47
+ });
48
+ }
49
+
50
+ const results = concerns.map(match => {
51
+ const meta = getRuleById(match.ruleId);
52
+ const fix = meta?.fix ? ` Fix: ${meta.fix}` : "";
53
+ const uri = match.file.replace(/\\/g, "/");
54
+ const suggested = options.getFix?.(match) ?? null;
55
+ return {
56
+ ruleId: match.ruleId,
57
+ ruleIndex: ruleIndex.get(match.ruleId),
58
+ level: SARIF_LEVEL[match.severity ?? "moderate"],
59
+ message: { text: `${match.pattern} (${match.category}/${match.subcategory}).${fix}` },
60
+ locations: [
61
+ {
62
+ physicalLocation: {
63
+ artifactLocation: { uri, uriBaseId: "SRCROOT" },
64
+ region: { startLine: match.line },
65
+ },
66
+ },
67
+ ],
68
+ partialFingerprints: {
69
+ // Content-based, line-number-free — matches the baseline fingerprint so
70
+ // code motion doesn't produce "new" alerts.
71
+ higDoctorKey: `${match.ruleId} ${match.file} ${match.lineContent.replace(/\s+/g, " ").trim()}`,
72
+ },
73
+ ...(suggested
74
+ ? {
75
+ fixes: [
76
+ {
77
+ description: { text: `${suggested.description}${suggested.safe ? "" : " (review before applying)"}` },
78
+ artifactChanges: [
79
+ {
80
+ artifactLocation: { uri, uriBaseId: "SRCROOT" },
81
+ replacements: [
82
+ {
83
+ deletedRegion: { startLine: match.line, endLine: match.line },
84
+ insertedContent: { text: suggested.after },
85
+ },
86
+ ],
87
+ },
88
+ ],
89
+ },
90
+ ],
91
+ }
92
+ : {}),
93
+ };
94
+ });
95
+
96
+ return {
97
+ $schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
98
+ version: "2.1.0",
99
+ runs: [
100
+ {
101
+ tool: {
102
+ driver: {
103
+ name: "hig-doctor",
104
+ informationUri: "https://github.com/raintree-technology/hig-doctor",
105
+ version: options.toolVersion,
106
+ ...(options.snapshotDate ? { properties: { higSnapshot: options.snapshotDate } } : {}),
107
+ rules,
108
+ },
109
+ },
110
+ originalUriBaseIds: {
111
+ SRCROOT: { description: { text: "Root of the audited project" } },
112
+ },
113
+ results,
114
+ },
115
+ ],
116
+ };
117
+ }
@@ -0,0 +1,153 @@
1
+ // scanner.test.ts
2
+ import { describe, test, expect } from "bun:test";
3
+ import { scanProject } from "./scanner";
4
+ import { mkdtemp, writeFile, mkdir, rm } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import { tmpdir } from "node:os";
7
+
8
+ describe("scanProject", () => {
9
+ test("discovers swift files", async () => {
10
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
11
+ try {
12
+ await writeFile(join(dir, "ContentView.swift"), "import SwiftUI\nstruct ContentView: View {}");
13
+ const result = await scanProject(dir);
14
+ expect(result.swiftFiles.length).toBe(1);
15
+ expect(result.swiftFiles[0].relativePath).toBe("ContentView.swift");
16
+ expect(result.codeFiles.length).toBe(1);
17
+ expect(result.frameworks).toContain("swiftui");
18
+ } finally { await rm(dir, { recursive: true }); }
19
+ });
20
+
21
+ test("discovers TSX/JSX files", async () => {
22
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
23
+ try {
24
+ await writeFile(join(dir, "App.tsx"), "export default function App() { return <div/> }");
25
+ await writeFile(join(dir, "package.json"), '{"dependencies":{"react":"^19"}}');
26
+ const result = await scanProject(dir);
27
+ expect(result.codeFiles.length).toBe(1);
28
+ expect(result.codeFiles[0].relativePath).toBe("App.tsx");
29
+ expect(result.configFiles.length).toBe(1);
30
+ expect(result.frameworks).toContain("react");
31
+ } finally { await rm(dir, { recursive: true }); }
32
+ });
33
+
34
+ test("discovers CSS files", async () => {
35
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
36
+ try {
37
+ await writeFile(join(dir, "globals.css"), "body { color: var(--foreground) }");
38
+ const result = await scanProject(dir);
39
+ expect(result.styleFiles.length).toBe(1);
40
+ } finally { await rm(dir, { recursive: true }); }
41
+ });
42
+
43
+ test("detects Next.js framework", async () => {
44
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
45
+ try {
46
+ await writeFile(join(dir, "next.config.ts"), "export default {}");
47
+ await writeFile(join(dir, "page.tsx"), "<main>Hello</main>");
48
+ const result = await scanProject(dir);
49
+ expect(result.frameworks).toContain("nextjs");
50
+ } finally { await rm(dir, { recursive: true }); }
51
+ });
52
+
53
+ test("discovers Info.plist", async () => {
54
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
55
+ try {
56
+ await writeFile(join(dir, "Info.plist"), "<plist></plist>");
57
+ const result = await scanProject(dir);
58
+ expect(result.infoPlistPaths.length).toBe(1);
59
+ } finally { await rm(dir, { recursive: true }); }
60
+ });
61
+
62
+ test("discovers xcassets directories", async () => {
63
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
64
+ try {
65
+ await mkdir(join(dir, "Assets.xcassets"), { recursive: true });
66
+ const result = await scanProject(dir);
67
+ expect(result.assetCatalogs.length).toBe(1);
68
+ } finally { await rm(dir, { recursive: true }); }
69
+ });
70
+
71
+ test("ignores .build, node_modules, and .next directories", async () => {
72
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
73
+ try {
74
+ await mkdir(join(dir, ".build"), { recursive: true });
75
+ await writeFile(join(dir, ".build", "Generated.swift"), "// generated");
76
+ await mkdir(join(dir, "node_modules"), { recursive: true });
77
+ await writeFile(join(dir, "node_modules", "lib.js"), "module.exports = {}");
78
+ await mkdir(join(dir, ".next"), { recursive: true });
79
+ await writeFile(join(dir, ".next", "build.js"), "// build");
80
+ await writeFile(join(dir, "App.swift"), "import SwiftUI");
81
+ const result = await scanProject(dir);
82
+ expect(result.swiftFiles.length).toBe(1);
83
+ expect(result.codeFiles.length).toBe(1);
84
+ } finally { await rm(dir, { recursive: true }); }
85
+ });
86
+ });
87
+
88
+ describe("scanProject — ignore patterns", () => {
89
+ test("--exclude option skips a matching file", async () => {
90
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
91
+ try {
92
+ await writeFile(join(dir, "App.tsx"), "export default function App() { return <div/> }");
93
+ await writeFile(join(dir, "fixtures.tsx"), "const bad = `<img src='x' />`");
94
+ const result = await scanProject(dir, { exclude: ["fixtures.tsx"] });
95
+ const paths = result.codeFiles.map(f => f.relativePath);
96
+ expect(paths).toContain("App.tsx");
97
+ expect(paths).not.toContain("fixtures.tsx");
98
+ } finally { await rm(dir, { recursive: true }); }
99
+ });
100
+
101
+ test(".higauditignore file is honored", async () => {
102
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
103
+ try {
104
+ await writeFile(join(dir, "App.tsx"), "export default function App() { return <div/> }");
105
+ await writeFile(join(dir, "samples.tsx"), "const bad = `<button></button>`");
106
+ await writeFile(join(dir, ".higauditignore"), "# demo fixtures\nsamples.tsx\n");
107
+ const result = await scanProject(dir);
108
+ const paths = result.codeFiles.map(f => f.relativePath);
109
+ expect(paths).toContain("App.tsx");
110
+ expect(paths).not.toContain("samples.tsx");
111
+ } finally { await rm(dir, { recursive: true }); }
112
+ });
113
+
114
+ test("** glob matches nested files at any depth", async () => {
115
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
116
+ try {
117
+ await mkdir(join(dir, "a", "b"), { recursive: true });
118
+ await writeFile(join(dir, "keep.ts"), "export const x = 1");
119
+ await writeFile(join(dir, "a", "b", "demo.stories.tsx"), "export const s = 1");
120
+ const result = await scanProject(dir, { exclude: ["**/*.stories.tsx"] });
121
+ const paths = result.codeFiles.map(f => f.relativePath);
122
+ expect(paths).toContain("keep.ts");
123
+ expect(paths.some(p => p.endsWith("demo.stories.tsx"))).toBe(false);
124
+ } finally { await rm(dir, { recursive: true }); }
125
+ });
126
+
127
+ test("directory pattern prunes the whole subtree", async () => {
128
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
129
+ try {
130
+ await mkdir(join(dir, "examples"), { recursive: true });
131
+ await writeFile(join(dir, "examples", "Bad.tsx"), "const bad = `<img src='x'/>`");
132
+ await writeFile(join(dir, "Good.tsx"), "export const ok = 1");
133
+ const result = await scanProject(dir, { exclude: ["examples"] });
134
+ const paths = result.codeFiles.map(f => f.relativePath);
135
+ expect(paths).toContain("Good.tsx");
136
+ expect(paths.some(p => p.startsWith("examples"))).toBe(false);
137
+ } finally { await rm(dir, { recursive: true }); }
138
+ });
139
+
140
+ test("a single * does not cross directory boundaries", async () => {
141
+ const dir = await mkdtemp(join(tmpdir(), "hig-test-"));
142
+ try {
143
+ await mkdir(join(dir, "nested"), { recursive: true });
144
+ await writeFile(join(dir, "top.ts"), "export const a = 1");
145
+ await writeFile(join(dir, "nested", "deep.ts"), "export const b = 2");
146
+ // "*.ts" should match only top-level .ts, not nested/deep.ts
147
+ const result = await scanProject(dir, { exclude: ["*.ts"] });
148
+ const paths = result.codeFiles.map(f => f.relativePath);
149
+ expect(paths).not.toContain("top.ts");
150
+ expect(paths.some(p => p.endsWith("deep.ts"))).toBe(true);
151
+ } finally { await rm(dir, { recursive: true }); }
152
+ });
153
+ });
package/src/scanner.ts ADDED
@@ -0,0 +1,304 @@
1
+ // scanner.ts — Framework-agnostic project scanner
2
+ import { readdir, readFile, stat } from "node:fs/promises";
3
+ import { join, relative, extname, sep } from "node:path";
4
+
5
+ export interface ScannedFile {
6
+ relativePath: string;
7
+ absolutePath: string;
8
+ content: string;
9
+ }
10
+
11
+ export type Framework = "swiftui" | "uikit" | "react" | "nextjs" | "react-native" | "vue" | "nuxt" | "svelte" | "sveltekit" | "angular" | "flutter" | "compose" | "android" | "html" | "unknown";
12
+
13
+ export interface ScanResult {
14
+ directory: string;
15
+ frameworks: Framework[];
16
+ // Universal collections
17
+ codeFiles: ScannedFile[];
18
+ styleFiles: ScannedFile[];
19
+ configFiles: ScannedFile[];
20
+ markupFiles: ScannedFile[];
21
+ // Swift-specific (backward compat)
22
+ swiftFiles: ScannedFile[];
23
+ infoPlistPaths: string[];
24
+ assetCatalogs: string[];
25
+ storyboards: ScannedFile[];
26
+ xcodeProjects: string[];
27
+ packageSwift: ScannedFile | null;
28
+ }
29
+
30
+ const IGNORED_DIRS = new Set([
31
+ ".build", ".git", "node_modules", "Pods", "DerivedData",
32
+ ".swiftpm", "Carthage", "Build", ".next", ".nuxt", ".output",
33
+ "dist", "build", ".cache", ".turbo", "coverage", "__pycache__",
34
+ ".dart_tool", ".pub-cache", "android", "ios", "macos", "linux", "windows",
35
+ ]);
36
+
37
+ // Skip files larger than this — generated bundles, minified assets, and data
38
+ // blobs cost memory and regex time without yielding real findings. The auditor
39
+ // runs on arbitrary paths (including via the MCP server), so this is also a DoS
40
+ // guard against being pointed at a multi-GB file with a code extension.
41
+ const MAX_FILE_BYTES = 1_500_000;
42
+ // Bound recursion depth so pathological or cyclic trees can't hang the walker.
43
+ const MAX_DEPTH = 25;
44
+ // Skip obviously generated files regardless of size.
45
+ const GENERATED_FILE = /\.(min|bundle|chunk)\.(js|css|mjs|cjs)$/i;
46
+
47
+ const CODE_EXTENSIONS = new Set([
48
+ ".swift", ".tsx", ".jsx", ".ts", ".js",
49
+ ".vue", ".svelte", ".dart", ".kt", ".java",
50
+ ]);
51
+
52
+ const STYLE_EXTENSIONS = new Set([
53
+ ".css", ".scss", ".sass", ".less", ".styl",
54
+ ]);
55
+
56
+ const MARKUP_EXTENSIONS = new Set([
57
+ ".html", ".htm", ".xml", ".storyboard", ".xib",
58
+ ]);
59
+
60
+ const CONFIG_FILES = new Set([
61
+ "tailwind.config.ts", "tailwind.config.js", "tailwind.config.mjs",
62
+ "next.config.ts", "next.config.js", "next.config.mjs",
63
+ "nuxt.config.ts", "nuxt.config.js",
64
+ "svelte.config.js", "svelte.config.ts",
65
+ "angular.json",
66
+ "package.json", "tsconfig.json",
67
+ "Info.plist", "Package.swift", "pubspec.yaml",
68
+ "app.json", "expo.json", "eas.json",
69
+ "components.json",
70
+ "build.gradle", "build.gradle.kts", "AndroidManifest.xml",
71
+ ]);
72
+
73
+ export interface ScanOptions {
74
+ /** Path globs (relative to the scanned root) to skip. Merged with `.higauditignore`. */
75
+ exclude?: string[];
76
+ }
77
+
78
+ const IGNORE_FILE = ".higauditignore";
79
+
80
+ // Convert a path glob to an anchored RegExp. Semantics (path-based, not gitignore):
81
+ // * → any run of characters except "/"
82
+ // ** → any run of characters including "/"
83
+ // **/ → zero or more leading path segments
84
+ // ? → a single character except "/"
85
+ // Patterns match the POSIX relative path from the scan root.
86
+ export function globToRegExp(glob: string): RegExp {
87
+ const g = glob.replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
88
+ let re = "";
89
+ for (let i = 0; i < g.length; i++) {
90
+ const ch = g[i];
91
+ if (ch === "*") {
92
+ if (g[i + 1] === "*") {
93
+ if (g[i + 2] === "/") { re += "(?:.*/)?"; i += 2; }
94
+ else { re += ".*"; i += 1; }
95
+ } else {
96
+ re += "[^/]*";
97
+ }
98
+ } else if (ch === "?") {
99
+ re += "[^/]";
100
+ } else if ("\\^$.|+()[]{}".includes(ch)) {
101
+ re += "\\" + ch;
102
+ } else {
103
+ re += ch;
104
+ }
105
+ }
106
+ return new RegExp("^" + re + "$");
107
+ }
108
+
109
+ async function loadIgnorePatterns(directory: string): Promise<string[]> {
110
+ try {
111
+ const content = await readFile(join(directory, IGNORE_FILE), "utf-8");
112
+ return content
113
+ .split("\n")
114
+ .map(line => line.trim())
115
+ .filter(line => line.length > 0 && !line.startsWith("#"));
116
+ } catch {
117
+ return [];
118
+ }
119
+ }
120
+
121
+ function buildIgnoreMatcher(patterns: string[]): (relPath: string) => boolean {
122
+ const regexps = patterns.map(globToRegExp);
123
+ if (regexps.length === 0) return () => false;
124
+ return (relPath: string) => {
125
+ const posix = relPath.split(sep).join("/");
126
+ return regexps.some(re => re.test(posix));
127
+ };
128
+ }
129
+
130
+ // Read a UTF-8 file, skipping anything too large to be worth scanning. Returns
131
+ // null on oversized files or read errors so callers can simply skip.
132
+ async function readText(path: string): Promise<string | null> {
133
+ try {
134
+ const info = await stat(path);
135
+ if (info.size > MAX_FILE_BYTES) return null;
136
+ return await readFile(path, "utf-8");
137
+ } catch {
138
+ return null;
139
+ }
140
+ }
141
+
142
+ async function walkDir(dir: string, rootDir: string, result: ScanResult, isIgnored: (relPath: string) => boolean, depth = 0): Promise<void> {
143
+ if (depth > MAX_DEPTH) return;
144
+ let entries;
145
+ try {
146
+ entries = await readdir(dir, { withFileTypes: true });
147
+ } catch {
148
+ return;
149
+ }
150
+ for (const entry of entries) {
151
+ const fullPath = join(dir, entry.name);
152
+ const relPath = relative(rootDir, fullPath);
153
+ // Never follow symlinks: avoids escaping the scanned tree (e.g. a link to /)
154
+ // and breaks any directory cycles.
155
+ if (entry.isSymbolicLink()) continue;
156
+ if (entry.isDirectory()) {
157
+ if (IGNORED_DIRS.has(entry.name)) continue;
158
+ if (isIgnored(relPath)) continue;
159
+ if (entry.name.endsWith(".xcassets")) { result.assetCatalogs.push(relPath); continue; }
160
+ if (entry.name.endsWith(".xcodeproj") || entry.name.endsWith(".xcworkspace")) { result.xcodeProjects.push(relPath); continue; }
161
+ await walkDir(fullPath, rootDir, result, isIgnored, depth + 1);
162
+ } else if (entry.isFile()) {
163
+ const ext = extname(entry.name);
164
+ // Skip test/spec files — they contain example code that triggers false positives
165
+ if (/\.(test|spec)\.[^.]+$/.test(entry.name)) continue;
166
+ // Skip generated/minified files regardless of size
167
+ if (GENERATED_FILE.test(entry.name)) continue;
168
+ // Skip files matching .higauditignore / --exclude globs
169
+ if (isIgnored(relPath)) continue;
170
+
171
+ const isConfig = CONFIG_FILES.has(entry.name);
172
+ const wantCode = CODE_EXTENSIONS.has(ext);
173
+ const wantStyle = STYLE_EXTENSIONS.has(ext);
174
+ const wantMarkup = MARKUP_EXTENSIONS.has(ext);
175
+ if (!isConfig && !wantCode && !wantStyle && !wantMarkup) continue;
176
+
177
+ const content = await readText(fullPath);
178
+ if (content === null) continue; // oversized or unreadable — skip
179
+ const file: ScannedFile = { relativePath: relPath, absolutePath: fullPath, content };
180
+
181
+ // Config files are always collected (and may also be code)
182
+ if (isConfig) {
183
+ result.configFiles.push(file);
184
+ if (entry.name === "Info.plist") result.infoPlistPaths.push(relPath);
185
+ if (entry.name === "Package.swift") result.packageSwift = file;
186
+ if (wantCode) {
187
+ result.codeFiles.push(file);
188
+ if (ext === ".swift") result.swiftFiles.push(file);
189
+ }
190
+ } else if (wantCode) {
191
+ result.codeFiles.push(file);
192
+ if (ext === ".swift") result.swiftFiles.push(file);
193
+ } else if (wantStyle) {
194
+ result.styleFiles.push(file);
195
+ } else if (wantMarkup) {
196
+ result.markupFiles.push(file);
197
+ if (ext === ".storyboard" || ext === ".xib") result.storyboards.push(file);
198
+ }
199
+ }
200
+ }
201
+ }
202
+
203
+ function detectFrameworks(result: ScanResult): Framework[] {
204
+ const frameworks: Framework[] = [];
205
+ const hasExt = (ext: string) => result.codeFiles.some(f => f.relativePath.endsWith(ext));
206
+ const hasConfig = (name: string) => result.configFiles.some(f => f.relativePath.endsWith(name));
207
+ const configContains = (name: string, text: string) => {
208
+ const file = result.configFiles.find(f => f.relativePath.endsWith(name));
209
+ return file?.content.includes(text) ?? false;
210
+ };
211
+
212
+ // Swift
213
+ if (hasExt(".swift")) {
214
+ const hasSwiftUI = result.codeFiles.some(f => f.content.includes("import SwiftUI"));
215
+ const hasUIKit = result.codeFiles.some(f => f.content.includes("import UIKit"));
216
+ if (hasSwiftUI) frameworks.push("swiftui");
217
+ if (hasUIKit) frameworks.push("uikit");
218
+ if (!hasSwiftUI && !hasUIKit) frameworks.push("swiftui"); // default for Swift
219
+ }
220
+
221
+ // Next.js
222
+ if (hasConfig("next.config.ts") || hasConfig("next.config.js") || hasConfig("next.config.mjs")) {
223
+ frameworks.push("nextjs");
224
+ }
225
+ // React (not Next.js)
226
+ else if ((hasExt(".tsx") || hasExt(".jsx")) && configContains("package.json", "\"react\"")) {
227
+ // React Native
228
+ if (configContains("package.json", "\"react-native\"") || hasConfig("app.json")) {
229
+ frameworks.push("react-native");
230
+ } else {
231
+ frameworks.push("react");
232
+ }
233
+ }
234
+
235
+ // Vue / Nuxt
236
+ if (hasExt(".vue")) {
237
+ if (hasConfig("nuxt.config.ts") || hasConfig("nuxt.config.js")) {
238
+ frameworks.push("nuxt");
239
+ } else {
240
+ frameworks.push("vue");
241
+ }
242
+ }
243
+
244
+ // Svelte / SvelteKit
245
+ if (hasExt(".svelte")) {
246
+ if (hasConfig("svelte.config.js") || hasConfig("svelte.config.ts")) {
247
+ frameworks.push("sveltekit");
248
+ } else {
249
+ frameworks.push("svelte");
250
+ }
251
+ }
252
+
253
+ // Angular
254
+ if (hasConfig("angular.json") || configContains("package.json", "\"@angular/core\"")) {
255
+ frameworks.push("angular");
256
+ }
257
+
258
+ // Flutter
259
+ if (hasExt(".dart") || hasConfig("pubspec.yaml")) {
260
+ frameworks.push("flutter");
261
+ }
262
+
263
+ // Kotlin / Jetpack Compose / Android
264
+ if (hasExt(".kt")) {
265
+ const hasCompose = result.codeFiles.some(f => f.content.includes("androidx.compose"));
266
+ if (hasCompose) {
267
+ frameworks.push("compose");
268
+ } else {
269
+ frameworks.push("android");
270
+ }
271
+ } else if (result.markupFiles.some(f => f.relativePath.endsWith(".xml") && f.content.includes("android:"))) {
272
+ frameworks.push("android");
273
+ }
274
+
275
+ // Plain HTML
276
+ if (frameworks.length === 0 && result.markupFiles.some(f => f.relativePath.endsWith(".html"))) {
277
+ frameworks.push("html");
278
+ }
279
+
280
+ if (frameworks.length === 0) frameworks.push("unknown");
281
+ return frameworks;
282
+ }
283
+
284
+ export async function scanProject(directory: string, options: ScanOptions = {}): Promise<ScanResult> {
285
+ const result: ScanResult = {
286
+ directory,
287
+ frameworks: [],
288
+ codeFiles: [],
289
+ styleFiles: [],
290
+ configFiles: [],
291
+ markupFiles: [],
292
+ swiftFiles: [],
293
+ infoPlistPaths: [],
294
+ assetCatalogs: [],
295
+ storyboards: [],
296
+ xcodeProjects: [],
297
+ packageSwift: null,
298
+ };
299
+ const patterns = [...(await loadIgnorePatterns(directory)), ...(options.exclude ?? [])];
300
+ const isIgnored = buildIgnoreMatcher(patterns);
301
+ await walkDir(directory, directory, result, isIgnored);
302
+ result.frameworks = detectFrameworks(result);
303
+ return result;
304
+ }