impeccable 3.6.1 → 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,432 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
-
5
- import { loadDesignSystemForTarget } from '../design-system.mjs';
6
- import { RULE_SCOPES, filterByScopes } from '../registry/antipatterns.mjs';
7
- import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
8
- import { detectHtml } from '../engines/static-html/detect-html.mjs';
9
- import { detectText } from '../engines/regex/detect-text.mjs';
10
- import {
11
- filterDetectionFindings,
12
- readDetectionConfig,
13
- shouldIgnoreDetectionFile,
14
- } from '../../lib/impeccable-config.mjs';
15
- import {
16
- HTML_EXTENSIONS,
17
- buildImportGraph,
18
- detectFrameworkConfig,
19
- isPortListening,
20
- walkDir,
21
- } from '../node/file-system.mjs';
22
-
23
- // ---------------------------------------------------------------------------
24
- // Output formatting
25
- // ---------------------------------------------------------------------------
26
-
27
- function formatFindingSummary(count) {
28
- return `${count} anti-pattern${count === 1 ? '' : 's'} found.`;
29
- }
30
-
31
- // Local filesystem path behind a file:// URL, or null when it can't be mapped.
32
- function fileUrlToLocalPath(url) {
33
- try {
34
- return fileURLToPath(url);
35
- } catch {
36
- return null;
37
- }
38
- }
39
-
40
- // Advisory findings are detected but never treated as failures: they list in a
41
- // separate, visually dimmed section, are excluded from the failure count that
42
- // drives the exit code, and carry `"advisory": true` in JSON so consumers can
43
- // filter. Every advisory finding carries the flag (stamped by the registry via
44
- // findings.mjs).
45
- function isAdvisory(finding) {
46
- return finding && finding.advisory === true;
47
- }
48
-
49
- function partitionAdvisory(findings) {
50
- const primary = [];
51
- const advisory = [];
52
- for (const f of findings) (isAdvisory(f) ? advisory : primary).push(f);
53
- return { primary, advisory };
54
- }
55
-
56
- // ANSI dim, when stderr is a TTY. Advisory output is chrome, so keep it quiet.
57
- function dim(text) {
58
- return process.stderr.isTTY ? `\x1b[2m${text}\x1b[0m` : text;
59
- }
60
-
61
- function formatFindingsBody(findings) {
62
- const grouped = {};
63
- for (const f of findings) {
64
- if (!grouped[f.file]) grouped[f.file] = [];
65
- grouped[f.file].push(f);
66
- }
67
- const out = [];
68
- for (const [file, items] of Object.entries(grouped)) {
69
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
70
- out.push(`\n${file}${importNote}`);
71
- for (const item of items) {
72
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
73
- out.push(` → ${item.description}`);
74
- }
75
- }
76
- return out;
77
- }
78
-
79
- function formatAdvisorySection(advisory) {
80
- if (!advisory || advisory.length === 0) return '';
81
- const lines = [`\n${dim('── Advisory (not counted as failures) ──')}`];
82
- for (const line of formatFindingsBody(advisory)) lines.push(dim(line));
83
- lines.push(dim(`\n${advisory.length} advisory note${advisory.length === 1 ? '' : 's'}. Suppress with --no-advisory.`));
84
- return lines.join('\n');
85
- }
86
-
87
- // Text/JSON formatter. `findings` is the full set; advisory items are separated
88
- // out into their own section and excluded from the failure summary count. JSON
89
- // output keeps every finding (each advisory one flagged) in a single array.
90
- function formatFindings(findings, jsonMode) {
91
- if (jsonMode) return JSON.stringify(findings, null, 2);
92
-
93
- const { primary, advisory } = partitionAdvisory(findings);
94
- const out = [...formatFindingsBody(primary)];
95
- out.push(`\n${formatFindingSummary(primary.length)}`);
96
- const advisorySection = formatAdvisorySection(advisory);
97
- if (advisorySection) out.push(advisorySection);
98
- return out.join('\n');
99
- }
100
-
101
- // ---------------------------------------------------------------------------
102
- // Stdin handling
103
- // ---------------------------------------------------------------------------
104
-
105
- // `optionsFor` maps a local path to scan options carrying that path's own
106
- // project design system (or base options when null). Falls back to a plain
107
- // object so direct/legacy callers still work.
108
- async function detectLocalFile(filePath, options) {
109
- if (HTML_EXTENSIONS.has(path.extname(filePath).toLowerCase())) {
110
- return detectHtml(filePath, options);
111
- }
112
- return detectText(fs.readFileSync(filePath, 'utf-8'), filePath, options);
113
- }
114
-
115
- async function handleStdin(optionsFor = () => ({})) {
116
- const resolve = typeof optionsFor === 'function' ? optionsFor : () => optionsFor;
117
- const chunks = [];
118
- for await (const chunk of process.stdin) chunks.push(chunk);
119
- const input = Buffer.concat(chunks).toString('utf-8');
120
- try {
121
- const parsed = JSON.parse(input);
122
- const fp = parsed?.tool_input?.file_path;
123
- if (fp && fs.existsSync(fp)) {
124
- return detectLocalFile(fp, resolve(fp));
125
- }
126
- } catch { /* not JSON */ }
127
- return detectText(input, '<stdin>', resolve(null));
128
- }
129
-
130
-
131
- // ---------------------------------------------------------------------------
132
- // CLI
133
- // ---------------------------------------------------------------------------
134
-
135
- async function confirm(question) {
136
- const rl = (await import('node:readline')).default.createInterface({
137
- input: process.stdin, output: process.stderr,
138
- });
139
- return new Promise((resolve) => {
140
- rl.question(`${question} [Y/n] `, (answer) => {
141
- rl.close();
142
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
143
- });
144
- });
145
- }
146
-
147
- function printUsage() {
148
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
149
-
150
- Scan files or URLs for UI anti-patterns and design quality issues.
151
-
152
- Options:
153
- --json Output results as JSON
154
- --quiet In text mode, only print the final findings count
155
- --scope <name> Only report rules in the given design domain
156
- (type, layout). Comma-separated.
157
- --viewport <WxH> Browser viewport for URL scans (default 1280x800),
158
- e.g. --viewport 390x844 for a mobile-width pass
159
- --no-config Do not apply project config, detector ignores, inline
160
- ignore comments, or DESIGN.md
161
- --no-inline-ignores Do not honor in-file impeccable-disable* ignore comments
162
- --no-design-system Do not load local DESIGN.md / .impeccable/design.json context
163
- --no-advisory Suppress advisory findings entirely (e.g. em-dash overuse)
164
- --help Show this help message
165
-
166
- Advisory findings:
167
- Some rules are advisory: detected and listed in a separate section, but never
168
- counted as failures and never changing the exit code. They stay out of the
169
- failure count so they never block automation. --no-advisory hides them.
170
-
171
- Project config:
172
- Respects .impeccable/config.json and .impeccable/config.local.json detector
173
- settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
174
- and detector.designSystem.enabled.
175
-
176
- Inline ignores:
177
- In-file comments waive a finding where it lives and travel with the file:
178
- <!-- impeccable-disable overused-font -- exported brand doc -->
179
- .brand { font-family: Inter } /* impeccable-disable-line overused-font */
180
- // impeccable-disable-next-line bounce-easing: intentional bounce
181
- impeccable-disable applies to the whole file; -line / -next-line are scoped.
182
- List one or more rule ids (comma-separated), or omit them / use * for all.
183
-
184
- Detection modes:
185
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
186
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
187
- URLs Puppeteer full browser rendering (auto-detected;
188
- http(s):// and file:// URLs)
189
-
190
- Examples:
191
- impeccable detect src/
192
- impeccable detect index.html
193
- impeccable detect https://example.com
194
- impeccable detect --json .
195
- impeccable detect --no-config src/`);
196
- }
197
-
198
- async function detectCli() {
199
- let args = process.argv.slice(2).map(arg => {
200
- if (arg === '-json') return '--json';
201
- if (arg === '-fast') return '--fast';
202
- return arg;
203
- });
204
- if (args[0] === 'detect') args = args.slice(1);
205
- const jsonMode = args.includes('--json');
206
- const quietMode = args.includes('--quiet');
207
- const helpMode = args.includes('--help');
208
- const noAdvisory = args.includes('--no-advisory');
209
- // --fast (regex-only) is deprecated: since the jsdom removal, the static
210
- // HTML/CSS analysis is fast and covers every rule, so the regex-only path
211
- // only loses coverage for no real speed win. Accept the flag for back-compat
212
- // but ignore it and run the full scan.
213
- if (args.includes('--fast')) {
214
- process.stderr.write(
215
- 'Note: --fast is deprecated and ignored. The full scan is fast now and runs every rule.\n',
216
- );
217
- }
218
- if (args.includes('--gpt') || args.includes('--gemini')) {
219
- process.stderr.write(
220
- 'Note: --gpt and --gemini are deprecated and ignored. Generated-UI tells now run by default.\n',
221
- );
222
- }
223
- const configEnabled = !args.includes('--no-config');
224
- const detectionConfig = configEnabled
225
- ? readDetectionConfig(process.cwd())
226
- : { ignoreRules: [], ignoreFiles: [], ignoreValues: [] };
227
- const scopes = [];
228
- for (let i = 0; i < args.length; i++) {
229
- if (args[i] !== '--scope' && !args[i].startsWith('--scope=')) continue;
230
- const inline = args[i].startsWith('--scope=');
231
- const value = inline ? args[i].slice('--scope='.length) : args[i + 1];
232
- const parsed = (value && !value.startsWith('--'))
233
- ? value.split(',').map(s => s.trim()).filter(Boolean)
234
- : [];
235
- // A bare `--scope` would otherwise fall out of `targets` and scan unscoped;
236
- // fail loudly so a mistyped pre-scan never runs the wrong rule set.
237
- if (parsed.length === 0) {
238
- process.stderr.write(
239
- `Error: --scope requires a value. Valid scopes: ${[...RULE_SCOPES].join(', ')}\n`,
240
- );
241
- process.exit(1);
242
- }
243
- scopes.push(...parsed);
244
- args.splice(i, inline ? 1 : 2);
245
- i -= 1;
246
- }
247
- let viewport = null;
248
- for (let i = 0; i < args.length; i++) {
249
- if (args[i] !== '--viewport' && !args[i].startsWith('--viewport=')) continue;
250
- const inline = args[i].startsWith('--viewport=');
251
- const value = inline ? args[i].slice('--viewport='.length) : args[i + 1];
252
- const match = /^(\d{2,5})x(\d{2,5})$/i.exec(value || '');
253
- if (!match) {
254
- process.stderr.write('Error: --viewport requires a WxH value, e.g. --viewport 390x844\n');
255
- process.exit(1);
256
- }
257
- viewport = { width: Number(match[1]), height: Number(match[2]) };
258
- args.splice(i, inline ? 1 : 2);
259
- i -= 1;
260
- }
261
- const unknownScopes = scopes.filter(s => !RULE_SCOPES.has(s));
262
- if (unknownScopes.length > 0) {
263
- process.stderr.write(
264
- `Error: unknown --scope value(s): ${unknownScopes.join(', ')}. Valid scopes: ${[...RULE_SCOPES].join(', ')}\n`,
265
- );
266
- process.exit(1);
267
- }
268
- const designSystemEnabled = configEnabled && !args.includes('--no-design-system') && detectionConfig.designSystem?.enabled !== false;
269
- // Inline `impeccable-disable*` waivers are part of the scanned file, so they
270
- // apply by default. `--no-config` (raw scan) and the dedicated
271
- // `--no-inline-ignores` both turn them off.
272
- const inlineIgnoresEnabled = configEnabled && !args.includes('--no-inline-ignores');
273
- const baseScanOptions = { inlineIgnores: inlineIgnoresEnabled };
274
- if (viewport) baseScanOptions.viewport = viewport;
275
- // DESIGN.md must resolve from EACH scan target's own project root, not from
276
- // process.cwd(): scanning project B's files from inside project A applied A's
277
- // design rules (cross-project contamination). Resolve per target, memoized by
278
- // resolved project root so a multi-file scan pays the read once per project.
279
- // A target with no project marker above it gets no design system (never cwd's).
280
- const designSystemCache = new Map();
281
- const scanOptionsFor = (localPath) => {
282
- if (!designSystemEnabled || !localPath) return baseScanOptions;
283
- const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
284
- return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
285
- };
286
- const targets = args.filter(a => !a.startsWith('--'));
287
-
288
- if (helpMode) { printUsage(); process.exit(0); }
289
-
290
- let allFindings = [];
291
-
292
- if (!process.stdin.isTTY && targets.length === 0) {
293
- allFindings = await handleStdin(scanOptionsFor);
294
- } else {
295
- const paths = targets.length > 0 ? targets : [process.cwd()];
296
- // file:// URLs get the same Puppeteer-rendered pass as http(s) — the
297
- // real cascade, real computed styles, real layout. Callers that want a
298
- // browser-grade scan of a local artifact can pass file:///abs/path.html
299
- // instead of the bare path (which stays on the static engine).
300
- const urlRe = /^(?:https?|file):\/\//i;
301
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
302
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
303
-
304
- try {
305
- for (const target of paths) {
306
- if (urlRe.test(target)) {
307
- // A file:// URL points at a local artifact, so its design system
308
- // resolves from that file's project. A remote http(s) URL has no
309
- // local project — it gets base options (no design system), never
310
- // process.cwd()'s.
311
- const urlOptions = /^file:/i.test(target)
312
- ? scanOptionsFor(fileUrlToLocalPath(target))
313
- : baseScanOptions;
314
- try {
315
- const scanner = browserDetector
316
- ? (url) => browserDetector.detectUrl(url, urlOptions)
317
- : (url) => detectUrl(url, urlOptions);
318
- allFindings.push(...await scanner(target));
319
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
320
- continue;
321
- }
322
-
323
- const resolved = path.resolve(target);
324
- let stat;
325
- try { stat = fs.statSync(resolved); }
326
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
327
-
328
- if (stat.isDirectory()) {
329
- // Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
330
- if (!jsonMode && !quietMode) {
331
- const fwConfig = detectFrameworkConfig(resolved);
332
- if (fwConfig) {
333
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
334
- if (probe.listening && probe.matched) {
335
- process.stderr.write(
336
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
337
- `For more accurate results, scan the running site:\n` +
338
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
339
- );
340
- } else if (probe.listening && !probe.matched) {
341
- process.stderr.write(
342
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
343
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
344
- );
345
- } else {
346
- process.stderr.write(
347
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
348
- `Start the dev server and scan via URL for best results:\n` +
349
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
350
- );
351
- }
352
- }
353
- }
354
-
355
- const files = walkDir(resolved)
356
- .filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
357
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
358
-
359
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
360
- if (files.length > 50 && process.stdin.isTTY && !jsonMode && !quietMode) {
361
- process.stderr.write(
362
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
363
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
364
- `Target a specific subdirectory to narrow scope.\n`
365
- );
366
- const ok = await confirm('Continue?');
367
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
368
- }
369
-
370
- // Build import graph for multi-file awareness
371
- const graph = buildImportGraph(files);
372
- // Build reverse map: file -> set of files that import it
373
- const importedByMap = new Map();
374
- for (const [importer, imports] of graph) {
375
- for (const imported of imports) {
376
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
377
- importedByMap.get(imported).add(importer);
378
- }
379
- }
380
-
381
- for (const file of files) {
382
- // Each file resolves its own project design system (cached by root),
383
- // so a scan spanning sibling projects applies the right rules per file.
384
- const fileOptions = scanOptionsFor(file);
385
- const fileFindings = await detectLocalFile(file, fileOptions);
386
- // Annotate findings with import context
387
- const importers = importedByMap.get(file);
388
- if (importers && importers.size > 0) {
389
- const importerNames = [...importers].map(f => path.basename(f));
390
- for (const f of fileFindings) {
391
- f.importedBy = importerNames;
392
- }
393
- }
394
- allFindings.push(...fileFindings);
395
- }
396
- } else if (stat.isFile()) {
397
- if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
398
- const fileOptions = scanOptionsFor(resolved);
399
- allFindings.push(...await detectLocalFile(resolved, fileOptions));
400
- }
401
- }
402
- } finally {
403
- if (browserDetector) await browserDetector.close();
404
- }
405
- }
406
-
407
- allFindings = filterDetectionFindings(allFindings, detectionConfig);
408
- allFindings = filterByScopes(allFindings, scopes);
409
- // --no-advisory drops advisory findings before any output or exit-code math.
410
- if (noAdvisory) allFindings = allFindings.filter((f) => !isAdvisory(f));
411
-
412
- // The exit code and failure count reflect non-advisory findings only. An
413
- // advisory-only scan still prints its notes but exits 0 (a clean pass), so
414
- // advisory rules never break CI or block automation.
415
- const { primary, advisory } = partitionAdvisory(allFindings);
416
-
417
- if (allFindings.length > 0) {
418
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
419
- else if (quietMode) {
420
- process.stderr.write(formatFindingSummary(primary.length) + '\n');
421
- if (advisory.length > 0) {
422
- process.stderr.write(dim(`${advisory.length} advisory note${advisory.length === 1 ? '' : 's'} (not counted).`) + '\n');
423
- }
424
- }
425
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
426
- process.exit(primary.length > 0 ? 2 : 0);
427
- }
428
- if (jsonMode) process.stdout.write('[]\n');
429
- process.exit(0);
430
- }
431
-
432
- export { formatFindings, handleStdin, confirm, printUsage, detectCli };