impeccable 3.6.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,213 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- // ---------------------------------------------------------------------------
5
- // File walker
6
- // ---------------------------------------------------------------------------
7
-
8
- // Hidden directories are skipped wholesale during recursion (below), which
9
- // covers .git / .next / .nuxt / .svelte-kit / .turbo / .vercel and — the
10
- // issue #303 class — every vendored AI-harness install (.claude, .cursor,
11
- // .codex, .agents, .impeccable, ...) whose bundled detector source would
12
- // otherwise be reported as findings on a root scan. Only the non-hidden
13
- // build/dependency dirs need naming. An explicitly passed hidden target
14
- // still scans: walkDir name-checks children, never the root it's given.
15
- const SKIP_DIRS = new Set([
16
- 'node_modules', 'dist', 'build', '__pycache__',
17
- ]);
18
-
19
- // The exceptions to the hidden-dir rule: hidden directories that
20
- // conventionally hold real UI source rather than tooling or vendored code.
21
- // VitePress and VuePress keep custom theme components in
22
- // .vitepress/theme/*.vue / .vuepress/theme/, and Storybook keeps preview
23
- // decorators/styles in .storybook/.
24
- const HIDDEN_SOURCE_DIRS = new Set(['.vitepress', '.vuepress', '.storybook']);
25
-
26
- const SCANNABLE_EXTENSIONS = new Set([
27
- '.html', '.htm', '.css', '.scss', '.sass', '.less',
28
- '.jsx', '.tsx', '.js', '.ts',
29
- '.vue', '.svelte', '.astro', '.blade.php',
30
- ]);
31
-
32
- const HTML_EXTENSIONS = new Set(['.html', '.htm']);
33
-
34
- function hasScannableExtension(filename) {
35
- const lower = filename.toLowerCase();
36
- if (SCANNABLE_EXTENSIONS.has(path.extname(lower))) return true;
37
- for (const ext of SCANNABLE_EXTENSIONS) {
38
- if (ext.indexOf('.', 1) !== -1 && lower.endsWith(ext)) return true;
39
- }
40
- return false;
41
- }
42
-
43
- const IMPORT_SPECIFIER_PATTERNS = [
44
- /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g,
45
- /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g,
46
- /@(?:use|forward)\s+['"]([^'"]+)['"]/g,
47
- ];
48
-
49
- function walkDir(dir) {
50
- const files = [];
51
- let entries;
52
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
53
- for (const entry of entries) {
54
- if (SKIP_DIRS.has(entry.name)) continue;
55
- if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
56
- const full = path.join(dir, entry.name);
57
- if (entry.isDirectory()) files.push(...walkDir(full));
58
- else if (hasScannableExtension(entry.name)) files.push(full);
59
- }
60
- return files;
61
- }
62
-
63
-
64
- // ---------------------------------------------------------------------------
65
- // Import graph (multi-file awareness)
66
- // ---------------------------------------------------------------------------
67
-
68
- function resolveImport(specifier, fromDir, fileSet) {
69
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
70
- const base = path.resolve(fromDir, specifier);
71
- if (fileSet.has(base)) return base;
72
- for (const ext of SCANNABLE_EXTENSIONS) {
73
- const withExt = base + ext;
74
- if (fileSet.has(withExt)) return withExt;
75
- }
76
- // index file convention
77
- for (const ext of SCANNABLE_EXTENSIONS) {
78
- const indexFile = path.join(base, 'index' + ext);
79
- if (fileSet.has(indexFile)) return indexFile;
80
- }
81
- return null;
82
- }
83
-
84
- function buildImportGraph(files) {
85
- const fileSet = new Set(files);
86
- const graph = new Map();
87
-
88
- for (const file of files) {
89
- const content = fs.readFileSync(file, 'utf-8');
90
- const dir = path.dirname(file);
91
- const imports = new Set();
92
-
93
- for (const pattern of IMPORT_SPECIFIER_PATTERNS) {
94
- for (const match of content.matchAll(pattern)) {
95
- const resolved = resolveImport(match[1], dir, fileSet);
96
- if (resolved) imports.add(resolved);
97
- }
98
- }
99
-
100
- graph.set(file, imports);
101
- }
102
- return graph;
103
- }
104
-
105
- // ---------------------------------------------------------------------------
106
- // Framework dev server detection
107
- // ---------------------------------------------------------------------------
108
-
109
- const FRAMEWORK_CONFIGS = [
110
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
111
- portRe: /port\s*[:=]\s*(\d+)/,
112
- fingerprint: { header: 'x-powered-by', value: /next/i } },
113
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
114
- portRe: /port\s*[:=]\s*(\d+)/,
115
- fingerprint: { header: 'x-sveltekit-page', value: null } },
116
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
117
- portRe: /port\s*[:=]\s*(\d+)/,
118
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
119
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
120
- portRe: /port\s*[:=]\s*(\d+)/,
121
- fingerprint: { body: /@vite\/client/ } },
122
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
123
- portRe: /port\s*[:=]\s*(\d+)/,
124
- fingerprint: { body: /astro/i } },
125
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
126
- portRe: /"port"\s*:\s*(\d+)/,
127
- fingerprint: { body: /ng-version/i } },
128
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
129
- portRe: /port\s*[:=]\s*(\d+)/,
130
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
131
- ];
132
-
133
- function detectFrameworkConfig(dir) {
134
- let entries;
135
- try { entries = fs.readdirSync(dir); } catch { return null; }
136
- const entrySet = new Set(entries);
137
-
138
- for (const cfg of FRAMEWORK_CONFIGS) {
139
- const match = cfg.files.find(f => entrySet.has(f));
140
- if (!match) continue;
141
-
142
- const configPath = path.join(dir, match);
143
- let port = cfg.defaultPort;
144
- try {
145
- const content = fs.readFileSync(configPath, 'utf-8');
146
- const portMatch = content.match(cfg.portRe);
147
- if (portMatch) port = parseInt(portMatch[1], 10);
148
- } catch { /* use default */ }
149
-
150
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
151
- }
152
- return null;
153
- }
154
-
155
- /**
156
- * Check if a port is listening and optionally verify it matches the expected framework.
157
- * Returns { listening: true, matched: true/false } or { listening: false }.
158
- */
159
- async function isPortListening(port, fingerprint = null) {
160
- if (!fingerprint) {
161
- // Simple TCP probe fallback
162
- const net = await import('node:net');
163
- return new Promise((resolve) => {
164
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
165
- sock.setTimeout(500);
166
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
167
- sock.on('error', () => resolve({ listening: false }));
168
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
169
- });
170
- }
171
-
172
- // HTTP probe with fingerprint matching
173
- try {
174
- const controller = new AbortController();
175
- const timeout = setTimeout(() => controller.abort(), 2000);
176
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
177
- clearTimeout(timeout);
178
-
179
- // Check header fingerprint
180
- if (fingerprint.header) {
181
- const val = res.headers.get(fingerprint.header);
182
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
183
- return { listening: true, matched: true };
184
- }
185
- }
186
-
187
- // Check body fingerprint
188
- if (fingerprint.body) {
189
- const body = await res.text();
190
- if (fingerprint.body.test(body)) {
191
- return { listening: true, matched: true };
192
- }
193
- }
194
-
195
- // Port is listening but doesn't match the expected framework
196
- return { listening: true, matched: false };
197
- } catch {
198
- return { listening: false };
199
- }
200
- }
201
-
202
- export {
203
- SKIP_DIRS,
204
- SCANNABLE_EXTENSIONS,
205
- HTML_EXTENSIONS,
206
- hasScannableExtension,
207
- walkDir,
208
- resolveImport,
209
- buildImportGraph,
210
- FRAMEWORK_CONFIGS,
211
- detectFrameworkConfig,
212
- isPortListening,
213
- };
@@ -1,166 +0,0 @@
1
- function profileNow() {
2
- return typeof performance !== 'undefined' && performance.now
3
- ? performance.now()
4
- : Date.now();
5
- }
6
-
7
- function createDetectorProfile() {
8
- return { events: [] };
9
- }
10
-
11
- function recordProfileEvent(profile, event) {
12
- if (!profile) return;
13
- const normalized = {
14
- engine: event.engine || 'unknown',
15
- phase: event.phase || 'unknown',
16
- ruleId: event.ruleId || 'unknown',
17
- target: event.target || '',
18
- ms: Number.isFinite(event.ms) ? event.ms : 0,
19
- findings: Number.isFinite(event.findings) ? event.findings : 0,
20
- };
21
- if (event.detail) normalized.detail = event.detail;
22
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
23
- normalized.findingIds = event.findingIds;
24
- }
25
- if (typeof profile === 'function') {
26
- profile(normalized);
27
- } else if (typeof profile.record === 'function') {
28
- profile.record(normalized);
29
- } else if (Array.isArray(profile.events)) {
30
- profile.events.push(normalized);
31
- } else if (Array.isArray(profile)) {
32
- profile.push(normalized);
33
- }
34
- }
35
-
36
- function extractFindingIds(findings) {
37
- if (!Array.isArray(findings) || findings.length === 0) return [];
38
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
39
- }
40
-
41
- function profileFindings(profile, meta, callback) {
42
- if (!profile) return callback();
43
- const started = profileNow();
44
- const findings = callback();
45
- recordProfileEvent(profile, {
46
- ...meta,
47
- ms: profileNow() - started,
48
- findings: Array.isArray(findings) ? findings.length : 0,
49
- findingIds: extractFindingIds(findings),
50
- });
51
- return findings;
52
- }
53
-
54
- function profileStep(profile, meta, callback) {
55
- if (!profile) return callback();
56
- const started = profileNow();
57
- try {
58
- return callback();
59
- } finally {
60
- recordProfileEvent(profile, {
61
- ...meta,
62
- ms: profileNow() - started,
63
- findings: 0,
64
- });
65
- }
66
- }
67
-
68
- async function profileFindingsAsync(profile, meta, callback) {
69
- if (!profile) return callback();
70
- const started = profileNow();
71
- const findings = await callback();
72
- recordProfileEvent(profile, {
73
- ...meta,
74
- ms: profileNow() - started,
75
- findings: Array.isArray(findings) ? findings.length : 0,
76
- findingIds: extractFindingIds(findings),
77
- });
78
- return findings;
79
- }
80
-
81
- async function profileStepAsync(profile, meta, callback) {
82
- if (!profile) return callback();
83
- const started = profileNow();
84
- try {
85
- return await callback();
86
- } finally {
87
- recordProfileEvent(profile, {
88
- ...meta,
89
- ms: profileNow() - started,
90
- findings: 0,
91
- });
92
- }
93
- }
94
-
95
- function percentile(sortedValues, pct) {
96
- if (!sortedValues.length) return 0;
97
- const idx = Math.min(
98
- sortedValues.length - 1,
99
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
100
- );
101
- return sortedValues[idx];
102
- }
103
-
104
- function summarizeDetectorProfile(profile) {
105
- const events = Array.isArray(profile)
106
- ? profile
107
- : (Array.isArray(profile?.events) ? profile.events : []);
108
- const groups = new Map();
109
- for (const event of events) {
110
- const key = [
111
- event.engine || 'unknown',
112
- event.phase || 'unknown',
113
- event.ruleId || 'unknown',
114
- event.target || '',
115
- ].join('\u0000');
116
- let group = groups.get(key);
117
- if (!group) {
118
- group = {
119
- engine: event.engine || 'unknown',
120
- phase: event.phase || 'unknown',
121
- ruleId: event.ruleId || 'unknown',
122
- target: event.target || '',
123
- calls: 0,
124
- totalMs: 0,
125
- findings: 0,
126
- samples: [],
127
- };
128
- groups.set(key, group);
129
- }
130
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
131
- group.calls += 1;
132
- group.totalMs += ms;
133
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
134
- group.samples.push(ms);
135
- }
136
- return [...groups.values()]
137
- .map(group => {
138
- const samples = group.samples.sort((a, b) => a - b);
139
- return {
140
- engine: group.engine,
141
- phase: group.phase,
142
- ruleId: group.ruleId,
143
- target: group.target,
144
- calls: group.calls,
145
- totalMs: Number(group.totalMs.toFixed(3)),
146
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
147
- p50: Number(percentile(samples, 50).toFixed(3)),
148
- p95: Number(percentile(samples, 95).toFixed(3)),
149
- findings: group.findings,
150
- };
151
- })
152
- .sort((a, b) => b.totalMs - a.totalMs);
153
- }
154
-
155
- export {
156
- profileNow,
157
- createDetectorProfile,
158
- recordProfileEvent,
159
- extractFindingIds,
160
- profileFindings,
161
- profileStep,
162
- profileFindingsAsync,
163
- profileStepAsync,
164
- percentile,
165
- summarizeDetectorProfile,
166
- };