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.
@@ -3,7 +3,7 @@
3
3
  * Copyright (c) 2026 Paul Bakaus
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  *
6
- * GENERATED -- do not edit. Source: detect-antipatterns.mjs
6
+ * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
7
7
  * Rebuild: node scripts/build-browser-detector.js
8
8
  *
9
9
  * Usage: <script src="detect-antipatterns-browser.js"></script>
@@ -11,33 +11,7 @@
11
11
  */
12
12
  (function () {
13
13
  if (typeof window === 'undefined') return;
14
-
15
- /**
16
- * Anti-Pattern Detector for Impeccable
17
- * Copyright (c) 2026 Paul Bakaus
18
- * SPDX-License-Identifier: Apache-2.0
19
- *
20
- * Universal file — auto-detects environment (browser vs Node) and adapts.
21
- *
22
- * Node usage:
23
- * node detect-antipatterns.mjs [file-or-dir...] # jsdom for HTML, regex for rest
24
- * node detect-antipatterns.mjs https://... # Puppeteer (auto)
25
- * node detect-antipatterns.mjs --fast [files...] # regex-only (skip jsdom)
26
- * node detect-antipatterns.mjs --json # JSON output
27
- *
28
- * Browser usage:
29
- * <script src="detect-antipatterns-browser.js"></script>
30
- * Re-scan: window.impeccableScan()
31
- *
32
- * Exit codes: 0 = clean, 2 = findings
33
- */
34
-
35
- // ─── Environment ────────────────────────────────────────────────────────────
36
-
37
- const IS_BROWSER = true;
38
- const IS_NODE = !IS_BROWSER;
39
-
40
-
14
+ // --- cli/engine/shared/constants.mjs ---
41
15
  // ─── Section 1: Constants ───────────────────────────────────────────────────
42
16
 
43
17
  const SAFE_TAGS = new Set([
@@ -64,7 +38,7 @@ const OVERUSED_FONTS = new Set([
64
38
  // Older monoculture (still ubiquitous):
65
39
  'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
66
40
  // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
67
- 'fraunces', 'instrument sans',
41
+ 'fraunces', 'instrument sans', 'instrument serif',
68
42
  'geist', 'geist sans', 'geist mono',
69
43
  'mona sans',
70
44
  'plus jakarta sans', 'space grotesk', 'recoleta',
@@ -103,6 +77,11 @@ const GENERIC_FONTS = new Set([
103
77
  'inherit', 'initial', 'unset', 'revert',
104
78
  ]);
105
79
 
80
+ // WCAG large text thresholds are defined in points: 18pt normal text and
81
+ // 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
82
+ const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
83
+ const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
84
+
106
85
  // Serif faces that show up in italic-display heroes. The rule also fires when
107
86
  // the primary face is unknown but the stack ends in the generic `serif` token,
108
87
  // which catches custom/private faces with a serif fallback.
@@ -120,6 +99,7 @@ const KNOWN_SERIF_FONTS = new Set([
120
99
  'freight display', 'freight text',
121
100
  ]);
122
101
 
102
+ // --- cli/engine/registry/antipatterns.mjs ---
123
103
  const ANTIPATTERNS = [
124
104
  // ── AI slop: tells that something was AI-generated ──
125
105
  {
@@ -185,6 +165,15 @@ const ANTIPATTERNS = [
185
165
  skillSection: 'Color & Contrast',
186
166
  skillGuideline: 'AI color palette',
187
167
  },
168
+ {
169
+ id: 'cream-palette',
170
+ category: 'slop',
171
+ name: 'Cream / beige palette',
172
+ description:
173
+ 'A warm cream or beige page background has become the default "tasteful" AI surface, reached for by reflex. Choose a background that comes from a deliberate palette, not the safe warm off-white.',
174
+ skillSection: 'Color & Contrast',
175
+ skillGuideline: 'cream and beige as the default surface',
176
+ },
188
177
  {
189
178
  id: 'nested-cards',
190
179
  category: 'slop',
@@ -203,15 +192,6 @@ const ANTIPATTERNS = [
203
192
  skillSection: 'Layout & Space',
204
193
  skillGuideline: 'same spacing everywhere',
205
194
  },
206
- {
207
- id: 'everything-centered',
208
- category: 'slop',
209
- name: 'Everything centered',
210
- description:
211
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
212
- skillSection: 'Layout & Space',
213
- skillGuideline: 'Center everything',
214
- },
215
195
  {
216
196
  id: 'bounce-easing',
217
197
  category: 'slop',
@@ -267,17 +247,72 @@ const ANTIPATTERNS = [
267
247
  skillSection: 'Typography',
268
248
  skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
269
249
  },
270
-
271
- // ── Quality: general design and accessibility issues ──
272
250
  {
273
- id: 'pure-black-white',
251
+ id: 'numbered-section-markers',
252
+ category: 'slop',
253
+ severity: 'advisory',
254
+ name: 'Numbered section markers (01 / 02 / 03)',
255
+ description:
256
+ 'Numbered display markers as section labels (01, 02, 03) are the AI editorial scaffold one tier deeper than tracked eyebrow chips. If you find yourself reaching for them, choose a different section cadence.',
257
+ skillSection: 'Layout & Space',
258
+ skillGuideline: 'numbered section markers',
259
+ },
260
+ {
261
+ id: 'em-dash-overuse',
262
+ category: 'slop',
263
+ name: 'Em-dash overuse',
264
+ description:
265
+ 'More than two em-dashes (— or --) in body copy is an AI cadence tell. Use commas, colons, periods, or parentheses instead.',
266
+ skillSection: 'Copy',
267
+ skillGuideline: 'no em dashes',
268
+ },
269
+ {
270
+ id: 'marketing-buzzword',
271
+ category: 'slop',
272
+ name: 'Marketing buzzword',
273
+ description:
274
+ 'Generic SaaS phrases (streamline / empower / supercharge / world-class / enterprise-grade / next-generation / cutting-edge / etc) are instant AI tells. Pick a specific verb and noun that says what the product literally does.',
275
+ skillSection: 'Copy',
276
+ skillGuideline: 'marketing buzzwords',
277
+ },
278
+ {
279
+ id: 'aphoristic-cadence',
280
+ category: 'slop',
281
+ name: 'Aphoristic-cadence copy',
282
+ description:
283
+ 'Three or more sections landing on a short rebuttal sentence ("X. No Y." / "X. Just Y.") or a manufactured-contrast aphorism ("Not a feature. A platform.") reads as AI cadence, not voice. Once is fine; the pattern is the tell.',
284
+ skillSection: 'Copy',
285
+ skillGuideline: 'aphoristic cadence',
286
+ },
287
+ {
288
+ id: 'oversized-h1',
289
+ category: 'slop',
290
+ name: 'Oversized hero headline',
291
+ description:
292
+ 'A full-sentence headline set at display size ends up dominating the viewport, leaving no room for anything else above the fold. A punchy one- or two-word headline at that size is fine — the problem is a long headline blown up too large. Set long headlines smaller, or tighten the copy.',
293
+ skillSection: 'Typography',
294
+ skillGuideline: 'long headline set at display size',
295
+ },
296
+ {
297
+ id: 'extreme-negative-tracking',
298
+ category: 'slop',
299
+ name: 'Crushed letter spacing',
300
+ description:
301
+ 'Letter-spacing pulled tighter than the point where characters keep their own shapes costs legibility. Tighten display type optically, not destructively.',
302
+ skillSection: 'Typography',
303
+ skillGuideline: 'letter spacing crushed past legibility',
304
+ },
305
+ {
306
+ id: 'broken-image',
274
307
  category: 'quality',
275
- name: 'Pure black background',
308
+ name: 'Broken or placeholder image',
276
309
  description:
277
- '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.',
278
- skillSection: 'Color & Contrast',
279
- skillGuideline: 'pure black (#000)',
310
+ '<img> tags with empty src, missing src, or placeholder values ship as broken-image boxes. Use real images, generated assets, or remove the tag.',
311
+ skillSection: 'Imagery',
312
+ skillGuideline: 'broken image references',
280
313
  },
314
+
315
+ // ── Quality: general design and accessibility issues ──
281
316
  {
282
317
  id: 'gray-on-color',
283
318
  category: 'quality',
@@ -317,7 +352,9 @@ const ANTIPATTERNS = [
317
352
  category: 'quality',
318
353
  name: 'Cramped padding',
319
354
  description:
320
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
355
+ 'Text is too close to the edge of its container. Two shapes: (1) an element with its own text where the padding is too low for the font size, and (2) a wrapper with text-bearing children and near-zero padding against a visible boundary (border, outline, or non-transparent background) — children land flush against the boundary line. Add at least 8px (ideally 12–16px) of padding inside bordered, outlined, or colored containers.',
356
+ skillSection: 'Layout & Space',
357
+ skillGuideline: 'inside bordered or colored containers',
321
358
  },
322
359
  {
323
360
  id: 'body-text-viewport-edge',
@@ -370,8 +407,73 @@ const ANTIPATTERNS = [
370
407
  description:
371
408
  'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
372
409
  },
410
+ {
411
+ id: 'text-overflow',
412
+ category: 'quality',
413
+ name: 'Content overflowing its container',
414
+ description:
415
+ 'Content renders wider than its container, spilling out or forcing a horizontal scrollbar. Let text wrap, constrain widths, or give the region a deliberate scroll affordance.',
416
+ skillSection: 'Layout & Space',
417
+ skillGuideline: 'content wider than its container',
418
+ },
419
+ {
420
+ id: 'clipped-overflow-container',
421
+ category: 'quality',
422
+ name: 'Positioned child clipped by overflow container',
423
+ description:
424
+ 'A clipping container (overflow hidden or clip) wrapping an absolutely-positioned child cuts off tooltips, menus, and popovers that need to escape. Let the overflow be visible, or move the positioned layer out of the clip.',
425
+ skillSection: 'Layout & Space',
426
+ skillGuideline: 'overflow container clipping positioned children',
427
+ },
428
+
429
+ // ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
430
+ {
431
+ id: 'gpt-thin-border-wide-shadow',
432
+ category: 'slop',
433
+ severity: 'advisory',
434
+ gated: 'gpt',
435
+ name: 'Hairline border with wide shadow',
436
+ description:
437
+ 'A hairline border paired with a wide, diffuse shadow is a recurring generated-UI signature. Commit to one — a defined edge or a soft elevation — rather than both at once.',
438
+ skillSection: 'Visual Details',
439
+ skillGuideline: 'hairline border plus wide diffuse shadow',
440
+ },
441
+ {
442
+ id: 'repeating-stripes-gradient',
443
+ category: 'slop',
444
+ severity: 'advisory',
445
+ gated: 'gpt',
446
+ name: 'Repeating-gradient stripes',
447
+ description:
448
+ 'Repeating-gradient stripes used as surface decoration are a recurring generated-UI signature. Reach for a deliberate texture or leave the surface plain.',
449
+ skillSection: 'Visual Details',
450
+ skillGuideline: 'repeating-gradient decorative stripes',
451
+ },
452
+ {
453
+ id: 'theater-slop-phrase',
454
+ category: 'slop',
455
+ severity: 'advisory',
456
+ gated: 'gpt',
457
+ name: 'Theater framing copy',
458
+ description:
459
+ 'Dismissing something as "theater" is a recurring generated-copy tic. Say plainly what the thing does or does not do.',
460
+ skillSection: 'Copy',
461
+ skillGuideline: 'theater framing copy',
462
+ },
463
+ {
464
+ id: 'image-hover-transform',
465
+ category: 'slop',
466
+ severity: 'advisory',
467
+ gated: 'gemini',
468
+ name: 'Image hover transform',
469
+ description:
470
+ 'Scaling or rotating an image on hover is a recurring generated-UI signature. Let imagery sit still, or use a subtler, purposeful interaction.',
471
+ skillSection: 'Motion',
472
+ skillGuideline: 'image scale or rotate on hover',
473
+ },
373
474
  ];
374
475
 
476
+ // --- cli/engine/shared/color.mjs ---
375
477
  // ─── Section 2: Color Utilities ─────────────────────────────────────────────
376
478
 
377
479
  function isNeutralColor(color) {
@@ -387,19 +489,19 @@ function isNeutralColor(color) {
387
489
  // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
388
490
  // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
389
491
  // literally (it does NOT convert them to rgb).
390
- const oklch = color.match(/oklch\(\s*[\d.%-]+\s+([\d.-]+)/i);
492
+ const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
391
493
  if (oklch) return parseFloat(oklch[1]) < 0.02;
392
- const lch = color.match(/lch\(\s*[\d.%-]+\s+([\d.-]+)/i);
494
+ const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
393
495
  if (lch) return parseFloat(lch[1]) < 3;
394
496
 
395
497
  // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
396
498
  // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
397
- const oklab = color.match(/oklab\(\s*[\d.%-]+\s+([\d.-]+)\s+([\d.-]+)/i);
499
+ const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
398
500
  if (oklab) {
399
501
  const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
400
502
  return Math.hypot(a, b) < 0.02;
401
503
  }
402
- const lab = color.match(/lab\(\s*[\d.%-]+\s+([\d.-]+)\s+([\d.-]+)/i);
504
+ const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
403
505
  if (lab) {
404
506
  const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
405
507
  return Math.hypot(a, b) < 3;
@@ -486,6 +588,9 @@ function colorToHex(c) {
486
588
  return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
487
589
  }
488
590
 
591
+ // --- cli/engine/rules/checks.mjs ---
592
+ const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
593
+
489
594
  // ─── Section 3: Pure Detection ──────────────────────────────────────────────
490
595
 
491
596
  function checkBorders(tag, widths, colors, radius) {
@@ -543,11 +648,6 @@ function checkColors(opts) {
543
648
  }
544
649
  const findings = [];
545
650
 
546
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
547
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
548
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
549
- }
550
-
551
651
  if (hasDirectText && textColor && !isEmojiOnly) {
552
652
  // Run background-dependent checks against either a solid bg or, if the
553
653
  // ancestor is a gradient, against every gradient stop (use the worst case).
@@ -566,8 +666,7 @@ function checkColors(opts) {
566
666
  let worstIdx = 0;
567
667
  for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
568
668
  const ratio = ratios[worstIdx];
569
- const isHeading = ['h1', 'h2', 'h3'].includes(tag);
570
- const isLargeText = fontSize >= 18 || (fontSize >= 14 && fontWeight >= 700) || isHeading;
669
+ const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
571
670
  const threshold = isLargeText ? 3.0 : 4.5;
572
671
  if (ratio < threshold) {
573
672
  // Skip the false-positive class where text has alpha < 1 AND we
@@ -580,7 +679,7 @@ function checkColors(opts) {
580
679
  // local bg. Real low-contrast bugs use alpha=1 and have a
581
680
  // resolvable opaque ancestor; semi-transparent Tailwind tokens
582
681
  // like `text-paper/60` on `bg-ink` sections are the FP pattern.
583
- const isAlphaFallbackFP = !IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
682
+ const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
584
683
  if (!isAlphaFallbackFP) {
585
684
  findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
586
685
  }
@@ -604,9 +703,6 @@ function checkColors(opts) {
604
703
  // Tailwind class checks
605
704
  if (classList) {
606
705
  const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
607
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
608
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
609
- }
610
706
 
611
707
  const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
612
708
  const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
@@ -922,12 +1018,6 @@ function checkHtmlPatterns(html) {
922
1018
 
923
1019
  // --- Color ---
924
1020
 
925
- // Pure black background
926
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
927
- if (pureBlackBgRe.test(html)) {
928
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
929
- }
930
-
931
1021
  // AI color palette: purple/violet
932
1022
  const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
933
1023
  if (purpleHexRe.test(html)) {
@@ -1044,6 +1134,39 @@ function checkHtmlPatterns(html) {
1044
1134
  }
1045
1135
  }
1046
1136
 
1137
+ // --- Provider tells (gated): repeating-gradient stripes (GPT) ---
1138
+ if (/repeating-(?:linear|radial|conic)-gradient\s*\(/i.test(html)) {
1139
+ findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
1140
+ }
1141
+
1142
+ // --- Provider tells (gated): "X theater" framing copy (GPT) ---
1143
+ // Lives here (regex-on-HTML) rather than in the text-content analyzers so it
1144
+ // runs in the bundled browser path too, not just the CLI/static path.
1145
+ {
1146
+ const bodyText = html
1147
+ .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, ' ')
1148
+ .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, ' ')
1149
+ .replace(/<[^>]+>/g, ' ');
1150
+ const tm = /\b(\w+)\s+theater\b/i.exec(bodyText);
1151
+ if (tm) findings.push({ id: 'theater-slop-phrase', snippet: `"${tm[0].trim()}"` });
1152
+ }
1153
+
1154
+ // --- Provider tells (gated): image hover transform (Gemini) ---
1155
+ // A CSS `img...:hover { transform: ... }` rule, or a Tailwind hover:scale /
1156
+ // hover:rotate / hover:translate utility on an <img>. Each distinct
1157
+ // mechanism is its own finding.
1158
+ const imgHoverCss = /\bimg\b[^,{}]*:hover\b[^{}]*\{[^}]*\btransform\s*:\s*(?:scale|rotate|translate|matrix|skew)/i;
1159
+ if (imgHoverCss.test(html)) {
1160
+ findings.push({ id: 'image-hover-transform', snippet: 'img:hover { transform } rule' });
1161
+ }
1162
+ const imgTagRe = /<img\b[^>]*\bclass\s*=\s*"([^"]*)"/gi;
1163
+ let im;
1164
+ while ((im = imgTagRe.exec(html)) !== null) {
1165
+ if (/\bhover:(?:scale|rotate|translate|skew)-/.test(im[1])) {
1166
+ findings.push({ id: 'image-hover-transform', snippet: 'Tailwind hover transform on <img>' });
1167
+ }
1168
+ }
1169
+
1047
1170
  return findings;
1048
1171
  }
1049
1172
 
@@ -1058,7 +1181,7 @@ function checkHtmlPatterns(html) {
1058
1181
  // a no-op there.
1059
1182
  function readOwnBackgroundColor(el, computedStyle) {
1060
1183
  const bg = parseRgb(computedStyle.backgroundColor);
1061
- if (IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
1184
+ if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
1062
1185
  const rawStyle = el.getAttribute?.('style') || '';
1063
1186
  const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
1064
1187
  const inlineBg = bgMatch ? bgMatch[1].trim() : '';
@@ -1080,7 +1203,7 @@ function readOwnBackgroundColor(el, computedStyle) {
1080
1203
  function resolveBackground(el, win, customPropMap) {
1081
1204
  let current = el;
1082
1205
  while (current && current.nodeType === 1) {
1083
- const style = IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
1206
+ const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
1084
1207
  const bgImage = style.backgroundImage || '';
1085
1208
  const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
1086
1209
 
@@ -1092,7 +1215,7 @@ function resolveBackground(el, win, customPropMap) {
1092
1215
  // caused massive false-positive contrast findings on grain-textured
1093
1216
  // body backgrounds.
1094
1217
  let bg = parseRgb(style.backgroundColor);
1095
- if (!IS_BROWSER && (!bg || bg.a < 0.1)) {
1218
+ if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
1096
1219
  // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
1097
1220
  // through customPropMap so Tailwind v4 color tokens become RGB.
1098
1221
  if (customPropMap) {
@@ -1111,7 +1234,7 @@ function resolveBackground(el, win, customPropMap) {
1111
1234
  }
1112
1235
 
1113
1236
  if (bg && bg.a > 0.1) {
1114
- if (IS_BROWSER || bg.a >= 0.5) return bg;
1237
+ if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
1115
1238
  }
1116
1239
  // No solid bg-color at this level. If THIS level has a gradient/url
1117
1240
  // with no underlying solid color we can read:
@@ -1142,13 +1265,13 @@ function resolveBackground(el, win, customPropMap) {
1142
1265
  function resolveGradientStops(el, win) {
1143
1266
  let current = el;
1144
1267
  while (current && current.nodeType === 1) {
1145
- const style = IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
1268
+ const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
1146
1269
  const bgImage = style.backgroundImage || '';
1147
1270
  if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
1148
1271
  const stops = parseGradientColors(bgImage);
1149
1272
  if (stops.length > 0) return stops;
1150
1273
  }
1151
- if (!IS_BROWSER) {
1274
+ if (!DETECTOR_IS_BROWSER) {
1152
1275
  // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
1153
1276
  const rawStyle = current.getAttribute?.('style') || '';
1154
1277
  const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
@@ -1185,57 +1308,10 @@ function parseRadiusToPx(value, widthPx) {
1185
1308
  return num;
1186
1309
  }
1187
1310
 
1188
- // jsdom from 29.0.2 onward returns "" for the `border-radius` shorthand
1189
- // in computed style and "0" for longhand reads when the source rule used
1190
- // the shorthand. The rule engine relied on parseFloat(style.borderRadius)
1191
- // to identify circular avatars (border-radius >= width/2) and rounded
1192
- // cards (border-radius > 0); both checks broke silently. This helper
1193
- // recovers the radius via a chain of fallbacks. Browsers resolve the
1194
- // shorthand correctly and exit on the first line.
1195
1311
  function resolveBorderRadiusPx(el, style, widthPx, win) {
1196
1312
  const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
1197
1313
  if (fromComputed !== null) return fromComputed;
1198
-
1199
- if (IS_BROWSER || !win) return 0;
1200
-
1201
- const fromLonghand = parseRadiusToPx(style.borderTopLeftRadius, widthPx);
1202
- if (fromLonghand !== null && fromLonghand > 0) return fromLonghand;
1203
-
1204
- const fromInlineProp = parseRadiusToPx(el.style?.borderRadius, widthPx);
1205
- if (fromInlineProp !== null) return fromInlineProp;
1206
-
1207
- const rawStyle = el.getAttribute?.('style') || '';
1208
- const inlineMatch = rawStyle.match(/border-radius\s*:\s*([^;]+)/i);
1209
- if (inlineMatch) {
1210
- const fromRaw = parseRadiusToPx(inlineMatch[1].trim(), widthPx);
1211
- if (fromRaw !== null) return fromRaw;
1212
- }
1213
-
1214
- // Walk every stylesheet looking for matching rules. Take the maximum
1215
- // pixel value across all matches so a circle declaration overridden by
1216
- // a more specific rounded-square selector still registers as a circle
1217
- // for the exclusion check (better to under-flag than to false-positive
1218
- // on round avatars).
1219
- let max = 0;
1220
- const sheets = win.document?.styleSheets;
1221
- if (sheets) {
1222
- for (const sheet of sheets) {
1223
- let rules;
1224
- try { rules = sheet.cssRules || []; } catch { continue; }
1225
- for (const rule of rules) {
1226
- if (!rule.style || !rule.selectorText) continue;
1227
- let matches = false;
1228
- try { matches = el.matches(rule.selectorText); } catch { continue; }
1229
- if (!matches) continue;
1230
- const ruleValue = rule.style.borderRadius
1231
- || (rule.style.getPropertyValue && rule.style.getPropertyValue('border-radius'))
1232
- || rule.style.borderTopLeftRadius;
1233
- const px = parseRadiusToPx(ruleValue, widthPx);
1234
- if (px !== null && px > max) max = px;
1235
- }
1236
- }
1237
- }
1238
- return max;
1314
+ return 0;
1239
1315
  }
1240
1316
 
1241
1317
  // ─── Section 5: Element Adapters ────────────────────────────────────────────
@@ -1737,7 +1813,7 @@ function resolveLengthPx(value, fontSizePx) {
1737
1813
  // Both adapters resolve font-size, line-height and letter-spacing to pixels
1738
1814
  // before calling this so the pure function only deals with numbers.
1739
1815
  function checkQuality(opts) {
1740
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
1816
+ const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0, win = null } = opts;
1741
1817
  const findings = [];
1742
1818
  // Skip browser extension injected elements
1743
1819
  const elId = el.id || '';
@@ -1788,6 +1864,155 @@ function checkQuality(opts) {
1788
1864
  }
1789
1865
  }
1790
1866
 
1867
+ // --- Flush against a visible boundary ---
1868
+ // Fires when a container has a visible boundary (border, outline, OR a
1869
+ // non-transparent background) AND near-zero padding on the bounded
1870
+ // side(s) AND text-bearing children land flush against the boundary.
1871
+ //
1872
+ // Distinct from cramped-padding: that rule needs the element itself to
1873
+ // have direct text (hasDirectText). This rule targets the OPPOSITE
1874
+ // shape — a container with NO direct text, only children — which is
1875
+ // exactly what cramped-padding misses (a section wrapping a label +
1876
+ // list lands a free pass).
1877
+ //
1878
+ // The classic shape: agent writes `padding: 28px 0 0` shorthand on a
1879
+ // section that also has a border, zeroing horizontal padding so the
1880
+ // text-bearing children touch the side borders. Background and
1881
+ // outline count too: a colored card with zero padding has the same
1882
+ // visual failure mode.
1883
+ {
1884
+ const FLUSH_SKIP_TAGS = new Set(['HTML', 'BODY', 'MAIN', 'HEADER', 'FOOTER', 'NAV', 'ARTICLE', 'ASIDE', 'BUTTON', 'A', 'LABEL', 'SUMMARY', 'CODE', 'PRE', 'INPUT', 'TEXTAREA', 'SELECT', 'FORM', 'FIGURE', 'TABLE', 'TBODY', 'THEAD', 'TR', 'TD', 'TH']);
1885
+ const upperTag = tag ? tag.toUpperCase() : '';
1886
+ const elPosition = style.position || '';
1887
+ if (
1888
+ !FLUSH_SKIP_TAGS.has(upperTag) &&
1889
+ !hasDirectText &&
1890
+ !['fixed', 'absolute'].includes(elPosition) &&
1891
+ el.children && el.children.length > 0
1892
+ ) {
1893
+ const isTransparent = (c) =>
1894
+ !c || c === 'transparent' || c === 'rgba(0, 0, 0, 0)' ||
1895
+ /^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*0(?:\.0+)?\s*\)$/.test(c);
1896
+
1897
+ const borderW = {
1898
+ top: parseFloat(style.borderTopWidth) || 0,
1899
+ right: parseFloat(style.borderRightWidth) || 0,
1900
+ bottom: parseFloat(style.borderBottomWidth) || 0,
1901
+ left: parseFloat(style.borderLeftWidth) || 0,
1902
+ };
1903
+ const borderVisible = {
1904
+ top: borderW.top > 0 && !isTransparent(style.borderTopColor),
1905
+ right: borderW.right > 0 && !isTransparent(style.borderRightColor),
1906
+ bottom: borderW.bottom > 0 && !isTransparent(style.borderBottomColor),
1907
+ left: borderW.left > 0 && !isTransparent(style.borderLeftColor),
1908
+ };
1909
+ // Outline detection. jsdom decomposes `border` shorthand into
1910
+ // border{Top,…}Width/Color but does NOT decompose `outline` —
1911
+ // the longhands come back empty when the value was set via the
1912
+ // shorthand. Fall back to parsing `style.outline` ourselves.
1913
+ let outlineW = parseFloat(style.outlineWidth) || 0;
1914
+ let outlineStyleVal = style.outlineStyle || '';
1915
+ let outlineColorVal = style.outlineColor || '';
1916
+ if (!outlineW && style.outline) {
1917
+ const wMatch = style.outline.match(/(\d+(?:\.\d+)?)\s*px/);
1918
+ if (wMatch) outlineW = parseFloat(wMatch[1]) || 0;
1919
+ if (!outlineStyleVal) {
1920
+ outlineStyleVal = /\b(solid|dashed|dotted|double|groove|ridge|inset|outset)\b/.test(style.outline) ? 'solid' : '';
1921
+ }
1922
+ if (!outlineColorVal) {
1923
+ const cMatch = style.outline.match(/(rgba?\([^)]+\)|#[0-9a-fA-F]{3,8}|[a-zA-Z]+)\s*$/);
1924
+ if (cMatch) outlineColorVal = cMatch[1];
1925
+ }
1926
+ }
1927
+ const outlineVisible = outlineW > 0 && !isTransparent(outlineColorVal) && outlineStyleVal && outlineStyleVal !== 'none';
1928
+ const bgVisible = !isTransparent(style.backgroundColor);
1929
+
1930
+ const anyVisible = borderVisible.top || borderVisible.right || borderVisible.bottom || borderVisible.left || outlineVisible || bgVisible;
1931
+ if (anyVisible) {
1932
+ // Resolve padding to px (jsdom returns raw "1.5rem" etc., not the
1933
+ // computed px value; parseFloat would strip the unit and treat
1934
+ // 1.5rem as 1.5px, false-flagging legitimate insets).
1935
+ const pad = {
1936
+ top: resolveLengthPx(style.paddingTop, fontSize) ?? 0,
1937
+ right: resolveLengthPx(style.paddingRight, fontSize) ?? 0,
1938
+ bottom: resolveLengthPx(style.paddingBottom, fontSize) ?? 0,
1939
+ left: resolveLengthPx(style.paddingLeft, fontSize) ?? 0,
1940
+ };
1941
+ const PAD_THRESHOLD = 2;
1942
+ // Children-insulate-this-side: a side is insulated if ANY direct
1943
+ // child has its own padding ≥ 4px on that side. Rationale: in
1944
+ // typical flow, only the first/last (or leftmost/rightmost)
1945
+ // children actually sit at the parent's edges. If even one of
1946
+ // them has its own padding, the visual flush is broken on that
1947
+ // side. Classic example: a column-flow card frame where the
1948
+ // top child (header) has padding-top:12 and the bottom child
1949
+ // (footer) has padding-bottom:8 — the parent's padding:0 doesn't
1950
+ // matter; nothing is actually flush. The `any-child-insulates`
1951
+ // heuristic accepts some false negatives (a card with one heavily
1952
+ // padded middle child won't flag) for far fewer false positives.
1953
+ const CHILD_INSULATE_THRESHOLD = 4;
1954
+ const childrenInsulate = { top: false, right: false, bottom: false, left: false };
1955
+ for (const child of el.children) {
1956
+ let childStyle = null;
1957
+ if (win && typeof win.getComputedStyle === 'function') {
1958
+ try { childStyle = win.getComputedStyle(child); } catch {}
1959
+ }
1960
+ if (!childStyle && typeof getComputedStyle === 'function') {
1961
+ try { childStyle = getComputedStyle(child); } catch {}
1962
+ }
1963
+ if (!childStyle) continue;
1964
+ const childPad = {
1965
+ top: resolveLengthPx(childStyle.paddingTop, fontSize) ?? 0,
1966
+ right: resolveLengthPx(childStyle.paddingRight, fontSize) ?? 0,
1967
+ bottom: resolveLengthPx(childStyle.paddingBottom, fontSize) ?? 0,
1968
+ left: resolveLengthPx(childStyle.paddingLeft, fontSize) ?? 0,
1969
+ };
1970
+ for (const s of ['top', 'right', 'bottom', 'left']) {
1971
+ if (childPad[s] >= CHILD_INSULATE_THRESHOLD) childrenInsulate[s] = true;
1972
+ }
1973
+ }
1974
+
1975
+ const flushSides = [];
1976
+ for (const side of ['top', 'right', 'bottom', 'left']) {
1977
+ const sideBounded = borderVisible[side] || outlineVisible || bgVisible;
1978
+ if (sideBounded && pad[side] <= PAD_THRESHOLD && !childrenInsulate[side]) {
1979
+ flushSides.push(side);
1980
+ }
1981
+ }
1982
+
1983
+ if (flushSides.length > 0) {
1984
+ // Confirm at least one direct child has substantial text content
1985
+ // (> 4 chars). Without this, the flush is harmless: e.g. an
1986
+ // image-only card.
1987
+ let hasTextChild = false;
1988
+ for (const child of el.children) {
1989
+ const childText = (child.textContent || '').trim();
1990
+ if (childText.length > 4) { hasTextChild = true; break; }
1991
+ }
1992
+ if (hasTextChild) {
1993
+ const cls = (typeof el.className === 'string' && el.className.trim())
1994
+ ? el.className.trim().split(/\s+/)[0]
1995
+ : '';
1996
+ const boundaryParts = [];
1997
+ const borderSidesVisible = ['top', 'right', 'bottom', 'left'].filter(s => borderVisible[s]);
1998
+ if (borderSidesVisible.length === 4) boundaryParts.push('border');
1999
+ else if (borderSidesVisible.length > 0) boundaryParts.push(`border-${borderSidesVisible.join('/')}`);
2000
+ if (outlineVisible) boundaryParts.push('outline');
2001
+ if (bgVisible) boundaryParts.push('bg');
2002
+ const sidesLabel = flushSides.length === 4 ? 'all sides' : flushSides.join('/');
2003
+ const ident = cls
2004
+ ? `<${tag.toLowerCase()}> "${cls}"`
2005
+ : `<${tag.toLowerCase()}>`;
2006
+ findings.push({
2007
+ id: 'cramped-padding',
2008
+ snippet: `${ident}: children flush against ${boundaryParts.join('+')} on ${sidesLabel} (no inset)`,
2009
+ });
2010
+ }
2011
+ }
2012
+ }
2013
+ }
2014
+ }
2015
+
1791
2016
  // --- Body text touching viewport edge --- (browser-only: needs rect)
1792
2017
  // Catches the failure mode where the agent ships body paragraphs
1793
2018
  // with NO container providing horizontal padding — text bleeds
@@ -1868,6 +2093,20 @@ function checkQuality(opts) {
1868
2093
  }
1869
2094
  }
1870
2095
 
2096
+ // --- Crushed letter spacing (mirror of wide-tracking) ---
2097
+ // Tracking pulled tighter than ~-0.05em crushes characters into each other.
2098
+ // Optical tightening that display type legitimately wants (around -0.02em)
2099
+ // stays well above this floor.
2100
+ if (hasDirectText && textLen > 20 && fontSize > 0) {
2101
+ if (letterSpacingPx != null && letterSpacingPx < 0) {
2102
+ const trackingEm = letterSpacingPx / fontSize;
2103
+ if (trackingEm <= -0.05) {
2104
+ const excerpt = (el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 40);
2105
+ findings.push({ id: 'extreme-negative-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em — "${excerpt}"` });
2106
+ }
2107
+ }
2108
+ }
2109
+
1871
2110
  return findings;
1872
2111
  }
1873
2112
 
@@ -1884,7 +2123,7 @@ function checkElementQualityDOM(el) {
1884
2123
  const rect = el.getBoundingClientRect();
1885
2124
  const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
1886
2125
  const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
1887
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
2126
+ return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth, win: typeof window !== 'undefined' ? window : null });
1888
2127
  }
1889
2128
 
1890
2129
  // Pure page-level skipped-heading walk. Takes a Document so it works in both
@@ -1926,7 +2165,7 @@ function checkElementQuality(el, style, tag, window) {
1926
2165
  const fontSize = resolveFontSizePx(el, window);
1927
2166
  const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
1928
2167
  const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
1929
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
2168
+ return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null, win: window });
1930
2169
  }
1931
2170
 
1932
2171
  function checkElementBorders(tag, style, overrides, resolvedRadius) {
@@ -2367,40 +2606,216 @@ function checkPageLayout(doc, win) {
2367
2606
  }
2368
2607
  }
2369
2608
 
2370
- // Everything centered
2371
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
2372
- let centeredCount = 0;
2373
- let totalText = 0;
2374
- for (const el of textEls) {
2375
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
2376
- if (!hasDirectText) continue;
2377
- totalText++;
2609
+ return findings;
2610
+ }
2378
2611
 
2379
- let cur = el;
2380
- let isCentered = false;
2381
- while (cur && cur.nodeType === 1) {
2382
- const rawStyle = cur.getAttribute?.('style') || '';
2383
- const cls = cur.getAttribute?.('class') || '';
2384
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
2385
- isCentered = true;
2386
- break;
2387
- }
2388
- if (cur.tagName === 'BODY') break;
2389
- cur = cur.parentElement;
2390
- }
2391
- if (isCentered) centeredCount++;
2612
+ // ─── Cream / beige palette (the default "tasteful" AI surface) ────────────────
2613
+ // A warm, lightly-tinted off-white page background — light, with R≥G≥B and a
2614
+ // small warm tint (not white, not a strong color). The current reflex surface.
2615
+ function isCreamColor(rgb) {
2616
+ if (!rgb) return false;
2617
+ const { r, g, b } = rgb;
2618
+ if (Math.min(r, g, b) < 209) return false; // must be light
2619
+ if (!(r >= g && g >= b)) return false; // warm ordering
2620
+ const warmth = r - b;
2621
+ return warmth >= 6 && warmth <= 48; // tinted, not white, not strong
2622
+ }
2623
+
2624
+ // Tailwind background utilities that render as a warm off-white surface. The
2625
+ // static engine doesn't fetch Tailwind's CSS, so a `bg-amber-50` on <body>
2626
+ // resolves to nothing in computed style — catch it from the class list
2627
+ // instead. Candidate tokens map to their actual Tailwind hex and are still
2628
+ // filtered through isCreamColor, so neutral grays (stone) and over-saturated
2629
+ // shades drop out on their own.
2630
+ const TAILWIND_BG_HEX = {
2631
+ 'bg-amber-50': '#fffbeb', 'bg-amber-100': '#fef3c7',
2632
+ 'bg-orange-50': '#fff7ed', 'bg-orange-100': '#ffedd5',
2633
+ 'bg-yellow-50': '#fefce8',
2634
+ 'bg-stone-50': '#fafaf9', 'bg-stone-100': '#f5f5f4', 'bg-stone-200': '#e7e5e4',
2635
+ };
2636
+
2637
+ function creamFromClassList(cls) {
2638
+ if (!cls) return null;
2639
+ // Arbitrary value: bg-[#f5f0e6] / bg-[rgb(245_240_230)] (underscores = spaces).
2640
+ const arb = cls.match(/\bbg-\[([^\]]+)\]/);
2641
+ if (arb && isCreamColor(parseAnyColor(arb[1].replace(/_/g, ' ')))) return `bg-[${arb[1]}]`;
2642
+ // Named warm-light utilities.
2643
+ for (const [tok, hex] of Object.entries(TAILWIND_BG_HEX)) {
2644
+ if (new RegExp(`(^|\\s)${tok}($|\\s)`).test(cls) && isCreamColor(parseAnyColor(hex))) return tok;
2392
2645
  }
2646
+ return null;
2647
+ }
2393
2648
 
2394
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
2395
- findings.push({
2396
- id: 'everything-centered',
2397
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
2398
- });
2649
+ function checkCreamPalette(doc, win) {
2650
+ const findings = [];
2651
+ const body = doc.body || (doc.querySelector ? doc.querySelector('body') : null);
2652
+ if (!body) return findings;
2653
+ const html = doc.documentElement;
2654
+ const getCS = (el) => (win ? win.getComputedStyle(el) : getComputedStyle(el));
2655
+
2656
+ // 1. Computed background — covers inline / <style> / linked CSS, and Tailwind
2657
+ // once it's actually rendered (browser path).
2658
+ let bg = readOwnBackgroundColor(body, getCS(body));
2659
+ if (!bg || bg.a === 0) {
2660
+ if (html) bg = readOwnBackgroundColor(html, getCS(html));
2661
+ }
2662
+ if (isCreamColor(bg)) {
2663
+ findings.push({ id: 'cream-palette', snippet: `cream/beige page background rgb(${bg.r}, ${bg.g}, ${bg.b})` });
2664
+ return findings;
2399
2665
  }
2400
2666
 
2667
+ // 2. Tailwind class fallback — for the static path, where utility classes
2668
+ // never resolve to computed CSS.
2669
+ for (const el of [body, html]) {
2670
+ const tok = creamFromClassList(el && el.getAttribute ? el.getAttribute('class') : '');
2671
+ if (tok) {
2672
+ findings.push({ id: 'cream-palette', snippet: `cream/beige page background (Tailwind ${tok})` });
2673
+ break;
2674
+ }
2675
+ }
2401
2676
  return findings;
2402
2677
  }
2403
2678
 
2679
+ // ─── Oversized hero headline ────────────────────────────────────────────────
2680
+ // Fires when a *long* headline is set at display size, so a full sentence ends
2681
+ // up dominating the viewport. A punchy one- or two-word headline at the same
2682
+ // size is a legitimate stylistic choice and must pass — length, not size
2683
+ // alone, is the tell.
2684
+ const OVERSIZED_H1_FONT_PX = 72;
2685
+ const OVERSIZED_H1_MIN_CHARS = 40;
2686
+ function checkOversizedH1({ tag, fontSize, headingText }) {
2687
+ if (tag !== 'h1') return [];
2688
+ const textLen = headingText.length;
2689
+ if (fontSize >= OVERSIZED_H1_FONT_PX && textLen >= OVERSIZED_H1_MIN_CHARS) {
2690
+ return [{ id: 'oversized-h1', snippet: `${Math.round(fontSize)}px h1, ${textLen} chars "${headingText.slice(0, 60)}"` }];
2691
+ }
2692
+ return [];
2693
+ }
2694
+
2695
+ function checkElementOversizedH1(el, style, tag, window) {
2696
+ if (tag !== 'h1') return [];
2697
+ const fontSize = resolveFontSizePx(el, window);
2698
+ const headingText = (el.textContent || '').trim().replace(/\s+/g, ' ');
2699
+ return checkOversizedH1({ tag, fontSize, headingText });
2700
+ }
2701
+
2702
+ function checkElementOversizedH1DOM(el) {
2703
+ const tag = el.tagName.toLowerCase();
2704
+ if (tag !== 'h1') return [];
2705
+ const style = getComputedStyle(el);
2706
+ const fontSize = parseFloat(style.fontSize) || 0;
2707
+ const headingText = (el.textContent || '').trim().replace(/\s+/g, ' ');
2708
+ return checkOversizedH1({ tag, fontSize, headingText });
2709
+ }
2710
+
2711
+ // ─── GPT tell: hairline border + wide diffuse shadow (gated --gpt) ────────────
2712
+ function shadowMaxBlurPx(boxShadow) {
2713
+ if (!boxShadow || boxShadow === 'none') return 0;
2714
+ let maxBlur = 0;
2715
+ // Split into layers on commas not inside parentheses (rgba(...) etc.).
2716
+ for (const layer of boxShadow.split(/,(?![^()]*\))/)) {
2717
+ // Strip colors and keywords (rgba()/hsl()/hex/named/inset/px), leaving the
2718
+ // ordered length tokens: offsetX offsetY blur [spread]. Static jsdom keeps
2719
+ // unitless zeros ("0 0 24px"); browsers normalize to px ("0px 0px 24px") —
2720
+ // both reduce to the same numbers here.
2721
+ const cleaned = layer.replace(/rgba?\([^)]*\)|hsla?\([^)]*\)|#[0-9a-f]+|\b[a-z]+\b/gi, ' ');
2722
+ const nums = [...cleaned.matchAll(/-?\d*\.?\d+/g)].map(m => parseFloat(m[0]));
2723
+ if (nums.length >= 3) maxBlur = Math.max(maxBlur, nums[2]);
2724
+ }
2725
+ return maxBlur;
2726
+ }
2727
+
2728
+ function checkGptThinBorderWideShadow({ borderWidths, boxShadow }) {
2729
+ const maxBorder = Math.max(0, ...borderWidths);
2730
+ const hasThinBorder = maxBorder > 0 && maxBorder <= 1.5;
2731
+ const blur = shadowMaxBlurPx(boxShadow);
2732
+ if (hasThinBorder && blur >= 16) {
2733
+ return [{ id: 'gpt-thin-border-wide-shadow', snippet: `${maxBorder}px border + ${Math.round(blur)}px shadow blur` }];
2734
+ }
2735
+ return [];
2736
+ }
2737
+
2738
+ function borderWidthsFromStyle(style) {
2739
+ return [
2740
+ parseFloat(style.borderTopWidth) || 0,
2741
+ parseFloat(style.borderRightWidth) || 0,
2742
+ parseFloat(style.borderBottomWidth) || 0,
2743
+ parseFloat(style.borderLeftWidth) || 0,
2744
+ ];
2745
+ }
2746
+
2747
+ function checkElementGptBorderShadow(el, style) {
2748
+ return checkGptThinBorderWideShadow({ borderWidths: borderWidthsFromStyle(style), boxShadow: style.boxShadow || '' });
2749
+ }
2750
+
2751
+ function checkElementGptBorderShadowDOM(el) {
2752
+ const style = getComputedStyle(el);
2753
+ return checkGptThinBorderWideShadow({ borderWidths: borderWidthsFromStyle(style), boxShadow: style.boxShadow || '' });
2754
+ }
2755
+
2756
+ // ─── Clipped overflow container ───────────────────────────────────────────────
2757
+ // A clipping container (overflow hidden/clip, not a scroll region) wrapping an
2758
+ // absolutely/fixed-positioned descendant clips popovers/menus that must escape.
2759
+ function classSelector(el) {
2760
+ const cls = (el.getAttribute ? el.getAttribute('class') : el.className) || '';
2761
+ const tokens = String(cls).trim().split(/\s+/).filter(Boolean);
2762
+ const tag = el.tagName ? el.tagName.toLowerCase() : 'el';
2763
+ return tokens.length ? `${tag}.${tokens.join('.')}` : tag;
2764
+ }
2765
+
2766
+ function checkClippedOverflow(el, style, getStyle) {
2767
+ const clips = (v) => v === 'hidden' || v === 'clip';
2768
+ const scrolls = (v) => v === 'auto' || v === 'scroll';
2769
+ const ox = style.overflowX || '', oy = style.overflowY || '', ov = style.overflow || '';
2770
+ const anyClip = clips(ox) || clips(oy) || clips(ov);
2771
+ const anyScroll = scrolls(ox) || scrolls(oy) || scrolls(ov);
2772
+ if (!anyClip || anyScroll) return [];
2773
+ if (!el.querySelectorAll) return [];
2774
+ for (const child of el.querySelectorAll('*')) {
2775
+ const pos = (getStyle(child).position) || '';
2776
+ if (pos === 'absolute' || pos === 'fixed') {
2777
+ return [{ id: 'clipped-overflow-container', snippet: `${classSelector(el)} clips a positioned child` }];
2778
+ }
2779
+ }
2780
+ return [];
2781
+ }
2782
+
2783
+ function checkElementClippedOverflow(el, style, tag, window) {
2784
+ return checkClippedOverflow(el, style, (n) => window.getComputedStyle(n));
2785
+ }
2786
+
2787
+ function checkElementClippedOverflowDOM(el) {
2788
+ const style = getComputedStyle(el);
2789
+ return checkClippedOverflow(el, style, (n) => getComputedStyle(n));
2790
+ }
2791
+
2792
+ // ─── Text overflow (browser-only: needs scrollWidth/clientWidth) ──────────────
2793
+ const TEXT_OVERFLOW_SKIP_TAGS = new Set(['pre', 'code', 'textarea', 'svg', 'canvas', 'select', 'option', 'marquee']);
2794
+
2795
+ function checkElementTextOverflowDOM(el) {
2796
+ const tag = el.tagName.toLowerCase();
2797
+ if (TEXT_OVERFLOW_SKIP_TAGS.has(tag)) return [];
2798
+ // Only the element that actually owns overflowing text — not its ancestors,
2799
+ // which inherit a wider scrollWidth from the spilling descendant.
2800
+ const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
2801
+ if (!hasDirectText) return [];
2802
+ const style = getComputedStyle(el);
2803
+ const isScrollRegion = (s) => /(auto|scroll)/.test(s.overflowX || '') || /(auto|scroll)/.test(s.overflow || '');
2804
+ if (isScrollRegion(style)) return [];
2805
+ // A scrollable ancestor means this overflow is intentional and scrollable.
2806
+ for (let p = el.parentElement; p; p = p.parentElement) {
2807
+ if (isScrollRegion(getComputedStyle(p))) return [];
2808
+ }
2809
+ const delta = el.scrollWidth - el.clientWidth;
2810
+ if (el.clientWidth > 0 && delta >= 16) {
2811
+ return [{ id: 'text-overflow', snippet: `${classSelector(el)} overflows its box by ${Math.round(delta)}px` }];
2812
+ }
2813
+ return [];
2814
+ }
2815
+
2816
+ // --- cli/engine/browser/injected/index.mjs ---
2817
+ const IS_BROWSER = typeof window !== 'undefined';
2818
+
2404
2819
  // ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
2405
2820
 
2406
2821
  if (IS_BROWSER) {
@@ -2410,8 +2825,21 @@ if (IS_BROWSER) {
2410
2825
  const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
2411
2826
  || document.documentElement.dataset.impeccableExtension === 'true';
2412
2827
 
2413
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
2414
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
2828
+ // Kinpaku gold — pinned to the site's brand token (see
2829
+ // site/styles/kinpaku-tokens.css --ks-kinpaku). Keep this in sync with
2830
+ // the picker's C.brand in skill/scripts/live-browser.js and the kit's
2831
+ // picker section in site/styles/kinpaku-kit.css.
2832
+ //
2833
+ // One color across both light and dark host pages. The outline is a
2834
+ // 2px gesture pointing at an element + a labeled tag — it's a marker,
2835
+ // not body text, so it doesn't need WCAG AA against the page. The
2836
+ // label text inside the gold tag is dark (LABEL_INK) which has ~16:1
2837
+ // against the leaf gold, so reading the rule name is solid in both
2838
+ // modes. Hover deepens the gold (preserves chroma — never drops it,
2839
+ // dropping chroma washes the gold into a sand/olive tone).
2840
+ const BRAND_COLOR = 'oklch(84% 0.19 80.46)';
2841
+ const BRAND_COLOR_HOVER = 'oklch(74% 0.18 80)';
2842
+ const LABEL_INK = 'oklch(4% 0.004 95)';
2415
2843
  const LABEL_BG = BRAND_COLOR;
2416
2844
  const OUTLINE_COLOR = BRAND_COLOR;
2417
2845
 
@@ -2466,16 +2894,12 @@ if (IS_BROWSER) {
2466
2894
  .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
2467
2895
  display: none !important;
2468
2896
  }
2469
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
2470
- display: none !important;
2471
- }
2472
2897
  `;
2473
2898
  (document.head || document.documentElement).appendChild(styleEl);
2474
2899
 
2475
2900
  // Spotlight backdrop element (created lazily on first use)
2476
2901
  let spotlightBackdrop = null;
2477
2902
  let spotlightTarget = null;
2478
- let spotlightTimer = null;
2479
2903
 
2480
2904
  function getSpotlightBackdrop() {
2481
2905
  if (!spotlightBackdrop) {
@@ -2518,7 +2942,6 @@ if (IS_BROWSER) {
2518
2942
 
2519
2943
  function hideSpotlight() {
2520
2944
  spotlightTarget = null;
2521
- if (spotlightTimer) { clearTimeout(spotlightTimer); spotlightTimer = null; }
2522
2945
  if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
2523
2946
  }
2524
2947
 
@@ -2624,6 +3047,20 @@ if (IS_BROWSER) {
2624
3047
  }
2625
3048
  }, { rootMargin: '99999px' });
2626
3049
 
3050
+ function detachOverlay(overlay) {
3051
+ if (!overlay) return;
3052
+ if (typeof overlay._cleanup === 'function') {
3053
+ try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
3054
+ }
3055
+ if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
3056
+ visibilityObserver.unobserve(overlay._targetEl);
3057
+ delete overlay._targetEl._impeccableOverlay;
3058
+ }
3059
+ const idx = overlays.indexOf(overlay);
3060
+ if (idx >= 0) overlays.splice(idx, 1);
3061
+ overlay.remove();
3062
+ }
3063
+
2627
3064
  // Reposition overlays after CSS transitions end (e.g. reveal animations).
2628
3065
  // Listens at document level so it catches transitions on ancestor elements
2629
3066
  // (the transform may be on a parent, not the flagged element itself).
@@ -2638,6 +3075,7 @@ if (IS_BROWSER) {
2638
3075
  });
2639
3076
 
2640
3077
  const highlight = function(el, findings) {
3078
+ if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
2641
3079
  const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
2642
3080
 
2643
3081
  const fixed = isInFixedContext(el);
@@ -2669,7 +3107,7 @@ if (IS_BROWSER) {
2669
3107
  display: 'flex', alignItems: 'center',
2670
3108
  whiteSpace: 'nowrap',
2671
3109
  fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
2672
- color: 'white', lineHeight: '14px',
3110
+ color: LABEL_INK, lineHeight: '14px',
2673
3111
  background: LABEL_BG,
2674
3112
  fontFamily: 'system-ui, sans-serif',
2675
3113
  borderRadius: '4px 4px 0 0',
@@ -2750,7 +3188,7 @@ if (IS_BROWSER) {
2750
3188
  };
2751
3189
 
2752
3190
  // Hover: show detail text, darken
2753
- el.addEventListener('mouseenter', () => {
3191
+ const onMouseEnter = () => {
2754
3192
  isHovered = true;
2755
3193
  outline.classList.add('impeccable-hover');
2756
3194
  outline.style.outlineColor = BRAND_COLOR_HOVER;
@@ -2760,8 +3198,8 @@ if (IS_BROWSER) {
2760
3198
  } else {
2761
3199
  textSpan.textContent = entries.map(e => e.detail).join(' | ');
2762
3200
  }
2763
- });
2764
- el.addEventListener('mouseleave', () => {
3201
+ };
3202
+ const onMouseLeave = () => {
2765
3203
  isHovered = false;
2766
3204
  outline.classList.remove('impeccable-hover');
2767
3205
  outline.style.outlineColor = '';
@@ -2771,7 +3209,13 @@ if (IS_BROWSER) {
2771
3209
  } else {
2772
3210
  textSpan.textContent = allText;
2773
3211
  }
2774
- });
3212
+ };
3213
+ el.addEventListener('mouseenter', onMouseEnter);
3214
+ el.addEventListener('mouseleave', onMouseLeave);
3215
+ outline._cleanup = () => {
3216
+ el.removeEventListener('mouseenter', onMouseEnter);
3217
+ el.removeEventListener('mouseleave', onMouseLeave);
3218
+ };
2775
3219
 
2776
3220
  document.body.appendChild(outline);
2777
3221
  overlays.push(outline);
@@ -2783,7 +3227,7 @@ if (IS_BROWSER) {
2783
3227
  banner.className = 'impeccable-overlay impeccable-banner';
2784
3228
  Object.assign(banner.style, {
2785
3229
  position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
2786
- background: LABEL_BG, color: 'white',
3230
+ background: LABEL_BG, color: LABEL_INK,
2787
3231
  fontFamily: 'system-ui, sans-serif', fontSize: '13px',
2788
3232
  display: 'flex', alignItems: 'center', pointerEvents: 'auto',
2789
3233
  height: '36px', overflow: 'hidden', maxWidth: '100vw',
@@ -2934,6 +3378,644 @@ if (IS_BROWSER) {
2934
3378
  return parts.join(' > ');
2935
3379
  }
2936
3380
 
3381
+ function getDirectText(el) {
3382
+ return [...el.childNodes]
3383
+ .filter(n => n.nodeType === 3)
3384
+ .map(n => n.textContent || '')
3385
+ .join('');
3386
+ }
3387
+
3388
+ function getDirectTextRect(el) {
3389
+ const rects = [];
3390
+ for (const node of el.childNodes) {
3391
+ if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
3392
+ const range = document.createRange();
3393
+ range.selectNodeContents(node);
3394
+ for (const rect of range.getClientRects()) {
3395
+ if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
3396
+ }
3397
+ range.detach?.();
3398
+ }
3399
+ if (rects.length === 0) return null;
3400
+ const left = Math.min(...rects.map(r => r.left));
3401
+ const top = Math.min(...rects.map(r => r.top));
3402
+ const right = Math.max(...rects.map(r => r.right));
3403
+ const bottom = Math.max(...rects.map(r => r.bottom));
3404
+ return {
3405
+ left,
3406
+ top,
3407
+ right,
3408
+ bottom,
3409
+ width: right - left,
3410
+ height: bottom - top,
3411
+ x: left,
3412
+ y: top,
3413
+ };
3414
+ }
3415
+
3416
+ function collectVisualContrastReasons(el, style) {
3417
+ const reasons = new Set();
3418
+ const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
3419
+ const ownBgImage = style.backgroundImage || '';
3420
+ if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
3421
+ reasons.add('background-clip text');
3422
+ }
3423
+ if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
3424
+
3425
+ let current = el;
3426
+ while (current && current.nodeType === 1) {
3427
+ const tag = current.tagName?.toLowerCase();
3428
+ const currentStyle = getComputedStyle(current);
3429
+ const bgImage = currentStyle.backgroundImage || '';
3430
+ const isDocumentSurface = tag === 'body' || tag === 'html';
3431
+
3432
+ if (!isDocumentSurface && bgImage && bgImage !== 'none') {
3433
+ if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
3434
+ if (/gradient/i.test(bgImage)) reasons.add('gradient background');
3435
+ }
3436
+ if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
3437
+ if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
3438
+ if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
3439
+ if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
3440
+
3441
+ const solidBg = parseRgb(currentStyle.backgroundColor);
3442
+ if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
3443
+ current = current.parentElement;
3444
+ }
3445
+
3446
+ const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
3447
+ if (sampleRect && document.elementsFromPoint) {
3448
+ const points = [
3449
+ [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
3450
+ [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
3451
+ [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
3452
+ ];
3453
+ for (const [x, y] of points) {
3454
+ if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
3455
+ const stack = document.elementsFromPoint(x, y);
3456
+ const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
3457
+ if (selfIndex < 0) continue;
3458
+ for (const node of stack.slice(selfIndex + 1)) {
3459
+ const nodeTag = node.tagName?.toLowerCase();
3460
+ if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
3461
+ reasons.add(`${nodeTag} underlay`);
3462
+ break;
3463
+ }
3464
+ }
3465
+ }
3466
+ }
3467
+
3468
+ return [...reasons];
3469
+ }
3470
+
3471
+ function collectVisualContrastCandidates(options = {}) {
3472
+ const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
3473
+ const candidates = [];
3474
+ for (const el of document.querySelectorAll('*')) {
3475
+ if (candidates.length >= maxCandidates) break;
3476
+ if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
3477
+ if (el.closest('[id^="impeccable-live-"]')) continue;
3478
+ if (el === document.body || el === document.documentElement) continue;
3479
+
3480
+ const tag = el.tagName.toLowerCase();
3481
+ const style = getComputedStyle(el);
3482
+ if (style.display === 'none' || style.visibility === 'hidden') continue;
3483
+ const directText = getDirectText(el);
3484
+ const hasDirectText = directText.trim().length > 0;
3485
+ if (!hasDirectText || isEmojiOnlyText(directText)) continue;
3486
+
3487
+ const bgColor = readOwnBackgroundColor(el, style);
3488
+ const isStyledButton = (tag === 'a' || tag === 'button')
3489
+ && bgColor && bgColor.a > 0.5;
3490
+ if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
3491
+
3492
+ const rect = getDirectTextRect(el) || el.getBoundingClientRect();
3493
+ if (!rect || rect.width < 4 || rect.height < 4) continue;
3494
+
3495
+ const reasons = collectVisualContrastReasons(el, style);
3496
+ if (reasons.length === 0) continue;
3497
+
3498
+ const textColor = parseRgb(style.color);
3499
+ const fontSize = parseFloat(style.fontSize) || 16;
3500
+ const fontWeight = parseInt(style.fontWeight) || 400;
3501
+ const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
3502
+ const threshold = isLargeText ? 3.0 : 4.5;
3503
+ const clip = {
3504
+ x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
3505
+ y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
3506
+ width: Math.max(1, Math.ceil(rect.width + 4)),
3507
+ height: Math.max(1, Math.ceil(rect.height + 4)),
3508
+ };
3509
+
3510
+ candidates.push({
3511
+ selector: generateSelector(el),
3512
+ tagName: tag,
3513
+ text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
3514
+ threshold,
3515
+ reasons,
3516
+ clip,
3517
+ textColor,
3518
+ preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
3519
+ reason === 'opacity stack' ||
3520
+ reason === 'blend mode' ||
3521
+ reason === 'filter' ||
3522
+ reason === 'backdrop filter' ||
3523
+ reason === 'background-clip text'
3524
+ ),
3525
+ backgroundClipText: reasons.includes('background-clip text'),
3526
+ });
3527
+ }
3528
+ return candidates;
3529
+ }
3530
+
3531
+ const visualContrastImageCache = new Map();
3532
+ const visualContrastRasterCache = new WeakMap();
3533
+
3534
+ function clampByte(value) {
3535
+ return Math.max(0, Math.min(255, Math.round(value)));
3536
+ }
3537
+
3538
+ function blendRgba(fg, bg) {
3539
+ if (!fg) return bg || null;
3540
+ if (!bg || fg.a == null || fg.a >= 0.999) {
3541
+ return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
3542
+ }
3543
+ const alpha = Math.max(0, Math.min(1, fg.a));
3544
+ return {
3545
+ r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
3546
+ g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
3547
+ b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
3548
+ a: 1,
3549
+ };
3550
+ }
3551
+
3552
+ function pickWorstContrastColor(textColor, colors) {
3553
+ const usable = (colors || []).filter(Boolean);
3554
+ if (!usable.length) return null;
3555
+ let worst = usable[0];
3556
+ let worstRatio = contrastRatio(textColor, worst);
3557
+ for (const color of usable.slice(1)) {
3558
+ const ratio = contrastRatio(textColor, color);
3559
+ if (ratio < worstRatio) {
3560
+ worst = color;
3561
+ worstRatio = ratio;
3562
+ }
3563
+ }
3564
+ return worst;
3565
+ }
3566
+
3567
+ function firstCssUrl(value) {
3568
+ const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
3569
+ if (!match) return '';
3570
+ return (match[1] || match[2] || match[3] || '').trim();
3571
+ }
3572
+
3573
+ function getLayerValue(value, index = 0) {
3574
+ return String(value || '').split(',')[index]?.trim() || '';
3575
+ }
3576
+
3577
+ function parsePositionToken(token, container, painted) {
3578
+ if (!token || token === 'center') return (container - painted) / 2;
3579
+ if (token === 'left' || token === 'top') return 0;
3580
+ if (token === 'right' || token === 'bottom') return container - painted;
3581
+ if (/%$/.test(token)) {
3582
+ const pct = parseFloat(token) / 100;
3583
+ return (container - painted) * pct;
3584
+ }
3585
+ if (/px$/.test(token)) return parseFloat(token) || 0;
3586
+ return (container - painted) / 2;
3587
+ }
3588
+
3589
+ function parsePositionPair(positionValue) {
3590
+ const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
3591
+ const first = tokens[0] || '50%';
3592
+ if (tokens.length < 2) {
3593
+ if (first === 'top' || first === 'bottom') return ['50%', first];
3594
+ return [first, '50%'];
3595
+ }
3596
+ return [first, tokens[1] || '50%'];
3597
+ }
3598
+
3599
+ function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
3600
+ const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
3601
+ const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
3602
+ let paintedWidth = intrinsicWidth;
3603
+ let paintedHeight = intrinsicHeight;
3604
+ const size = String(sizeValue || 'auto').trim();
3605
+
3606
+ if (size === 'cover' || size === 'contain') {
3607
+ const scale = size === 'cover'
3608
+ ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
3609
+ : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
3610
+ paintedWidth = intrinsicWidth * scale;
3611
+ paintedHeight = intrinsicHeight * scale;
3612
+ } else if (size && size !== 'auto') {
3613
+ const parts = size.split(/\s+/);
3614
+ const widthToken = parts[0];
3615
+ const heightToken = parts[1] || 'auto';
3616
+ if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
3617
+ else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
3618
+ if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
3619
+ else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
3620
+ else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
3621
+ }
3622
+
3623
+ const [xToken, yToken] = parsePositionPair(positionValue);
3624
+ const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
3625
+ const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
3626
+ return {
3627
+ left: containerRect.left + positionX,
3628
+ top: containerRect.top + positionY,
3629
+ width: paintedWidth,
3630
+ height: paintedHeight,
3631
+ intrinsicWidth,
3632
+ intrinsicHeight,
3633
+ };
3634
+ }
3635
+
3636
+ function parseObjectPosition(positionValue) {
3637
+ return parsePositionPair(positionValue);
3638
+ }
3639
+
3640
+ function resolveObjectImageRect(containerRect, image, style) {
3641
+ const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
3642
+ const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
3643
+ const fit = style.objectFit || 'fill';
3644
+ let paintedWidth = containerRect.width;
3645
+ let paintedHeight = containerRect.height;
3646
+ if (fit === 'contain' || fit === 'cover') {
3647
+ const scale = fit === 'cover'
3648
+ ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
3649
+ : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
3650
+ paintedWidth = intrinsicWidth * scale;
3651
+ paintedHeight = intrinsicHeight * scale;
3652
+ } else if (fit === 'none') {
3653
+ paintedWidth = intrinsicWidth;
3654
+ paintedHeight = intrinsicHeight;
3655
+ } else if (fit === 'scale-down') {
3656
+ const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
3657
+ paintedWidth = intrinsicWidth * containScale;
3658
+ paintedHeight = intrinsicHeight * containScale;
3659
+ }
3660
+ const [xToken, yToken] = parseObjectPosition(style.objectPosition);
3661
+ return {
3662
+ left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
3663
+ top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
3664
+ width: paintedWidth,
3665
+ height: paintedHeight,
3666
+ intrinsicWidth,
3667
+ intrinsicHeight,
3668
+ };
3669
+ }
3670
+
3671
+ function pointToImageSource(point, paintedRect) {
3672
+ if (
3673
+ point.x < paintedRect.left ||
3674
+ point.y < paintedRect.top ||
3675
+ point.x > paintedRect.left + paintedRect.width ||
3676
+ point.y > paintedRect.top + paintedRect.height
3677
+ ) {
3678
+ return null;
3679
+ }
3680
+ return {
3681
+ x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
3682
+ y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
3683
+ };
3684
+ }
3685
+
3686
+ async function loadVisualContrastImage(src) {
3687
+ if (!src) return null;
3688
+ if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
3689
+ const promise = new Promise(resolve => {
3690
+ const img = new Image();
3691
+ let settled = false;
3692
+ const finish = value => {
3693
+ if (settled) return;
3694
+ settled = true;
3695
+ clearTimeout(timer);
3696
+ resolve(value);
3697
+ };
3698
+ const timer = setTimeout(() => finish(null), 800);
3699
+ try {
3700
+ const absolute = new URL(src, location.href);
3701
+ if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
3702
+ img.crossOrigin = 'anonymous';
3703
+ }
3704
+ } catch {
3705
+ // Let the browser resolve unusual URLs itself.
3706
+ }
3707
+ img.onload = () => finish(img);
3708
+ img.onerror = () => finish(null);
3709
+ img.src = src;
3710
+ });
3711
+ visualContrastImageCache.set(src, promise);
3712
+ return promise;
3713
+ }
3714
+
3715
+ function sampleDrawablePixel(drawable, sourcePoint) {
3716
+ if (visualContrastRasterCache.has(drawable)) {
3717
+ const cached = visualContrastRasterCache.get(drawable);
3718
+ if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
3719
+ try {
3720
+ const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
3721
+ const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
3722
+ const data = cached.ctx.getImageData(x, y, 1, 1).data;
3723
+ return {
3724
+ status: 'sampled',
3725
+ color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
3726
+ };
3727
+ } catch (err) {
3728
+ return {
3729
+ status: 'unresolved',
3730
+ reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
3731
+ };
3732
+ }
3733
+ }
3734
+
3735
+ const canvas = document.createElement('canvas');
3736
+ const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
3737
+ const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
3738
+ const maxRasterSide = 640;
3739
+ const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
3740
+ canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
3741
+ canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
3742
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
3743
+ if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
3744
+ try {
3745
+ ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
3746
+ const cached = {
3747
+ ctx,
3748
+ width: canvas.width,
3749
+ height: canvas.height,
3750
+ scaleX: canvas.width / intrinsicWidth,
3751
+ scaleY: canvas.height / intrinsicHeight,
3752
+ };
3753
+ visualContrastRasterCache.set(drawable, cached);
3754
+ const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
3755
+ const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
3756
+ const data = ctx.getImageData(x, y, 1, 1).data;
3757
+ return {
3758
+ status: 'sampled',
3759
+ color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
3760
+ };
3761
+ } catch (err) {
3762
+ const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
3763
+ visualContrastRasterCache.set(drawable, { ctx: null, reason });
3764
+ return {
3765
+ status: 'unresolved',
3766
+ reason,
3767
+ };
3768
+ }
3769
+ }
3770
+
3771
+ async function sampleCssBackground(el, style, point, textColor) {
3772
+ const rect = el.getBoundingClientRect();
3773
+ const bgImage = style.backgroundImage || '';
3774
+ if (bgImage && bgImage !== 'none') {
3775
+ if (/gradient/i.test(bgImage)) {
3776
+ const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
3777
+ if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
3778
+ }
3779
+ if (/url\s*\(/i.test(bgImage)) {
3780
+ const img = await loadVisualContrastImage(firstCssUrl(bgImage));
3781
+ if (!img) return { status: 'unresolved', reason: 'image unavailable' };
3782
+ const paintedRect = resolvePaintedImageRect(
3783
+ rect,
3784
+ img,
3785
+ getLayerValue(style.backgroundSize) || 'auto',
3786
+ getLayerValue(style.backgroundPosition) || '50% 50%',
3787
+ );
3788
+ const sourcePoint = pointToImageSource(point, paintedRect);
3789
+ if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
3790
+ const sample = sampleDrawablePixel(img, sourcePoint);
3791
+ if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
3792
+ return sample;
3793
+ }
3794
+ }
3795
+ const bg = parseRgb(style.backgroundColor);
3796
+ if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
3797
+ return { status: 'unresolved', reason: 'no readable background' };
3798
+ }
3799
+
3800
+ async function sampleImageElement(img, point) {
3801
+ const rect = img.getBoundingClientRect();
3802
+ const style = getComputedStyle(img);
3803
+ const paintedRect = resolveObjectImageRect(rect, img, style);
3804
+ const sourcePoint = pointToImageSource(point, paintedRect);
3805
+ if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
3806
+ const sample = sampleDrawablePixel(img, sourcePoint);
3807
+ if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
3808
+
3809
+ if (img.currentSrc || img.src) {
3810
+ const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
3811
+ if (loaded) {
3812
+ const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
3813
+ const loadedPoint = pointToImageSource(point, loadedRect);
3814
+ if (loadedPoint) {
3815
+ const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
3816
+ if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
3817
+ }
3818
+ }
3819
+ }
3820
+ return sample;
3821
+ }
3822
+
3823
+ function textSamplePoints(rect) {
3824
+ const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
3825
+ const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
3826
+ const xs = rect.width < 28
3827
+ ? [rect.left + rect.width / 2]
3828
+ : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
3829
+ const ys = rect.height < 22
3830
+ ? [rect.top + rect.height / 2]
3831
+ : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
3832
+ const points = [];
3833
+ for (const y of ys) {
3834
+ for (const x of xs) {
3835
+ if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
3836
+ }
3837
+ }
3838
+ return points;
3839
+ }
3840
+
3841
+ async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
3842
+ if (depth > 8) {
3843
+ return { status: 'unresolved', reason: 'background stack too deep' };
3844
+ }
3845
+ const stack = typeof document.elementsFromPoint === 'function'
3846
+ ? document.elementsFromPoint(point.x, point.y)
3847
+ : [];
3848
+ const selfIndex = stack.findIndex(node => node === el || el.contains(node));
3849
+ const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
3850
+ const unresolved = [];
3851
+
3852
+ for (const node of nodes) {
3853
+ if (!node || node.nodeType !== 1) continue;
3854
+ if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
3855
+ const tag = node.tagName?.toLowerCase();
3856
+ if (tag === 'img') {
3857
+ const sample = await sampleImageElement(node, point);
3858
+ if (sample.status === 'sampled') return sample;
3859
+ unresolved.push(sample.reason);
3860
+ continue;
3861
+ }
3862
+ if (tag === 'canvas' || tag === 'video') {
3863
+ const rect = node.getBoundingClientRect();
3864
+ const sourcePoint = pointToImageSource(point, {
3865
+ left: rect.left,
3866
+ top: rect.top,
3867
+ width: rect.width,
3868
+ height: rect.height,
3869
+ intrinsicWidth: node.width || node.videoWidth || rect.width,
3870
+ intrinsicHeight: node.height || node.videoHeight || rect.height,
3871
+ });
3872
+ if (sourcePoint) {
3873
+ const sample = sampleDrawablePixel(node, sourcePoint);
3874
+ if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
3875
+ unresolved.push(sample.reason);
3876
+ }
3877
+ continue;
3878
+ }
3879
+ const style = getComputedStyle(node);
3880
+ const sample = await sampleCssBackground(node, style, point, textColor);
3881
+ if (sample.status === 'sampled') {
3882
+ if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
3883
+ const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
3884
+ if (under.status === 'sampled') {
3885
+ return {
3886
+ status: 'sampled',
3887
+ color: blendRgba(sample.color, under.color),
3888
+ method: `${sample.method}+alpha`,
3889
+ };
3890
+ }
3891
+ return sample;
3892
+ }
3893
+ unresolved.push(sample.reason);
3894
+ }
3895
+
3896
+ return {
3897
+ status: 'unresolved',
3898
+ reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
3899
+ };
3900
+ }
3901
+
3902
+ async function analyzeVisualContrastCandidate(candidate) {
3903
+ let el;
3904
+ try {
3905
+ el = document.querySelector(candidate.selector);
3906
+ } catch {
3907
+ return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
3908
+ }
3909
+ if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
3910
+
3911
+ const blockingReason = (candidate.reasons || []).find(reason =>
3912
+ reason === 'background-clip text' ||
3913
+ reason === 'blend mode' ||
3914
+ reason === 'filter' ||
3915
+ reason === 'backdrop filter' ||
3916
+ reason === 'opacity stack' ||
3917
+ reason === 'text shadow'
3918
+ );
3919
+ if (blockingReason) {
3920
+ return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
3921
+ }
3922
+
3923
+ const style = getComputedStyle(el);
3924
+ const textColor = parseRgb(style.color) || candidate.textColor;
3925
+ if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
3926
+
3927
+ const rect = getDirectTextRect(el) || el.getBoundingClientRect();
3928
+ if (!rect || rect.width < 4 || rect.height < 4) {
3929
+ return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
3930
+ }
3931
+
3932
+ const points = textSamplePoints(rect);
3933
+ if (points.length === 0) {
3934
+ return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
3935
+ }
3936
+
3937
+ const ratios = [];
3938
+ const methods = new Set();
3939
+ const unresolved = [];
3940
+ for (const point of points) {
3941
+ const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
3942
+ if (sample.status !== 'sampled' || !sample.color) {
3943
+ unresolved.push(sample.reason);
3944
+ continue;
3945
+ }
3946
+ const fg = blendRgba(textColor, sample.color);
3947
+ ratios.push(contrastRatio(fg, sample.color));
3948
+ if (sample.method) methods.add(sample.method);
3949
+ }
3950
+
3951
+ if (ratios.length < Math.min(3, points.length)) {
3952
+ return {
3953
+ ...candidate,
3954
+ status: 'unresolved',
3955
+ confidence: 'none',
3956
+ samples: ratios.length,
3957
+ reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
3958
+ };
3959
+ }
3960
+
3961
+ ratios.sort((a, b) => a - b);
3962
+ const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
3963
+ const measuredRatio = pick(10);
3964
+ const medianRatio = pick(50);
3965
+ const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
3966
+ const method = [...methods].sort().join(', ') || 'browser-visual';
3967
+ const textLabel = candidate.text ? ` "${candidate.text}"` : '';
3968
+ const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
3969
+ return {
3970
+ ...candidate,
3971
+ status,
3972
+ confidence: method.includes('canvas-') ? 'high' : 'medium',
3973
+ method,
3974
+ ratio: measuredRatio,
3975
+ medianRatio,
3976
+ samples: ratios.length,
3977
+ finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
3978
+ };
3979
+ }
3980
+
3981
+ function waitForVisualPaint() {
3982
+ return new Promise(resolve => {
3983
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
3984
+ });
3985
+ }
3986
+
3987
+ async function analyzeVisualContrast(options = {}) {
3988
+ const candidates = collectVisualContrastCandidates(options);
3989
+ const results = [];
3990
+ const shouldScrollOffscreen = options.scrollOffscreen === true;
3991
+ const restoreScroll = { x: window.scrollX, y: window.scrollY };
3992
+ for (const candidate of candidates) {
3993
+ if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
3994
+ window.scrollTo(restoreScroll.x, restoreScroll.y);
3995
+ await waitForVisualPaint();
3996
+ }
3997
+ let result = await analyzeVisualContrastCandidate(candidate);
3998
+ if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
3999
+ let el = null;
4000
+ try {
4001
+ el = document.querySelector(candidate.selector);
4002
+ } catch {
4003
+ el = null;
4004
+ }
4005
+ if (el && typeof el.scrollIntoView === 'function') {
4006
+ el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
4007
+ await waitForVisualPaint();
4008
+ result = await analyzeVisualContrastCandidate(candidate);
4009
+ }
4010
+ }
4011
+ results.push(result);
4012
+ }
4013
+ if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
4014
+ window.scrollTo(restoreScroll.x, restoreScroll.y);
4015
+ }
4016
+ return results;
4017
+ }
4018
+
2937
4019
  function isElementHidden(el) {
2938
4020
  if (!el || el === document.body || el === document.documentElement) return false;
2939
4021
  if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
@@ -2970,26 +4052,36 @@ if (IS_BROWSER) {
2970
4052
  }
2971
4053
  console.group(
2972
4054
  `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
2973
- 'color: oklch(60% 0.25 350); font-weight: bold'
4055
+ 'color: oklch(84% 0.19 80.46); font-weight: bold'
2974
4056
  );
2975
4057
  for (const { el, findings } of allFindings) {
2976
4058
  for (const f of findings) {
2977
4059
  console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
2978
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
4060
+ 'color: oklch(84% 0.19 80.46); font-weight: bold', 'color: inherit', el);
2979
4061
  }
2980
4062
  }
2981
4063
  console.groupEnd();
2982
4064
  };
2983
4065
 
2984
- let firstScanDone = false;
2985
- const scan = function() {
2986
- for (const o of overlays) o.remove();
2987
- overlays.length = 0;
2988
- visibilityObserver.disconnect();
2989
- overlayIndex = 0;
2990
- const allFindings = [];
4066
+ function addBrowserFindings(groupMap, el, findings) {
4067
+ if (!findings || findings.length === 0) return;
4068
+ const existing = groupMap.get(el);
4069
+ if (existing) existing.push(...findings);
4070
+ else groupMap.set(el, [...findings]);
4071
+ }
4072
+
4073
+ function browserFindingsFromMap(groupMap) {
4074
+ return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
4075
+ }
4076
+
4077
+ function collectBrowserFindings() {
4078
+ const groupMap = new Map();
2991
4079
  const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
2992
4080
  const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
4081
+ // Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
4082
+ // real browser env (detector page, live overlay, extension) running every
4083
+ // check is free, so we always surface them; the gating is purely a CLI
4084
+ // output concern, applied in the Node engines' detect* return paths.
2993
4085
 
2994
4086
  for (const el of document.querySelectorAll('*')) {
2995
4087
  // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
@@ -3011,13 +4103,22 @@ if (IS_BROWSER) {
3011
4103
  ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3012
4104
  ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3013
4105
  ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3014
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3015
4106
  ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4107
+ ...checkElementOversizedH1DOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4108
+ ...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4109
+ ...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4110
+ ...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
3016
4111
  ].filter(f => _ruleOk(f.type));
3017
4112
 
3018
- if (findings.length > 0) {
3019
- highlight(el, findings);
3020
- allFindings.push({ el, findings });
4113
+ addBrowserFindings(groupMap, el, findings);
4114
+
4115
+ // Hero eyebrow: the offending element is the eyebrow above the heading,
4116
+ // not the heading itself — highlight the previous sibling instead.
4117
+ const eyebrowFindings = checkElementHeroEyebrowDOM(el)
4118
+ .map(f => ({ type: f.id, detail: f.snippet }))
4119
+ .filter(f => _ruleOk(f.type));
4120
+ if (eyebrowFindings.length > 0 && el.previousElementSibling) {
4121
+ addBrowserFindings(groupMap, el.previousElementSibling, eyebrowFindings);
3021
4122
  }
3022
4123
  }
3023
4124
 
@@ -3026,7 +4127,7 @@ if (IS_BROWSER) {
3026
4127
  const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
3027
4128
  if (typoFindings.length > 0) {
3028
4129
  pageLevelFindings.push(...typoFindings);
3029
- allFindings.push({ el: document.body, findings: typoFindings });
4130
+ addBrowserFindings(groupMap, document.body, typoFindings);
3030
4131
  }
3031
4132
 
3032
4133
  const sectionKickerFindings = checkRepeatedSectionKickersDOM()
@@ -3034,32 +4135,28 @@ if (IS_BROWSER) {
3034
4135
  .filter(f => _ruleOk(f.type));
3035
4136
  if (sectionKickerFindings.length > 0) {
3036
4137
  pageLevelFindings.push(...sectionKickerFindings);
3037
- allFindings.push({ el: document.body, findings: sectionKickerFindings });
4138
+ addBrowserFindings(groupMap, document.body, sectionKickerFindings);
3038
4139
  }
3039
4140
 
3040
4141
  const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
3041
4142
  for (const f of layoutFindings) {
3042
4143
  const el = f.el || document.body;
3043
- delete f.el;
3044
- // Merge into existing overlay if this element already has one
3045
- const existing = el._impeccableOverlay;
3046
- if (existing) {
3047
- const nameRow = existing.querySelector('.impeccable-label-name');
3048
- const detailRow = existing.querySelector('.impeccable-label-detail');
3049
- const newType = TYPE_LABELS[f.type] || f.type;
3050
- if (nameRow) nameRow.textContent += ', ' + newType;
3051
- if (detailRow) detailRow.textContent += ' | ' + (f.detail || '');
3052
- } else {
3053
- highlight(el, [f]);
3054
- }
3055
- allFindings.push({ el, findings: [f] });
4144
+ addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
3056
4145
  }
3057
4146
 
3058
4147
  // Page-level quality checks (headings, etc.)
3059
4148
  const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
3060
4149
  if (qualityFindings.length > 0) {
3061
4150
  pageLevelFindings.push(...qualityFindings);
3062
- allFindings.push({ el: document.body, findings: qualityFindings });
4151
+ addBrowserFindings(groupMap, document.body, qualityFindings);
4152
+ }
4153
+
4154
+ const creamFindings = checkCreamPalette(document)
4155
+ .map(f => ({ type: f.id, detail: f.snippet }))
4156
+ .filter(f => _ruleOk(f.type));
4157
+ if (creamFindings.length > 0) {
4158
+ pageLevelFindings.push(...creamFindings);
4159
+ addBrowserFindings(groupMap, document.body, creamFindings);
3063
4160
  }
3064
4161
 
3065
4162
  // Regex-on-HTML checks (shared with Node)
@@ -3074,7 +4171,222 @@ if (IS_BROWSER) {
3074
4171
  if (htmlPatternFindings.length > 0) {
3075
4172
  const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
3076
4173
  pageLevelFindings.push(...mapped);
3077
- allFindings.push({ el: document.body, findings: mapped });
4174
+ addBrowserFindings(groupMap, document.body, mapped);
4175
+ }
4176
+
4177
+ return {
4178
+ groupMap,
4179
+ allFindings: browserFindingsFromMap(groupMap),
4180
+ pageLevelFindings,
4181
+ };
4182
+ }
4183
+
4184
+ function shouldRunVisualContrast(options = {}) {
4185
+ return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
4186
+ }
4187
+
4188
+ function visualContrastOptions(options = {}) {
4189
+ const config = window.__IMPECCABLE_CONFIG__ || {};
4190
+ const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
4191
+ ? options.scrollOffscreen
4192
+ : typeof options.visualContrastScrollOffscreen === 'boolean'
4193
+ ? options.visualContrastScrollOffscreen
4194
+ : typeof config.visualContrastScrollOffscreen === 'boolean'
4195
+ ? config.visualContrastScrollOffscreen
4196
+ : false;
4197
+ return {
4198
+ ...options,
4199
+ maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
4200
+ ? options.visualContrastMaxCandidates
4201
+ : Number.isFinite(options.maxCandidates)
4202
+ ? options.maxCandidates
4203
+ : Number.isFinite(config.visualContrastMaxCandidates)
4204
+ ? config.visualContrastMaxCandidates
4205
+ : undefined,
4206
+ scrollOffscreen,
4207
+ };
4208
+ }
4209
+
4210
+ let lastVisualContrastAnalyses = [];
4211
+ let lazyVisualContrastObserver = null;
4212
+ let lazyVisualContrastPending = new WeakMap();
4213
+ const lazyVisualContrastResolving = new WeakSet();
4214
+ let scanGeneration = 0;
4215
+
4216
+ function rememberVisualContrastAnalysis(result) {
4217
+ if (!result?.selector) {
4218
+ lastVisualContrastAnalyses.push(result);
4219
+ return;
4220
+ }
4221
+ const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
4222
+ if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
4223
+ else lastVisualContrastAnalyses.push(result);
4224
+ }
4225
+
4226
+ function disconnectLazyVisualContrastObserver() {
4227
+ if (lazyVisualContrastObserver) {
4228
+ lazyVisualContrastObserver.disconnect();
4229
+ lazyVisualContrastObserver = null;
4230
+ }
4231
+ lazyVisualContrastPending = new WeakMap();
4232
+ }
4233
+
4234
+ function addVisualContrastResult(groupMap, result, options = {}) {
4235
+ if (result.status !== 'fail' || !result.finding || !result.selector) return false;
4236
+ let el = null;
4237
+ try {
4238
+ el = document.querySelector(result.selector);
4239
+ } catch {
4240
+ el = null;
4241
+ }
4242
+ if (!el) return false;
4243
+ const findingType = result.finding.type || result.finding.id || 'low-contrast';
4244
+ const existing = groupMap.get(el) || [];
4245
+ if (existing.some(f => (f.type || f.id) === findingType)) return false;
4246
+ addBrowserFindings(groupMap, el, [{
4247
+ type: findingType,
4248
+ detail: result.finding.detail || result.finding.snippet,
4249
+ }]);
4250
+ if (options.decorate && el !== document.body && el !== document.documentElement) {
4251
+ highlight(el, groupMap.get(el) || []);
4252
+ }
4253
+ return true;
4254
+ }
4255
+
4256
+ function postSerializedFindings(groupMap) {
4257
+ if (!EXTENSION_MODE) return;
4258
+ const allFindings = browserFindingsFromMap(groupMap);
4259
+ window.postMessage({
4260
+ source: 'impeccable-results',
4261
+ findings: serializeFindings(allFindings),
4262
+ count: allFindings.length,
4263
+ }, '*');
4264
+ }
4265
+
4266
+ function postExtensionError(err) {
4267
+ if (!EXTENSION_MODE) return;
4268
+ window.postMessage({
4269
+ source: 'impeccable-error',
4270
+ message: err?.message || String(err),
4271
+ }, '*');
4272
+ }
4273
+
4274
+ function reportVisualContrastError(err, detail = {}) {
4275
+ window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
4276
+ detail: {
4277
+ ...detail,
4278
+ message: err?.message || String(err),
4279
+ },
4280
+ }));
4281
+ if (EXTENSION_MODE) {
4282
+ postExtensionError(err);
4283
+ } else {
4284
+ console.warn('[impeccable] visual contrast scan failed', err);
4285
+ }
4286
+ }
4287
+
4288
+ function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
4289
+ disconnectLazyVisualContrastObserver();
4290
+ if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
4291
+ if (typeof IntersectionObserver === 'undefined') return;
4292
+ const unresolved = (analyses || []).filter(result =>
4293
+ result?.status === 'unresolved' &&
4294
+ result.reason === 'text outside viewport' &&
4295
+ result.selector
4296
+ );
4297
+ if (unresolved.length === 0) return;
4298
+ const generation = runtime.generation || scanGeneration;
4299
+
4300
+ lazyVisualContrastObserver = new IntersectionObserver((entries) => {
4301
+ for (const entry of entries) {
4302
+ if (!entry.isIntersecting) continue;
4303
+ const el = entry.target;
4304
+ const candidate = lazyVisualContrastPending.get(el);
4305
+ if (!candidate || lazyVisualContrastResolving.has(el)) continue;
4306
+ lazyVisualContrastObserver?.unobserve(el);
4307
+ lazyVisualContrastPending.delete(el);
4308
+ lazyVisualContrastResolving.add(el);
4309
+ waitForVisualPaint()
4310
+ .then(() => analyzeVisualContrastCandidate(candidate))
4311
+ .then(result => {
4312
+ if (generation !== scanGeneration) return;
4313
+ rememberVisualContrastAnalysis(result);
4314
+ const added = addVisualContrastResult(groupMap, result, { decorate: true });
4315
+ if (added) {
4316
+ postSerializedFindings(groupMap);
4317
+ window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
4318
+ detail: {
4319
+ selector: result.selector,
4320
+ status: result.status,
4321
+ finding: result.finding || null,
4322
+ },
4323
+ }));
4324
+ }
4325
+ })
4326
+ .catch(err => {
4327
+ reportVisualContrastError(err, { selector: candidate.selector });
4328
+ })
4329
+ .finally(() => {
4330
+ lazyVisualContrastResolving.delete(el);
4331
+ });
4332
+ }
4333
+ }, { threshold: 0.5 });
4334
+
4335
+ for (const candidate of unresolved) {
4336
+ let el = null;
4337
+ try {
4338
+ el = document.querySelector(candidate.selector);
4339
+ } catch {
4340
+ el = null;
4341
+ }
4342
+ if (!el) continue;
4343
+ lazyVisualContrastPending.set(el, candidate);
4344
+ lazyVisualContrastObserver.observe(el);
4345
+ }
4346
+ }
4347
+
4348
+ async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
4349
+ if (!shouldRunVisualContrast(options)) {
4350
+ lastVisualContrastAnalyses = [];
4351
+ disconnectLazyVisualContrastObserver();
4352
+ return [];
4353
+ }
4354
+ const resolvedOptions = visualContrastOptions(options);
4355
+ const analyses = await analyzeVisualContrast(resolvedOptions);
4356
+ if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
4357
+ lastVisualContrastAnalyses = analyses;
4358
+ for (const result of analyses) {
4359
+ addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
4360
+ }
4361
+ if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
4362
+ return analyses;
4363
+ }
4364
+
4365
+ async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
4366
+ const collected = collectBrowserFindings();
4367
+ await addVisualContrastFindings(collected.groupMap, options, runtime);
4368
+ return {
4369
+ ...collected,
4370
+ allFindings: browserFindingsFromMap(collected.groupMap),
4371
+ visualContrastAnalyses: lastVisualContrastAnalyses,
4372
+ };
4373
+ }
4374
+
4375
+ function clearOverlays() {
4376
+ scanGeneration += 1;
4377
+ disconnectLazyVisualContrastObserver();
4378
+ for (const o of [...overlays]) detachOverlay(o);
4379
+ overlays.length = 0;
4380
+ visibilityObserver.disconnect();
4381
+ overlayIndex = 0;
4382
+ }
4383
+
4384
+ function renderBrowserFindings(collected) {
4385
+ const { allFindings, pageLevelFindings } = collected;
4386
+
4387
+ for (const { el, findings } of allFindings) {
4388
+ if (el === document.body || el === document.documentElement) continue;
4389
+ highlight(el, findings);
3078
4390
  }
3079
4391
 
3080
4392
  if (pageLevelFindings.length > 0) {
@@ -3096,6 +4408,52 @@ if (IS_BROWSER) {
3096
4408
  setTimeout(() => { firstScanDone = true; }, 1000);
3097
4409
 
3098
4410
  return allFindings;
4411
+ }
4412
+
4413
+ let firstScanDone = false;
4414
+ const scan = function(options = {}) {
4415
+ clearOverlays();
4416
+ const generation = scanGeneration;
4417
+ const collected = collectBrowserFindings();
4418
+ const allFindings = renderBrowserFindings(collected);
4419
+ if (shouldRunVisualContrast(options)) {
4420
+ addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
4421
+ .then(() => {
4422
+ if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
4423
+ })
4424
+ .catch(err => {
4425
+ reportVisualContrastError(err);
4426
+ });
4427
+ }
4428
+ return allFindings;
4429
+ };
4430
+
4431
+ const scanAsync = async function(options = {}) {
4432
+ clearOverlays();
4433
+ const generation = scanGeneration;
4434
+ if (shouldRunVisualContrast(options)) {
4435
+ const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
4436
+ if (generation !== scanGeneration) return [];
4437
+ return renderBrowserFindings(collected);
4438
+ }
4439
+ lastVisualContrastAnalyses = [];
4440
+ return renderBrowserFindings(collectBrowserFindings());
4441
+ };
4442
+
4443
+ const detect = function(options = {}) {
4444
+ lastVisualContrastAnalyses = [];
4445
+ const { allFindings } = collectBrowserFindings();
4446
+ return options.serialize === false ? allFindings : serializeFindings(allFindings);
4447
+ };
4448
+
4449
+ const detectAsync = async function(options = {}) {
4450
+ if (shouldRunVisualContrast(options)) {
4451
+ const { allFindings } = await collectBrowserFindingsAsync(options);
4452
+ return options.serialize === false ? allFindings : serializeFindings(allFindings);
4453
+ }
4454
+ lastVisualContrastAnalyses = [];
4455
+ const { allFindings } = collectBrowserFindings();
4456
+ return options.serialize === false ? allFindings : serializeFindings(allFindings);
3099
4457
  };
3100
4458
 
3101
4459
  if (EXTENSION_MODE) {
@@ -3104,7 +4462,11 @@ if (IS_BROWSER) {
3104
4462
  if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
3105
4463
  if (e.data.action === 'scan') {
3106
4464
  if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
3107
- scan();
4465
+ try {
4466
+ scan(e.data.config || {});
4467
+ } catch (err) {
4468
+ postExtensionError(err);
4469
+ }
3108
4470
  }
3109
4471
  if (e.data.action === 'toggle-overlays') {
3110
4472
  const visible = !document.body.classList.contains('impeccable-hidden');
@@ -3112,15 +4474,12 @@ if (IS_BROWSER) {
3112
4474
  window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
3113
4475
  }
3114
4476
  if (e.data.action === 'remove') {
3115
- for (const o of overlays) o.remove();
3116
- overlays.length = 0;
3117
- visibilityObserver.disconnect();
4477
+ clearOverlays();
3118
4478
  styleEl.remove();
3119
4479
  if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
3120
4480
  document.body.classList.remove('impeccable-hidden');
3121
4481
  }
3122
4482
  if (e.data.action === 'highlight') {
3123
- if (spotlightTimer) { clearTimeout(spotlightTimer); spotlightTimer = null; }
3124
4483
  try {
3125
4484
  const target = e.data.selector ? document.querySelector(e.data.selector) : null;
3126
4485
  if (target) {
@@ -3156,18 +4515,29 @@ if (IS_BROWSER) {
3156
4515
  });
3157
4516
  window.postMessage({ source: 'impeccable-ready' }, '*');
3158
4517
  } else {
3159
- if (document.readyState === 'loading') {
3160
- document.addEventListener('DOMContentLoaded', () => setTimeout(scan, 100));
3161
- } else {
3162
- setTimeout(scan, 100);
4518
+ if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
4519
+ const runAutoScan = () => {
4520
+ try {
4521
+ scan();
4522
+ } catch (err) {
4523
+ console.warn('[impeccable] scan failed', err);
4524
+ }
4525
+ };
4526
+ if (document.readyState === 'loading') {
4527
+ document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
4528
+ } else {
4529
+ setTimeout(runAutoScan, 100);
4530
+ }
3163
4531
  }
3164
4532
  }
3165
4533
 
4534
+ window.impeccableDetect = detect;
4535
+ window.impeccableDetectAsync = detectAsync;
3166
4536
  window.impeccableScan = scan;
4537
+ window.impeccableScanAsync = scanAsync;
4538
+ window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
4539
+ window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
4540
+ window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
3167
4541
  }
3168
4542
 
3169
- // ─── Section 8: Node Engine ─────────────────────────────────────────────────
3170
-
3171
- // ─── Section 9: Exports ─────────────────────────────────────────────────────
3172
-
3173
4543
  })();