impeccable 2.1.9 → 2.2.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.
@@ -5,4339 +5,39 @@
5
5
  * Copyright (c) 2026 Paul Bakaus
6
6
  * SPDX-License-Identifier: Apache-2.0
7
7
  *
8
- * Universal file — auto-detects environment (browser vs Node) and adapts.
9
- *
10
- * Node usage:
11
- * node detect-antipatterns.mjs [file-or-dir...] # jsdom for HTML, regex for rest
12
- * node detect-antipatterns.mjs https://... # Puppeteer (auto)
13
- * node detect-antipatterns.mjs --fast [files...] # regex-only (skip jsdom)
14
- * node detect-antipatterns.mjs --json # JSON output
15
- *
16
- * Browser usage:
17
- * <script src="detect-antipatterns-browser.js"></script>
18
- * Re-scan: window.impeccableScan()
19
- *
20
- * Exit codes: 0 = clean, 2 = findings
8
+ * Public API facade. Runtime engines live under cli/engine/engines/.
21
9
  */
22
10
 
23
- // ─── Environment ────────────────────────────────────────────────────────────
24
-
25
- const IS_BROWSER = typeof window !== 'undefined';
26
- const IS_NODE = !IS_BROWSER;
27
-
28
- // @browser-strip-start
29
- let fs, path, fileURLToPath;
30
- if (!IS_BROWSER) {
31
- fs = (await import('node:fs')).default;
32
- path = (await import('node:path')).default;
33
- fileURLToPath = (await import('node:url')).fileURLToPath;
34
- }
35
- // @browser-strip-end
36
-
37
- // ─── Section 1: Constants ───────────────────────────────────────────────────
38
-
39
- const SAFE_TAGS = new Set([
40
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
41
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
42
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
43
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
44
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
45
- ]);
46
-
47
- // Per-check safe-tags override for the border (side-tab / border-accent)
48
- // rule. We intentionally re-allow <label> here because card-shaped clickable
49
- // labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
50
- // canonical side-tab anti-pattern shapes and must be detected. The rule's
51
- // other preconditions (non-neutral color, width >= 2px on a single side,
52
- // radius > 0 or width >= 3, element size >= 20x20 in the browser path)
53
- // already filter out plain inline form labels so this does not introduce
54
- // false positives. See modern-color-borders.html for the test matrix.
55
- const BORDER_SAFE_TAGS = new Set(
56
- [...SAFE_TAGS].filter(t => t !== 'label')
57
- );
58
-
59
- const OVERUSED_FONTS = new Set([
60
- // Older monoculture (still ubiquitous):
61
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
62
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
63
- 'fraunces', 'instrument sans',
64
- 'geist', 'geist sans', 'geist mono',
65
- 'mona sans',
66
- 'plus jakarta sans', 'space grotesk', 'recoleta',
67
- ]);
68
-
69
- // Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
70
- // Keys are font names, values are arrays of hostname suffixes where the font is allowed.
71
- const GOOGLE_DOMAINS = [
72
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
73
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
74
- ];
75
- const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
76
- const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
77
- const BRAND_FONT_DOMAINS = {
78
- 'roboto': GOOGLE_DOMAINS,
79
- 'google sans': GOOGLE_DOMAINS,
80
- 'product sans': GOOGLE_DOMAINS,
81
- 'geist': VERCEL_DOMAINS,
82
- 'geist sans': VERCEL_DOMAINS,
83
- 'geist mono': VERCEL_DOMAINS,
84
- 'mona sans': GITHUB_DOMAINS,
85
- };
86
-
87
- function isBrandFontOnOwnDomain(font) {
88
- if (typeof location === 'undefined') return false;
89
- const allowed = BRAND_FONT_DOMAINS[font];
90
- if (!allowed) return false;
91
- const host = location.hostname.toLowerCase();
92
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
93
- }
94
-
95
- const GENERIC_FONTS = new Set([
96
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
97
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
98
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
99
- 'inherit', 'initial', 'unset', 'revert',
100
- ]);
101
-
102
- // Serif faces that show up in italic-display heroes. The rule also fires when
103
- // the primary face is unknown but the stack ends in the generic `serif` token,
104
- // which catches custom/private faces with a serif fallback.
105
- const KNOWN_SERIF_FONTS = new Set([
106
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
107
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
108
- 'tiempos', 'tiempos headline', 'tiempos text',
109
- 'lora', 'vollkorn', 'spectral',
110
- 'source serif pro', 'source serif 4', 'source serif',
111
- 'ibm plex serif', 'merriweather',
112
- 'libre caslon', 'libre baskerville', 'baskerville',
113
- 'georgia', 'times new roman', 'times',
114
- 'dm serif display', 'dm serif text',
115
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
116
- 'freight display', 'freight text',
117
- ]);
118
-
119
- const ANTIPATTERNS = [
120
- // ── AI slop: tells that something was AI-generated ──
121
- {
122
- id: 'side-tab',
123
- category: 'slop',
124
- name: 'Side-tab accent border',
125
- description:
126
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
127
- skillSection: 'Visual Details',
128
- skillGuideline: 'colored accent stripe',
129
- },
130
- {
131
- id: 'border-accent-on-rounded',
132
- category: 'slop',
133
- name: 'Border accent on rounded element',
134
- description:
135
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
136
- skillSection: 'Visual Details',
137
- skillGuideline: 'colored accent stripe',
138
- },
139
- {
140
- id: 'overused-font',
141
- category: 'slop',
142
- name: 'Overused font',
143
- description:
144
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
145
- skillSection: 'Typography',
146
- skillGuideline: 'overused fonts like Inter',
147
- },
148
- {
149
- id: 'single-font',
150
- category: 'slop',
151
- name: 'Single font for everything',
152
- description:
153
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
154
- skillSection: 'Typography',
155
- skillGuideline: 'only one font family for the entire page',
156
- },
157
- {
158
- id: 'flat-type-hierarchy',
159
- category: 'slop',
160
- name: 'Flat type hierarchy',
161
- description:
162
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
163
- skillSection: 'Typography',
164
- skillGuideline: 'flat type hierarchy',
165
- },
166
- {
167
- id: 'gradient-text',
168
- category: 'slop',
169
- name: 'Gradient text',
170
- description:
171
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
172
- skillSection: 'Color & Contrast',
173
- skillGuideline: 'gradient text for',
174
- },
175
- {
176
- id: 'ai-color-palette',
177
- category: 'slop',
178
- name: 'AI color palette',
179
- description:
180
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
181
- skillSection: 'Color & Contrast',
182
- skillGuideline: 'AI color palette',
183
- },
184
- {
185
- id: 'nested-cards',
186
- category: 'slop',
187
- name: 'Nested cards',
188
- description:
189
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
190
- skillSection: 'Layout & Space',
191
- skillGuideline: 'Nest cards inside cards',
192
- },
193
- {
194
- id: 'monotonous-spacing',
195
- category: 'slop',
196
- name: 'Monotonous spacing',
197
- description:
198
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
199
- skillSection: 'Layout & Space',
200
- skillGuideline: 'same spacing everywhere',
201
- },
202
- {
203
- id: 'everything-centered',
204
- category: 'slop',
205
- name: 'Everything centered',
206
- description:
207
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
208
- skillSection: 'Layout & Space',
209
- skillGuideline: 'Center everything',
210
- },
211
- {
212
- id: 'bounce-easing',
213
- category: 'slop',
214
- name: 'Bounce or elastic easing',
215
- description:
216
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
217
- skillSection: 'Motion',
218
- skillGuideline: 'bounce or elastic easing',
219
- },
220
- {
221
- id: 'dark-glow',
222
- category: 'slop',
223
- name: 'Dark mode with glowing accents',
224
- description:
225
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
226
- skillSection: 'Color & Contrast',
227
- skillGuideline: 'dark mode with glowing accents',
228
- },
229
- {
230
- id: 'icon-tile-stack',
231
- category: 'slop',
232
- name: 'Icon tile stacked above heading',
233
- description:
234
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
235
- skillSection: 'Typography',
236
- skillGuideline: 'large icons with rounded corners above every heading',
237
- },
238
- {
239
- id: 'italic-serif-display',
240
- category: 'slop',
241
- name: 'Italic serif display headline',
242
- description:
243
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
244
- skillSection: 'Typography',
245
- skillGuideline: 'oversized italic serif as the hero headline',
246
- },
247
- {
248
- id: 'hero-eyebrow-chip',
249
- category: 'slop',
250
- name: 'Hero eyebrow / pill chip',
251
- description:
252
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
253
- skillSection: 'Typography',
254
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
255
- },
256
- {
257
- id: 'repeated-section-kickers',
258
- category: 'slop',
259
- severity: 'advisory',
260
- name: 'Repeated section kicker labels',
261
- description:
262
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
263
- skillSection: 'Typography',
264
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
265
- },
266
-
267
- // ── Quality: general design and accessibility issues ──
268
- {
269
- id: 'pure-black-white',
270
- category: 'quality',
271
- name: 'Pure black background',
272
- description:
273
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
274
- skillSection: 'Color & Contrast',
275
- skillGuideline: 'pure black (#000)',
276
- },
277
- {
278
- id: 'gray-on-color',
279
- category: 'quality',
280
- name: 'Gray text on colored background',
281
- description:
282
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
283
- skillSection: 'Color & Contrast',
284
- skillGuideline: 'gray text on colored backgrounds',
285
- },
286
- {
287
- id: 'low-contrast',
288
- category: 'quality',
289
- name: 'Low contrast text',
290
- description:
291
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
292
- },
293
- {
294
- id: 'layout-transition',
295
- category: 'quality',
296
- name: 'Layout property animation',
297
- description:
298
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
299
- skillSection: 'Motion',
300
- skillGuideline: 'Animate layout properties',
301
- },
302
- {
303
- id: 'line-length',
304
- category: 'quality',
305
- name: 'Line length too long',
306
- description:
307
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
308
- skillSection: 'Layout & Space',
309
- skillGuideline: 'wrap beyond ~80 characters',
310
- },
311
- {
312
- id: 'cramped-padding',
313
- category: 'quality',
314
- name: 'Cramped padding',
315
- description:
316
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
317
- },
318
- {
319
- id: 'body-text-viewport-edge',
320
- category: 'quality',
321
- name: 'Body text touching viewport edge',
322
- description:
323
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
324
- },
325
- {
326
- id: 'tight-leading',
327
- category: 'quality',
328
- name: 'Tight line height',
329
- description:
330
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
331
- },
332
- {
333
- id: 'skipped-heading',
334
- category: 'quality',
335
- name: 'Skipped heading level',
336
- description:
337
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
338
- },
339
- {
340
- id: 'justified-text',
341
- category: 'quality',
342
- name: 'Justified text',
343
- description:
344
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
345
- },
346
- {
347
- id: 'tiny-text',
348
- category: 'quality',
349
- name: 'Tiny body text',
350
- description:
351
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
352
- },
353
- {
354
- id: 'all-caps-body',
355
- category: 'quality',
356
- name: 'All-caps body text',
357
- description:
358
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
359
- skillSection: 'Typography',
360
- skillGuideline: 'long body passages in uppercase',
361
- },
362
- {
363
- id: 'wide-tracking',
364
- category: 'quality',
365
- name: 'Wide letter spacing on body text',
366
- description:
367
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
368
- },
369
- ];
370
-
371
- // ─── Section 2: Color Utilities ─────────────────────────────────────────────
372
-
373
- function isNeutralColor(color) {
374
- if (!color || color === 'transparent') return true;
375
-
376
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
377
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
378
- if (rgb) {
379
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
380
- }
381
-
382
- // oklch()/lch() — chroma is the second numeric component.
383
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
384
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
385
- // literally (it does NOT convert them to rgb).
386
- const oklch = color.match(/oklch\(\s*[\d.%-]+\s+([\d.-]+)/i);
387
- if (oklch) return parseFloat(oklch[1]) < 0.02;
388
- const lch = color.match(/lch\(\s*[\d.%-]+\s+([\d.-]+)/i);
389
- if (lch) return parseFloat(lch[1]) < 3;
390
-
391
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
392
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
393
- const oklab = color.match(/oklab\(\s*[\d.%-]+\s+([\d.-]+)\s+([\d.-]+)/i);
394
- if (oklab) {
395
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
396
- return Math.hypot(a, b) < 0.02;
397
- }
398
- const lab = color.match(/lab\(\s*[\d.%-]+\s+([\d.-]+)\s+([\d.-]+)/i);
399
- if (lab) {
400
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
401
- return Math.hypot(a, b) < 3;
402
- }
403
-
404
- // hsl/hsla — saturation is the second numeric component (percent).
405
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
406
- // safety across versions and for any engine that preserves the format.
407
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
408
- if (hsl) return parseFloat(hsl[1]) < 10;
409
-
410
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
411
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
412
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
413
- if (hwb) {
414
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
415
- return (1 - Math.min(100, w + b) / 100) < 0.1;
416
- }
417
-
418
- // Unknown / unrecognized format — err on the side of DETECTING rather
419
- // than silently skipping. This is the opposite of the previous default,
420
- // which was the root cause of the oklch bug.
421
- return false;
422
- }
423
-
424
- function parseRgb(color) {
425
- if (!color || color === 'transparent') return null;
426
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
427
- if (!m) return null;
428
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
429
- }
430
-
431
- function relativeLuminance({ r, g, b }) {
432
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
433
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
434
- );
435
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
436
- }
437
-
438
- function contrastRatio(c1, c2) {
439
- const l1 = relativeLuminance(c1);
440
- const l2 = relativeLuminance(c2);
441
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
442
- }
443
-
444
- function parseGradientColors(bgImage) {
445
- if (!bgImage || !bgImage.includes('gradient')) return [];
446
- const colors = [];
447
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
448
- const c = parseRgb(m[0]);
449
- if (c) colors.push(c);
450
- }
451
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
452
- const h = m[1];
453
- if (h.length === 6) {
454
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
455
- } else {
456
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
457
- }
458
- }
459
- return colors;
460
- }
461
-
462
- function hasChroma(c, threshold = 30) {
463
- if (!c) return false;
464
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
465
- }
466
-
467
- function getHue(c) {
468
- if (!c) return 0;
469
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
470
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
471
- if (max === min) return 0;
472
- const d = max - min;
473
- let h;
474
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
475
- else if (max === g) h = ((b - r) / d + 2) / 6;
476
- else h = ((r - g) / d + 4) / 6;
477
- return Math.round(h * 360);
478
- }
479
-
480
- function colorToHex(c) {
481
- if (!c) return '?';
482
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
483
- }
484
-
485
- // ─── Section 3: Pure Detection ──────────────────────────────────────────────
486
-
487
- function checkBorders(tag, widths, colors, radius) {
488
- if (BORDER_SAFE_TAGS.has(tag)) return [];
489
- const findings = [];
490
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
491
-
492
- for (const side of sides) {
493
- const w = widths[side];
494
- if (w < 1 || isNeutralColor(colors[side])) continue;
495
-
496
- const otherSides = sides.filter(s => s !== side);
497
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
498
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
499
-
500
- const sn = side.toLowerCase();
501
- const isSide = side === 'Left' || side === 'Right';
502
-
503
- if (isSide) {
504
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
505
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
506
- } else {
507
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
508
- }
509
- }
510
-
511
- return findings;
512
- }
513
-
514
- // Returns true if the given text is composed entirely of emoji characters
515
- // (plus whitespace / variation selectors). Emojis render as multicolor glyphs
516
- // regardless of CSS `color`, so contrast checks against the element's text
517
- // color are meaningless for these nodes.
518
- const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
519
- const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
520
- function isEmojiOnlyText(text) {
521
- if (!text) return false;
522
- if (!EMOJI_CHAR_RE.test(text)) return false;
523
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
524
- }
525
-
526
- function checkColors(opts) {
527
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
528
- if (SAFE_TAGS.has(tag)) {
529
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
530
- // exists to suppress contrast noise on inline links and unstyled controls,
531
- // where the element has no own background and the contrast against the
532
- // ancestor surface is already the intended visual. When the element has
533
- // its own opaque background and direct text, it is a styled button — and
534
- // contrast on its own surface is a real, frequent bug worth flagging.
535
- const isStyledButton = (tag === 'a' || tag === 'button')
536
- && hasDirectText
537
- && bgColor && bgColor.a > 0.5;
538
- if (!isStyledButton) return [];
539
- }
540
- const findings = [];
541
-
542
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
543
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
544
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
545
- }
546
-
547
- if (hasDirectText && textColor && !isEmojiOnly) {
548
- // Run background-dependent checks against either a solid bg or, if the
549
- // ancestor is a gradient, against every gradient stop (use the worst case).
550
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
551
- if (bgs) {
552
- // Gray on colored background — flag if every stop is chromatic
553
- const textLum = relativeLuminance(textColor);
554
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
555
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
556
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
557
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
558
- }
559
-
560
- // Low contrast (WCAG AA) — worst case across all bg stops
561
- const ratios = bgs.map(b => contrastRatio(textColor, b));
562
- let worstIdx = 0;
563
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
564
- const ratio = ratios[worstIdx];
565
- const isHeading = ['h1', 'h2', 'h3'].includes(tag);
566
- const isLargeText = fontSize >= 18 || (fontSize >= 14 && fontWeight >= 700) || isHeading;
567
- const threshold = isLargeText ? 3.0 : 4.5;
568
- if (ratio < threshold) {
569
- // Skip the false-positive class where text has alpha < 1 AND we
570
- // couldn't find an opaque ancestor (effectiveBg is null, we're
571
- // comparing against gradient-stop fallback). In jsdom mode the
572
- // detector can't resolve `var(--X)` color tokens, so a dark
573
- // section sitting between the text and the body's decorative
574
- // gradient is invisible to us — we end up measuring contrast
575
- // against the body's paper-grain noise instead of the real
576
- // local bg. Real low-contrast bugs use alpha=1 and have a
577
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
578
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
579
- const isAlphaFallbackFP = !IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
580
- if (!isAlphaFallbackFP) {
581
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
582
- }
583
- }
584
- }
585
-
586
- // AI palette: purple/violet on headings
587
- if (hasChroma(textColor, 50)) {
588
- const hue = getHue(textColor);
589
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
590
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
591
- }
592
- }
593
- }
594
-
595
- // Gradient text
596
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
597
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
598
- }
599
-
600
- // Tailwind class checks
601
- if (classList) {
602
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
603
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
604
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
605
- }
606
-
607
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
608
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
609
- if (grayMatch && colorBgMatch) {
610
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
611
- }
612
-
613
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
614
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
615
- }
616
-
617
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
618
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
619
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
620
- }
621
-
622
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
623
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
624
- }
625
- }
626
-
627
- return findings;
628
- }
629
-
630
- function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
631
- if (!hasShadow && !hasBorder) return false;
632
- return hasRadius || hasBg;
633
- }
634
-
635
- const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
636
-
637
- // Pure check: given a heading and metrics about its previousElementSibling,
638
- // decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
639
- //
640
- // Triggers when ALL of the following hold for the sibling:
641
- // • size 32–128px on both axes (not too small, not a hero image)
642
- // • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
643
- // • has a non-transparent background-color, background-image, OR a visible border
644
- // (covers solid colors, white-with-border, gradients — anything that visually
645
- // defines a tile)
646
- // • border-radius < width/2 (excludes round avatars; rounded squares pass)
647
- // • contains an <svg> or icon-class <i> element that's smaller than the tile
648
- // • the tile sits above the heading (its bottom is above the heading's top)
649
- function checkIconTile(opts) {
650
- const { headingTag, headingText, headingTop,
651
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
652
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
653
- hasIconChild, iconChildWidth } = opts;
654
- if (!HEADING_TAGS.has(headingTag)) return [];
655
- if (!siblingTag) return [];
656
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
657
- if (HEADING_TAGS.has(siblingTag)) return [];
658
-
659
- // Size window: 32–128px on each axis
660
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
661
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
662
-
663
- // Squarish aspect ratio
664
- const ratio = siblingWidth / siblingHeight;
665
- if (ratio < 0.7 || ratio > 1.4) return [];
666
-
667
- // Must have something that visually defines the tile
668
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
669
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
670
- const borderVisible = siblingBorderWidth > 0;
671
- if (!bgVisible && !borderVisible) return [];
672
-
673
- // Exclude circles (avatars). Rounded squares pass.
674
- if (siblingBorderRadius >= siblingWidth / 2) return [];
675
-
676
- // Must contain an icon element smaller than the tile
677
- if (!hasIconChild) return [];
678
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
679
-
680
- // Vertical stacking: tile must end above where the heading starts.
681
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
682
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
683
-
684
- const text = (headingText || '').trim().slice(0, 60);
685
- return [{
686
- id: 'icon-tile-stack',
687
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
688
- }];
689
- }
690
-
691
- // Resolve the primary (non-generic) face from a font-family string and return
692
- // whether the resolved primary is serif. Two paths:
693
- // 1. Primary face is in KNOWN_SERIF_FONTS → serif.
694
- // 2. Primary face is unknown but the stack ends in the generic `serif`
695
- // token → treat as serif. Authors who declare `font-family: 'X', serif`
696
- // almost always have a serif primary; a sans declared with a serif
697
- // fallback is a code smell, not the common case.
698
- // Returns { primary, isSerif } so the snippet can name the face.
699
- function resolveSerif(fontFamily) {
700
- if (!fontFamily) return { primary: null, isSerif: false };
701
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
702
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
703
- if (!primary) return { primary: null, isSerif: false };
704
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
705
- if (tokens.includes('serif')) return { primary, isSerif: true };
706
- return { primary, isSerif: false };
707
- }
708
-
709
- function checkItalicSerif(opts) {
710
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
711
- if (fontStyle !== 'italic') return [];
712
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
713
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
714
- // to an h2 but keeps the size.
715
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
716
- if (fontSize < 48) return [];
717
- const { primary, isSerif } = resolveSerif(fontFamily);
718
- if (!isSerif) return [];
719
-
720
- const text = (headingText || '').trim().slice(0, 60);
721
- return [{
722
- id: 'italic-serif-display',
723
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
724
- }];
725
- }
726
-
727
- // Color saturation check. Returns true when the color has visible
728
- // chroma — i.e., it's an "accent color" rather than near-neutral.
729
- // Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
730
- // expected to be pre-resolved by the caller.
731
- function isAccentColor(cssColor) {
732
- if (!cssColor) return false;
733
- const s = String(cssColor).trim();
734
- // rgb / rgba — direct channel-distance check.
735
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
736
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
737
- if (rgbStrict) {
738
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
739
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
740
- }
741
- // #hex — 3, 4, 6, or 8 digit.
742
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
743
- if (hexM) {
744
- let h = hexM[1];
745
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
746
- else h = h.slice(0, 6);
747
- if (h.length === 6) {
748
- const r = parseInt(h.slice(0, 2), 16);
749
- const g = parseInt(h.slice(2, 4), 16);
750
- const b = parseInt(h.slice(4, 6), 16);
751
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
752
- }
753
- }
754
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
755
- // have C < 0.02; visible accents are 0.05+. CSS minification can
756
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
757
- // extract all numbers and take the second rather than matching a
758
- // strict L-then-whitespace-then-C pattern.
759
- if (/^oklch\(/i.test(s)) {
760
- const nums = s.match(/\d*\.\d+|\d+/g);
761
- if (nums && nums.length >= 2) {
762
- const c = parseFloat(nums[1]);
763
- return !Number.isNaN(c) && c >= 0.05;
764
- }
765
- }
766
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
767
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
768
- if (hslM) {
769
- const sat = parseFloat(hslM[1]);
770
- return !Number.isNaN(sat) && sat >= 20;
771
- }
772
- return false;
773
- }
774
-
775
- // Sibling-relationship rule. Anchor on a hero-scale h1, look at the
776
- // previousElementSibling, and gate on EITHER the classic tracked-
777
- // uppercase eyebrow OR the modern accent-colored bold eyebrow.
778
- function checkHeroEyebrow(opts) {
779
- const {
780
- headingTag, headingText, headingFontSize,
781
- siblingTag, siblingText, siblingTextTransform,
782
- siblingFontSize, siblingLetterSpacing,
783
- siblingFontWeight, siblingColor,
784
- } = opts;
785
- if (headingTag !== 'h1') return [];
786
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
787
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
788
- // jsdom can resolve — the computed value comes back as "2em" or
789
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
790
- // on virtually every Tailwind v4 / framework build. The other gates
791
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
792
- // tracked-caps) are tight enough to avoid false positives on non-
793
- // hero h1s — a tiny tan label directly above any h1 is the
794
- // antipattern regardless of how big the h1 ends up.
795
- if (!siblingTag) return [];
796
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
797
- // headings) — never an eyebrow.
798
- if (HEADING_TAGS.has(siblingTag)) return [];
799
-
800
- const text = (siblingText || '').trim();
801
- if (text.length < 2 || text.length > 60) return [];
802
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
803
-
804
- // Branch A: classic tracked-uppercase eyebrow.
805
- const isUppercased = siblingTextTransform === 'uppercase'
806
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
807
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
808
-
809
- // Branch B: modern accent-bold eyebrow — sentence case, low
810
- // tracking, but bold + accent-colored. The style choices changed;
811
- // the pattern is the same kicker-above-headline anti-pattern.
812
- const weight = Number(siblingFontWeight) || 400;
813
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
814
-
815
- if (!isClassicTracked && !isAccentBold) return [];
816
-
817
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
818
- const eyebrowSnippet = text.slice(0, 40);
819
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
820
- return [{
821
- id: 'hero-eyebrow-chip',
822
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
823
- }];
824
- }
825
-
826
- function checkRepeatedSectionKickers(opts) {
827
- const { candidates, minCount = 3 } = opts;
828
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
829
- return candidates.map(candidate => ({
830
- id: 'repeated-section-kickers',
831
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
832
- }));
833
- }
834
-
835
- const LAYOUT_TRANSITION_PROPS = new Set([
836
- 'width', 'height', 'padding', 'margin',
837
- 'max-height', 'max-width', 'min-height', 'min-width',
838
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
839
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
840
- ]);
841
-
842
- function checkMotion(opts) {
843
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
844
- if (SAFE_TAGS.has(tag)) return [];
845
- const findings = [];
846
-
847
- // --- Bounce/elastic easing ---
848
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
849
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
850
- }
851
- if (classList && /\banimate-bounce\b/.test(classList)) {
852
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
853
- }
854
-
855
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
856
- if (timingFunctions) {
857
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
858
- let m;
859
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
860
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
861
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
862
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
863
- break;
864
- }
865
- }
866
- }
867
-
868
- // --- Layout property transition ---
869
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
870
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
871
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
872
- if (layoutFound.length > 0) {
873
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
874
- }
875
- }
876
-
877
- return findings;
878
- }
879
-
880
- function checkGlow(opts) {
881
- const { boxShadow, effectiveBg } = opts;
882
- if (!boxShadow || boxShadow === 'none') return [];
883
- if (!effectiveBg) return [];
884
-
885
- // Only flag on dark backgrounds (luminance < 0.1)
886
- const bgLum = relativeLuminance(effectiveBg);
887
- if (bgLum >= 0.1) return [];
888
-
889
- // Split multiple shadows (commas not inside parentheses)
890
- const parts = boxShadow.split(/,(?![^(]*\))/);
891
- for (const shadow of parts) {
892
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
893
- if (!colorMatch) continue;
894
- const color = parseRgb(colorMatch[0]);
895
- if (!color || !hasChroma(color, 30)) continue;
896
-
897
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
898
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
899
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
900
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
901
- .map(m => parseFloat(m[1]));
902
-
903
- // Third value is blur (offset-x, offset-y, blur, [spread])
904
- if (pxVals.length >= 3 && pxVals[2] > 4) {
905
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
906
- }
907
- }
908
-
909
- return [];
910
- }
911
-
912
- /**
913
- * Regex-on-HTML checks shared between browser and Node page-level detection.
914
- * These don't need DOM access, just the raw HTML string.
915
- */
916
- function checkHtmlPatterns(html) {
917
- const findings = [];
918
-
919
- // --- Color ---
920
-
921
- // Pure black background
922
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
923
- if (pureBlackBgRe.test(html)) {
924
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
925
- }
926
-
927
- // AI color palette: purple/violet
928
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
929
- if (purpleHexRe.test(html)) {
930
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
931
- if (purpleTextRe.test(html)) {
932
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
933
- }
934
- }
935
-
936
- // Gradient text (background-clip: text + gradient)
937
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
938
- let gm;
939
- while ((gm = gradientRe.exec(html)) !== null) {
940
- const start = Math.max(0, gm.index - 200);
941
- const context = html.substring(start, gm.index + gm[0].length + 200);
942
- if (/gradient/i.test(context)) {
943
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
944
- break;
945
- }
946
- }
947
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
948
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
949
- }
950
-
951
- // --- Layout ---
952
-
953
- // Monotonous spacing
954
- const spacingValues = [];
955
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
956
- let sm;
957
- while ((sm = spacingRe.exec(html)) !== null) {
958
- const v = parseInt(sm[1], 10);
959
- if (v > 0 && v < 200) spacingValues.push(v);
960
- }
961
- const gapRe = /gap\s*:\s*(\d+)px/gi;
962
- while ((sm = gapRe.exec(html)) !== null) {
963
- spacingValues.push(parseInt(sm[1], 10));
964
- }
965
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
966
- while ((sm = twSpaceRe.exec(html)) !== null) {
967
- spacingValues.push(parseInt(sm[1], 10) * 4);
968
- }
969
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
970
- while ((sm = remSpacingRe.exec(html)) !== null) {
971
- const v = Math.round(parseFloat(sm[1]) * 16);
972
- if (v > 0 && v < 200) spacingValues.push(v);
973
- }
974
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
975
- if (roundedSpacing.length >= 10) {
976
- const counts = {};
977
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
978
- const maxCount = Math.max(...Object.values(counts));
979
- const dominantPct = maxCount / roundedSpacing.length;
980
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
981
- if (dominantPct > 0.6 && unique.length <= 3) {
982
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
983
- findings.push({
984
- id: 'monotonous-spacing',
985
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
986
- });
987
- }
988
- }
989
-
990
- // --- Motion ---
991
-
992
- // Bounce/elastic animation names
993
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
994
- if (bounceRe.test(html)) {
995
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
996
- }
997
-
998
- // Overshoot cubic-bezier
999
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
1000
- let bm;
1001
- while ((bm = bezierRe.exec(html)) !== null) {
1002
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
1003
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
1004
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
1005
- break;
1006
- }
1007
- }
1008
-
1009
- // Layout property transitions
1010
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
1011
- let tm;
1012
- while ((tm = transRe.exec(html)) !== null) {
1013
- const val = tm[1].toLowerCase();
1014
- if (/\ball\b/.test(val)) continue;
1015
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
1016
- if (found) {
1017
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
1018
- break;
1019
- }
1020
- }
1021
-
1022
- // --- Dark glow ---
1023
-
1024
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
1025
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
1026
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
1027
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
1028
- let shm;
1029
- while ((shm = shadowRe.exec(html)) !== null) {
1030
- const val = shm[1];
1031
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
1032
- if (!colorMatch) continue;
1033
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
1034
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
1035
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
1036
- if (pxVals.length >= 3 && pxVals[2] > 4) {
1037
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
1038
- break;
1039
- }
1040
- }
1041
- }
1042
-
1043
- return findings;
1044
- }
1045
-
1046
- // ─── Section 4: resolveBackground (unified) ─────────────────────────────────
1047
-
1048
- // Read the element's own background color, computed-style first, with a
1049
- // jsdom-friendly fallback that parses the inline `background:` shorthand
1050
- // from the raw style attribute. jsdom (~v29) does not decompose the
1051
- // shorthand into `backgroundColor`, so without this fallback the CLI silently
1052
- // returns null for any element styled via `background: rgb(...)` or
1053
- // `background: #abc`. Real browsers always decompose, so the fallback is
1054
- // a no-op there.
1055
- function readOwnBackgroundColor(el, computedStyle) {
1056
- const bg = parseRgb(computedStyle.backgroundColor);
1057
- if (IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
1058
- const rawStyle = el.getAttribute?.('style') || '';
1059
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
1060
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
1061
- if (!inlineBg) return bg;
1062
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
1063
- const fromRgb = parseRgb(inlineBg);
1064
- if (fromRgb) return fromRgb;
1065
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
1066
- if (hexMatch) {
1067
- const h = hexMatch[1];
1068
- if (h.length === 6) {
1069
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
1070
- }
1071
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
1072
- }
1073
- return bg;
1074
- }
1075
-
1076
- function resolveBackground(el, win, customPropMap) {
1077
- let current = el;
1078
- while (current && current.nodeType === 1) {
1079
- const style = IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
1080
- const bgImage = style.backgroundImage || '';
1081
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
1082
-
1083
- // Try the solid bg-color FIRST. If the element has both a solid color
1084
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
1085
- // radial-gradient(...)` for paper-grain texture), the solid color is the
1086
- // dominant visible surface for contrast purposes; the overlay is
1087
- // decorative. The old behavior bailed on any gradient ancestor, which
1088
- // caused massive false-positive contrast findings on grain-textured
1089
- // body backgrounds.
1090
- let bg = parseRgb(style.backgroundColor);
1091
- if (!IS_BROWSER && (!bg || bg.a < 0.1)) {
1092
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
1093
- // through customPropMap so Tailwind v4 color tokens become RGB.
1094
- if (customPropMap) {
1095
- bg = parseColorResolved(style.backgroundColor, customPropMap);
1096
- }
1097
- if (!bg || bg.a < 0.1) {
1098
- // Inline-style fallback. jsdom doesn't decompose background
1099
- // shorthand, so colors set via inline style are otherwise invisible.
1100
- const rawStyle = current.getAttribute?.('style') || '';
1101
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
1102
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
1103
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
1104
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
1105
- }
1106
- }
1107
- }
1108
-
1109
- if (bg && bg.a > 0.1) {
1110
- if (IS_BROWSER || bg.a >= 0.5) return bg;
1111
- }
1112
- // No solid bg-color at this level. If THIS level has a gradient/url
1113
- // with no underlying solid color we can read:
1114
- // • on body/html: assume white. Body-level gradients are almost
1115
- // always decorative texture (paper grain, noise) on top of a
1116
- // solid bg-color the page set via `background: var(--paper)`
1117
- // shorthand — which jsdom can't decompose into bg-color. The
1118
- // downstream gradient-stops fallback path produces catastrophic
1119
- // false positives in this case (gradient noise stops have
1120
- // accidental browns/blacks that look like card backgrounds).
1121
- // • on other elements: bail to null and let the caller fall back
1122
- // to gradient stops (gradient buttons / hero sections are real
1123
- // bgs worth checking against).
1124
- if (hasGradientOrUrl) {
1125
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
1126
- return { r: 255, g: 255, b: 255, a: 1 };
1127
- }
1128
- return null;
1129
- }
1130
- current = current.parentElement;
1131
- }
1132
- return { r: 255, g: 255, b: 255 };
1133
- }
1134
-
1135
- // Walk parents looking for a gradient background and return its color stops.
1136
- // Used as a fallback when resolveBackground() returns null because the
1137
- // effective background is a gradient (no single solid color to compare against).
1138
- function resolveGradientStops(el, win) {
1139
- let current = el;
1140
- while (current && current.nodeType === 1) {
1141
- const style = IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
1142
- const bgImage = style.backgroundImage || '';
1143
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
1144
- const stops = parseGradientColors(bgImage);
1145
- if (stops.length > 0) return stops;
1146
- }
1147
- if (!IS_BROWSER) {
1148
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
1149
- const rawStyle = current.getAttribute?.('style') || '';
1150
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
1151
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
1152
- const stops = parseGradientColors(bgMatch[1]);
1153
- if (stops.length > 0) return stops;
1154
- }
1155
- }
1156
- current = current.parentElement;
1157
- }
1158
- return null;
1159
- }
1160
-
1161
- // Parse a single CSS length token to pixels. Accepts "12px", "50%", a
1162
- // shorthand like "12px 4px" (uses the first value), or empty / null.
1163
- // Returns the pixel value, or null when the input is unparseable.
1164
- // Percentages convert against `widthPx` when one is supplied. Without a
1165
- // usable width (jsdom returns "auto" for many real-world elements,
1166
- // which parseFloat collapses to 0), fall back to the raw percentage
1167
- // number so callers gating on `> 0` (border-accent-on-rounded,
1168
- // isCardLike's hasRadius) still see a positive value, matching the
1169
- // original parseFloat("50%") === 50 behavior.
1170
- function parseRadiusToPx(value, widthPx) {
1171
- if (!value || typeof value !== 'string') return null;
1172
- const trimmed = value.trim();
1173
- if (!trimmed) return null;
1174
- const first = trimmed.split(/\s+/)[0];
1175
- const num = parseFloat(first);
1176
- if (Number.isNaN(num)) return null;
1177
- if (/%$/.test(first)) {
1178
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
1179
- return num;
1180
- }
1181
- return num;
1182
- }
1183
-
1184
- // jsdom from 29.0.2 onward returns "" for the `border-radius` shorthand
1185
- // in computed style and "0" for longhand reads when the source rule used
1186
- // the shorthand. The rule engine relied on parseFloat(style.borderRadius)
1187
- // to identify circular avatars (border-radius >= width/2) and rounded
1188
- // cards (border-radius > 0); both checks broke silently. This helper
1189
- // recovers the radius via a chain of fallbacks. Browsers resolve the
1190
- // shorthand correctly and exit on the first line.
1191
- function resolveBorderRadiusPx(el, style, widthPx, win) {
1192
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
1193
- if (fromComputed !== null) return fromComputed;
1194
-
1195
- if (IS_BROWSER || !win) return 0;
1196
-
1197
- const fromLonghand = parseRadiusToPx(style.borderTopLeftRadius, widthPx);
1198
- if (fromLonghand !== null && fromLonghand > 0) return fromLonghand;
1199
-
1200
- const fromInlineProp = parseRadiusToPx(el.style?.borderRadius, widthPx);
1201
- if (fromInlineProp !== null) return fromInlineProp;
1202
-
1203
- const rawStyle = el.getAttribute?.('style') || '';
1204
- const inlineMatch = rawStyle.match(/border-radius\s*:\s*([^;]+)/i);
1205
- if (inlineMatch) {
1206
- const fromRaw = parseRadiusToPx(inlineMatch[1].trim(), widthPx);
1207
- if (fromRaw !== null) return fromRaw;
1208
- }
1209
-
1210
- // Walk every stylesheet looking for matching rules. Take the maximum
1211
- // pixel value across all matches so a circle declaration overridden by
1212
- // a more specific rounded-square selector still registers as a circle
1213
- // for the exclusion check (better to under-flag than to false-positive
1214
- // on round avatars).
1215
- let max = 0;
1216
- const sheets = win.document?.styleSheets;
1217
- if (sheets) {
1218
- for (const sheet of sheets) {
1219
- let rules;
1220
- try { rules = sheet.cssRules || []; } catch { continue; }
1221
- for (const rule of rules) {
1222
- if (!rule.style || !rule.selectorText) continue;
1223
- let matches = false;
1224
- try { matches = el.matches(rule.selectorText); } catch { continue; }
1225
- if (!matches) continue;
1226
- const ruleValue = rule.style.borderRadius
1227
- || (rule.style.getPropertyValue && rule.style.getPropertyValue('border-radius'))
1228
- || rule.style.borderTopLeftRadius;
1229
- const px = parseRadiusToPx(ruleValue, widthPx);
1230
- if (px !== null && px > max) max = px;
1231
- }
1232
- }
1233
- }
1234
- return max;
1235
- }
1236
-
1237
- // ─── Section 5: Element Adapters ────────────────────────────────────────────
1238
-
1239
- // Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
1240
-
1241
- function checkElementBordersDOM(el) {
1242
- const tag = el.tagName.toLowerCase();
1243
- if (BORDER_SAFE_TAGS.has(tag)) return [];
1244
- const rect = el.getBoundingClientRect();
1245
- if (rect.width < 20 || rect.height < 20) return [];
1246
- const style = getComputedStyle(el);
1247
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
1248
- const widths = {}, colors = {};
1249
- for (const s of sides) {
1250
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
1251
- colors[s] = style[`border${s}Color`] || '';
1252
- }
1253
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
1254
- }
1255
-
1256
- function checkElementColorsDOM(el) {
1257
- const tag = el.tagName.toLowerCase();
1258
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
1259
- // includes the styled-button exception for <a> / <button> with their own
1260
- // opaque background. Bailing here would prevent that exception from firing.
1261
- const rect = el.getBoundingClientRect();
1262
- if (rect.width < 10 || rect.height < 10) return [];
1263
- const style = getComputedStyle(el);
1264
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
1265
- const hasDirectText = directText.trim().length > 0;
1266
- const effectiveBg = resolveBackground(el);
1267
- return checkColors({
1268
- tag,
1269
- textColor: parseRgb(style.color),
1270
- bgColor: readOwnBackgroundColor(el, style),
1271
- effectiveBg,
1272
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
1273
- fontSize: parseFloat(style.fontSize) || 16,
1274
- fontWeight: parseInt(style.fontWeight) || 400,
1275
- hasDirectText,
1276
- isEmojiOnly: isEmojiOnlyText(directText),
1277
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
1278
- bgImage: style.backgroundImage || '',
1279
- classList: el.getAttribute('class') || '',
1280
- });
1281
- }
1282
-
1283
- function checkElementIconTileDOM(el) {
1284
- const tag = el.tagName.toLowerCase();
1285
- if (!HEADING_TAGS.has(tag)) return [];
1286
- const sibling = el.previousElementSibling;
1287
- if (!sibling) return [];
1288
-
1289
- const sibRect = sibling.getBoundingClientRect();
1290
- const headRect = el.getBoundingClientRect();
1291
- const sibStyle = getComputedStyle(sibling);
1292
-
1293
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
1294
- // may contain an emoji/symbol character directly as its only text content
1295
- // (the "card-icon" pattern from many AI-generated demos).
1296
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
1297
- const iconRect = iconChild?.getBoundingClientRect();
1298
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
1299
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
1300
-
1301
- return checkIconTile({
1302
- headingTag: tag,
1303
- headingText: el.textContent || '',
1304
- headingTop: headRect.top,
1305
- siblingTag: sibling.tagName.toLowerCase(),
1306
- siblingWidth: sibRect.width,
1307
- siblingHeight: sibRect.height,
1308
- siblingBottom: sibRect.bottom,
1309
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
1310
- siblingBgImage: sibStyle.backgroundImage || '',
1311
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
1312
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
1313
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
1314
- iconChildWidth: iconRect?.width || 0,
1315
- });
1316
- }
1317
-
1318
- function checkElementItalicSerifDOM(el) {
1319
- const tag = el.tagName.toLowerCase();
1320
- if (tag !== 'h1' && tag !== 'h2') return [];
1321
- const style = getComputedStyle(el);
1322
- return checkItalicSerif({
1323
- tag,
1324
- fontStyle: style.fontStyle || '',
1325
- fontFamily: style.fontFamily || '',
1326
- fontSize: parseFloat(style.fontSize) || 0,
1327
- headingText: el.textContent || '',
1328
- });
1329
- }
1330
-
1331
- function checkElementHeroEyebrowDOM(el) {
1332
- const tag = el.tagName.toLowerCase();
1333
- if (tag !== 'h1') return [];
1334
- const sibling = el.previousElementSibling;
1335
- if (!sibling) return [];
1336
- const headStyle = getComputedStyle(el);
1337
- const sibStyle = getComputedStyle(sibling);
1338
- return checkHeroEyebrow({
1339
- headingTag: tag,
1340
- headingText: el.textContent || '',
1341
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
1342
- siblingTag: sibling.tagName.toLowerCase(),
1343
- siblingText: sibling.textContent || '',
1344
- siblingTextTransform: sibStyle.textTransform || '',
1345
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
1346
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
1347
- siblingFontWeight: sibStyle.fontWeight || '',
1348
- siblingColor: sibStyle.color || '',
1349
- });
1350
- }
1351
-
1352
- // Build a map of CSS custom properties declared on :root / :host / html.
1353
- // Used to resolve var(--X) refs that jsdom returns verbatim in
1354
- // getComputedStyle. Tailwind v4 routes every utility class through
1355
- // CSS vars (font-weight: var(--font-weight-bold), font-size:
1356
- // var(--text-xs), letter-spacing: var(--tracking-widest)), so without
1357
- // resolution every style-based check silently fails on Tailwind v4
1358
- // builds — the values come back as literal "var(--font-weight-bold)"
1359
- // strings and parseFloat returns NaN.
1360
- function buildCustomPropMap(document) {
1361
- const map = new Map();
1362
- let sheets;
1363
- try { sheets = Array.from(document.styleSheets || []); }
1364
- catch { return map; }
1365
- for (const sheet of sheets) {
1366
- let rules;
1367
- try { rules = Array.from(sheet.cssRules || []); }
1368
- catch { continue; }
1369
- for (const rule of rules) {
1370
- // Style rules only (type 1). Walk @media / @supports if present.
1371
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
1372
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
1373
- continue;
1374
- }
1375
- if (rule.type !== 1 /* STYLE_RULE */) continue;
1376
- const sel = rule.selectorText || '';
1377
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
1378
- const style = rule.style;
1379
- if (!style) continue;
1380
- for (let i = 0; i < style.length; i++) {
1381
- const prop = style[i];
1382
- if (!prop || !prop.startsWith('--')) continue;
1383
- const val = style.getPropertyValue(prop).trim();
1384
- if (val) map.set(prop, val);
1385
- }
1386
- }
1387
- }
1388
- return map;
1389
- }
1390
-
1391
- // Resolve var(--X[, fallback]) refs in a computed-style value string.
1392
- // Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
1393
- // the original string when no refs are present or the chain doesn't
1394
- // resolve. Safe to call on already-resolved values.
1395
- function resolveVarRefs(raw, customPropMap, depth = 0) {
1396
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
1397
- if (depth > 8) return raw;
1398
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
1399
- const v = customPropMap.get(name);
1400
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
1401
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
1402
- });
1403
- }
1404
-
1405
- // OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
1406
- // C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
1407
- // Needed because jsdom doesn't compute oklch() values — getComputedStyle
1408
- // returns the literal "oklch(...)" string. Without this, the entire
1409
- // Tailwind v4 color palette (which is OKLCH-based) is invisible to the
1410
- // detector's contrast / color checks.
1411
- function oklchToRgb(L, C, H) {
1412
- const hRad = (H * Math.PI) / 180;
1413
- const a = C * Math.cos(hRad);
1414
- const b = C * Math.sin(hRad);
1415
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
1416
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
1417
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
1418
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
1419
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
1420
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
1421
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
1422
- const enc = (x) => {
1423
- const c = Math.max(0, Math.min(1, x));
1424
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
1425
- };
1426
- return {
1427
- r: Math.round(enc(rLin) * 255),
1428
- g: Math.round(enc(gLin) * 255),
1429
- b: Math.round(enc(bLin) * 255),
1430
- a: 1,
1431
- };
1432
- }
1433
-
1434
- // Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
1435
- // Use this when the input might be any CSS color form; use plain parseRgb
1436
- // when you only expect computed rgb() values from real browsers.
1437
- function parseAnyColor(s) {
1438
- if (!s || typeof s !== 'string') return null;
1439
- const str = s.trim();
1440
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
1441
- let m;
1442
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
1443
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
1444
- m = str.match(/^#([0-9a-f]{3,8})$/i);
1445
- if (m) {
1446
- const h = m[1];
1447
- if (h.length === 3 || h.length === 4) {
1448
- return {
1449
- r: parseInt(h[0] + h[0], 16),
1450
- g: parseInt(h[1] + h[1], 16),
1451
- b: parseInt(h[2] + h[2], 16),
1452
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
1453
- };
1454
- }
1455
- if (h.length === 6 || h.length === 8) {
1456
- return {
1457
- r: parseInt(h.slice(0, 2), 16),
1458
- g: parseInt(h.slice(2, 4), 16),
1459
- b: parseInt(h.slice(4, 6), 16),
1460
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
1461
- };
1462
- }
1463
- }
1464
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
1465
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
1466
- // Match L (with optional %), then C and H separated permissively.
1467
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
1468
- if (m) {
1469
- const Lnum = parseFloat(m[1]);
1470
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
1471
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
1472
- }
1473
- return null;
1474
- }
1475
-
1476
- // Resolve var() refs in a color string (via customPropMap), then parse.
1477
- // Returns null on any failure. Used in jsdom-mode paths where
1478
- // getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
1479
- function parseColorResolved(str, customPropMap) {
1480
- if (!str) return null;
1481
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
1482
- return parseAnyColor(resolved);
1483
- }
1484
-
1485
- const REPEATED_KICKER_SKIP_SELECTOR = [
1486
- 'nav',
1487
- 'form',
1488
- 'table',
1489
- 'thead',
1490
- 'tbody',
1491
- 'tfoot',
1492
- 'figure',
1493
- 'figcaption',
1494
- 'ol',
1495
- 'ul',
1496
- 'li',
1497
- '[role="navigation"]',
1498
- '[aria-label*="breadcrumb" i]',
1499
- '[class*="breadcrumb" i]',
1500
- '[data-impeccable-allow-kickers]',
1501
- ].join(',');
1502
-
1503
- function cleanInlineText(el) {
1504
- return [...el.childNodes]
1505
- .filter(n => n.nodeType === 3)
1506
- .map(n => n.textContent)
1507
- .join(' ')
1508
- .replace(/\s+/g, ' ')
1509
- .trim();
1510
- }
1511
-
1512
- function isRepeatedKickerCandidate(opts) {
1513
- const {
1514
- headingTag,
1515
- headingText,
1516
- headingFontSize,
1517
- kickerTag,
1518
- kickerText,
1519
- kickerTextTransform,
1520
- kickerFontSize,
1521
- kickerLetterSpacing,
1522
- } = opts;
1523
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
1524
- if (!headingText || headingText.length < 3) return false;
1525
- if (!(headingFontSize >= 20)) return false;
1526
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
1527
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
1528
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
1529
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
1530
-
1531
- const isUppercased = kickerTextTransform === 'uppercase'
1532
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
1533
- if (!isUppercased) return false;
1534
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
1535
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
1536
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
1537
- return true;
1538
- }
1539
-
1540
- function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
1541
- const candidates = [];
1542
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
1543
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
1544
- const kicker = heading.previousElementSibling;
1545
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
1546
-
1547
- const headingStyle = getStyle(heading);
1548
- const kickerStyle = getStyle(kicker);
1549
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
1550
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
1551
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
1552
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
1553
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
1554
-
1555
- if (!isRepeatedKickerCandidate({
1556
- headingTag: heading.tagName.toLowerCase(),
1557
- headingText,
1558
- headingFontSize,
1559
- kickerTag: kicker.tagName.toLowerCase(),
1560
- kickerText,
1561
- kickerTextTransform: kickerStyle.textTransform || '',
1562
- kickerFontSize,
1563
- kickerLetterSpacing,
1564
- })) {
1565
- continue;
1566
- }
1567
-
1568
- candidates.push({
1569
- headingTag: heading.tagName.toLowerCase(),
1570
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
1571
- kickerText: kickerText.slice(0, 40),
1572
- });
1573
- }
1574
- return candidates;
1575
- }
1576
-
1577
- function checkRepeatedSectionKickersDOM() {
1578
- const candidates = collectRepeatedSectionKickerCandidates(
1579
- document,
1580
- (el) => getComputedStyle(el),
1581
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
1582
- );
1583
- return checkRepeatedSectionKickers({ candidates });
1584
- }
1585
-
1586
- function checkElementMotionDOM(el) {
1587
- const tag = el.tagName.toLowerCase();
1588
- if (SAFE_TAGS.has(tag)) return [];
1589
- const style = getComputedStyle(el);
1590
- return checkMotion({
1591
- tag,
1592
- transitionProperty: style.transitionProperty || '',
1593
- animationName: style.animationName || '',
1594
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
1595
- classList: el.getAttribute('class') || '',
1596
- });
1597
- }
1598
-
1599
- function checkElementGlowDOM(el) {
1600
- const tag = el.tagName.toLowerCase();
1601
- const style = getComputedStyle(el);
1602
- if (!style.boxShadow || style.boxShadow === 'none') return [];
1603
- // Use parent's background — glow radiates outward, so the surrounding context matters
1604
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
1605
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
1606
- if (!parentBg) {
1607
- // Gradient background — sample its colors to determine if it's dark
1608
- let cur = el.parentElement;
1609
- while (cur && cur.nodeType === 1) {
1610
- const bgImage = getComputedStyle(cur).backgroundImage || '';
1611
- const gradColors = parseGradientColors(bgImage);
1612
- if (gradColors.length > 0) {
1613
- // Average the gradient colors
1614
- const avg = { r: 0, g: 0, b: 0 };
1615
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
1616
- avg.r = Math.round(avg.r / gradColors.length);
1617
- avg.g = Math.round(avg.g / gradColors.length);
1618
- avg.b = Math.round(avg.b / gradColors.length);
1619
- parentBg = avg;
1620
- break;
1621
- }
1622
- cur = cur.parentElement;
1623
- }
1624
- }
1625
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
1626
- }
1627
-
1628
- function checkElementAIPaletteDOM(el) {
1629
- const style = getComputedStyle(el);
1630
- const findings = [];
1631
-
1632
- // Check gradient backgrounds for purple/violet or cyan
1633
- const bgImage = style.backgroundImage || '';
1634
- const gradColors = parseGradientColors(bgImage);
1635
- for (const c of gradColors) {
1636
- if (hasChroma(c, 50)) {
1637
- const hue = getHue(c);
1638
- if (hue >= 260 && hue <= 310) {
1639
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
1640
- break;
1641
- }
1642
- if (hue >= 160 && hue <= 200) {
1643
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
1644
- break;
1645
- }
1646
- }
1647
- }
1648
-
1649
- // Check for neon text (vivid cyan/purple color on dark background)
1650
- const textColor = parseRgb(style.color);
1651
- if (textColor && hasChroma(textColor, 80)) {
1652
- const hue = getHue(textColor);
1653
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
1654
- if (isAIPalette) {
1655
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
1656
- // Also check gradient parents
1657
- let effectiveBg = parentBg;
1658
- if (!effectiveBg) {
1659
- let cur = el.parentElement;
1660
- while (cur && cur.nodeType === 1) {
1661
- const gi = getComputedStyle(cur).backgroundImage || '';
1662
- const gc = parseGradientColors(gi);
1663
- if (gc.length > 0) {
1664
- const avg = { r: 0, g: 0, b: 0 };
1665
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
1666
- avg.r = Math.round(avg.r / gc.length);
1667
- avg.g = Math.round(avg.g / gc.length);
1668
- avg.b = Math.round(avg.b / gc.length);
1669
- effectiveBg = avg;
1670
- break;
1671
- }
1672
- cur = cur.parentElement;
1673
- }
1674
- }
1675
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
1676
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
1677
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
1678
- }
1679
- }
1680
- }
1681
-
1682
- return findings;
1683
- }
1684
-
1685
- const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
1686
-
1687
- // Resolve a CSS font-size value to pixels by walking up the parent chain.
1688
- // Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
1689
- // specified value verbatim — so for the Node path we walk parents ourselves.
1690
- function resolveFontSizePx(el, win) {
1691
- const chain = []; // raw font-size strings, leaf → root
1692
- let cur = el;
1693
- while (cur && cur.nodeType === 1) {
1694
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
1695
- chain.push(fs || '');
1696
- cur = cur.parentElement;
1697
- }
1698
- // Walk root → leaf, resolving each value relative to its parent context.
1699
- let px = 16; // root default
1700
- for (let i = chain.length - 1; i >= 0; i--) {
1701
- const v = chain[i];
1702
- if (!v || v === 'inherit') continue;
1703
- const num = parseFloat(v);
1704
- if (isNaN(num)) continue;
1705
- if (v.endsWith('px')) px = num;
1706
- else if (v.endsWith('rem')) px = num * 16;
1707
- else if (v.endsWith('em')) px = num * px;
1708
- else if (v.endsWith('%')) px = (num / 100) * px;
1709
- else px = num; // unitless — already resolved
1710
- }
1711
- return px;
1712
- }
1713
-
1714
- // Resolve a CSS length value (line-height, letter-spacing, etc.) given a
1715
- // known font-size context. Returns null for "normal" / unparseable values.
1716
- function resolveLengthPx(value, fontSizePx) {
1717
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
1718
- const num = parseFloat(value);
1719
- if (isNaN(num)) return null;
1720
- if (value.endsWith('px')) return num;
1721
- if (value.endsWith('rem')) return num * 16;
1722
- if (value.endsWith('em')) return num * fontSizePx;
1723
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
1724
- // Unitless line-height = multiplier, return px equivalent
1725
- return num * fontSizePx;
1726
- }
1727
-
1728
- // Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
1729
- // jsdom and the browser). Two checks (line-length, cramped-padding) gate on
1730
- // element rect dimensions, which jsdom can't compute — pass `rect: null` from
1731
- // the Node adapter to skip those.
1732
- //
1733
- // Both adapters resolve font-size, line-height and letter-spacing to pixels
1734
- // before calling this so the pure function only deals with numbers.
1735
- function checkQuality(opts) {
1736
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
1737
- const findings = [];
1738
- // Skip browser extension injected elements
1739
- const elId = el.id || '';
1740
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
1741
-
1742
- // --- Line length too long --- (browser-only: needs rect.width)
1743
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
1744
- const charsPerLine = rect.width / (fontSize * 0.5);
1745
- if (charsPerLine > lineMax + 5) {
1746
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
1747
- }
1748
- }
1749
-
1750
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
1751
- // Vertical and horizontal thresholds are independent because line-height
1752
- // already provides built-in vertical breathing room (the line box is taller
1753
- // than the cap height), but horizontal has no equivalent. Both scale with
1754
- // font-size — bigger text demands proportionally more padding.
1755
- // vertical: max(4px, fontSize × 0.3)
1756
- // horizontal: max(8px, fontSize × 0.5)
1757
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
1758
- const borders = {
1759
- top: parseFloat(style.borderTopWidth) || 0,
1760
- right: parseFloat(style.borderRightWidth) || 0,
1761
- bottom: parseFloat(style.borderBottomWidth) || 0,
1762
- left: parseFloat(style.borderLeftWidth) || 0,
1763
- };
1764
- const borderCount = Object.values(borders).filter(w => w > 0).length;
1765
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
1766
- if (borderCount >= 2 || hasBg) {
1767
- const vPads = [], hPads = [];
1768
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
1769
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
1770
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
1771
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
1772
-
1773
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
1774
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
1775
- const vThresh = Math.max(4, fontSize * 0.3);
1776
- const hThresh = Math.max(8, fontSize * 0.5);
1777
-
1778
- // Emit at most one finding per element — pick whichever axis is worse.
1779
- if (vMin < vThresh) {
1780
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
1781
- } else if (hMin < hThresh) {
1782
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
1783
- }
1784
- }
1785
- }
1786
-
1787
- // --- Body text touching viewport edge --- (browser-only: needs rect)
1788
- // Catches the failure mode where the agent ships body paragraphs
1789
- // with NO container providing horizontal padding — text bleeds
1790
- // directly to the viewport edge. Different from cramped-padding,
1791
- // which requires a colored/bordered container. Here the failure
1792
- // is the absence of the container entirely.
1793
- //
1794
- // Gate aggressively to avoid false positives:
1795
- // - <p> or <li> only (body content; not headings, not nav, not
1796
- // wrappers)
1797
- // - text > 40 chars (paragraph-like, not a label)
1798
- // - rect.width > 50% of viewport (real body, not a pull-quote)
1799
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
1800
- // touching the edge)
1801
- // - not inside <nav> or <header> (those legitimately bleed)
1802
- // - element itself has no background-color (intentional full-bleed
1803
- // sections set a bg-color and provide their own internal padding)
1804
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
1805
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
1806
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
1807
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
1808
- const widthRatio = rect.width / viewportWidth;
1809
- const leftClose = rect.left < 16;
1810
- const rightClose = rect.right > viewportWidth - 16;
1811
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
1812
- const which = leftClose && rightClose
1813
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
1814
- : leftClose
1815
- ? `left ${Math.round(rect.left)}px`
1816
- : `right ${Math.round(viewportWidth - rect.right)}px`;
1817
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
1818
- }
1819
- }
1820
-
1821
- // --- Tight line height ---
1822
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
1823
- if (lineHeightPx != null && fontSize > 0) {
1824
- const ratio = lineHeightPx / fontSize;
1825
- if (ratio > 0 && ratio < 1.3) {
1826
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
1827
- }
1828
- }
1829
- }
1830
-
1831
- // --- Justified text (without hyphens) ---
1832
- if (hasDirectText && style.textAlign === 'justify') {
1833
- const hyphens = style.hyphens || style.webkitHyphens || '';
1834
- if (hyphens !== 'auto') {
1835
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
1836
- }
1837
- }
1838
-
1839
- // --- Tiny body text ---
1840
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
1841
- if (hasDirectText && textLen > 20 && fontSize < 12) {
1842
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
1843
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
1844
- const isUppercase = style.textTransform === 'uppercase';
1845
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
1846
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
1847
- }
1848
- }
1849
-
1850
- // --- All-caps body text ---
1851
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
1852
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
1853
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
1854
- }
1855
- }
1856
-
1857
- // --- Wide letter spacing on body text ---
1858
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
1859
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
1860
- const trackingEm = letterSpacingPx / fontSize;
1861
- if (trackingEm > 0.05) {
1862
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
1863
- }
1864
- }
1865
- }
1866
-
1867
- return findings;
1868
- }
1869
-
1870
- function checkElementQualityDOM(el) {
1871
- const tag = el.tagName.toLowerCase();
1872
- const style = getComputedStyle(el);
1873
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
1874
- const textLen = el.textContent?.trim().length || 0;
1875
- // Browser getComputedStyle resolves everything to px — direct parseFloat
1876
- // works.
1877
- const fontSize = parseFloat(style.fontSize) || 16;
1878
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
1879
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
1880
- const rect = el.getBoundingClientRect();
1881
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
1882
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
1883
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
1884
- }
1885
-
1886
- // Pure page-level skipped-heading walk. Takes a Document so it works in both
1887
- // the browser and jsdom.
1888
- function checkPageQualityFromDoc(doc) {
1889
- const findings = [];
1890
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
1891
- let prevLevel = 0;
1892
- let prevText = '';
1893
- for (const h of headings) {
1894
- const level = parseInt(h.tagName[1]);
1895
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
1896
- if (prevLevel > 0 && level > prevLevel + 1) {
1897
- findings.push({
1898
- id: 'skipped-heading',
1899
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
1900
- });
1901
- }
1902
- prevLevel = level;
1903
- prevText = text;
1904
- }
1905
- return findings;
1906
- }
1907
-
1908
- // Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
1909
- function checkPageQualityDOM() {
1910
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
1911
- }
1912
-
1913
- // Node adapters — take pre-extracted jsdom computed style
1914
-
1915
- // jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
1916
- // CSS length the rule needs ourselves (walking the parent chain for
1917
- // font-size inheritance), and pass `rect: null` to skip the two rules that
1918
- // genuinely need element rects (line-length, cramped-padding).
1919
- function checkElementQuality(el, style, tag, window) {
1920
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
1921
- const textLen = el.textContent?.trim().length || 0;
1922
- const fontSize = resolveFontSizePx(el, window);
1923
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
1924
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
1925
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
1926
- }
1927
-
1928
- function checkElementBorders(tag, style, overrides, resolvedRadius) {
1929
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
1930
- const widths = {}, colors = {};
1931
- for (const s of sides) {
1932
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
1933
- colors[s] = style[`border${s}Color`] || '';
1934
- // jsdom silently drops any border shorthand containing var(), leaving
1935
- // both width and color empty on the computed style. When the detectHtml
1936
- // pre-pass pulled a resolved value off the rule, use it to fill in the
1937
- // missing side so the side-tab check can run. Real browsers resolve
1938
- // var() natively, so this fallback is a no-op in the browser path.
1939
- if (widths[s] === 0 && overrides && overrides[s]) {
1940
- widths[s] = overrides[s].width;
1941
- colors[s] = overrides[s].color;
1942
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
1943
- // Longhand case: jsdom kept the width but left the color as the
1944
- // literal `var(...)` string. Substitute the resolved color.
1945
- colors[s] = overrides[s].color;
1946
- }
1947
- }
1948
- // resolvedRadius lets the caller pre-resolve the radius via
1949
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
1950
- // shorthand serialization. Falls back to the computed value for tests
1951
- // and browser callers that don't pre-resolve.
1952
- const radius = resolvedRadius != null
1953
- ? resolvedRadius
1954
- : (parseFloat(style.borderRadius) || 0);
1955
- return checkBorders(tag, widths, colors, radius);
1956
- }
1957
-
1958
- function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
1959
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
1960
- const hasDirectText = directText.trim().length > 0;
1961
-
1962
- const effectiveBg = resolveBackground(el, window, customPropMap);
1963
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
1964
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
1965
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
1966
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
1967
- if (!textColor) textColor = parseRgb(style.color);
1968
-
1969
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
1970
- // blue }` at high specificity. The page's `a { color: inherit }` rule
1971
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
1972
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
1973
- // When the page declares the inherit rule AND we see jsdom's default
1974
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
1975
- // use its color instead.
1976
- if (
1977
- hasAnchorInheritRule &&
1978
- textColor &&
1979
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
1980
- (tag === 'a' || el.closest?.('a'))
1981
- ) {
1982
- let cur = el.parentElement;
1983
- while (cur && cur.tagName !== 'HTML') {
1984
- if (cur.tagName !== 'A') {
1985
- const ps = window.getComputedStyle(cur);
1986
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
1987
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
1988
- textColor = inh;
1989
- break;
1990
- }
1991
- }
1992
- cur = cur.parentElement;
1993
- }
1994
- }
1995
-
1996
- return checkColors({
1997
- tag,
1998
- textColor,
1999
- bgColor: readOwnBackgroundColor(el, style),
2000
- effectiveBg,
2001
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
2002
- fontSize: parseFloat(style.fontSize) || 16,
2003
- fontWeight: parseInt(style.fontWeight) || 400,
2004
- hasDirectText,
2005
- isEmojiOnly: isEmojiOnlyText(directText),
2006
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
2007
- bgImage: style.backgroundImage || '',
2008
- classList: el.getAttribute?.('class') || el.className || '',
2009
- });
2010
- }
2011
-
2012
- function checkElementIconTile(el, tag, window) {
2013
- if (!HEADING_TAGS.has(tag)) return [];
2014
- const sibling = el.previousElementSibling;
2015
- if (!sibling) return [];
2016
-
2017
- const sibStyle = window.getComputedStyle(sibling);
2018
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
2019
- const sibWidth = parseFloat(sibStyle.width) || 0;
2020
- const sibHeight = parseFloat(sibStyle.height) || 0;
2021
-
2022
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
2023
- let iconWidth = 0;
2024
- if (iconChild) {
2025
- const iconStyle = window.getComputedStyle(iconChild);
2026
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
2027
- }
2028
- // Or: tile contains an emoji/symbol character directly as its only content
2029
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
2030
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
2031
-
2032
- return checkIconTile({
2033
- headingTag: tag,
2034
- headingText: el.textContent || '',
2035
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
2036
- siblingTag: sibling.tagName.toLowerCase(),
2037
- siblingWidth: sibWidth,
2038
- siblingHeight: sibHeight,
2039
- siblingBottom: 0,
2040
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
2041
- siblingBgImage: sibStyle.backgroundImage || '',
2042
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
2043
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
2044
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
2045
- iconChildWidth: iconWidth,
2046
- });
2047
- }
2048
-
2049
- function checkElementItalicSerif(el, style, tag) {
2050
- if (tag !== 'h1' && tag !== 'h2') return [];
2051
- return checkItalicSerif({
2052
- tag,
2053
- fontStyle: style.fontStyle || '',
2054
- fontFamily: style.fontFamily || '',
2055
- fontSize: parseFloat(style.fontSize) || 0,
2056
- headingText: el.textContent || '',
2057
- });
2058
- }
2059
-
2060
- function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
2061
- if (tag !== 'h1') return [];
2062
- const sibling = el.previousElementSibling;
2063
- if (!sibling) return [];
2064
- const sibStyle = window.getComputedStyle(sibling);
2065
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
2066
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
2067
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
2068
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
2069
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
2070
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
2071
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
2072
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
2073
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
2074
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
2075
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
2076
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
2077
- return checkHeroEyebrow({
2078
- headingTag: tag,
2079
- headingText: el.textContent || '',
2080
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
2081
- siblingTag: sibling.tagName.toLowerCase(),
2082
- siblingText: sibling.textContent || '',
2083
- siblingTextTransform: sibStyle.textTransform || '',
2084
- siblingFontSize,
2085
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
2086
- siblingFontWeight: fontWeightRaw || '',
2087
- siblingColor: colorRaw || '',
2088
- });
2089
- }
2090
-
2091
- function checkRepeatedSectionKickersFromDoc(doc, win) {
2092
- const candidates = collectRepeatedSectionKickerCandidates(
2093
- doc,
2094
- (el) => win.getComputedStyle(el),
2095
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
2096
- );
2097
- return checkRepeatedSectionKickers({ candidates });
2098
- }
2099
-
2100
- function checkElementMotion(tag, style) {
2101
- return checkMotion({
2102
- tag,
2103
- transitionProperty: style.transitionProperty || '',
2104
- animationName: style.animationName || '',
2105
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
2106
- classList: '',
2107
- });
2108
- }
2109
-
2110
- function checkElementGlow(tag, style, effectiveBg) {
2111
- if (!style.boxShadow || style.boxShadow === 'none') return [];
2112
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
2113
- }
2114
-
2115
- // ─── Section 6: Page-Level Checks ───────────────────────────────────────────
2116
-
2117
- // Browser page-level checks — use document/getComputedStyle globals
2118
-
2119
- function checkTypography() {
2120
- const findings = [];
2121
-
2122
- // Walk actual text-bearing elements and tally font usage by *computed style*.
2123
- // This is much more accurate than scanning CSS rules — it ignores rules that
2124
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
2125
- // anti-patterns), and counts what the user actually sees.
2126
- const fontUsage = new Map(); // primary font name → count of elements
2127
- let totalTextElements = 0;
2128
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
2129
- // Skip impeccable's own elements
2130
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
2131
- // Only count elements that actually have visible direct text
2132
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
2133
- if (!hasText) continue;
2134
- const style = getComputedStyle(el);
2135
- const ff = style.fontFamily;
2136
- if (!ff) continue;
2137
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
2138
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
2139
- if (!primary) continue;
2140
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
2141
- totalTextElements++;
2142
- }
2143
-
2144
- if (totalTextElements >= 20) {
2145
- // A font is "primary" if it's used by at least 15% of text elements
2146
- const PRIMARY_THRESHOLD = 0.15;
2147
- for (const [font, count] of fontUsage) {
2148
- const share = count / totalTextElements;
2149
- if (share < PRIMARY_THRESHOLD) continue;
2150
- if (!OVERUSED_FONTS.has(font)) continue;
2151
- if (isBrandFontOnOwnDomain(font)) continue;
2152
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
2153
- }
2154
-
2155
- // Single-font check: only one distinct primary font across all text
2156
- if (fontUsage.size === 1) {
2157
- const only = [...fontUsage.keys()][0];
2158
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
2159
- }
2160
- }
2161
-
2162
- const sizes = new Set();
2163
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
2164
- const fs = parseFloat(getComputedStyle(el).fontSize);
2165
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
2166
- }
2167
- if (sizes.size >= 3) {
2168
- const sorted = [...sizes].sort((a, b) => a - b);
2169
- const ratio = sorted[sorted.length - 1] / sorted[0];
2170
- if (ratio < 2.0) {
2171
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
2172
- }
2173
- }
2174
-
2175
- return findings;
2176
- }
2177
-
2178
- function isCardLikeDOM(el) {
2179
- const tag = el.tagName.toLowerCase();
2180
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
2181
- const style = getComputedStyle(el);
2182
- const cls = el.getAttribute('class') || '';
2183
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
2184
- const hasBorder = /\bborder\b/.test(cls);
2185
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
2186
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
2187
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
2188
- }
2189
-
2190
- function checkLayout() {
2191
- const findings = [];
2192
- const flaggedEls = new Set();
2193
-
2194
- for (const el of document.querySelectorAll('*')) {
2195
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
2196
- const cls = el.getAttribute('class') || '';
2197
- const style = getComputedStyle(el);
2198
- if (style.position === 'absolute' || style.position === 'fixed') continue;
2199
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
2200
- if ((el.textContent?.trim().length || 0) < 10) continue;
2201
- const rect = el.getBoundingClientRect();
2202
- if (rect.width < 50 || rect.height < 30) continue;
2203
-
2204
- let parent = el.parentElement;
2205
- while (parent) {
2206
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
2207
- parent = parent.parentElement;
2208
- }
2209
- }
2210
-
2211
- for (const el of flaggedEls) {
2212
- let isAncestor = false;
2213
- for (const other of flaggedEls) {
2214
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
2215
- }
2216
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
2217
- }
2218
-
2219
- return findings;
2220
- }
2221
-
2222
- // Node page-level checks — take document/window as parameters
2223
-
2224
- function checkPageTypography(doc, win) {
2225
- const findings = [];
2226
-
2227
- const fonts = new Set();
2228
- const overusedFound = new Set();
2229
-
2230
- for (const sheet of doc.styleSheets) {
2231
- let rules;
2232
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
2233
- if (!rules) continue;
2234
- for (const rule of rules) {
2235
- if (rule.type !== 1) continue;
2236
- const ff = rule.style?.fontFamily;
2237
- if (!ff) continue;
2238
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
2239
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
2240
- if (primary) {
2241
- fonts.add(primary);
2242
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
2243
- }
2244
- }
2245
- }
2246
-
2247
- // Check Google Fonts links in HTML
2248
- const html = doc.documentElement?.outerHTML || '';
2249
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
2250
- let m;
2251
- while ((m = gfRe.exec(html)) !== null) {
2252
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
2253
- for (const f of families) {
2254
- fonts.add(f);
2255
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
2256
- }
2257
- }
2258
-
2259
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
2260
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
2261
- let fm;
2262
- while ((fm = ffRe.exec(html)) !== null) {
2263
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
2264
- if (f && !GENERIC_FONTS.has(f)) {
2265
- fonts.add(f);
2266
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
2267
- }
2268
- }
2269
- }
2270
-
2271
- for (const font of overusedFound) {
2272
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
2273
- }
2274
-
2275
- // Single font
2276
- if (fonts.size === 1) {
2277
- const els = doc.querySelectorAll('*');
2278
- if (els.length >= 20) {
2279
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
2280
- }
2281
- }
2282
-
2283
- // Flat type hierarchy
2284
- const sizes = new Set();
2285
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
2286
- for (const el of textEls) {
2287
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
2288
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
2289
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
2290
- }
2291
- if (sizes.size >= 3) {
2292
- const sorted = [...sizes].sort((a, b) => a - b);
2293
- const ratio = sorted[sorted.length - 1] / sorted[0];
2294
- if (ratio < 2.0) {
2295
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
2296
- }
2297
- }
2298
-
2299
- return findings;
2300
- }
2301
-
2302
- function isCardLike(el, win) {
2303
- const tag = el.tagName.toLowerCase();
2304
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
2305
-
2306
- const style = win.getComputedStyle(el);
2307
- const rawStyle = el.getAttribute?.('style') || '';
2308
- const cls = el.getAttribute?.('class') || '';
2309
-
2310
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
2311
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
2312
- const hasBorder = /\bborder\b/.test(cls);
2313
- const widthPx = parseFloat(style.width) || 0;
2314
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
2315
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
2316
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
2317
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
2318
-
2319
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
2320
- }
2321
-
2322
- function checkPageLayout(doc, win) {
2323
- const findings = [];
2324
-
2325
- // Nested cards
2326
- const allEls = doc.querySelectorAll('*');
2327
- const flaggedEls = new Set();
2328
- for (const el of allEls) {
2329
- if (!isCardLike(el, win)) continue;
2330
- if (flaggedEls.has(el)) continue;
2331
-
2332
- const tag = el.tagName.toLowerCase();
2333
- const cls = el.getAttribute?.('class') || '';
2334
- const rawStyle = el.getAttribute?.('style') || '';
2335
-
2336
- if (['pre', 'code'].includes(tag)) continue;
2337
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
2338
- if ((el.textContent?.trim().length || 0) < 10) continue;
2339
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
2340
-
2341
- // Walk up to find card-like ancestor
2342
- let parent = el.parentElement;
2343
- while (parent) {
2344
- if (isCardLike(parent, win)) {
2345
- flaggedEls.add(el);
2346
- break;
2347
- }
2348
- parent = parent.parentElement;
2349
- }
2350
- }
2351
-
2352
- // Only report innermost nested cards
2353
- for (const el of flaggedEls) {
2354
- let isAncestorOfFlagged = false;
2355
- for (const other of flaggedEls) {
2356
- if (other !== el && el.contains(other)) {
2357
- isAncestorOfFlagged = true;
2358
- break;
2359
- }
2360
- }
2361
- if (!isAncestorOfFlagged) {
2362
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
2363
- }
2364
- }
2365
-
2366
- // Everything centered
2367
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
2368
- let centeredCount = 0;
2369
- let totalText = 0;
2370
- for (const el of textEls) {
2371
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
2372
- if (!hasDirectText) continue;
2373
- totalText++;
2374
-
2375
- let cur = el;
2376
- let isCentered = false;
2377
- while (cur && cur.nodeType === 1) {
2378
- const rawStyle = cur.getAttribute?.('style') || '';
2379
- const cls = cur.getAttribute?.('class') || '';
2380
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
2381
- isCentered = true;
2382
- break;
2383
- }
2384
- if (cur.tagName === 'BODY') break;
2385
- cur = cur.parentElement;
2386
- }
2387
- if (isCentered) centeredCount++;
2388
- }
2389
-
2390
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
2391
- findings.push({
2392
- id: 'everything-centered',
2393
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
2394
- });
2395
- }
2396
-
2397
- return findings;
2398
- }
2399
-
2400
- // ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
2401
-
2402
- if (IS_BROWSER) {
2403
- // Detect extension mode via the script tag's data attribute or the document element fallback.
2404
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
2405
- const _myScript = document.currentScript;
2406
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
2407
- || document.documentElement.dataset.impeccableExtension === 'true';
2408
-
2409
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
2410
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
2411
- const LABEL_BG = BRAND_COLOR;
2412
- const OUTLINE_COLOR = BRAND_COLOR;
2413
-
2414
- // Inject hover styles via CSS (more reliable than JS event listeners)
2415
- const styleEl = document.createElement('style');
2416
- styleEl.textContent = `
2417
- @keyframes impeccable-reveal {
2418
- from { opacity: 0; }
2419
- to { opacity: 1; }
2420
- }
2421
- .impeccable-overlay:not(.impeccable-banner) {
2422
- pointer-events: none;
2423
- outline: 2px solid ${OUTLINE_COLOR};
2424
- border-radius: 4px;
2425
- transition: outline-color 0.15s ease;
2426
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
2427
- animation-play-state: paused;
2428
- border-top-left-radius: 0;
2429
- }
2430
- .impeccable-overlay.impeccable-visible {
2431
- animation-play-state: running;
2432
- }
2433
- .impeccable-overlay.impeccable-hover {
2434
- outline-color: ${BRAND_COLOR_HOVER};
2435
- z-index: 100001 !important;
2436
- }
2437
- .impeccable-overlay.impeccable-hover .impeccable-label {
2438
- background: ${BRAND_COLOR_HOVER};
2439
- }
2440
- .impeccable-overlay.impeccable-spotlight {
2441
- z-index: 100002 !important;
2442
- }
2443
- .impeccable-overlay.impeccable-spotlight-dimmed {
2444
- opacity: 0.15 !important;
2445
- animation: none !important;
2446
- filter: blur(3px);
2447
- }
2448
- .impeccable-spotlight-backdrop {
2449
- position: fixed;
2450
- top: 0; left: 0; right: 0; bottom: 0;
2451
- backdrop-filter: blur(3px) brightness(0.6);
2452
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
2453
- pointer-events: none;
2454
- z-index: 99998;
2455
- opacity: 0;
2456
- outline: none !important;
2457
- animation: none !important;
2458
- }
2459
- .impeccable-spotlight-backdrop.impeccable-visible {
2460
- opacity: 1;
2461
- }
2462
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
2463
- display: none !important;
2464
- }
2465
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
2466
- display: none !important;
2467
- }
2468
- `;
2469
- (document.head || document.documentElement).appendChild(styleEl);
2470
-
2471
- // Spotlight backdrop element (created lazily on first use)
2472
- let spotlightBackdrop = null;
2473
- let spotlightTarget = null;
2474
- let spotlightTimer = null;
2475
-
2476
- function getSpotlightBackdrop() {
2477
- if (!spotlightBackdrop) {
2478
- spotlightBackdrop = document.createElement('div');
2479
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
2480
- document.body.appendChild(spotlightBackdrop);
2481
- }
2482
- return spotlightBackdrop;
2483
- }
2484
-
2485
- function updateSpotlightClipPath() {
2486
- if (!spotlightBackdrop || !spotlightTarget) return;
2487
- const r = spotlightTarget.getBoundingClientRect();
2488
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
2489
- const inset = 4;
2490
- const radius = 6; // outline border-radius (4) + outline width (2)
2491
- const x1 = r.left - inset;
2492
- const y1 = r.top - inset;
2493
- const x2 = r.right + inset;
2494
- const y2 = r.bottom + inset;
2495
- const vw = window.innerWidth;
2496
- const vh = window.innerHeight;
2497
- // Outer rect + rounded inner rect (evenodd creates a hole)
2498
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
2499
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
2500
- }
2501
-
2502
- function showSpotlight(target) {
2503
- if (!target || !target.getBoundingClientRect) return;
2504
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
2505
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
2506
- spotlightTarget = target;
2507
- return;
2508
- }
2509
- spotlightTarget = target;
2510
- const bd = getSpotlightBackdrop();
2511
- updateSpotlightClipPath();
2512
- bd.classList.add('impeccable-visible');
2513
- }
2514
-
2515
- function hideSpotlight() {
2516
- spotlightTarget = null;
2517
- if (spotlightTimer) { clearTimeout(spotlightTimer); spotlightTimer = null; }
2518
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
2519
- }
2520
-
2521
- function isInViewport(el) {
2522
- const r = el.getBoundingClientRect();
2523
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
2524
- }
2525
-
2526
- // Reposition spotlight on scroll/resize
2527
- window.addEventListener('scroll', () => {
2528
- if (spotlightTarget) updateSpotlightClipPath();
2529
- }, { passive: true });
2530
- window.addEventListener('resize', () => {
2531
- if (spotlightTarget) updateSpotlightClipPath();
2532
- });
2533
-
2534
- const overlays = [];
2535
- const TYPE_LABELS = {};
2536
- const RULE_CATEGORY = {};
2537
- for (const ap of ANTIPATTERNS) {
2538
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
2539
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
2540
- }
2541
-
2542
- function isInFixedContext(el) {
2543
- let p = el;
2544
- while (p && p !== document.body) {
2545
- if (getComputedStyle(p).position === 'fixed') return true;
2546
- p = p.parentElement;
2547
- }
2548
- return false;
2549
- }
2550
-
2551
- function positionOverlay(overlay) {
2552
- const el = overlay._targetEl;
2553
- if (!el) return;
2554
- const rect = el.getBoundingClientRect();
2555
- if (overlay._isFixed) {
2556
- // Viewport-relative coords for fixed targets
2557
- overlay.style.top = `${rect.top - 2}px`;
2558
- overlay.style.left = `${rect.left - 2}px`;
2559
- } else {
2560
- // Document-relative coords for normal targets
2561
- overlay.style.top = `${rect.top + scrollY - 2}px`;
2562
- overlay.style.left = `${rect.left + scrollX - 2}px`;
2563
- }
2564
- overlay.style.width = `${rect.width + 4}px`;
2565
- overlay.style.height = `${rect.height + 4}px`;
2566
- }
2567
-
2568
- function repositionOverlays() {
2569
- for (const o of overlays) {
2570
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
2571
- // Skip overlays whose target is currently hidden (display: none on the overlay)
2572
- if (o.style.display === 'none') continue;
2573
- positionOverlay(o);
2574
- }
2575
- }
2576
-
2577
- let resizeRAF;
2578
- const onResize = () => {
2579
- cancelAnimationFrame(resizeRAF);
2580
- resizeRAF = requestAnimationFrame(repositionOverlays);
2581
- };
2582
- window.addEventListener('resize', onResize);
2583
- // Reposition on scroll too -- catches sticky/parallax shifts
2584
- window.addEventListener('scroll', onResize, { passive: true });
2585
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
2586
- if (typeof ResizeObserver !== 'undefined') {
2587
- const bodyResizeObserver = new ResizeObserver(onResize);
2588
- bodyResizeObserver.observe(document.body);
2589
- }
2590
-
2591
- // Track target element visibility via IntersectionObserver.
2592
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
2593
- // while display:none / closed <details> / hidden modals etc. do not.
2594
- // This is event-driven -- no polling needed.
2595
- let overlayIndex = 0;
2596
- const visibilityObserver = new IntersectionObserver((entries) => {
2597
- for (const entry of entries) {
2598
- const overlay = entry.target._impeccableOverlay;
2599
- if (!overlay) continue;
2600
- if (entry.isIntersecting) {
2601
- overlay.style.display = '';
2602
- positionOverlay(overlay);
2603
- if (!overlay._revealed) {
2604
- overlay._revealed = true;
2605
- if (firstScanDone) {
2606
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
2607
- overlay.style.animation = 'none';
2608
- } else {
2609
- // Initial scan: staggered cascade reveal
2610
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
2611
- }
2612
- requestAnimationFrame(() => {
2613
- overlay.classList.add('impeccable-visible');
2614
- if (overlay._checkLabel) overlay._checkLabel();
2615
- });
2616
- }
2617
- } else {
2618
- overlay.style.display = 'none';
2619
- }
2620
- }
2621
- }, { rootMargin: '99999px' });
2622
-
2623
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
2624
- // Listens at document level so it catches transitions on ancestor elements
2625
- // (the transform may be on a parent, not the flagged element itself).
2626
- document.addEventListener('transitionend', (e) => {
2627
- if (e.propertyName !== 'transform') return;
2628
- for (const o of overlays) {
2629
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
2630
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
2631
- positionOverlay(o);
2632
- }
2633
- }
2634
- });
2635
-
2636
- const highlight = function(el, findings) {
2637
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
2638
-
2639
- const fixed = isInFixedContext(el);
2640
- const rect = el.getBoundingClientRect();
2641
- const outline = document.createElement('div');
2642
- outline.className = 'impeccable-overlay';
2643
- outline._targetEl = el;
2644
- outline._isFixed = fixed;
2645
- Object.assign(outline.style, {
2646
- position: fixed ? 'fixed' : 'absolute',
2647
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
2648
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
2649
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
2650
- zIndex: '99999', boxSizing: 'border-box',
2651
- });
2652
-
2653
- // Build per-finding label entries: ✦ prefix for slop
2654
- const entries = findings.map(f => {
2655
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
2656
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
2657
- return { name: prefix + name, detail: f.detail || f.snippet };
2658
- });
2659
- const allText = entries.map(e => e.name).join(', ');
2660
-
2661
- const label = document.createElement('div');
2662
- label.className = 'impeccable-label';
2663
- Object.assign(label.style, {
2664
- position: 'absolute', bottom: '100%', left: '-2px',
2665
- display: 'flex', alignItems: 'center',
2666
- whiteSpace: 'nowrap',
2667
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
2668
- color: 'white', lineHeight: '14px',
2669
- background: LABEL_BG,
2670
- fontFamily: 'system-ui, sans-serif',
2671
- borderRadius: '4px 4px 0 0',
2672
- });
2673
-
2674
- const textSpan = document.createElement('span');
2675
- textSpan.style.padding = '3px 8px';
2676
- textSpan.textContent = allText;
2677
- label.appendChild(textSpan);
2678
-
2679
- // State for cycling mode
2680
- let cycleMode = false;
2681
- let cycleIndex = 0;
2682
- let isHovered = false;
2683
- let prevBtn, nextBtn;
2684
-
2685
- function updateCycleText() {
2686
- const e = entries[cycleIndex];
2687
- textSpan.textContent = isHovered ? e.detail : e.name;
2688
- }
2689
-
2690
- function enableCycleMode() {
2691
- if (cycleMode || entries.length < 2) return;
2692
- cycleMode = true;
2693
-
2694
- const btnStyle = {
2695
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
2696
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
2697
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
2698
- pointerEvents: 'auto',
2699
- };
2700
-
2701
- const navGroup = document.createElement('span');
2702
- Object.assign(navGroup.style, {
2703
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
2704
- });
2705
-
2706
- prevBtn = document.createElement('button');
2707
- prevBtn.textContent = '\u2039';
2708
- Object.assign(prevBtn.style, btnStyle);
2709
- prevBtn.style.paddingLeft = '6px';
2710
- prevBtn.addEventListener('click', (e) => {
2711
- e.stopPropagation();
2712
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
2713
- updateCycleText();
2714
- });
2715
-
2716
- nextBtn = document.createElement('button');
2717
- nextBtn.textContent = '\u203A';
2718
- Object.assign(nextBtn.style, btnStyle);
2719
- nextBtn.style.paddingRight = '2px';
2720
- nextBtn.addEventListener('click', (e) => {
2721
- e.stopPropagation();
2722
- cycleIndex = (cycleIndex + 1) % entries.length;
2723
- updateCycleText();
2724
- });
2725
-
2726
- navGroup.appendChild(prevBtn);
2727
- navGroup.appendChild(nextBtn);
2728
- label.insertBefore(navGroup, textSpan);
2729
- textSpan.style.padding = '3px 8px 3px 4px';
2730
- updateCycleText();
2731
- }
2732
-
2733
- outline.appendChild(label);
2734
-
2735
- // Start hidden; the IntersectionObserver will show it once the target is rendered
2736
- outline.style.display = 'none';
2737
- outline._staggerIndex = overlayIndex++;
2738
- el._impeccableOverlay = outline;
2739
- visibilityObserver.observe(el);
2740
-
2741
- // After first paint, check label width vs outline
2742
- outline._checkLabel = () => {
2743
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
2744
- enableCycleMode();
2745
- }
2746
- };
2747
-
2748
- // Hover: show detail text, darken
2749
- el.addEventListener('mouseenter', () => {
2750
- isHovered = true;
2751
- outline.classList.add('impeccable-hover');
2752
- outline.style.outlineColor = BRAND_COLOR_HOVER;
2753
- label.style.background = BRAND_COLOR_HOVER;
2754
- if (cycleMode) {
2755
- updateCycleText();
2756
- } else {
2757
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
2758
- }
2759
- });
2760
- el.addEventListener('mouseleave', () => {
2761
- isHovered = false;
2762
- outline.classList.remove('impeccable-hover');
2763
- outline.style.outlineColor = '';
2764
- label.style.background = LABEL_BG;
2765
- if (cycleMode) {
2766
- updateCycleText();
2767
- } else {
2768
- textSpan.textContent = allText;
2769
- }
2770
- });
2771
-
2772
- document.body.appendChild(outline);
2773
- overlays.push(outline);
2774
- };
2775
-
2776
- const showPageBanner = function(findings) {
2777
- if (!findings.length) return;
2778
- const banner = document.createElement('div');
2779
- banner.className = 'impeccable-overlay impeccable-banner';
2780
- Object.assign(banner.style, {
2781
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
2782
- background: LABEL_BG, color: 'white',
2783
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
2784
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
2785
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
2786
- transform: 'translateY(-100%)',
2787
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
2788
- });
2789
- requestAnimationFrame(() => requestAnimationFrame(() => {
2790
- banner.style.transform = 'translateY(0)';
2791
- }));
2792
-
2793
- // Scrollable findings area
2794
- const scrollArea = document.createElement('div');
2795
- Object.assign(scrollArea.style, {
2796
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
2797
- display: 'flex', gap: '8px', alignItems: 'center',
2798
- padding: '0 12px', scrollSnapType: 'x mandatory',
2799
- scrollbarWidth: 'none',
2800
- });
2801
- for (const f of findings) {
2802
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
2803
- const tag = document.createElement('span');
2804
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
2805
- Object.assign(tag.style, {
2806
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
2807
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
2808
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
2809
- });
2810
- scrollArea.appendChild(tag);
2811
- }
2812
- banner.appendChild(scrollArea);
2813
-
2814
- // Controls area (only in standalone mode, not extension)
2815
- if (!EXTENSION_MODE) {
2816
- const controls = document.createElement('div');
2817
- Object.assign(controls.style, {
2818
- display: 'flex', alignItems: 'center', gap: '2px',
2819
- padding: '0 8px', flexShrink: '0',
2820
- });
2821
-
2822
- // Toggle visibility button
2823
- const toggle = document.createElement('button');
2824
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
2825
- toggle.title = 'Toggle overlay visibility';
2826
- Object.assign(toggle.style, {
2827
- background: 'none', border: 'none',
2828
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
2829
- opacity: '0.85', transition: 'opacity 0.15s',
2830
- });
2831
- let overlaysVisible = true;
2832
- toggle.addEventListener('click', () => {
2833
- overlaysVisible = !overlaysVisible;
2834
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
2835
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
2836
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
2837
- });
2838
- controls.appendChild(toggle);
2839
-
2840
- // Close button
2841
- const close = document.createElement('button');
2842
- close.textContent = '\u00d7';
2843
- close.title = 'Dismiss banner';
2844
- Object.assign(close.style, {
2845
- background: 'none', border: 'none',
2846
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
2847
- });
2848
- close.addEventListener('click', () => banner.remove());
2849
- controls.appendChild(close);
2850
-
2851
- banner.appendChild(controls);
2852
- }
2853
- document.body.appendChild(banner);
2854
- overlays.push(banner);
2855
- };
2856
-
2857
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
2858
- // These change between builds and produce brittle, ugly selectors.
2859
- function isLikelyHashedClass(c) {
2860
- if (!c) return true;
2861
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
2862
- if (/^_[\w-]{5,}$/.test(c)) return true;
2863
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
2864
- return false;
2865
- }
2866
-
2867
- function buildSelectorSegment(el) {
2868
- const tag = el.tagName.toLowerCase();
2869
- let sel = tag;
2870
-
2871
- if (el.classList && el.classList.length > 0) {
2872
- const classes = [...el.classList]
2873
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
2874
- .slice(0, 2);
2875
- if (classes.length > 0) {
2876
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
2877
- }
2878
- }
2879
-
2880
- // Disambiguate among siblings only if the parent has multiple matches
2881
- const parent = el.parentElement;
2882
- if (parent) {
2883
- try {
2884
- const matching = parent.querySelectorAll(':scope > ' + sel);
2885
- if (matching.length > 1) {
2886
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
2887
- const idx = sameType.indexOf(el) + 1;
2888
- sel += `:nth-of-type(${idx})`;
2889
- }
2890
- } catch {
2891
- const idx = [...parent.children].indexOf(el) + 1;
2892
- sel = `${tag}:nth-child(${idx})`;
2893
- }
2894
- }
2895
- return sel;
2896
- }
2897
-
2898
- function generateSelector(el) {
2899
- if (el === document.body) return 'body';
2900
- if (el === document.documentElement) return 'html';
2901
- if (el.id) return '#' + CSS.escape(el.id);
2902
-
2903
- const parts = [];
2904
- let current = el;
2905
- let depth = 0;
2906
- const MAX_DEPTH = 10;
2907
-
2908
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
2909
- parts.unshift(buildSelectorSegment(current));
2910
-
2911
- // Anchor on an ancestor's ID and stop walking up
2912
- if (current.id) {
2913
- parts[0] = '#' + CSS.escape(current.id);
2914
- break;
2915
- }
2916
-
2917
- // Stop as soon as the partial selector uniquely identifies the target
2918
- const trySelector = parts.join(' > ');
2919
- try {
2920
- const matches = document.querySelectorAll(trySelector);
2921
- if (matches.length === 1 && matches[0] === el) {
2922
- return trySelector;
2923
- }
2924
- } catch { /* invalid selector — keep walking */ }
2925
-
2926
- current = current.parentElement;
2927
- depth++;
2928
- }
2929
-
2930
- return parts.join(' > ');
2931
- }
2932
-
2933
- function isElementHidden(el) {
2934
- if (!el || el === document.body || el === document.documentElement) return false;
2935
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
2936
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
2937
- return el.offsetWidth === 0 && el.offsetHeight === 0;
2938
- }
2939
-
2940
- function serializeFindings(allFindings) {
2941
- return allFindings.map(({ el, findings }) => ({
2942
- selector: generateSelector(el),
2943
- tagName: el.tagName?.toLowerCase() || 'unknown',
2944
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
2945
- ? el.getBoundingClientRect().toJSON() : null,
2946
- isPageLevel: el === document.body || el === document.documentElement,
2947
- isHidden: isElementHidden(el),
2948
- findings: findings.map(f => {
2949
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
2950
- return {
2951
- type: f.type || f.id,
2952
- category: ap ? ap.category : 'quality',
2953
- severity: ap?.severity || 'warning',
2954
- detail: f.detail || f.snippet,
2955
- name: ap ? ap.name : (f.type || f.id),
2956
- description: ap ? ap.description : '',
2957
- };
2958
- }),
2959
- }));
2960
- }
2961
-
2962
- const printSummary = function(allFindings) {
2963
- if (allFindings.length === 0) {
2964
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
2965
- return;
2966
- }
2967
- console.group(
2968
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
2969
- 'color: oklch(60% 0.25 350); font-weight: bold'
2970
- );
2971
- for (const { el, findings } of allFindings) {
2972
- for (const f of findings) {
2973
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
2974
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
2975
- }
2976
- }
2977
- console.groupEnd();
2978
- };
2979
-
2980
- let firstScanDone = false;
2981
- const scan = function() {
2982
- for (const o of overlays) o.remove();
2983
- overlays.length = 0;
2984
- visibilityObserver.disconnect();
2985
- overlayIndex = 0;
2986
- const allFindings = [];
2987
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
2988
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
2989
-
2990
- for (const el of document.querySelectorAll('*')) {
2991
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
2992
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
2993
- // Skip browser extension elements (Claude, etc.)
2994
- const elId = el.id || '';
2995
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
2996
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
2997
- // These are inspector chrome, not part of the user's design.
2998
- if (el.closest('[id^="impeccable-live-"]')) continue;
2999
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
3000
- if (el === document.body || el === document.documentElement) continue;
3001
-
3002
- const findings = [
3003
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3004
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3005
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3006
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3007
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3008
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3009
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3010
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3011
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3012
- ].filter(f => _ruleOk(f.type));
3013
-
3014
- if (findings.length > 0) {
3015
- highlight(el, findings);
3016
- allFindings.push({ el, findings });
3017
- }
3018
- }
3019
-
3020
- const pageLevelFindings = [];
3021
-
3022
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
3023
- if (typoFindings.length > 0) {
3024
- pageLevelFindings.push(...typoFindings);
3025
- allFindings.push({ el: document.body, findings: typoFindings });
3026
- }
3027
-
3028
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
3029
- .map(f => ({ type: f.id, detail: f.snippet }))
3030
- .filter(f => _ruleOk(f.type));
3031
- if (sectionKickerFindings.length > 0) {
3032
- pageLevelFindings.push(...sectionKickerFindings);
3033
- allFindings.push({ el: document.body, findings: sectionKickerFindings });
3034
- }
3035
-
3036
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
3037
- for (const f of layoutFindings) {
3038
- const el = f.el || document.body;
3039
- delete f.el;
3040
- // Merge into existing overlay if this element already has one
3041
- const existing = el._impeccableOverlay;
3042
- if (existing) {
3043
- const nameRow = existing.querySelector('.impeccable-label-name');
3044
- const detailRow = existing.querySelector('.impeccable-label-detail');
3045
- const newType = TYPE_LABELS[f.type] || f.type;
3046
- if (nameRow) nameRow.textContent += ', ' + newType;
3047
- if (detailRow) detailRow.textContent += ' | ' + (f.detail || '');
3048
- } else {
3049
- highlight(el, [f]);
3050
- }
3051
- allFindings.push({ el, findings: [f] });
3052
- }
3053
-
3054
- // Page-level quality checks (headings, etc.)
3055
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
3056
- if (qualityFindings.length > 0) {
3057
- pageLevelFindings.push(...qualityFindings);
3058
- allFindings.push({ el: document.body, findings: qualityFindings });
3059
- }
3060
-
3061
- // Regex-on-HTML checks (shared with Node)
3062
- // Clone the document and strip impeccable-live overlay nodes before the
3063
- // regex scan, so the inspector's own inline styles (transitions on top/
3064
- // left/width/height, etc.) don't register as page anti-patterns.
3065
- const docClone = document.documentElement.cloneNode(true);
3066
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
3067
- node.remove();
3068
- }
3069
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
3070
- if (htmlPatternFindings.length > 0) {
3071
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
3072
- pageLevelFindings.push(...mapped);
3073
- allFindings.push({ el: document.body, findings: mapped });
3074
- }
3075
-
3076
- if (pageLevelFindings.length > 0) {
3077
- showPageBanner(pageLevelFindings);
3078
- }
3079
-
3080
- if (!EXTENSION_MODE) printSummary(allFindings);
3081
-
3082
- // In extension mode, post serialized results for the DevTools panel
3083
- if (EXTENSION_MODE) {
3084
- window.postMessage({
3085
- source: 'impeccable-results',
3086
- findings: serializeFindings(allFindings),
3087
- count: allFindings.length,
3088
- }, '*');
3089
- }
3090
-
3091
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
3092
- setTimeout(() => { firstScanDone = true; }, 1000);
3093
-
3094
- return allFindings;
3095
- };
3096
-
3097
- if (EXTENSION_MODE) {
3098
- // Extension mode: listen for commands, don't auto-scan
3099
- window.addEventListener('message', (e) => {
3100
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
3101
- if (e.data.action === 'scan') {
3102
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
3103
- scan();
3104
- }
3105
- if (e.data.action === 'toggle-overlays') {
3106
- const visible = !document.body.classList.contains('impeccable-hidden');
3107
- document.body.classList.toggle('impeccable-hidden', visible);
3108
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
3109
- }
3110
- if (e.data.action === 'remove') {
3111
- for (const o of overlays) o.remove();
3112
- overlays.length = 0;
3113
- visibilityObserver.disconnect();
3114
- styleEl.remove();
3115
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
3116
- document.body.classList.remove('impeccable-hidden');
3117
- }
3118
- if (e.data.action === 'highlight') {
3119
- if (spotlightTimer) { clearTimeout(spotlightTimer); spotlightTimer = null; }
3120
- try {
3121
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
3122
- if (target) {
3123
- // Scroll first so positionOverlay reads the post-scroll rect
3124
- if (!isInViewport(target) && target.scrollIntoView) {
3125
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
3126
- }
3127
- for (const o of overlays) {
3128
- if (o.classList.contains('impeccable-banner')) continue;
3129
- const isMatch = o._targetEl === target;
3130
- o.classList.toggle('impeccable-spotlight', isMatch);
3131
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
3132
- if (isMatch) {
3133
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
3134
- o.style.display = '';
3135
- o.style.animation = 'none';
3136
- o.classList.add('impeccable-visible');
3137
- o._revealed = true;
3138
- positionOverlay(o);
3139
- }
3140
- }
3141
- showSpotlight(target);
3142
- }
3143
- } catch { /* invalid selector */ }
3144
- }
3145
- if (e.data.action === 'unhighlight') {
3146
- hideSpotlight();
3147
- for (const o of overlays) {
3148
- o.classList.remove('impeccable-spotlight');
3149
- o.classList.remove('impeccable-spotlight-dimmed');
3150
- }
3151
- }
3152
- });
3153
- window.postMessage({ source: 'impeccable-ready' }, '*');
3154
- } else {
3155
- if (document.readyState === 'loading') {
3156
- document.addEventListener('DOMContentLoaded', () => setTimeout(scan, 100));
3157
- } else {
3158
- setTimeout(scan, 100);
3159
- }
3160
- }
3161
-
3162
- window.impeccableScan = scan;
3163
- }
3164
-
3165
- // ─── Section 8: Node Engine ─────────────────────────────────────────────────
3166
- // @browser-strip-start
3167
-
3168
- function getAP(id) {
3169
- return ANTIPATTERNS.find(a => a.id === id);
3170
- }
3171
-
3172
- function finding(id, filePath, snippet, line = 0) {
3173
- const ap = getAP(id);
3174
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
3175
- }
3176
-
3177
- /** Check if content looks like a full page (not a component/partial) */
3178
- function isFullPage(content) {
3179
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
3180
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
3181
- }
3182
-
3183
- // ---------------------------------------------------------------------------
3184
- // jsdom CSS-variable border override map
3185
- // ---------------------------------------------------------------------------
3186
- //
3187
- // jsdom's CSSOM silently drops any border shorthand that contains a var()
3188
- // reference — the computed style for the element then shows empty width,
3189
- // empty style, and a default black color. That's enough to hide the most
3190
- // common real-world side-tab pattern in AI-generated pages:
3191
- //
3192
- // :root { --brand: #87a8ff; }
3193
- // .card { border-left: 5px solid var(--brand); border-radius: 4px; }
3194
- //
3195
- // Real browsers (and therefore the browser detector path) resolve var()
3196
- // natively, so this only affects the Node jsdom path.
3197
- //
3198
- // This pre-pass walks the stylesheets, finds any rule whose per-side or
3199
- // all-sides border property contains var(), resolves the var() against
3200
- // :root-level custom properties (read from the documentElement's computed
3201
- // style, which jsdom DOES handle correctly), and attaches the resolved
3202
- // width+color to every element that matches the rule's selector. The
3203
- // Node-side `checkElementBorders` adapter consumes that map as a fallback
3204
- // whenever jsdom's computed style came back empty.
3205
- //
3206
- // Limitations (intentional, to keep the pass simple):
3207
- // * Only :root-level custom properties are resolved. Scoped overrides on
3208
- // descendants are not tracked — uncommon in practice and would require
3209
- // a per-element cascade walk.
3210
- // * @media / @supports wrapped rules are ignored (jsdom often mishandles
3211
- // these anyway).
3212
- // * The fallback only fills sides that jsdom left empty, so any rule
3213
- // whose border parses normally still wins via the computed style.
3214
-
3215
- const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
3216
-
3217
- // isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
3218
- // CSS variables typically hold hex or named colors, so normalize those to
3219
- // rgb() before handing the value off to the shared check. Anything we don't
3220
- // recognise is passed through unchanged — isNeutralColor then treats it as
3221
- // non-neutral, which is the safer default (matches the oklch-era bugfix).
3222
- const NAMED_COLORS = {
3223
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
3224
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
3225
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
3226
- };
3227
-
3228
- function normalizeColorForCheck(value) {
3229
- if (!value) return value;
3230
- const v = value.trim();
3231
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
3232
- if (hex6) {
3233
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
3234
- return `rgb(${r}, ${g}, ${b})`;
3235
- }
3236
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
3237
- if (hex3) {
3238
- const [r, g, b] = [
3239
- parseInt(hex3[1] + hex3[1], 16),
3240
- parseInt(hex3[2] + hex3[2], 16),
3241
- parseInt(hex3[3] + hex3[3], 16),
3242
- ];
3243
- return `rgb(${r}, ${g}, ${b})`;
3244
- }
3245
- const named = NAMED_COLORS[v.toLowerCase()];
3246
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
3247
- return v;
3248
- }
3249
-
3250
- function buildBorderOverrideMap(document, window) {
3251
- const map = new Map();
3252
- const rootStyle = window.getComputedStyle(document.documentElement);
3253
-
3254
- function resolveVar(value, depth = 0) {
3255
- if (!value || depth > 10 || !value.includes('var(')) return value;
3256
- return value.replace(
3257
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
3258
- (_, name, fallback) => {
3259
- const v = rootStyle.getPropertyValue(name).trim();
3260
- if (v) return resolveVar(v, depth + 1);
3261
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
3262
- return '';
3263
- }
3264
- );
3265
- }
3266
-
3267
- function parseShorthand(text) {
3268
- const m = text.trim().match(BORDER_SHORTHAND_RE);
3269
- if (!m) return null;
3270
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
3271
- }
3272
-
3273
- // Read from the per-property accessors on rule.style. jsdom preserves
3274
- // each border-* shorthand it parsed, even when the overall cssText has
3275
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
3276
- // `border-left: ...` loses the first declaration but keeps the second).
3277
- const SIDE_PROPS = [
3278
- ['borderLeft', 'Left'],
3279
- ['borderRight', 'Right'],
3280
- ['borderTop', 'Top'],
3281
- ['borderBottom', 'Bottom'],
3282
- ['borderInlineStart', 'Left'],
3283
- ['borderInlineEnd', 'Right'],
3284
- ];
3285
-
3286
- for (const sheet of document.styleSheets) {
3287
- let rules;
3288
- try { rules = sheet.cssRules || []; } catch { continue; }
3289
- for (const rule of rules) {
3290
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
3291
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
3292
-
3293
- const perSide = {};
3294
-
3295
- for (const [prop, side] of SIDE_PROPS) {
3296
- const val = rule.style[prop];
3297
- if (!val || !val.includes('var(')) continue;
3298
- const parsed = parseShorthand(resolveVar(val));
3299
- if (parsed && parsed.color) perSide[side] = parsed;
3300
- }
3301
-
3302
- // Uniform `border: <w> <style> var(...)` applies to every side the
3303
- // per-side map didn't already claim.
3304
- const borderAll = rule.style.border;
3305
- if (borderAll && borderAll.includes('var(')) {
3306
- const parsed = parseShorthand(resolveVar(borderAll));
3307
- if (parsed && parsed.color) {
3308
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
3309
- if (!perSide[s]) perSide[s] = parsed;
3310
- }
3311
- }
3312
- }
3313
-
3314
- // Longhand `border-*-color: var(...)` with width/style in separate
3315
- // declarations. Rare in AI-generated pages, but cheap to cover.
3316
- for (const [prop, side] of [
3317
- ['borderLeftColor', 'Left'],
3318
- ['borderRightColor', 'Right'],
3319
- ['borderTopColor', 'Top'],
3320
- ['borderBottomColor', 'Bottom'],
3321
- ]) {
3322
- const val = rule.style[prop];
3323
- if (!val || !val.includes('var(')) continue;
3324
- const resolved = resolveVar(val).trim();
3325
- if (!resolved) continue;
3326
- // Width may or may not come from this rule — that's fine; the
3327
- // adapter only substitutes the color when jsdom left it as a
3328
- // literal var() string.
3329
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
3330
- }
3331
-
3332
- if (Object.keys(perSide).length === 0) continue;
3333
-
3334
- let matched;
3335
- try { matched = document.querySelectorAll(rule.selectorText); }
3336
- catch { continue; }
3337
-
3338
- for (const el of matched) {
3339
- const existing = map.get(el);
3340
- if (existing) {
3341
- // Later rules overwrite earlier ones — approximates source-order
3342
- // cascade for equal-specificity rules and is good enough for the
3343
- // uncontested var()-dropped sides we're trying to recover.
3344
- Object.assign(existing, perSide);
3345
- } else {
3346
- map.set(el, { ...perSide });
3347
- }
3348
- }
3349
- }
3350
- }
3351
-
3352
- return map;
3353
- }
3354
-
3355
- // Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
3356
- // the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
3357
- // any rule inside a layer block becomes invisible to getComputedStyle.
3358
- // Tailwind v4 makes this ubiquitous: every utility class lives in
3359
- // `@layer utilities`, and Preflight lives in `@layer base`. Without
3360
- // unwrapping, every Tailwind-styled element returns empty computed
3361
- // styles. We walk the source character-by-character, balancing braces
3362
- // so we correctly handle nested style rules inside the layer block.
3363
- function unwrapCssAtLayer(source) {
3364
- if (!source || !source.includes('@layer')) return source;
3365
- // Find `@layer <name>? {` openers. The match starts at the @, and
3366
- // we then balance braces from the opening { onward.
3367
- const re = /@layer\b[^{;]*\{/g;
3368
- let out = '';
3369
- let lastIdx = 0;
3370
- let m;
3371
- while ((m = re.exec(source)) !== null) {
3372
- const openStart = m.index;
3373
- const openEnd = m.index + m[0].length; // position right after `{`
3374
- let depth = 1;
3375
- let i = openEnd;
3376
- while (i < source.length && depth > 0) {
3377
- const c = source.charCodeAt(i);
3378
- if (c === 0x7b /* { */) depth++;
3379
- else if (c === 0x7d /* } */) depth--;
3380
- i++;
3381
- }
3382
- if (depth !== 0) {
3383
- // Unbalanced — bail and return source unchanged.
3384
- return source;
3385
- }
3386
- // Emit everything before the @layer, then the inner contents
3387
- // (between the opening { and the matched closing }), then advance.
3388
- out += source.slice(lastIdx, openStart);
3389
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
3390
- lastIdx = i;
3391
- re.lastIndex = i;
3392
- }
3393
- out += source.slice(lastIdx);
3394
- return out;
3395
- }
3396
-
3397
- // ---------------------------------------------------------------------------
3398
- // jsdom detection (default for HTML files)
3399
- // ---------------------------------------------------------------------------
3400
-
3401
- async function detectHtml(filePath) {
3402
- let JSDOM;
3403
- try {
3404
- ({ JSDOM } = await import('jsdom'));
3405
- } catch {
3406
- const content = fs.readFileSync(filePath, 'utf-8');
3407
- return detectText(content, filePath);
3408
- }
3409
-
3410
- const html = fs.readFileSync(filePath, 'utf-8');
3411
- const resolvedPath = path.resolve(filePath);
3412
- const fileDir = path.dirname(resolvedPath);
3413
-
3414
- // Inline linked local stylesheets so jsdom can see them
3415
- let processedHtml = html;
3416
- const linkRes = [
3417
- /<link[^>]+rel=["']stylesheet["'][^>]*href=["']([^"']+)["'][^>]*>/gi,
3418
- /<link[^>]+href=["']([^"']+)["'][^>]*rel=["']stylesheet["'][^>]*>/gi,
3419
- ];
3420
- for (const re of linkRes) {
3421
- let m;
3422
- while ((m = re.exec(html)) !== null) {
3423
- const href = m[1];
3424
- if (/^(https?:)?\/\//.test(href)) continue;
3425
- const cssPath = path.resolve(fileDir, href);
3426
- try {
3427
- const css = fs.readFileSync(cssPath, 'utf-8');
3428
- processedHtml = processedHtml.replace(m[0], `<style>/* ${href} */\n${css}\n</style>`);
3429
- } catch { /* skip unreadable */ }
3430
- }
3431
- }
3432
-
3433
- // jsdom does not implement CSS `@layer` rules — every utility class
3434
- // inside `@layer utilities { ... }` is silently ignored, so computed
3435
- // styles come back empty. Tailwind v4 wraps every utility class in
3436
- // an @layer, which means jsdom returns empty strings for fontSize /
3437
- // fontWeight / textTransform / letterSpacing on every Tailwind-styled
3438
- // element. Strip the @layer wrapper, keep the inner rules as flat
3439
- // CSS that jsdom can process. The cascade ordering @layer provides
3440
- // doesn't matter for our checks — we only read computed values.
3441
- processedHtml = unwrapCssAtLayer(processedHtml);
3442
-
3443
- const dom = new JSDOM(processedHtml, {
3444
- url: `file://${resolvedPath}`,
3445
- });
3446
- const { window } = dom;
3447
- const { document } = window;
3448
-
3449
- const findings = [];
3450
-
3451
- // Pre-pass: recover border declarations that jsdom dropped because they
3452
- // contained a var() reference. The map is keyed by element and consulted
3453
- // by the border check adapter as a fallback.
3454
- const borderOverrides = buildBorderOverrideMap(document, window);
3455
-
3456
- // Pre-pass: collect :root / :host / html CSS custom properties so the
3457
- // checks can resolve var(--X) refs that jsdom returns verbatim from
3458
- // getComputedStyle. Tailwind v4 wraps every utility-class value in a
3459
- // CSS var; without this, font-weight / font-size / letter-spacing /
3460
- // color all come back as literal "var(--X)" strings.
3461
- const customPropMap = buildCustomPropMap(document);
3462
-
3463
- // Pre-pass: detect whether the page's CSS declares `a { color: inherit }`
3464
- // (Tailwind v4 preflight signature). When present, real browsers render
3465
- // anchors using the cascaded ancestor color, but jsdom's UA stylesheet
3466
- // applies `:link { color: blue }` at higher specificity, so anchors come
3467
- // back as `rgb(0, 0, 238)` regardless. checkElementColors uses this
3468
- // flag to walk for the cascaded color when it sees jsdom's blue default
3469
- // on an anchor — preventing a whole class of contrast false positives
3470
- // on Tailwind v4 pages.
3471
- let hasAnchorInheritRule = false;
3472
- const scanForAnchorInherit = (rules) => {
3473
- for (const rule of rules) {
3474
- if (rule.selectorText === 'a' && rule.style && rule.style.color === 'inherit') return true;
3475
- // Recurse into @layer / @media / @supports / etc.
3476
- if (rule.cssRules && scanForAnchorInherit(rule.cssRules)) return true;
3477
- }
3478
- return false;
3479
- };
3480
- for (const sheet of document.styleSheets) {
3481
- try {
3482
- if (scanForAnchorInherit(sheet.cssRules || [])) {
3483
- hasAnchorInheritRule = true;
3484
- break;
3485
- }
3486
- } catch (e) { /* cross-origin sheet, skip */ }
3487
- }
3488
-
3489
- // Element-level checks (borders + colors + motion)
3490
- for (const el of document.querySelectorAll('*')) {
3491
- const tag = el.tagName.toLowerCase();
3492
- const style = window.getComputedStyle(el);
3493
- const resolvedRadius = resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window);
3494
- for (const f of checkElementBorders(tag, style, borderOverrides.get(el), resolvedRadius)) {
3495
- findings.push(finding(f.id, filePath, f.snippet));
3496
- }
3497
- for (const f of checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule)) {
3498
- findings.push(finding(f.id, filePath, f.snippet));
3499
- }
3500
- for (const f of checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap))) {
3501
- findings.push(finding(f.id, filePath, f.snippet));
3502
- }
3503
- for (const f of checkElementMotion(tag, style)) {
3504
- findings.push(finding(f.id, filePath, f.snippet));
3505
- }
3506
- for (const f of checkElementIconTile(el, tag, window)) {
3507
- findings.push(finding(f.id, filePath, f.snippet));
3508
- }
3509
- for (const f of checkElementItalicSerif(el, style, tag)) {
3510
- findings.push(finding(f.id, filePath, f.snippet));
3511
- }
3512
- for (const f of checkElementHeroEyebrow(el, style, tag, window, customPropMap)) {
3513
- findings.push(finding(f.id, filePath, f.snippet));
3514
- }
3515
- for (const f of checkElementQuality(el, style, tag, window)) {
3516
- findings.push(finding(f.id, filePath, f.snippet));
3517
- }
3518
- }
3519
-
3520
- // Page-level checks (only for full pages, not partials)
3521
- if (isFullPage(html)) {
3522
- for (const f of checkPageTypography(document, window)) {
3523
- findings.push(finding(f.id, filePath, f.snippet));
3524
- }
3525
- for (const f of checkRepeatedSectionKickersFromDoc(document, window)) {
3526
- findings.push(finding(f.id, filePath, f.snippet));
3527
- }
3528
- for (const f of checkPageLayout(document, window)) {
3529
- findings.push(finding(f.id, filePath, f.snippet));
3530
- }
3531
- for (const f of checkPageQualityFromDoc(document)) {
3532
- findings.push(finding(f.id, filePath, f.snippet));
3533
- }
3534
- for (const f of checkHtmlPatterns(html)) {
3535
- findings.push(finding(f.id, filePath, f.snippet));
3536
- }
3537
- }
3538
-
3539
- window.close();
3540
- return findings;
3541
- }
3542
-
3543
- // ---------------------------------------------------------------------------
3544
- // Puppeteer detection (for URLs)
3545
- // ---------------------------------------------------------------------------
3546
-
3547
- async function detectUrl(url) {
3548
- let puppeteer;
3549
- try {
3550
- puppeteer = await import('puppeteer');
3551
- } catch {
3552
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
3553
- }
3554
-
3555
- // Read the browser detection script — reuse it instead of reimplementing
3556
- const browserScriptPath = path.resolve(
3557
- path.dirname(fileURLToPath(import.meta.url)),
3558
- 'detect-antipatterns-browser.js'
3559
- );
3560
- let browserScript;
3561
- try {
3562
- browserScript = fs.readFileSync(browserScriptPath, 'utf-8');
3563
- } catch {
3564
- throw new Error(`Browser script not found at ${browserScriptPath}`);
3565
- }
3566
-
3567
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
3568
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
3569
- // running in CI; local users keep the default hardened launch.
3570
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
3571
- const browser = await puppeteer.default.launch({ headless: true, args: launchArgs });
3572
- const page = await browser.newPage();
3573
- await page.setViewport({ width: 1280, height: 800 });
3574
- await page.goto(url, { waitUntil: 'networkidle0', timeout: 30000 });
3575
-
3576
- // Inject the browser detection script and collect results
3577
- await page.evaluate(browserScript);
3578
- const results = await page.evaluate(() => {
3579
- if (!window.impeccableScan) return [];
3580
- const allFindings = window.impeccableScan();
3581
- return allFindings.flatMap(({ findings }) =>
3582
- findings.map(f => ({ id: f.type, snippet: f.detail }))
3583
- );
3584
- });
3585
-
3586
- await browser.close();
3587
- return results.map(f => finding(f.id, url, f.snippet));
3588
- }
3589
-
3590
- // ---------------------------------------------------------------------------
3591
- // Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
3592
- // ---------------------------------------------------------------------------
3593
-
3594
- const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
3595
- const hasBorderRadius = (line) => /border-radius/i.test(line);
3596
- const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
3597
-
3598
- function isNeutralBorderColor(str) {
3599
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
3600
- if (!m) return false;
3601
- const c = m[1].toLowerCase();
3602
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
3603
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
3604
- if (hex) {
3605
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
3606
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
3607
- }
3608
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
3609
- if (shex) {
3610
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
3611
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
3612
- }
3613
- return false;
3614
- }
3615
-
3616
- const REGEX_MATCHERS = [
3617
- // --- Side-tab ---
3618
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
3619
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
3620
- fmt: (m) => m[0] },
3621
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
3622
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
3623
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
3624
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
3625
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
3626
- fmt: (m) => m[0] },
3627
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
3628
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
3629
- fmt: (m) => m[0] },
3630
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
3631
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
3632
- fmt: (m) => m[0] },
3633
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
3634
- test: (m) => +m[1] >= 3,
3635
- fmt: (m) => m[0] },
3636
- // --- Border accent on rounded ---
3637
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
3638
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
3639
- fmt: (m) => m[0] },
3640
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
3641
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
3642
- fmt: (m) => m[0] },
3643
- // --- Overused font ---
3644
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
3645
- test: () => true,
3646
- fmt: (m) => m[0] },
3647
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
3648
- test: () => true,
3649
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
3650
- // --- Pure black background ---
3651
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
3652
- test: () => true,
3653
- fmt: (m) => m[0] },
3654
- // --- Gradient text ---
3655
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
3656
- test: (m, line) => /gradient/i.test(line),
3657
- fmt: () => 'background-clip: text + gradient' },
3658
- // --- Gradient text (Tailwind) ---
3659
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
3660
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
3661
- fmt: () => 'bg-clip-text + bg-gradient' },
3662
- // --- Tailwind pure black background ---
3663
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
3664
- test: () => true,
3665
- fmt: (m) => m[0] },
3666
- // --- Tailwind gray on colored bg ---
3667
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
3668
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
3669
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
3670
- // --- Tailwind AI palette ---
3671
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
3672
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
3673
- fmt: (m) => `${m[0]} on heading` },
3674
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
3675
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
3676
- fmt: (m) => `${m[0]} gradient` },
3677
- // --- Bounce/elastic easing ---
3678
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
3679
- test: () => true,
3680
- fmt: () => 'animate-bounce (Tailwind)' },
3681
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
3682
- test: () => true,
3683
- fmt: (m) => m[0] },
3684
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
3685
- test: (m) => {
3686
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
3687
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
3688
- },
3689
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
3690
- // --- Layout property transition ---
3691
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
3692
- test: (m) => {
3693
- const val = m[1].toLowerCase();
3694
- if (/\ball\b/.test(val)) return false;
3695
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
3696
- },
3697
- fmt: (m) => {
3698
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
3699
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
3700
- } },
3701
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
3702
- test: (m) => {
3703
- const val = m[1].toLowerCase();
3704
- if (/\ball\b/.test(val)) return false;
3705
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
3706
- },
3707
- fmt: (m) => {
3708
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
3709
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
3710
- } },
3711
- ];
3712
-
3713
- const REGEX_ANALYZERS = [
3714
- // Single font
3715
- (content, filePath) => {
3716
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
3717
- const fonts = new Set();
3718
- let m;
3719
- while ((m = fontFamilyRe.exec(content)) !== null) {
3720
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
3721
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
3722
- }
3723
- }
3724
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
3725
- while ((m = gfRe.exec(content)) !== null) {
3726
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
3727
- }
3728
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
3729
- const name = [...fonts][0];
3730
- const lines = content.split('\n');
3731
- let line = 1;
3732
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
3733
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
3734
- },
3735
- // Flat type hierarchy
3736
- (content, filePath) => {
3737
- const sizes = new Set();
3738
- const REM = 16;
3739
- let m;
3740
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
3741
- while ((m = sizeRe.exec(content)) !== null) {
3742
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
3743
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
3744
- }
3745
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
3746
- while ((m = clampRe.exec(content)) !== null) {
3747
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
3748
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
3749
- }
3750
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
3751
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
3752
- if (sizes.size < 3) return [];
3753
- const sorted = [...sizes].sort((a, b) => a - b);
3754
- const ratio = sorted[sorted.length - 1] / sorted[0];
3755
- if (ratio >= 2.0) return [];
3756
- const lines = content.split('\n');
3757
- let line = 1;
3758
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
3759
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
3760
- },
3761
- // Monotonous spacing (regex)
3762
- (content, filePath) => {
3763
- const vals = [];
3764
- let m;
3765
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
3766
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
3767
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
3768
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
3769
- const gapRe = /gap\s*:\s*(\d+)px/gi;
3770
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
3771
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
3772
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
3773
- const rounded = vals.map(v => Math.round(v / 4) * 4);
3774
- if (rounded.length < 10) return [];
3775
- const counts = {};
3776
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
3777
- const maxCount = Math.max(...Object.values(counts));
3778
- const pct = maxCount / rounded.length;
3779
- const unique = [...new Set(rounded)].filter(v => v > 0);
3780
- if (pct <= 0.6 || unique.length > 3) return [];
3781
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
3782
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
3783
- },
3784
- // Everything centered (regex)
3785
- (content, filePath) => {
3786
- const lines = content.split('\n');
3787
- let centered = 0, total = 0;
3788
- for (const line of lines) {
3789
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
3790
- total++;
3791
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
3792
- }
3793
- }
3794
- if (total < 5 || centered / total <= 0.7) return [];
3795
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
3796
- },
3797
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
3798
- (content, filePath) => {
3799
- // Check if page has a dark background
3800
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
3801
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
3802
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
3803
- if (!hasDarkBg) return [];
3804
-
3805
- // Check for colored box-shadow with blur > 4px
3806
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
3807
- let m;
3808
- while ((m = shadowRe.exec(content)) !== null) {
3809
- const val = m[1];
3810
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
3811
- if (!colorMatch) continue;
3812
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
3813
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
3814
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
3815
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
3816
- if (pxVals.length >= 3 && pxVals[2] > 4) {
3817
- const lines = content.substring(0, m.index).split('\n');
3818
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
3819
- }
3820
- }
3821
- return [];
3822
- },
3823
- ];
3824
-
3825
- // ---------------------------------------------------------------------------
3826
- // Style block extraction (Vue/Svelte <style> blocks)
3827
- // ---------------------------------------------------------------------------
3828
-
3829
- function extractStyleBlocks(content, ext) {
3830
- ext = ext.toLowerCase();
3831
- if (ext !== '.vue' && ext !== '.svelte') return [];
3832
- const blocks = [];
3833
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
3834
- let m;
3835
- while ((m = re.exec(content)) !== null) {
3836
- const before = content.substring(0, m.index);
3837
- const startLine = before.split('\n').length + 1;
3838
- blocks.push({ content: m[1], startLine });
3839
- }
3840
- return blocks;
3841
- }
3842
-
3843
- // ---------------------------------------------------------------------------
3844
- // CSS-in-JS extraction (styled-components, emotion)
3845
- // ---------------------------------------------------------------------------
3846
-
3847
- const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
3848
-
3849
- function extractCSSinJS(content, ext) {
3850
- ext = ext.toLowerCase();
3851
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
3852
- const blocks = [];
3853
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
3854
- let m;
3855
- while ((m = re.exec(content)) !== null) {
3856
- const before = content.substring(0, m.index);
3857
- const startLine = before.split('\n').length;
3858
- blocks.push({ content: m[1], startLine });
3859
- }
3860
- return blocks;
3861
- }
3862
-
3863
- function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null) {
3864
- const findings = [];
3865
- for (const matcher of REGEX_MATCHERS) {
3866
- for (let i = 0; i < lines.length; i++) {
3867
- const line = lines[i];
3868
- matcher.regex.lastIndex = 0;
3869
- let m;
3870
- while ((m = matcher.regex.exec(line)) !== null) {
3871
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
3872
- const context = blockContext
3873
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
3874
- : line;
3875
- if (matcher.test(m, context)) {
3876
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
3877
- }
3878
- }
3879
- }
3880
- }
3881
- return findings;
3882
- }
3883
-
3884
- function detectText(content, filePath) {
3885
- const findings = [];
3886
- const lines = content.split('\n');
3887
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
3888
-
3889
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
3890
- // Enable block context for CSS files where related properties span multiple lines
3891
- const cssLike = new Set(['.css', '.scss', '.less']);
3892
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null));
3893
-
3894
- // Extract and scan <style> blocks from Vue/Svelte SFCs
3895
- const styleBlocks = extractStyleBlocks(content, ext);
3896
- for (const block of styleBlocks) {
3897
- const blockLines = block.content.split('\n');
3898
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true));
3899
- }
3900
-
3901
- // Extract and scan CSS-in-JS template literals
3902
- const cssJsBlocks = extractCSSinJS(content, ext);
3903
- for (const block of cssJsBlocks) {
3904
- const blockLines = block.content.split('\n');
3905
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true));
3906
- }
3907
-
3908
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
3909
- const deduped = [];
3910
- for (const f of findings) {
3911
- const isDupe = deduped.some(d =>
3912
- d.antipattern === f.antipattern &&
3913
- d.snippet === f.snippet &&
3914
- Math.abs(d.line - f.line) <= 2
3915
- );
3916
- if (!isDupe) deduped.push(f);
3917
- }
3918
-
3919
- // Page-level analyzers only run on full pages
3920
- if (isFullPage(content)) {
3921
- for (const analyzer of REGEX_ANALYZERS) {
3922
- deduped.push(...analyzer(content, filePath));
3923
- }
3924
- }
3925
-
3926
- return deduped;
3927
- }
3928
-
3929
- // ---------------------------------------------------------------------------
3930
- // File walker
3931
- // ---------------------------------------------------------------------------
3932
-
3933
- const SKIP_DIRS = new Set([
3934
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
3935
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
3936
- ]);
3937
-
3938
- const SCANNABLE_EXTENSIONS = new Set([
3939
- '.html', '.htm', '.css', '.scss', '.less',
3940
- '.jsx', '.tsx', '.js', '.ts',
3941
- '.vue', '.svelte', '.astro',
3942
- ]);
3943
-
3944
- const HTML_EXTENSIONS = new Set(['.html', '.htm']);
3945
-
3946
- function walkDir(dir) {
3947
- const files = [];
3948
- let entries;
3949
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
3950
- for (const entry of entries) {
3951
- if (SKIP_DIRS.has(entry.name)) continue;
3952
- const full = path.join(dir, entry.name);
3953
- if (entry.isDirectory()) files.push(...walkDir(full));
3954
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
3955
- }
3956
- return files;
3957
- }
3958
-
3959
- // ---------------------------------------------------------------------------
3960
- // Output formatting
3961
- // ---------------------------------------------------------------------------
3962
-
3963
- function formatFindings(findings, jsonMode) {
3964
- if (jsonMode) return JSON.stringify(findings, null, 2);
3965
-
3966
- const grouped = {};
3967
- for (const f of findings) {
3968
- if (!grouped[f.file]) grouped[f.file] = [];
3969
- grouped[f.file].push(f);
3970
- }
3971
- const out = [];
3972
- for (const [file, items] of Object.entries(grouped)) {
3973
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
3974
- out.push(`\n${file}${importNote}`);
3975
- for (const item of items) {
3976
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
3977
- out.push(` → ${item.description}`);
3978
- }
3979
- }
3980
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
3981
- return out.join('\n');
3982
- }
3983
-
3984
- // ---------------------------------------------------------------------------
3985
- // Stdin handling
3986
- // ---------------------------------------------------------------------------
3987
-
3988
- async function handleStdin() {
3989
- const chunks = [];
3990
- for await (const chunk of process.stdin) chunks.push(chunk);
3991
- const input = Buffer.concat(chunks).toString('utf-8');
3992
- try {
3993
- const parsed = JSON.parse(input);
3994
- const fp = parsed?.tool_input?.file_path;
3995
- if (fp && fs.existsSync(fp)) {
3996
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
3997
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
3998
- }
3999
- } catch { /* not JSON */ }
4000
- return detectText(input, '<stdin>');
4001
- }
4002
-
4003
- // ---------------------------------------------------------------------------
4004
- // Import graph (multi-file awareness)
4005
- // ---------------------------------------------------------------------------
4006
-
4007
- function resolveImport(specifier, fromDir, fileSet) {
4008
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
4009
- const base = path.resolve(fromDir, specifier);
4010
- if (fileSet.has(base)) return base;
4011
- for (const ext of SCANNABLE_EXTENSIONS) {
4012
- const withExt = base + ext;
4013
- if (fileSet.has(withExt)) return withExt;
4014
- }
4015
- // index file convention
4016
- for (const ext of SCANNABLE_EXTENSIONS) {
4017
- const indexFile = path.join(base, 'index' + ext);
4018
- if (fileSet.has(indexFile)) return indexFile;
4019
- }
4020
- return null;
4021
- }
4022
-
4023
- function buildImportGraph(files) {
4024
- const fileSet = new Set(files);
4025
- const graph = new Map();
4026
-
4027
- for (const file of files) {
4028
- const content = fs.readFileSync(file, 'utf-8');
4029
- const dir = path.dirname(file);
4030
- const imports = new Set();
4031
-
4032
- // ES imports: import ... from '...' and import '...'
4033
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
4034
- let m;
4035
- while ((m = esRe.exec(content)) !== null) {
4036
- const resolved = resolveImport(m[1], dir, fileSet);
4037
- if (resolved) imports.add(resolved);
4038
- }
4039
-
4040
- // CSS @import
4041
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
4042
- while ((m = cssRe.exec(content)) !== null) {
4043
- const resolved = resolveImport(m[1], dir, fileSet);
4044
- if (resolved) imports.add(resolved);
4045
- }
4046
-
4047
- // SCSS @use / @forward
4048
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
4049
- while ((m = scssRe.exec(content)) !== null) {
4050
- const resolved = resolveImport(m[1], dir, fileSet);
4051
- if (resolved) imports.add(resolved);
4052
- }
4053
-
4054
- graph.set(file, imports);
4055
- }
4056
- return graph;
4057
- }
4058
-
4059
- // ---------------------------------------------------------------------------
4060
- // Framework dev server detection
4061
- // ---------------------------------------------------------------------------
4062
-
4063
- const FRAMEWORK_CONFIGS = [
4064
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
4065
- portRe: /port\s*[:=]\s*(\d+)/,
4066
- fingerprint: { header: 'x-powered-by', value: /next/i } },
4067
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
4068
- portRe: /port\s*[:=]\s*(\d+)/,
4069
- fingerprint: { header: 'x-sveltekit-page', value: null } },
4070
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
4071
- portRe: /port\s*[:=]\s*(\d+)/,
4072
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
4073
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
4074
- portRe: /port\s*[:=]\s*(\d+)/,
4075
- fingerprint: { body: /@vite\/client/ } },
4076
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
4077
- portRe: /port\s*[:=]\s*(\d+)/,
4078
- fingerprint: { body: /astro/i } },
4079
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
4080
- portRe: /"port"\s*:\s*(\d+)/,
4081
- fingerprint: { body: /ng-version/i } },
4082
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
4083
- portRe: /port\s*[:=]\s*(\d+)/,
4084
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
4085
- ];
4086
-
4087
- function detectFrameworkConfig(dir) {
4088
- let entries;
4089
- try { entries = fs.readdirSync(dir); } catch { return null; }
4090
- const entrySet = new Set(entries);
4091
-
4092
- for (const cfg of FRAMEWORK_CONFIGS) {
4093
- const match = cfg.files.find(f => entrySet.has(f));
4094
- if (!match) continue;
4095
-
4096
- const configPath = path.join(dir, match);
4097
- let port = cfg.defaultPort;
4098
- try {
4099
- const content = fs.readFileSync(configPath, 'utf-8');
4100
- const portMatch = content.match(cfg.portRe);
4101
- if (portMatch) port = parseInt(portMatch[1], 10);
4102
- } catch { /* use default */ }
4103
-
4104
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
4105
- }
4106
- return null;
4107
- }
4108
-
4109
- /**
4110
- * Check if a port is listening and optionally verify it matches the expected framework.
4111
- * Returns { listening: true, matched: true/false } or { listening: false }.
4112
- */
4113
- async function isPortListening(port, fingerprint = null) {
4114
- if (!fingerprint) {
4115
- // Simple TCP probe fallback
4116
- const net = await import('node:net');
4117
- return new Promise((resolve) => {
4118
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
4119
- sock.setTimeout(500);
4120
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
4121
- sock.on('error', () => resolve({ listening: false }));
4122
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
4123
- });
4124
- }
4125
-
4126
- // HTTP probe with fingerprint matching
4127
- try {
4128
- const controller = new AbortController();
4129
- const timeout = setTimeout(() => controller.abort(), 2000);
4130
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
4131
- clearTimeout(timeout);
4132
-
4133
- // Check header fingerprint
4134
- if (fingerprint.header) {
4135
- const val = res.headers.get(fingerprint.header);
4136
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
4137
- return { listening: true, matched: true };
4138
- }
4139
- }
4140
-
4141
- // Check body fingerprint
4142
- if (fingerprint.body) {
4143
- const body = await res.text();
4144
- if (fingerprint.body.test(body)) {
4145
- return { listening: true, matched: true };
4146
- }
4147
- }
4148
-
4149
- // Port is listening but doesn't match the expected framework
4150
- return { listening: true, matched: false };
4151
- } catch {
4152
- return { listening: false };
4153
- }
4154
- }
4155
-
4156
- // ---------------------------------------------------------------------------
4157
- // CLI
4158
- // ---------------------------------------------------------------------------
4159
-
4160
- async function confirm(question) {
4161
- const rl = (await import('node:readline')).default.createInterface({
4162
- input: process.stdin, output: process.stderr,
4163
- });
4164
- return new Promise((resolve) => {
4165
- rl.question(`${question} [Y/n] `, (answer) => {
4166
- rl.close();
4167
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
4168
- });
4169
- });
4170
- }
4171
-
4172
- function printUsage() {
4173
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
4174
-
4175
- Scan files or URLs for UI anti-patterns and design quality issues.
4176
-
4177
- Options:
4178
- --fast Regex-only mode (skip jsdom, faster but misses linked stylesheets)
4179
- --json Output results as JSON
4180
- --help Show this help message
4181
-
4182
- Detection modes:
4183
- HTML files jsdom with computed styles (default, catches linked CSS)
4184
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
4185
- URLs Puppeteer full browser rendering (auto-detected)
4186
- --fast Forces regex for all files
4187
-
4188
- Examples:
4189
- impeccable detect src/
4190
- impeccable detect index.html
4191
- impeccable detect https://example.com
4192
- impeccable detect --fast --json .`);
4193
- }
4194
-
4195
- async function main() {
4196
- const args = process.argv.slice(2).map(arg => {
4197
- if (arg === '-json') return '--json';
4198
- if (arg === '-fast') return '--fast';
4199
- return arg;
4200
- });
4201
- const jsonMode = args.includes('--json');
4202
- const helpMode = args.includes('--help');
4203
- const fastMode = args.includes('--fast');
4204
- const targets = args.filter(a => !a.startsWith('--'));
4205
-
4206
- if (helpMode) { printUsage(); process.exit(0); }
4207
-
4208
- let allFindings = [];
4209
-
4210
- if (!process.stdin.isTTY && targets.length === 0) {
4211
- allFindings = await handleStdin();
4212
- } else {
4213
- const paths = targets.length > 0 ? targets : [process.cwd()];
4214
-
4215
- for (const target of paths) {
4216
- if (/^https?:\/\//i.test(target)) {
4217
- try { allFindings.push(...await detectUrl(target)); }
4218
- catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
4219
- continue;
4220
- }
4221
-
4222
- const resolved = path.resolve(target);
4223
- let stat;
4224
- try { stat = fs.statSync(resolved); }
4225
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
4226
-
4227
- if (stat.isDirectory()) {
4228
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
4229
- if (!jsonMode) {
4230
- const fwConfig = detectFrameworkConfig(resolved);
4231
- if (fwConfig) {
4232
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
4233
- if (probe.listening && probe.matched) {
4234
- process.stderr.write(
4235
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
4236
- `For more accurate results, scan the running site:\n` +
4237
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
4238
- );
4239
- } else if (probe.listening && !probe.matched) {
4240
- process.stderr.write(
4241
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
4242
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
4243
- );
4244
- } else {
4245
- process.stderr.write(
4246
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
4247
- `Start the dev server and scan via URL for best results:\n` +
4248
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
4249
- );
4250
- }
4251
- }
4252
- }
4253
-
4254
- const files = walkDir(resolved);
4255
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
4256
-
4257
- // Warn and confirm if scanning many files (jsdom is slow per HTML file)
4258
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
4259
- process.stderr.write(
4260
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
4261
- `Scanning may take a while${htmlCount > 10 ? ' (jsdom processes each HTML file individually)' : ''}.\n` +
4262
- `Use --fast to skip jsdom, or target a specific subdirectory.\n`
4263
- );
4264
- const ok = await confirm('Continue?');
4265
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
4266
- }
4267
-
4268
- // Build import graph for multi-file awareness
4269
- const graph = buildImportGraph(files);
4270
- // Build reverse map: file -> set of files that import it
4271
- const importedByMap = new Map();
4272
- for (const [importer, imports] of graph) {
4273
- for (const imported of imports) {
4274
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
4275
- importedByMap.get(imported).add(importer);
4276
- }
4277
- }
4278
-
4279
- for (const file of files) {
4280
- const ext = path.extname(file).toLowerCase();
4281
- let fileFindings;
4282
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
4283
- fileFindings = await detectHtml(file);
4284
- } else {
4285
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
4286
- }
4287
- // Annotate findings with import context
4288
- const importers = importedByMap.get(file);
4289
- if (importers && importers.size > 0) {
4290
- const importerNames = [...importers].map(f => path.basename(f));
4291
- for (const f of fileFindings) {
4292
- f.importedBy = importerNames;
4293
- }
4294
- }
4295
- allFindings.push(...fileFindings);
4296
- }
4297
- } else if (stat.isFile()) {
4298
- const ext = path.extname(resolved).toLowerCase();
4299
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
4300
- allFindings.push(...await detectHtml(resolved));
4301
- } else {
4302
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
4303
- }
4304
- }
4305
- }
4306
- }
4307
-
4308
- if (allFindings.length > 0) {
4309
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
4310
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
4311
- process.exit(2);
4312
- }
4313
- if (jsonMode) process.stdout.write('[]\n');
4314
- process.exit(0);
4315
- }
4316
-
4317
- // ---------------------------------------------------------------------------
4318
- // Entry point
4319
- // ---------------------------------------------------------------------------
4320
-
4321
- if (!IS_BROWSER) {
4322
- const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
4323
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
4324
- if (isMainModule) main();
4325
- }
4326
-
4327
- // @browser-strip-end
4328
-
4329
- // ─── Section 9: Exports ─────────────────────────────────────────────────────
4330
- // @browser-strip-start
11
+ import { detectCli } from './cli/main.mjs';
4331
12
 
13
+ export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
14
+ export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
15
+ export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
16
+ export { isFullPage } from './shared/page.mjs';
4332
17
  export {
4333
- ANTIPATTERNS, SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS,
4334
- checkElementBorders, checkElementMotion, checkElementGlow, checkPageTypography, checkPageLayout, isNeutralColor, isFullPage,
4335
- detectHtml, detectUrl, detectText,
4336
- walkDir, formatFindings, SCANNABLE_EXTENSIONS, SKIP_DIRS,
4337
- extractStyleBlocks, extractCSSinJS,
4338
- buildImportGraph, resolveImport,
4339
- detectFrameworkConfig, isPortListening, FRAMEWORK_CONFIGS,
4340
- main as detectCli,
4341
- };
4342
-
4343
- // @browser-strip-end
18
+ checkElementBorders,
19
+ checkElementMotion,
20
+ checkElementGlow,
21
+ checkPageTypography,
22
+ checkPageLayout,
23
+ checkHtmlPatterns,
24
+ } from './rules/checks.mjs';
25
+ export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
26
+ export { detectHtml } from './engines/static-html/detect-html.mjs';
27
+ export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
28
+ export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
29
+ export {
30
+ walkDir,
31
+ SCANNABLE_EXTENSIONS,
32
+ SKIP_DIRS,
33
+ buildImportGraph,
34
+ resolveImport,
35
+ detectFrameworkConfig,
36
+ isPortListening,
37
+ FRAMEWORK_CONFIGS,
38
+ } from './node/file-system.mjs';
39
+ export { formatFindings, detectCli } from './cli/main.mjs';
40
+
41
+ const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
42
+ process.argv[1]?.endsWith('detect-antipatterns.mjs/');
43
+ if (isMainModule) detectCli();